From b6f3bcf36e78adf33743cae7d7556db5fd8e3039 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 21 Sep 2026 11:25:31 +1200 Subject: [PATCH 01/68] Persist replay evidence and retention-safe V4 repository substrate --- .../runtime-and-data.md | 2 +- .../automation-and-scheduler-runtime.md | 2 + .../entity/ScriptWorkItem.java | 19 + .../ScriptDeadLetterReplayRepository.java | 312 +++++++++++++++++ .../ScriptHandoffEventRepository.java | 102 ++++++ .../repository/ScriptWorkItemRepository.java | 315 +++++++++++++++-- .../V4__execution_replay_and_retention.sql | 126 +++++++ ...AndRetentionRepositoryIntegrationTest.java | 69 ++++ ...4__execution_replay_and_retentionTest.java | 81 +++++ .../ScriptDeadLetterReplayRepositoryTest.java | 116 ++++++ .../ScriptHandoffEventRepositoryTest.java | 162 +++++++++ .../ScriptWorkItemRepositoryTest.java | 331 ++++++++++++++++-- 12 files changed, 1581 insertions(+), 56 deletions(-) create mode 100644 services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptDeadLetterReplayRepository.java create mode 100644 services/automation-scripting-service/src/main/resources/db/migration/V4__execution_replay_and_retention.sql create mode 100644 services/automation-scripting-service/src/test/java/unit/db/migration/V4__execution_replay_and_retentionTest.java create mode 100644 services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptDeadLetterReplayRepositoryTest.java 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 b4099f88c6..8db2ddec2d 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -50,7 +50,7 @@ Tick-driven automation and event handling never use synchronous sagas or Tempora ## Runtime Data Model - `script` holds compiled component definitions and version metadata. -- `npc_memory` stores persistent state for NPC behaviors. +- `npc_memory` is a live but latent NPC-behavior state family. The baseline schema and repository key it only by `tenantId`, `npcId`, and `key`; they do not carry a stable playable-state namespace or a typed runtime-actor identity. Owner classification and any required mapping/application evidence are not established, so no S1/S2/S3 selection is made. The path is non-admissible for replacement until its owner classification, identity mapping, and focused proof exist; this is not a claim that it is S3 or disposable. - **Target-state:** Admitted script work items are persisted durably in a PostgreSQL-backed outbox in `PENDING_EVALUATION`, keyed only by the full canonical Trigger Identity plus sequencing fields as needed, including `playableStateScope` and `regionEpoch`; the exact observed `(scriptPatchVersion, scriptPinEpoch)` tuple, captured plugin `pluginActivationEpoch` and owner `lifecycleRevision` where applicable, resolved binding `priorityTag`/`quotaClass`, immutable `lane`, and bounded `cost_class` are execution evidence used for the canonical charge lifecycle. The owner-committed `controlPlaneRequestId` is persisted separately as owner-grounded projection/correlation evidence and retained through reload, convergence, handoff, and recovery; it is not part of Trigger Identity, sequencing, uniqueness, or deduplication. Pre-DSL records retain the sealed immutable handler input manifest, including `priorityTag`, `quotaClass`, `lane`, `cost_class`, `componentCostRegistryDigest`, and `artifactRuntimeCapDigest` where applicable. Gameplay/runtime persistence, handoff, retry/replay, and recovery preserve these values unchanged; missing, changed, or contradictory lane/cost or plugin lifecycle-fence evidence fails closed rather than being inferred or refreshed. - For scheduler-derived plugin work, the captured `pluginActivationEpoch` is also a tagged input to the durable schedule-candidate/firing-claim identity and therefore transitively to the derived event-scope `scriptEventId`; it remains excluded from handler Trigger Identity and Command-Handoff Identity, while `lifecycleRevision` remains fence-only. Ordinary producer ingress must not fabricate either scheduler-owned field. - `automation:queue:{tenantInstanceTag}:` keys in Redis buffer indexes or pointers for admitted handler work after its durable `PENDING_EVALUATION` work item is persisted. Each entry includes enough identity to locate the durable work item and must not be treated as an authoritative log of commands. 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 cfaecae93d..1d66f84f1d 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for automation and scheduler runt ## Current Status +Adjudicated retention identity gap: `npc_memory` is live but latent and remains unclassified for replacement. Its replacement admission is blocked pending owner classification, mapping, and proof; see the [Automation runtime/data owner contract](../../architecture/microservices/automation-scripting-service/runtime-and-data.md#runtime-data-model). + The bounded implementation slices recorded here are complete at their stated boundaries. This tracker is the permanent reader-facing implementation record for the live automation ingress, scheduling, execution, handoff, readiness, and runtime/operator projection contracts. Current residual: the legacy NPC formation REST controllers are removed and `/formations` fails closed at the service-local HTTP boundary. Formation behavior remains `partial`: internal gRPC methods retain only the global admin-role guard, not the target tenant-bound `tenantAdmin` check, and do not prove Entity-owned leader/member NPC tenant/namespace ownership. HTTP 404 proof is not internal authorization/ownership proof; exact internal binding and cross-tenant negative tests remain open. diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/entity/ScriptWorkItem.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/entity/ScriptWorkItem.java index 8b2b63c1a9..d39eb39d85 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/entity/ScriptWorkItem.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/entity/ScriptWorkItem.java @@ -20,6 +20,25 @@ public class ScriptWorkItem { private String bindingId = ""; private String pluginId; private String pluginVersionId; + + /** Captured plugin activation fence; zero means this is core-script work. */ + private long pluginActivationEpoch; + + /** Captured plugin lifecycle fence; zero means this is core-script work. */ + private long lifecycleRevision; + + /** Monotonic execution-attempt generation used to fence dead-letter replay. */ + private long failureGeneration; + + /** First time this item observed a transient authority-unavailable fence result. */ + private Instant authorityUnavailableSince; + + /** Number of transient authority-unavailable outcomes in the current execution attempt. */ + private int authorityUnavailableCount; + + /** Earliest instant at which the durable scanner may claim this item again. */ + private Instant nextEligibleAt; + private String targetScopeType = ""; private String targetScopeId = ""; private String eventType; diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptDeadLetterReplayRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptDeadLetterReplayRepository.java new file mode 100644 index 0000000000..e5ece2cf26 --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptDeadLetterReplayRepository.java @@ -0,0 +1,312 @@ +package net.firedevops.firemud.automationscripting.repository; + +import static net.firedevops.firemud.automationscripting.jooq.tables.ScriptDeadLetterReplayRequests.SCRIPT_DEAD_LETTER_REPLAY_REQUESTS; +import static net.firedevops.firemud.automationscripting.jooq.tables.ScriptDeadLetterReplayResults.SCRIPT_DEAD_LETTER_REPLAY_RESULTS; +import static org.jooq.impl.DSL.field; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import net.firedevops.firemud.automationscripting.jooq.tables.records.ScriptDeadLetterReplayRequestsRecord; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.springframework.stereotype.Repository; + +/** Durable request/result ledger for operator dead-letter replay. */ +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class ScriptDeadLetterReplayRepository { + private static final Field REQUEST_HOLD_UNTIL = + field("retention_hold_until", java.time.OffsetDateTime.class); + private static final Field RESULT_HOLD_UNTIL = + field("retention_hold_until", java.time.OffsetDateTime.class); + private final DSLContext dsl; + + public ScriptDeadLetterReplayRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** Applies or clears the durable owner hold for one replay request. */ + public boolean setRequestRetentionHold(String tenantId, long requestId, Instant holdUntil) { + return dsl.update(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS) + .set( + REQUEST_HOLD_UNTIL, + holdUntil == null ? null : holdUntil.atOffset(java.time.ZoneOffset.UTC)) + .where( + SCRIPT_DEAD_LETTER_REPLAY_REQUESTS + .ID + .eq(requestId) + .and(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.TENANT_ID.eq(tenantId))) + .execute() + == 1; + } + + /** Applies or clears the durable owner hold for one replay result. */ + public boolean setResultRetentionHold(String tenantId, long resultId, Instant holdUntil) { + return dsl.update(SCRIPT_DEAD_LETTER_REPLAY_RESULTS) + .set( + RESULT_HOLD_UNTIL, + holdUntil == null ? null : holdUntil.atOffset(java.time.ZoneOffset.UTC)) + .where( + SCRIPT_DEAD_LETTER_REPLAY_RESULTS + .ID + .eq(resultId) + .and(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.TENANT_ID.eq(tenantId))) + .execute() + == 1; + } + + public Optional findRequest(String tenantId, String requestId) { + return dsl.selectFrom(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS) + .where( + SCRIPT_DEAD_LETTER_REPLAY_REQUESTS + .TENANT_ID + .eq(tenantId) + .and(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.CONTROL_PLANE_REQUEST_ID.eq(requestId))) + .fetchOptional(this::toRequest); + } + + public ReplayRequest insertOrGet( + String tenantId, + String requestId, + String fingerprint, + String actorPrincipal, + String reason, + Instant now) { + ScriptDeadLetterReplayRequestsRecord row = dsl.newRecord(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS); + row.setTenantId(tenantId); + row.setControlPlaneRequestId(requestId); + row.setRequestFingerprint(fingerprint); + row.setActorPrincipal(actorPrincipal); + row.setReason(reason); + row.setStatus("RUNNING"); + row.setReplayedCount(0L); + row.setRejectedCount(0L); + row.setCreatedAt(now.atOffset(java.time.ZoneOffset.UTC)); + row.setUpdatedAt(now.atOffset(java.time.ZoneOffset.UTC)); + row.setRowVersion(0); + return dsl.insertInto(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS) + .set(row) + .onConflict( + SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.TENANT_ID, + SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.CONTROL_PLANE_REQUEST_ID) + .doUpdate() + .set( + SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.CONTROL_PLANE_REQUEST_ID, + SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.CONTROL_PLANE_REQUEST_ID) + .returningResult(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.fields()) + .fetchOne(this::toRequest); + } + + public void saveResult( + long requestId, + long requestedWorkItemId, + Long workItemId, + String outcome, + String rejectionReason, + String failureReason, + long scriptPinEpoch, + long pluginActivationEpoch, + long lifecycleRevision, + long failureGeneration, + Instant now) { + saveResult( + requestId, + requestedWorkItemId, + workItemId, + outcome, + rejectionReason, + failureReason, + scriptPinEpoch, + pluginActivationEpoch, + lifecycleRevision, + failureGeneration, + "", + "", + now); + } + + public void saveResult( + long requestId, + long requestedWorkItemId, + Long workItemId, + String outcome, + String rejectionReason, + String failureReason, + long scriptPinEpoch, + long pluginActivationEpoch, + long lifecycleRevision, + long failureGeneration, + String originalFailureStage, + String originalFailureReason, + Instant now) { + String tenantId = + dsl.select(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.TENANT_ID) + .from(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS) + .where(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.ID.eq(requestId)) + .fetchOptional(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.TENANT_ID) + .orElseThrow( + () -> new IllegalStateException("Replay result request owner is unavailable")); + dsl.insertInto(SCRIPT_DEAD_LETTER_REPLAY_RESULTS) + .set(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.TENANT_ID, tenantId) + .set(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.REPLAY_REQUEST_ID, requestId) + .set(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.REQUESTED_WORK_ITEM_ID, requestedWorkItemId) + .set(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.WORK_ITEM_ID, workItemId) + .set(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.OUTCOME, outcome) + .set(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.REJECTION_REASON, rejectionReason) + .set( + SCRIPT_DEAD_LETTER_REPLAY_RESULTS.ORIGINAL_FAILURE_STAGE, + originalFailureStage == null ? "" : originalFailureStage) + .set( + SCRIPT_DEAD_LETTER_REPLAY_RESULTS.ORIGINAL_FAILURE_REASON, + originalFailureReason == null ? "" : originalFailureReason) + .set(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.FAILURE_REASON, failureReason) + .set(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.SCRIPT_PIN_EPOCH, scriptPinEpoch) + .set(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.PLUGIN_ACTIVATION_EPOCH, pluginActivationEpoch) + .set(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.LIFECYCLE_REVISION, lifecycleRevision) + .set(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.FAILURE_GENERATION, failureGeneration) + .set(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.CREATED_AT, now.atOffset(java.time.ZoneOffset.UTC)) + .onConflict( + SCRIPT_DEAD_LETTER_REPLAY_RESULTS.REPLAY_REQUEST_ID, + SCRIPT_DEAD_LETTER_REPLAY_RESULTS.REQUESTED_WORK_ITEM_ID) + // A competing replay may observe a stale work-item state and produce a rejection after the + // winner has recorded the successful retry. Result rows are immutable evidence; never let + // that later observer overwrite the first durable outcome. + .doNothing() + .execute(); + } + + public List findResults(long requestId) { + return dsl.selectFrom(SCRIPT_DEAD_LETTER_REPLAY_RESULTS) + .where(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.REPLAY_REQUEST_ID.eq(requestId)) + .orderBy(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.ID.asc()) + .fetch(this::toItem); + } + + public boolean complete(long requestId, long replayedCount, long rejectedCount, Instant now) { + return dsl.update(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS) + .set(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.STATUS, "COMPLETED") + .set(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.REPLAYED_COUNT, replayedCount) + .set(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.REJECTED_COUNT, rejectedCount) + .set( + SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.UPDATED_AT, + now.atOffset(java.time.ZoneOffset.UTC)) + // A replay request is completed once. A competing worker must not overwrite the + // aggregate counts established by the first worker after immutable item results exist. + .where( + SCRIPT_DEAD_LETTER_REPLAY_REQUESTS + .ID + .eq(requestId) + .and(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.STATUS.eq("RUNNING"))) + .execute() + == 1; + } + + private ReplayRequest toRequest(org.jooq.Record record) { + return new ReplayRequest( + record.get(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.ID), + record.get(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.REQUEST_FINGERPRINT), + record.get(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.STATUS), + record.get(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.REPLAYED_COUNT), + record.get(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.REJECTED_COUNT)); + } + + private ReplayItem toItem(org.jooq.Record record) { + return new ReplayItem( + record.get(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.REQUESTED_WORK_ITEM_ID), + record.get(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.WORK_ITEM_ID), + record.get(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.OUTCOME), + record.get(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.REJECTION_REASON), + record.get(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.FAILURE_REASON), + record.get(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.SCRIPT_PIN_EPOCH), + record.get(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.PLUGIN_ACTIVATION_EPOCH), + record.get(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.LIFECYCLE_REVISION), + record.get(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.FAILURE_GENERATION), + record.get(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.ORIGINAL_FAILURE_STAGE), + record.get(SCRIPT_DEAD_LETTER_REPLAY_RESULTS.ORIGINAL_FAILURE_REASON)); + } + + public record ReplayRequest( + long id, String requestFingerprint, String status, long replayedCount, long rejectedCount) {} + + public record ReplayItem( + long requestedWorkItemId, + Long workItemId, + String outcome, + String rejectionReason, + String failureReason, + long scriptPinEpoch, + long pluginActivationEpoch, + long lifecycleRevision, + long failureGeneration, + String originalFailureStage, + String originalFailureReason) { + /** + * Compatibility constructor for callers that use the work-item ID as both result IDs. + * + * @param workItemId requested and persisted work-item identifier + * @param outcome replay outcome + * @param rejectionReason bounded rejection reason + * @param scriptPinEpoch script pin evidence + * @param pluginActivationEpoch plugin activation evidence + * @param lifecycleRevision plugin lifecycle evidence + * @param failureGeneration work-item failure generation + */ + public ReplayItem( + long workItemId, + String outcome, + String rejectionReason, + long scriptPinEpoch, + long pluginActivationEpoch, + long lifecycleRevision, + long failureGeneration) { + this( + workItemId, + workItemId, + outcome, + rejectionReason, + "", + scriptPinEpoch, + pluginActivationEpoch, + lifecycleRevision, + failureGeneration, + "", + ""); + } + + public ReplayItem( + long requestedWorkItemId, + Long workItemId, + String outcome, + String rejectionReason, + String failureReason, + long scriptPinEpoch, + long pluginActivationEpoch, + long lifecycleRevision, + long failureGeneration) { + this( + requestedWorkItemId, + workItemId, + outcome, + rejectionReason, + failureReason, + scriptPinEpoch, + pluginActivationEpoch, + lifecycleRevision, + failureGeneration, + "", + ""); + } + + public String originalFailureStage() { + return originalFailureStage == null ? "" : originalFailureStage; + } + + public String originalFailureReason() { + return originalFailureReason == null ? "" : originalFailureReason; + } + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepository.java index 227f24806f..bc5250b226 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepository.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepository.java @@ -1,15 +1,22 @@ package net.firedevops.firemud.automationscripting.repository; import static net.firedevops.firemud.automationscripting.jooq.tables.ScriptHandoffEvents.SCRIPT_HANDOFF_EVENTS; +import static net.firedevops.firemud.automationscripting.jooq.tables.ScriptWorkItems.SCRIPT_WORK_ITEMS; import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.blankToEmpty; import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.blankToNull; import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.limitOrDefault; import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.offsetOrZero; import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toOffsetDateTime; +import static org.jooq.impl.DSL.field; +import static org.jooq.impl.DSL.notExists; +import static org.jooq.impl.DSL.row; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; import java.util.List; import java.util.Objects; import java.util.Optional; @@ -17,6 +24,7 @@ import net.firedevops.firemud.automationscripting.jooq.tables.records.ScriptHandoffEventsRecord; import org.jooq.Condition; import org.jooq.DSLContext; +import org.jooq.Field; import org.jooq.Record; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; @@ -26,12 +34,79 @@ value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class ScriptHandoffEventRepository { + private static final int RETENTION_DELETE_BATCH_SIZE = 500; + private static final Field RETENTION_HOLD_UNTIL = + field("retention_hold_until", OffsetDateTime.class); private final DSLContext dsl; public ScriptHandoffEventRepository(DSLContext dsl) { this.dsl = dsl; } + /** + * Disposes one ordered batch of terminal handoff evidence before its parent work item is swept. + * Later scheduled cleanup runs continue from the remaining eligible rows. + */ + public long deleteExpiredRetentionEvidence(Instant safeWatermark, Instant now) { + LocalDateTime cutoff = toLocalDateTime(safeWatermark); + OffsetDateTime current = toOffsetDateTime(now); + var candidates = SCRIPT_HANDOFF_EVENTS.as("retention_candidates"); + return dsl.deleteFrom(SCRIPT_HANDOFF_EVENTS) + .where( + row(SCRIPT_HANDOFF_EVENTS.ID, SCRIPT_HANDOFF_EVENTS.TENANT_ID) + .in( + dsl.select(candidates.ID, candidates.TENANT_ID) + .from(candidates) + .where( + candidates + .TENANT_ID + .isNotNull() + .and(candidates.OBSERVED_AT.lt(cutoff)) + .and( + RETENTION_HOLD_UNTIL + .isNull() + .or(RETENTION_HOLD_UNTIL.le(current))) + .and( + notExists( + org.jooq + .impl + .DSL + .selectOne() + .from(SCRIPT_WORK_ITEMS) + .where( + SCRIPT_WORK_ITEMS + .TENANT_ID + .eq(candidates.TENANT_ID) + .and( + SCRIPT_WORK_ITEMS.ID.eq( + candidates.WORK_ITEM_ID)) + .and( + SCRIPT_WORK_ITEMS + .STATUS + .notIn( + AutomationScriptingJooqRepositorySupport + .TERMINAL_WORK_ITEM_STATUSES) + .or( + SCRIPT_WORK_ITEMS.STATUS.eq( + "DEAD_LETTERED"))))))) + .orderBy(candidates.EVENT_ID.asc()) + .limit(RETENTION_DELETE_BATCH_SIZE))) + .execute(); + } + + /** Applies or clears the durable owner hold for one tenant-qualified handoff row. */ + public boolean setRetentionHold(String tenantId, long handoffId, Instant holdUntil) { + return dsl.update(SCRIPT_HANDOFF_EVENTS) + .set(RETENTION_HOLD_UNTIL, holdUntil == null ? null : toOffsetDateTime(holdUntil)) + .where( + SCRIPT_HANDOFF_EVENTS + .ID + .eq(handoffId) + .and(SCRIPT_HANDOFF_EVENTS.TENANT_ID.eq(tenantId))) + .execute() + == 1; + } + public List findEvents( String tenantId, String gameInstanceId, @@ -138,6 +213,22 @@ public List findEvents( .fetch(this::toEntity); } + /** Returns the single durable logical child projection for a work-item command. */ + public Optional findByTenantIdAndWorkItemIdAndCommandOrdinal( + String tenantId, Long workItemId, int commandOrdinal) { + if (tenantId == null || tenantId.isBlank() || workItemId == null) { + return Optional.empty(); + } + return dsl.selectFrom(SCRIPT_HANDOFF_EVENTS) + .where( + SCRIPT_HANDOFF_EVENTS + .TENANT_ID + .eq(tenantId) + .and(SCRIPT_HANDOFF_EVENTS.WORK_ITEM_ID.eq(workItemId)) + .and(SCRIPT_HANDOFF_EVENTS.COMMAND_ORDINAL.eq(commandOrdinal))) + .fetchOptional(this::toEntity); + } + public ScriptHandoffEvent save(ScriptHandoffEvent entity) { requireCoherentPinTuple(entity); if (entity.getId() == null) { @@ -254,6 +345,8 @@ private static boolean immutableIdentityMatches( && Objects.equals( blankToEmpty(existing.getPluginVersionId()), blankToEmpty(incoming.getPluginVersionId())) + && existing.getPluginActivationEpoch() == incoming.getPluginActivationEpoch() + && existing.getLifecycleRevision() == incoming.getLifecycleRevision() && Objects.equals(existing.getWorkItemId(), incoming.getWorkItemId()) && existing.getCommandOrdinal() == incoming.getCommandOrdinal() && Objects.equals(existing.getAutomationDispatchId(), incoming.getAutomationDispatchId()) @@ -293,6 +386,8 @@ private static Condition immutableIdentityCondition(ScriptHandoffEvent entity) { .and( SCRIPT_HANDOFF_EVENTS.PLUGIN_VERSION_ID.isNotDistinctFrom( blankToEmpty(entity.getPluginVersionId()))) + .and(SCRIPT_HANDOFF_EVENTS.PLUGIN_ACTIVATION_EPOCH.eq(entity.getPluginActivationEpoch())) + .and(SCRIPT_HANDOFF_EVENTS.LIFECYCLE_REVISION.eq(entity.getLifecycleRevision())) .and(SCRIPT_HANDOFF_EVENTS.WORK_ITEM_ID.eq(entity.getWorkItemId())) .and(SCRIPT_HANDOFF_EVENTS.COMMAND_ORDINAL.eq(entity.getCommandOrdinal())) .and( @@ -334,6 +429,9 @@ private void populate(ScriptHandoffEventsRecord record, ScriptHandoffEvent entit record.setBindingId(entity.getBindingId()); record.setPluginId(blankToEmpty(entity.getPluginId())); record.setPluginVersionId(blankToEmpty(entity.getPluginVersionId())); + record.setScriptPinEpoch(entity.getScriptPinEpoch()); + record.setPluginActivationEpoch(entity.getPluginActivationEpoch()); + record.setLifecycleRevision(entity.getLifecycleRevision()); record.setWorkItemId(entity.getWorkItemId()); record.setCommandOrdinal(entity.getCommandOrdinal()); record.setAutomationDispatchId(entity.getAutomationDispatchId()); @@ -386,6 +484,10 @@ private ScriptHandoffEvent toEntity(Record record) { entity.setBindingId(record.get(SCRIPT_HANDOFF_EVENTS.BINDING_ID)); entity.setPluginId(blankToEmpty(record.get(SCRIPT_HANDOFF_EVENTS.PLUGIN_ID))); entity.setPluginVersionId(blankToEmpty(record.get(SCRIPT_HANDOFF_EVENTS.PLUGIN_VERSION_ID))); + Long pluginActivationEpoch = record.get(SCRIPT_HANDOFF_EVENTS.PLUGIN_ACTIVATION_EPOCH); + entity.setPluginActivationEpoch(pluginActivationEpoch == null ? 0L : pluginActivationEpoch); + Long lifecycleRevision = record.get(SCRIPT_HANDOFF_EVENTS.LIFECYCLE_REVISION); + entity.setLifecycleRevision(lifecycleRevision == null ? 0L : lifecycleRevision); entity.setWorkItemId(record.get(SCRIPT_HANDOFF_EVENTS.WORK_ITEM_ID)); Integer commandOrdinal = record.get(SCRIPT_HANDOFF_EVENTS.COMMAND_ORDINAL); entity.setCommandOrdinal(commandOrdinal == null ? 0 : commandOrdinal); diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepository.java index 5cf81014ef..b4112800d7 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepository.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepository.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.automationscripting.repository; +import static net.firedevops.firemud.automationscripting.jooq.tables.ScriptDeadLetterReplayResults.SCRIPT_DEAD_LETTER_REPLAY_RESULTS; import static net.firedevops.firemud.automationscripting.jooq.tables.ScriptEventAudit.SCRIPT_EVENT_AUDIT; import static net.firedevops.firemud.automationscripting.jooq.tables.ScriptHandoffEvents.SCRIPT_HANDOFF_EVENTS; import static net.firedevops.firemud.automationscripting.jooq.tables.ScriptWorkItems.SCRIPT_WORK_ITEMS; @@ -10,9 +11,13 @@ import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; import static org.jooq.impl.DSL.field; +import static org.jooq.impl.DSL.notExists; +import static org.jooq.impl.DSL.selectOne; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -36,10 +41,17 @@ justification = "Injected DSLContext is an internal Spring collaborator.") public class ScriptWorkItemRepository { private static final int MAX_TRIGGER_IDENTITY_INSERT_ATTEMPTS = 2; + private static final int MAX_CANCELLATION_ROWS = 100; private static final String PIN_OWNER_EVIDENCE_CONFLICT_MESSAGE = "script_pin_control_plane_request_id conflicts with existing identity"; private static final Field INSERTED_ROW = field("xmax = 0", Boolean.class).as("inserted"); + private static final Field CURRENT_TIMESTAMP = + field("CURRENT_TIMESTAMP", LocalDateTime.class); + private static final Field CURRENT_OFFSET_TIMESTAMP = + field("CURRENT_TIMESTAMP", OffsetDateTime.class); + private static final Field HANDOFF_RETENTION_HOLD_UNTIL = + field("retention_hold_until", OffsetDateTime.class); @SuppressFBWarnings( value = "EI_EXPOSE_REP", @@ -173,6 +185,37 @@ public boolean existsByTenantIdAndScriptIdAndStatusIn( SCRIPT_WORK_ITEMS.ID.asc()); } + /** + * Selects one bounded cancellation page while holding row locks through the caller's transaction. + * The optional scope selectors are exact filters, never wildcards. + */ + public List + findByTenantIdAndScriptPatchVersionAndStatusInForUpdateOrderByCreatedAtAscIdAsc( + String tenantId, + String scriptPatchVersion, + String gameInstanceId, + String regionId, + Collection statuses) { + Condition condition = + SCRIPT_WORK_ITEMS + .TENANT_ID + .eq(tenantId) + .and(SCRIPT_WORK_ITEMS.SCRIPT_PATCH_VERSION.eq(scriptPatchVersion)) + .and(SCRIPT_WORK_ITEMS.STATUS.in(statuses)); + if (gameInstanceId != null && !gameInstanceId.isBlank()) { + condition = condition.and(SCRIPT_WORK_ITEMS.GAME_INSTANCE_ID.eq(gameInstanceId)); + } + if (regionId != null && !regionId.isBlank()) { + condition = condition.and(SCRIPT_WORK_ITEMS.REGION_ID.eq(regionId)); + } + return dsl.selectFrom(SCRIPT_WORK_ITEMS) + .where(condition) + .orderBy(SCRIPT_WORK_ITEMS.CREATED_AT.asc(), SCRIPT_WORK_ITEMS.ID.asc()) + .limit(MAX_CANCELLATION_ROWS) + .forUpdate() + .fetch(this::toEntity); + } + public List findByTenantIdAndPluginIdAndPluginVersionIdAndStatusInOrderByCreatedAtAscIdAsc( String tenantId, String pluginId, String pluginVersionId, Collection statuses) { @@ -187,6 +230,36 @@ public boolean existsByTenantIdAndScriptIdAndStatusIn( SCRIPT_WORK_ITEMS.ID.asc()); } + /** Selects one bounded plugin-version cancellation page under row locks. */ + public List + findByTenantIdAndPluginIdAndPluginVersionIdAndStatusInForUpdateOrderByCreatedAtAscIdAsc( + String tenantId, + String pluginId, + String pluginVersionId, + String gameInstanceId, + String regionId, + Collection statuses) { + Condition condition = + SCRIPT_WORK_ITEMS + .TENANT_ID + .eq(tenantId) + .and(SCRIPT_WORK_ITEMS.PLUGIN_ID.eq(blankToEmpty(pluginId))) + .and(SCRIPT_WORK_ITEMS.PLUGIN_VERSION_ID.eq(blankToEmpty(pluginVersionId))) + .and(SCRIPT_WORK_ITEMS.STATUS.in(statuses)); + if (gameInstanceId != null && !gameInstanceId.isBlank()) { + condition = condition.and(SCRIPT_WORK_ITEMS.GAME_INSTANCE_ID.eq(gameInstanceId)); + } + if (regionId != null && !regionId.isBlank()) { + condition = condition.and(SCRIPT_WORK_ITEMS.REGION_ID.eq(regionId)); + } + return dsl.selectFrom(SCRIPT_WORK_ITEMS) + .where(condition) + .orderBy(SCRIPT_WORK_ITEMS.CREATED_AT.asc(), SCRIPT_WORK_ITEMS.ID.asc()) + .limit(MAX_CANCELLATION_ROWS) + .forUpdate() + .fetch(this::toEntity); + } + public List findByTenantIdAndScriptPatchVersion( String tenantId, String scriptPatchVersion) { return fetchMany( @@ -270,6 +343,26 @@ public List findByStatusOrderByCreatedAtAscIdAsc( SCRIPT_WORK_ITEMS.ID.asc()); } + /** + * Claims a bounded page of pending work under PostgreSQL row locks. Retry backoff is evaluated by + * the database clock so a scanner cannot claim an authority-fenced item before its next eligible + * instant. + */ + public List findByStatusForUpdateOrderByCreatedAtAscIdAsc( + String status, Pageable pageable) { + Condition condition = SCRIPT_WORK_ITEMS.STATUS.eq(status); + if ("PENDING_EVALUATION".equals(status)) { + condition = condition.and(retryEligibilityCondition()); + } + return dsl.selectFrom(SCRIPT_WORK_ITEMS) + .where(condition) + .orderBy(SCRIPT_WORK_ITEMS.CREATED_AT.asc(), SCRIPT_WORK_ITEMS.ID.asc()) + .limit(limitOrDefault(pageable, 100)) + .forUpdate() + .skipLocked() + .fetch(this::toEntity); + } + public List findByIdInAndStatusOrderByCreatedAtAscIdAsc( Collection ids, String status, Pageable pageable) { if (ids == null || ids.isEmpty()) { @@ -282,6 +375,25 @@ public List findByIdInAndStatusOrderByCreatedAtAscIdAsc( SCRIPT_WORK_ITEMS.ID.asc()); } + /** Claims explicitly selected pending rows under the same retry/backoff fence as the scanner. */ + public List findByIdInAndStatusForUpdateOrderByCreatedAtAscIdAsc( + Collection ids, String status, Pageable pageable) { + if (ids == null || ids.isEmpty()) { + return List.of(); + } + Condition condition = SCRIPT_WORK_ITEMS.ID.in(ids).and(SCRIPT_WORK_ITEMS.STATUS.eq(status)); + if ("PENDING_EVALUATION".equals(status)) { + condition = condition.and(retryEligibilityCondition()); + } + return dsl.selectFrom(SCRIPT_WORK_ITEMS) + .where(condition) + .orderBy(SCRIPT_WORK_ITEMS.CREATED_AT.asc(), SCRIPT_WORK_ITEMS.ID.asc()) + .limit(limitOrDefault(pageable, 100)) + .forUpdate() + .skipLocked() + .fetch(this::toEntity); + } + public List findByStatusInOrderByCreatedAtAscIdAsc( Collection statuses, Pageable pageable) { return fetchManyPaged( @@ -331,6 +443,54 @@ public long countByStatus(String status) { return dsl.fetchCount(SCRIPT_WORK_ITEMS, SCRIPT_WORK_ITEMS.STATUS.eq(status)); } + /** + * Counts terminal rows older than the supplied evidence watermark that remain blocked by child + * evidence or, for dead letters, by the missing recovery-aware deletion proof. This is + * observability only and never authorizes deletion. + */ + public long countTerminalRowsBlockedByEvidence(String status, Instant safeWatermark) { + Condition agedRows = + SCRIPT_WORK_ITEMS + .STATUS + .eq(status) + .and(SCRIPT_WORK_ITEMS.UPDATED_AT.lt(toLocalDateTime(safeWatermark))); + // DEAD_LETTERED cleanup is fail-closed even when no child evidence remains: the current + // schema has no recovery-aware parent hold/generation proof, so every aged row is blocked. + return "DEAD_LETTERED".equals(status) + ? dsl.fetchCount(SCRIPT_WORK_ITEMS, agedRows) + : dsl.fetchCount(SCRIPT_WORK_ITEMS, agedRows.and(noBlockingRetentionEvidence().not())); + } + + /** + * Parent-cleanup proof for the current schema. Replay results always remain attached until a + * receipt-retention horizon exists; handoff rows may be removed only when their owner hold is + * absent or no longer active. Audit rows are detached separately and therefore do not block the + * parent here. + */ + private static Condition noBlockingRetentionEvidence() { + return notExists( + selectOne() + .from(SCRIPT_DEAD_LETTER_REPLAY_RESULTS) + .where( + SCRIPT_DEAD_LETTER_REPLAY_RESULTS + .TENANT_ID + .eq(SCRIPT_WORK_ITEMS.TENANT_ID) + .and( + SCRIPT_DEAD_LETTER_REPLAY_RESULTS.WORK_ITEM_ID.eq( + SCRIPT_WORK_ITEMS.ID)))) + .and( + notExists( + selectOne() + .from(SCRIPT_HANDOFF_EVENTS) + .where( + SCRIPT_HANDOFF_EVENTS + .TENANT_ID + .eq(SCRIPT_WORK_ITEMS.TENANT_ID) + .and(SCRIPT_HANDOFF_EVENTS.WORK_ITEM_ID.eq(SCRIPT_WORK_ITEMS.ID)) + .and(HANDOFF_RETENTION_HOLD_UNTIL.isNotNull()) + .and(HANDOFF_RETENTION_HOLD_UNTIL.gt(CURRENT_OFFSET_TIMESTAMP))))); + } + /** * Deletes eligible rows while retaining the eligibility decision through child and parent * deletion. The transaction keeps the row locks held until all child and parent rows are @@ -339,8 +499,8 @@ public long countByStatus(String status) { @Transactional public long deleteByStatusAndUpdatedAtBefore(String status, Instant updatedAt) { if ("DEAD_LETTERED".equals(status)) { - // The live schema has no recovery aggregate, generation/claim state, expected-child ledger, - // or evidence-retention horizons. Deleting a dead-letter parent cannot prove that its + // The live schema has no recovery aggregate, expected-child ledger, or evidence-retention + // horizon. Deleting a dead-letter parent cannot prove that its // recovery and supporting evidence are terminal and retention-eligible. return 0L; } @@ -388,6 +548,7 @@ public List findAllById(Collection ids) { } public ScriptWorkItem save(ScriptWorkItem entity) { + requireCoherentPluginFence(entity); if (entity.getId() == null) { return insertIfAbsentByTriggerIdentity(entity).workItem(); } @@ -407,6 +568,16 @@ public ScriptWorkItem save(ScriptWorkItem entity) { .set(SCRIPT_WORK_ITEMS.BINDING_ID, blankToEmpty(entity.getBindingId())) .set(SCRIPT_WORK_ITEMS.PLUGIN_ID, blankToEmpty(entity.getPluginId())) .set(SCRIPT_WORK_ITEMS.PLUGIN_VERSION_ID, blankToEmpty(entity.getPluginVersionId())) + .set(SCRIPT_WORK_ITEMS.PLUGIN_ACTIVATION_EPOCH, entity.getPluginActivationEpoch()) + .set(SCRIPT_WORK_ITEMS.LIFECYCLE_REVISION, entity.getLifecycleRevision()) + .set(SCRIPT_WORK_ITEMS.FAILURE_GENERATION, entity.getFailureGeneration()) + .set( + SCRIPT_WORK_ITEMS.AUTHORITY_UNAVAILABLE_SINCE, + toLocalDateTime(entity.getAuthorityUnavailableSince())) + .set( + SCRIPT_WORK_ITEMS.AUTHORITY_UNAVAILABLE_COUNT, + entity.getAuthorityUnavailableCount()) + .set(SCRIPT_WORK_ITEMS.NEXT_ELIGIBLE_AT, toLocalDateTime(entity.getNextEligibleAt())) .set(SCRIPT_WORK_ITEMS.TARGET_SCOPE_TYPE, entity.getTargetScopeType()) .set(SCRIPT_WORK_ITEMS.TARGET_SCOPE_ID, entity.getTargetScopeId()) .set(SCRIPT_WORK_ITEMS.EVENT_TYPE, entity.getEventType()) @@ -462,6 +633,7 @@ public IdempotentInsertResult insertIfAbsentByTriggerIdentity(ScriptWorkItem ent if (entity.getId() != null) { throw new IllegalArgumentException("A new script work item is required"); } + requireCoherentPluginFence(entity); String normalizedRequestId = normalizedScriptPinControlPlaneRequestId(entity); for (int attempt = 0; attempt < MAX_TRIGGER_IDENTITY_INSERT_ATTEMPTS; attempt++) { Optional insertResult = insertTriggerIdentity(entity); @@ -470,6 +642,7 @@ public IdempotentInsertResult insertIfAbsentByTriggerIdentity(ScriptWorkItem ent if (!result.inserted()) { requireMatchingPinOwnerEvidence( normalizedRequestId, result.workItem().getScriptPinControlPlaneRequestId()); + requireMatchingPluginFence(entity, result.workItem()); } return new IdempotentInsertResult(result.workItem(), result.inserted()); } @@ -497,6 +670,7 @@ public IdempotentInsertResult insertIfAbsentByTriggerIdentity(ScriptWorkItem ent if (existing.isPresent()) { requireMatchingPinOwnerEvidence( normalizedRequestId, existing.orElseThrow().getScriptPinControlPlaneRequestId()); + requireMatchingPluginFence(entity, existing.orElseThrow()); return new IdempotentInsertResult(existing.orElseThrow(), false); } } @@ -661,17 +835,34 @@ public Optional findById(Long id) { .fetchOptional(this::toEntity); } - @Transactional - public void deleteAll(Collection entities) { - if (entities == null || entities.isEmpty()) { - return; - } - List ids = - entities.stream().map(ScriptWorkItem::getId).filter(java.util.Objects::nonNull).toList(); - if (ids.isEmpty()) { - return; - } - deleteByIds(ids); + /** + * Claims one dead-letter row for replay using the observed row version and failure generation. A + * competing request therefore gets an empty result instead of overwriting a newer recovery + * decision. + */ + public Optional claimDeadLetterForReplay( + Long id, + String tenantId, + int expectedRowVersion, + long expectedFailureGeneration, + Instant now) { + return dsl.update(SCRIPT_WORK_ITEMS) + .set(SCRIPT_WORK_ITEMS.STATUS, "PENDING_EVALUATION") + .set(SCRIPT_WORK_ITEMS.AUTHORITY_UNAVAILABLE_SINCE, (LocalDateTime) null) + .set(SCRIPT_WORK_ITEMS.AUTHORITY_UNAVAILABLE_COUNT, 0) + .set(SCRIPT_WORK_ITEMS.NEXT_ELIGIBLE_AT, (LocalDateTime) null) + .set(SCRIPT_WORK_ITEMS.UPDATED_AT, toLocalDateTime(now)) + .set(SCRIPT_WORK_ITEMS.ROW_VERSION, expectedRowVersion + 1) + .where( + SCRIPT_WORK_ITEMS + .ID + .eq(id) + .and(SCRIPT_WORK_ITEMS.TENANT_ID.eq(tenantId)) + .and(SCRIPT_WORK_ITEMS.STATUS.eq("DEAD_LETTERED")) + .and(SCRIPT_WORK_ITEMS.ROW_VERSION.eq(expectedRowVersion)) + .and(SCRIPT_WORK_ITEMS.FAILURE_GENERATION.eq(expectedFailureGeneration))) + .returningResult(SCRIPT_WORK_ITEMS.fields()) + .fetchOptional(this::toEntity); } /** @@ -679,31 +870,58 @@ public void deleteAll(Collection entities) { * rows are disposed with the parent, while audit rows remain under their independent retention * policy and are detached from the deleted work-item through their nullable foreign key. */ - private long deleteByIds(Collection ids) { - return deleteByIds(ids, org.jooq.impl.DSL.noCondition()); - } - private long deleteByIds(Collection ids, Condition parentEligibility) { if (ids == null || ids.isEmpty()) { return 0L; } + // Lock the complete handoff bundle before deleting any child. The subsequent parent recheck + // handles a hold that committed after the initial candidate scan but before these locks. + dsl.select(SCRIPT_HANDOFF_EVENTS.ID) + .from(SCRIPT_HANDOFF_EVENTS) + .where(SCRIPT_HANDOFF_EVENTS.WORK_ITEM_ID.in(ids)) + .forUpdate() + .fetch(SCRIPT_HANDOFF_EVENTS.ID); + + // Re-evaluate every parent's complete receipt/hold eligibility after the child locks are + // held. A hold can commit after the initial parent candidate scan but before this lock; only + // this second decision may authorize detaching or deleting any child evidence. + List eligibleIds = + dsl.select(SCRIPT_WORK_ITEMS.ID) + .from(SCRIPT_WORK_ITEMS) + .where(SCRIPT_WORK_ITEMS.ID.in(ids).and(parentEligibility)) + .forUpdate() + .fetch(SCRIPT_WORK_ITEMS.ID); + if (eligibleIds.isEmpty()) { + return 0L; + } dsl.update(SCRIPT_EVENT_AUDIT) .set(SCRIPT_EVENT_AUDIT.WORK_ITEM_ID, (Long) null) - .where(SCRIPT_EVENT_AUDIT.WORK_ITEM_ID.in(ids)) + .where(SCRIPT_EVENT_AUDIT.WORK_ITEM_ID.in(eligibleIds)) .execute(); dsl.deleteFrom(SCRIPT_HANDOFF_EVENTS) - .where(SCRIPT_HANDOFF_EVENTS.WORK_ITEM_ID.in(ids)) + .where( + SCRIPT_HANDOFF_EVENTS + .WORK_ITEM_ID + .in(eligibleIds) + .and( + HANDOFF_RETENTION_HOLD_UNTIL + .isNull() + .or(HANDOFF_RETENTION_HOLD_UNTIL.le(CURRENT_OFFSET_TIMESTAMP)))) .execute(); + // Repeat the full parent eligibility predicate after the locked child cleanup. A concurrent + // replay receipt or owner hold must leave the parent in place rather than relying on the + // recheck above. return dsl.deleteFrom(SCRIPT_WORK_ITEMS) - .where(SCRIPT_WORK_ITEMS.ID.in(ids).and(parentEligibility)) + .where(SCRIPT_WORK_ITEMS.ID.in(eligibleIds).and(parentEligibility)) .execute(); } private static Condition cleanupEligibility(String status, Instant updatedAt) { Condition condition = SCRIPT_WORK_ITEMS.STATUS.eq(status); - return updatedAt == null - ? condition - : condition.and(SCRIPT_WORK_ITEMS.UPDATED_AT.lt(toLocalDateTime(updatedAt))); + if (updatedAt != null) { + condition = condition.and(SCRIPT_WORK_ITEMS.UPDATED_AT.lt(toLocalDateTime(updatedAt))); + } + return condition.and(noBlockingRetentionEvidence()); } private List fetchMany(Condition condition, org.jooq.SortField... orderBy) { @@ -723,7 +941,15 @@ private List fetchManyPaged( .fetch(this::toEntity); } + private static Condition retryEligibilityCondition() { + return SCRIPT_WORK_ITEMS + .NEXT_ELIGIBLE_AT + .isNull() + .or(SCRIPT_WORK_ITEMS.NEXT_ELIGIBLE_AT.le(CURRENT_TIMESTAMP)); + } + private void populate(ScriptWorkItemsRecord record, ScriptWorkItem entity) { + requireCoherentPluginFence(entity); record.setTenantId(entity.getTenantId()); record.setGameInstanceId(entity.getGameInstanceId()); record.setRegionId(entity.getRegionId()); @@ -737,6 +963,12 @@ private void populate(ScriptWorkItemsRecord record, ScriptWorkItem entity) { record.setBindingId(blankToEmpty(entity.getBindingId())); record.setPluginId(blankToEmpty(entity.getPluginId())); record.setPluginVersionId(blankToEmpty(entity.getPluginVersionId())); + record.setPluginActivationEpoch(entity.getPluginActivationEpoch()); + record.setLifecycleRevision(entity.getLifecycleRevision()); + record.setFailureGeneration(entity.getFailureGeneration()); + record.setAuthorityUnavailableSince(toLocalDateTime(entity.getAuthorityUnavailableSince())); + record.setAuthorityUnavailableCount(entity.getAuthorityUnavailableCount()); + record.setNextEligibleAt(toLocalDateTime(entity.getNextEligibleAt())); record.setTargetScopeType(entity.getTargetScopeType()); record.setTargetScopeId(entity.getTargetScopeId()); record.setEventType(entity.getEventType()); @@ -786,6 +1018,21 @@ private static String normalizedScriptPinControlPlaneRequestId(ScriptWorkItem en return requestId; } + private static void requireCoherentPluginFence(ScriptWorkItem entity) { + requireCoherentPluginFence(entity.getPluginActivationEpoch(), entity.getLifecycleRevision()); + } + + private static void requireCoherentPluginFence( + long pluginActivationEpoch, long lifecycleRevision) { + if (pluginActivationEpoch < 0L || lifecycleRevision < 0L) { + throw new IllegalArgumentException("plugin fence values must be non-negative"); + } + if ((pluginActivationEpoch == 0L) != (lifecycleRevision == 0L)) { + throw new IllegalArgumentException( + "plugin_activation_epoch and lifecycle_revision must both be zero or both be positive"); + } + } + private static void requireMatchingPinOwnerEvidence( String requestedRequestId, String existingRequestId) { if (!Objects.equals(requestedRequestId, blankToNull(existingRequestId))) { @@ -793,6 +1040,16 @@ private static void requireMatchingPinOwnerEvidence( } } + private static void requireMatchingPluginFence( + ScriptWorkItem requested, ScriptWorkItem existing) { + if (requested.getPluginActivationEpoch() != existing.getPluginActivationEpoch()) { + throw new IllegalStateException("plugin_activation_epoch conflicts with existing identity"); + } + if (requested.getLifecycleRevision() != existing.getLifecycleRevision()) { + throw new IllegalStateException("lifecycle_revision conflicts with existing identity"); + } + } + private ScriptWorkItem toEntity(Record record) { ScriptWorkItem entity = new ScriptWorkItem(); entity.setId(record.get(SCRIPT_WORK_ITEMS.ID)); @@ -809,6 +1066,18 @@ private ScriptWorkItem toEntity(Record record) { entity.setBindingId(blankToEmpty(record.get(SCRIPT_WORK_ITEMS.BINDING_ID))); entity.setPluginId(blankToEmpty(record.get(SCRIPT_WORK_ITEMS.PLUGIN_ID))); entity.setPluginVersionId(blankToEmpty(record.get(SCRIPT_WORK_ITEMS.PLUGIN_VERSION_ID))); + Long pluginActivationEpoch = record.get(SCRIPT_WORK_ITEMS.PLUGIN_ACTIVATION_EPOCH); + entity.setPluginActivationEpoch(pluginActivationEpoch == null ? 0L : pluginActivationEpoch); + Long lifecycleRevision = record.get(SCRIPT_WORK_ITEMS.LIFECYCLE_REVISION); + entity.setLifecycleRevision(lifecycleRevision == null ? 0L : lifecycleRevision); + Long failureGeneration = record.get(SCRIPT_WORK_ITEMS.FAILURE_GENERATION); + entity.setFailureGeneration(failureGeneration == null ? 0L : failureGeneration); + entity.setAuthorityUnavailableSince( + toInstant(record.get(SCRIPT_WORK_ITEMS.AUTHORITY_UNAVAILABLE_SINCE))); + Integer authorityUnavailableCount = record.get(SCRIPT_WORK_ITEMS.AUTHORITY_UNAVAILABLE_COUNT); + entity.setAuthorityUnavailableCount( + authorityUnavailableCount == null ? 0 : authorityUnavailableCount); + entity.setNextEligibleAt(toInstant(record.get(SCRIPT_WORK_ITEMS.NEXT_ELIGIBLE_AT))); entity.setTargetScopeType(record.get(SCRIPT_WORK_ITEMS.TARGET_SCOPE_TYPE)); entity.setTargetScopeId(record.get(SCRIPT_WORK_ITEMS.TARGET_SCOPE_ID)); entity.setEventType(record.get(SCRIPT_WORK_ITEMS.EVENT_TYPE)); diff --git a/services/automation-scripting-service/src/main/resources/db/migration/V4__execution_replay_and_retention.sql b/services/automation-scripting-service/src/main/resources/db/migration/V4__execution_replay_and_retention.sql new file mode 100644 index 0000000000..51c14b97d4 --- /dev/null +++ b/services/automation-scripting-service/src/main/resources/db/migration/V4__execution_replay_and_retention.sql @@ -0,0 +1,126 @@ +-- Durable execution/replay substrate for the Automation owner. V1 is the +-- direct schema baseline, V2 owns readiness, and V3 owns plugin lifecycle +-- fences; this migration adds only the execution failure, replay, retry, and +-- retention evidence that those schemas do not already provide. + +ALTER TABLE script_work_items + ADD COLUMN failure_generation BIGINT NOT NULL DEFAULT 0, + ADD COLUMN authority_unavailable_since TIMESTAMP, + ADD COLUMN authority_unavailable_count INTEGER NOT NULL DEFAULT 0, + ADD COLUMN next_eligible_at TIMESTAMP; + +-- New work starts before its first dead-letter transition. Existing dead letters +-- already represent one completed failure generation and retain that evidence. +UPDATE script_work_items + SET failure_generation = 1 + WHERE status = 'DEAD_LETTERED' + AND failure_generation = 0; + +CREATE INDEX idx_script_work_items_execution_fences + ON script_work_items (tenant_id, game_instance_id, script_patch_version, + script_pin_epoch, plugin_id, plugin_activation_epoch, + lifecycle_revision, status); + +CREATE INDEX idx_script_work_items_retry_eligibility + ON script_work_items (status, next_eligible_at, created_at, id); + +-- A replay request is immutable idempotency evidence. The tenant-qualified +-- keys keep owner scope explicit even where a surrogate row id is globally +-- unique in this database. +CREATE TABLE script_dead_letter_replay_requests ( + id BIGSERIAL PRIMARY KEY, + tenant_id VARCHAR(64) NOT NULL, + control_plane_request_id VARCHAR(128) NOT NULL, + request_fingerprint VARCHAR(64) NOT NULL, + actor_principal VARCHAR(256) NOT NULL DEFAULT '', + reason VARCHAR(256) NOT NULL DEFAULT '', + status VARCHAR(64) NOT NULL, + replayed_count BIGINT NOT NULL DEFAULT 0, + rejected_count BIGINT NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + row_version INT NOT NULL DEFAULT 0, + CONSTRAINT uq_script_dead_letter_replay_request UNIQUE ( + tenant_id, control_plane_request_id + ), + CONSTRAINT uq_script_dead_letter_replay_request_tenant_id UNIQUE (tenant_id, id), + CONSTRAINT ck_script_dead_letter_replay_request_fingerprint CHECK ( + request_fingerprint ~ '^[0-9a-f]{64}$' + ), + CONSTRAINT ck_script_dead_letter_replay_request_status CHECK ( + status IN ('RUNNING', 'COMPLETED') + ), + CONSTRAINT ck_script_dead_letter_replay_request_counts CHECK ( + replayed_count >= 0 AND rejected_count >= 0 + ) +); + +CREATE TABLE script_dead_letter_replay_results ( + id BIGSERIAL PRIMARY KEY, + tenant_id VARCHAR(64) NOT NULL, + replay_request_id BIGINT NOT NULL, + requested_work_item_id BIGINT NOT NULL, + -- A requested id may have no owned parent row. The nullable resolved id + -- preserves that deterministic rejection without weakening tenant scoping. + work_item_id BIGINT, + outcome VARCHAR(64) NOT NULL, + rejection_reason VARCHAR(256) NOT NULL DEFAULT '', + -- Snapshot the dead-letter failure before replay changes the mutable work item/audit. + -- These fields are distinct from failure_reason, which describes a failed recovery attempt. + original_failure_stage VARCHAR(64) NOT NULL DEFAULT '', + original_failure_reason VARCHAR(256) NOT NULL DEFAULT '', + failure_reason VARCHAR(256) NOT NULL DEFAULT '', + script_pin_epoch BIGINT NOT NULL DEFAULT 0, + plugin_activation_epoch BIGINT NOT NULL DEFAULT 0, + lifecycle_revision BIGINT NOT NULL DEFAULT 0, + failure_generation BIGINT NOT NULL DEFAULT 1, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CONSTRAINT uq_script_dead_letter_replay_result + UNIQUE (replay_request_id, requested_work_item_id), + CONSTRAINT fk_script_dead_letter_replay_result_request + FOREIGN KEY (tenant_id, replay_request_id) + REFERENCES script_dead_letter_replay_requests (tenant_id, id), + CONSTRAINT fk_script_dead_letter_replay_result_work_item + FOREIGN KEY (tenant_id, work_item_id) + REFERENCES script_work_items (tenant_id, id), + CONSTRAINT ck_script_dead_letter_replay_result_plugin_fence CHECK ( + (plugin_activation_epoch = 0 AND lifecycle_revision = 0) + OR (plugin_activation_epoch > 0 AND lifecycle_revision > 0) + ), + CONSTRAINT ck_script_dead_letter_replay_result_nonnegative_evidence CHECK ( + script_pin_epoch >= 0 AND failure_generation >= 0 + ) +); + +CREATE INDEX idx_script_dead_letter_replay_results_request + ON script_dead_letter_replay_results (replay_request_id, id); + +CREATE INDEX idx_script_dead_letter_replay_results_work_item + ON script_dead_letter_replay_results (tenant_id, work_item_id); + +-- Holds are owner-controlled safety fences. Cleanup must still prove the +-- relevant replay/child and lifecycle conditions; a hold is never a retention +-- horizon and this migration invents no TTL. +ALTER TABLE script_event_audit + ADD COLUMN retention_hold_until TIMESTAMPTZ NULL; + +ALTER TABLE script_handoff_events + ADD COLUMN retention_hold_until TIMESTAMPTZ NULL; + +ALTER TABLE script_dead_letter_replay_requests + ADD COLUMN retention_hold_until TIMESTAMPTZ NULL; + +ALTER TABLE script_dead_letter_replay_results + ADD COLUMN retention_hold_until TIMESTAMPTZ NULL; + +CREATE INDEX idx_script_event_audit_retention + ON script_event_audit (updated_at, retention_hold_until, tenant_id); + +CREATE INDEX idx_script_handoff_events_retention + ON script_handoff_events (observed_at, retention_hold_until, tenant_id); + +CREATE INDEX idx_script_dead_letter_replay_requests_retention + ON script_dead_letter_replay_requests (updated_at, retention_hold_until, tenant_id); + +CREATE INDEX idx_script_dead_letter_replay_results_retention + ON script_dead_letter_replay_results (created_at, retention_hold_until, tenant_id); diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java index 9f93170ce4..9d93b9b219 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java @@ -236,6 +236,52 @@ void concurrentUnpinnedWorkClaimsHaveOnePostgresWinnerAndOneLoser() throws Excep assertThat(dsl.fetchCount(SCRIPT_WORK_ITEMS)).isEqualTo(1); } + @Test + void handlerAuditInsertDiscriminatorPreservesTenantIdentityOnDuplicate() { + ScriptEventAudit first = handlerAudit("tenant-handler-audit"); + + ScriptEventAuditRepository.IdempotentInsertResult inserted = + eventAuditRepository.insertIfAbsentByHandlerIdentity(first); + + assertThat(inserted.inserted()).isTrue(); + assertThat(inserted.audit().getId()).isNotNull(); + assertThat(dsl.fetchCount(SCRIPT_EVENT_AUDIT)).isEqualTo(1); + + ScriptEventAudit duplicate = handlerAudit("tenant-handler-audit"); + duplicate.setSourceService("duplicate-service"); + duplicate.setFinalOutcome("DUPLICATE_ATTEMPT"); + duplicate.setFinalReason("duplicate-attempt"); + + ScriptEventAuditRepository.IdempotentInsertResult existing = + eventAuditRepository.insertIfAbsentByHandlerIdentity(duplicate); + + assertThat(existing.inserted()).isFalse(); + assertThat(existing.audit().getId()).isEqualTo(inserted.audit().getId()); + assertThat(existing.audit().getTenantId()).isEqualTo("tenant-handler-audit"); + assertThat(existing.audit().getScriptEventId()).isEqualTo("handler-event-1"); + assertThat(existing.audit().getSourceService()).isEqualTo("automation-scripting-service"); + assertThat(existing.audit().getFinalOutcome()).isEqualTo("HANDLER_ACCEPTED"); + assertThat(dsl.fetchCount(SCRIPT_EVENT_AUDIT)).isEqualTo(1); + assertThat( + dsl.fetchCount( + SCRIPT_EVENT_AUDIT, SCRIPT_EVENT_AUDIT.TENANT_ID.eq("tenant-handler-audit"))) + .isEqualTo(1); + + ScriptEventAudit conflictingOwnerEvidence = handlerAudit("tenant-handler-audit"); + conflictingOwnerEvidence.setScriptPinControlPlaneRequestId("pin-request-2"); + + assertThatThrownBy( + () -> eventAuditRepository.insertIfAbsentByHandlerIdentity(conflictingOwnerEvidence)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("script_pin_control_plane_request_id conflicts with existing identity"); + assertThat( + dsl.fetchValue( + SCRIPT_EVENT_AUDIT.SCRIPT_PIN_CONTROL_PLANE_REQUEST_ID, + SCRIPT_EVENT_AUDIT.ID.eq(inserted.audit().getId()))) + .isEqualTo("pin-request-1"); + assertThat(dsl.fetchCount(SCRIPT_EVENT_AUDIT)).isEqualTo(1); + } + @Test void scriptOnlyPluginIdentityDefaultsToEmptyAndLookupFindsTheCanonicalRow() { dsl.insertInto(SCRIPT_WORK_ITEMS) @@ -1017,6 +1063,29 @@ private ScriptEventAudit retainedEventAudit(Long workItemId) { return audit; } + private ScriptEventAudit handlerAudit(String tenantId) { + ScriptEventAudit audit = new ScriptEventAudit(); + audit.setTenantId(tenantId); + audit.setGameInstanceId("instance-handler-audit"); + audit.setRegionId("region-handler-audit"); + audit.setRegionEpoch(1L); + audit.setEntityId("entity-handler-audit"); + audit.setPlayableStateScope("INSTANCE"); + audit.setScriptId("script-handler-audit"); + audit.setEventType("onEnterRegion"); + audit.setEventSchemaVersion("v1"); + audit.setScriptPatchVersion("patch-handler-audit"); + audit.setScriptPinEpoch(2L); + audit.setScriptPinControlPlaneRequestId("pin-request-1"); + audit.setScriptEventId("handler-event-1"); + audit.setSourceService("automation-scripting-service"); + audit.setTriggerMode("EVENT"); + audit.setFinalStage("HANDLER"); + audit.setFinalOutcome("HANDLER_ACCEPTED"); + audit.setFinalReason("accepted"); + return audit; + } + private ScriptScheduleInstance scheduleInstance() { ScriptScheduleInstance schedule = new ScriptScheduleInstance(); schedule.setTenantId("tenant-schedule-binding"); diff --git a/services/automation-scripting-service/src/test/java/unit/db/migration/V4__execution_replay_and_retentionTest.java b/services/automation-scripting-service/src/test/java/unit/db/migration/V4__execution_replay_and_retentionTest.java new file mode 100644 index 0000000000..1f2b92021a --- /dev/null +++ b/services/automation-scripting-service/src/test/java/unit/db/migration/V4__execution_replay_and_retentionTest.java @@ -0,0 +1,81 @@ +package db.migration; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; + +class V4__execution_replay_and_retentionTest { + + @Test + void declaresTheTenantScopedExecutionReplayAndRetentionContract() throws IOException { + String migration; + try (var stream = + getClass() + .getClassLoader() + .getResourceAsStream("db/migration/V4__execution_replay_and_retention.sql")) { + assertThat(stream).isNotNull(); + migration = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + + String normalized = migration.replaceAll("\\s+", " ").trim(); + + assertThat(normalized) + .contains( + "ADD COLUMN failure_generation BIGINT NOT NULL DEFAULT 0", + "ADD COLUMN authority_unavailable_since TIMESTAMP", + "ADD COLUMN authority_unavailable_count INTEGER NOT NULL DEFAULT 0", + "ADD COLUMN next_eligible_at TIMESTAMP", + "CREATE TABLE script_dead_letter_replay_requests", + "CREATE TABLE script_dead_letter_replay_results", + "requested_work_item_id BIGINT NOT NULL", + "work_item_id BIGINT", + "original_failure_stage VARCHAR(64) NOT NULL DEFAULT ''", + "original_failure_reason VARCHAR(256) NOT NULL DEFAULT ''", + "failure_reason VARCHAR(256) NOT NULL DEFAULT ''", + "FOREIGN KEY (tenant_id, replay_request_id) REFERENCES script_dead_letter_replay_requests (tenant_id, id)", + "FOREIGN KEY (tenant_id, work_item_id) REFERENCES script_work_items (tenant_id, id)", + "UNIQUE (replay_request_id, requested_work_item_id)", + "CONSTRAINT ck_script_dead_letter_replay_request_fingerprint CHECK ( request_fingerprint ~ '^[0-9a-f]{64}$' )", + "CONSTRAINT ck_script_dead_letter_replay_request_status CHECK ( status IN ('RUNNING', 'COMPLETED') )", + "CONSTRAINT ck_script_dead_letter_replay_request_counts CHECK ( replayed_count >= 0 AND rejected_count >= 0 )", + "CONSTRAINT ck_script_dead_letter_replay_result_plugin_fence CHECK ( (plugin_activation_epoch = 0 AND lifecycle_revision = 0) OR (plugin_activation_epoch > 0 AND lifecycle_revision > 0) )", + "CONSTRAINT ck_script_dead_letter_replay_result_nonnegative_evidence CHECK ( script_pin_epoch >= 0 AND failure_generation >= 0 )", + "ADD COLUMN retention_hold_until TIMESTAMPTZ NULL", + "idx_script_work_items_execution_fences", + "idx_script_work_items_retry_eligibility", + "idx_script_dead_letter_replay_results_request", + "idx_script_dead_letter_replay_results_work_item", + "idx_script_event_audit_retention", + "idx_script_handoff_events_retention", + "idx_script_dead_letter_replay_requests_retention", + "idx_script_dead_letter_replay_results_retention") + .doesNotContain("IF NOT EXISTS", "DROP TABLE", "DROP COLUMN", "DELETE FROM"); + + assertThat(normalized) + .contains( + "UPDATE script_work_items SET failure_generation = 1 WHERE status = 'DEAD_LETTERED' AND failure_generation = 0"); + + assertThat(normalized) + .contains( + "CONSTRAINT uq_script_dead_letter_replay_request UNIQUE ( tenant_id, control_plane_request_id )", + "CONSTRAINT uq_script_dead_letter_replay_request_tenant_id UNIQUE (tenant_id, id)"); + + String resultTable = tableBlock(normalized, "script_dead_letter_replay_results"); + assertThat(resultTable) + .contains( + "requested_work_item_id BIGINT NOT NULL", + "work_item_id BIGINT", + "CONSTRAINT uq_script_dead_letter_replay_result UNIQUE (replay_request_id, requested_work_item_id)") + .doesNotContain(" work_item_id BIGINT NOT NULL"); + } + + private static String tableBlock(String normalized, String tableName) { + String marker = "CREATE TABLE " + tableName + " ("; + int start = normalized.indexOf(marker); + assertThat(start).isGreaterThanOrEqualTo(0); + int end = normalized.indexOf("CREATE TABLE ", start + marker.length()); + return normalized.substring(start, end < 0 ? normalized.length() : end); + } +} diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptDeadLetterReplayRepositoryTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptDeadLetterReplayRepositoryTest.java new file mode 100644 index 0000000000..8f78c93048 --- /dev/null +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptDeadLetterReplayRepositoryTest.java @@ -0,0 +1,116 @@ +package net.firedevops.firemud.automationscripting.repository; + +import static net.firedevops.firemud.automationscripting.jooq.tables.ScriptDeadLetterReplayRequests.SCRIPT_DEAD_LETTER_REPLAY_REQUESTS; +import static org.assertj.core.api.Assertions.assertThat; + +import java.time.Instant; +import java.util.Locale; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Result; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.tools.jdbc.MockConnection; +import org.jooq.tools.jdbc.MockDataProvider; +import org.jooq.tools.jdbc.MockResult; +import org.junit.jupiter.api.Test; + +class ScriptDeadLetterReplayRepositoryTest { + @Test + void saveResultPreservesFirstConcurrentOutcome() { + AtomicReference sqlRef = new AtomicReference<>(); + AtomicInteger callCount = new AtomicInteger(); + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + MockDataProvider provider = + context -> { + sqlRef.set(context.sql()); + if (callCount.getAndIncrement() == 0) { + Field[] ownerFields = {SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.TENANT_ID}; + Result ownerResult = resultDsl.newResult(ownerFields); + Record owner = resultDsl.newRecord(ownerFields); + owner.set(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.TENANT_ID, "tenant-1"); + ownerResult.add(owner); + return new MockResult[] {new MockResult(1, ownerResult)}; + } + return new MockResult[] {new MockResult(1)}; + }; + ScriptDeadLetterReplayRepository repository = + new ScriptDeadLetterReplayRepository( + DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + + repository.saveResult( + 1L, 42L, 42L, "retried_evaluation", "", "", 3L, 4L, 5L, 2L, Instant.EPOCH); + + assertThat(sqlRef.get().toLowerCase(Locale.ROOT)).contains("on conflict", "do nothing"); + } + + @Test + void saveResultBindsImmutableOriginalFailureEvidenceSeparatelyFromRecoveryFailure() { + AtomicReference sqlRef = new AtomicReference<>(); + AtomicReference bindingsRef = new AtomicReference<>(); + AtomicInteger callCount = new AtomicInteger(); + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + MockDataProvider provider = + context -> { + sqlRef.set(context.sql()); + bindingsRef.set(context.bindings()); + if (callCount.getAndIncrement() == 0) { + Field[] ownerFields = {SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.TENANT_ID}; + Result ownerResult = resultDsl.newResult(ownerFields); + Record owner = resultDsl.newRecord(ownerFields); + owner.set(SCRIPT_DEAD_LETTER_REPLAY_REQUESTS.TENANT_ID, "tenant-1"); + ownerResult.add(owner); + return new MockResult[] {new MockResult(1, ownerResult)}; + } + return new MockResult[] {new MockResult(1)}; + }; + ScriptDeadLetterReplayRepository repository = + new ScriptDeadLetterReplayRepository( + DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + + repository.saveResult( + 1L, + 42L, + 42L, + "retried_evaluation", + "", + "", + 3L, + 4L, + 5L, + 2L, + "TICK_HANDOFF", + "GAME_SESSION_UNAVAILABLE", + Instant.EPOCH); + + assertThat(sqlRef.get().toLowerCase(Locale.ROOT)) + .contains("original_failure_stage", "original_failure_reason"); + assertThat(bindingsRef.get()).contains("TICK_HANDOFF", "GAME_SESSION_UNAVAILABLE"); + } + + @Test + void completeUsesRunningCasSoAConcurrentCompletionCannotOverwriteCounts() { + AtomicInteger callCount = new AtomicInteger(); + AtomicReference sqlRef = new AtomicReference<>(); + AtomicReference bindingsRef = new AtomicReference<>(); + MockDataProvider provider = + context -> { + sqlRef.set(context.sql()); + bindingsRef.set(context.bindings()); + return new MockResult[] {new MockResult(callCount.getAndIncrement() == 0 ? 1 : 0)}; + }; + ScriptDeadLetterReplayRepository repository = + new ScriptDeadLetterReplayRepository( + DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + + assertThat(repository.complete(7L, 3L, 1L, Instant.EPOCH)).isTrue(); + assertThat(repository.complete(7L, 1L, 3L, Instant.EPOCH)).isFalse(); + String sql = sqlRef.get().toLowerCase(Locale.ROOT); + String whereClause = sql.substring(sql.indexOf(" where ")); + assertThat(whereClause.replaceAll("\\s+", " ")).contains("\"status\" = ?"); + assertThat(bindingsRef.get()).contains("RUNNING"); + } +} diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepositoryTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepositoryTest.java index 98403320ad..fe41eefa48 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepositoryTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepositoryTest.java @@ -5,6 +5,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.time.Instant; import java.time.LocalDateTime; import java.util.Locale; import java.util.concurrent.atomic.AtomicReference; @@ -448,6 +449,167 @@ void treatsEventIdAsImmutableOnExistingIdUpdate() { }); } + @Test + void retentionCleanupBindsUtcOffsetDateTimeForNullableHoldComparison() { + Instant safeWatermark = Instant.parse("2026-08-01T00:00:00Z"); + Instant now = Instant.parse("2026-08-02T00:00:00Z"); + AtomicReference sqlRef = new AtomicReference<>(); + AtomicReference bindingsRef = new AtomicReference<>(); + MockDataProvider provider = + context -> { + sqlRef.set(context.sql()); + bindingsRef.set(context.bindings()); + return new MockResult[] {new MockResult(0)}; + }; + ScriptHandoffEventRepository repository = + new ScriptHandoffEventRepository( + DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + + assertThat(repository.deleteExpiredRetentionEvidence(safeWatermark, now)).isZero(); + + assertThat(bindingsRef.get()[0]).isInstanceOf(java.sql.Timestamp.class); + assertThat(bindingsRef.get()).contains("2026-08-02 00:00:00+00:00"); + assertThat(bindingsRef.get()).contains("DEAD_LETTERED"); + assertThat(bindingsRef.get()) + .anySatisfy( + binding -> { + assertThat(binding).isInstanceOf(Number.class); + assertThat(((Number) binding).longValue()).isEqualTo(500L); + }); + String renderedSql = sqlRef.get().toLowerCase(Locale.ROOT).replaceAll("\\s+", " "); + int outerTuplePredicate = renderedSql.indexOf(") in ("); + assertThat(outerTuplePredicate).as(renderedSql).isGreaterThanOrEqualTo(0); + assertThat(renderedSql.substring(0, outerTuplePredicate)) + .contains("\"script_handoff_events\".\"id\"", "\"script_handoff_events\".\"tenant_id\""); + assertThat(renderedSql) + .contains( + "select \"retention_candidates\".\"id\", \"retention_candidates\".\"tenant_id\"", + "tenant_id", + "observed_at", + " < ", + "retention_hold_until", + "is null", + " <= ", + "status", + "not in", + "order by \"retention_candidates\".\"event_id\" asc", + "fetch next ? rows only"); + assertThat(renderedSql).doesNotContain("select \"retention_candidates\".\"event_id\""); + } + + @Test + void retentionHoldWriteUsesUtcOffsetDateTimeAndAllowsClearingHold() { + Instant holdUntil = Instant.parse("2026-08-03T00:00:00Z"); + AtomicReference bindingsRef = new AtomicReference<>(); + AtomicReference sqlRef = new AtomicReference<>(); + MockDataProvider provider = + context -> { + bindingsRef.set(context.bindings()); + sqlRef.set(context.sql()); + return new MockResult[] {new MockResult(1)}; + }; + ScriptHandoffEventRepository repository = + new ScriptHandoffEventRepository( + DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + + assertThat(repository.setRetentionHold("tenant-1", 41L, holdUntil)).isTrue(); + assertThat(bindingsRef.get()).contains("2026-08-03 00:00:00+00:00"); + + assertThat(repository.setRetentionHold("tenant-1", 41L, null)).isTrue(); + assertThat(retentionHoldSetClause(sqlRef.get())).contains("retention_hold_until"); + assertThat(bindingsRef.get()).contains((Object) null); + } + + @Test + void newLogicalChildUsesAtomicCurrentEventIdConflictUpsert() { + AtomicReference sql = new AtomicReference<>(); + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + MockDataProvider provider = + context -> { + sql.set(context.sql()); + ScriptHandoffEventsRecord row = handoffRecord(); + var result = resultDsl.newResult(SCRIPT_HANDOFF_EVENTS); + result.add(row); + return new MockResult[] {new MockResult(1, result)}; + }; + ScriptHandoffEventRepository repository = + new ScriptHandoffEventRepository( + DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + + ScriptHandoffEvent saved = repository.save(handoffEvent()); + + assertThat(saved.getId()).isEqualTo(41L); + String renderedSql = sql.get().toLowerCase(Locale.ROOT); + int conflictIndex = renderedSql.indexOf("on conflict"); + int updateIndex = renderedSql.indexOf("do update", conflictIndex); + assertThat(conflictIndex).as(renderedSql).isGreaterThanOrEqualTo(0); + assertThat(updateIndex).as(renderedSql).isGreaterThan(conflictIndex); + assertThat(renderedSql.substring(conflictIndex, updateIndex)).contains("event_id"); + assertThat(renderedSql).contains("where"); + assertThat(renderedSql).contains("returning", "do update"); + } + + @Test + void newLogicalChildFailsWhenConflictResolutionReturnsNoDurableRow() { + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + MockDataProvider provider = + context -> new MockResult[] {new MockResult(0, resultDsl.newResult(SCRIPT_HANDOFF_EVENTS))}; + ScriptHandoffEventRepository repository = + new ScriptHandoffEventRepository( + DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + + assertThatThrownBy(() -> repository.save(handoffEvent())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("did not yield a persisted row"); + } + + private static ScriptHandoffEventsRecord handoffRecord() { + ScriptHandoffEventsRecord record = new ScriptHandoffEventsRecord(); + record.setId(41L); + record.setEventId("event-1"); + record.setTenantId("tenant-1"); + record.setGameInstanceId("game-1"); + record.setScriptPatchVersion("patch-1"); + record.setScriptId("script-1"); + record.setWorkItemId(99L); + record.setCommandOrdinal(0); + record.setAutomationDispatchId("dispatch-1"); + record.setTargetEntityId("entity-1"); + record.setEmittedCommandText("look"); + record.setHandoffOutcome("enqueued"); + record.setHandoffReason("game_session_accepted"); + record.setObservedAt(java.time.LocalDateTime.of(2026, 1, 1, 0, 0)); + record.setRowVersion(0); + return record; + } + + private static ScriptHandoffEvent handoffEvent() { + ScriptHandoffEvent event = new ScriptHandoffEvent(); + event.setEventId("event-1"); + event.setTenantId("tenant-1"); + event.setGameInstanceId("game-1"); + event.setScriptPatchVersion("patch-1"); + event.setScriptId("script-1"); + event.setWorkItemId(99L); + event.setCommandOrdinal(0); + event.setAutomationDispatchId("dispatch-1"); + event.setTargetEntityId("entity-1"); + event.setEmittedCommandText("look"); + event.setHandoffOutcome("enqueued"); + event.setHandoffReason("game_session_accepted"); + event.setObservedAt(Instant.parse("2026-01-01T00:00:00Z")); + return event; + } + + private static String retentionHoldSetClause(String sql) { + String normalized = sql.toLowerCase(Locale.ROOT); + int setStart = normalized.indexOf(" set "); + int whereStart = normalized.indexOf(" where ", setStart); + assertThat(setStart).as(sql).isGreaterThanOrEqualTo(0); + assertThat(whereStart).as(sql).isGreaterThan(setStart); + return normalized.substring(setStart, whereStart); + } + private static String conflictTarget(String sql) { String normalized = sql.toLowerCase(Locale.ROOT); int conflictStart = normalized.indexOf("on conflict"); diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepositoryTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepositoryTest.java index 2d604b288c..2e954f9b60 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepositoryTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepositoryTest.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.automationscripting.repository; +import static net.firedevops.firemud.automationscripting.jooq.tables.ScriptHandoffEvents.SCRIPT_HANDOFF_EVENTS; import static net.firedevops.firemud.automationscripting.jooq.tables.ScriptWorkItems.SCRIPT_WORK_ITEMS; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; @@ -95,6 +96,179 @@ void insertRejectsOwnerRequestIdOnUnpinnedTuple() { .withMessage("script_pin_control_plane_request_id requires a positive script_pin_epoch"); } + @Test + void insertAndHydratePluginFencePersistsBothValues() { + ScriptWorkItemsRecord row = workItemRecord(13L, 0, 0L); + row.setPluginActivationEpoch(4L); + row.setLifecycleRevision(8L); + row.setFailureGeneration(3L); + row.setAuthorityUnavailableSince(LocalDateTime.parse("2026-08-01T00:00:02")); + row.setAuthorityUnavailableCount(2); + row.setNextEligibleAt(LocalDateTime.parse("2026-08-01T00:00:03")); + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + AtomicReference insertSql = new AtomicReference<>(); + MockDataProvider provider = + context -> { + insertSql.set(context.sql().toLowerCase(Locale.ROOT)); + Field insertedField = DSL.field("xmax = 0", Boolean.class).as("inserted"); + List> fields = new ArrayList<>(); + Collections.addAll(fields, SCRIPT_WORK_ITEMS.fields()); + fields.add(insertedField); + Record returned = resultDsl.newRecord(fields.toArray(new Field[0])); + returned.from(row); + returned.set(insertedField, true); + Result result = resultDsl.newResult(fields.toArray(new Field[0])); + result.add(returned); + return new MockResult[] {new MockResult(1, result)}; + }; + ScriptWorkItemRepository repository = + new ScriptWorkItemRepository(DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + + ScriptWorkItem item = new ScriptWorkItem(); + item.setTenantId("tenant-1"); + item.setGameInstanceId("game-1"); + item.setRegionId("region-1"); + item.setRegionEpoch(7L); + item.setEntityId("entity-1"); + item.setScriptId("script-1"); + item.setPluginId("plugin-1"); + item.setPluginVersionId("plugin-v1"); + item.setPluginActivationEpoch(4L); + item.setLifecycleRevision(8L); + item.setFailureGeneration(3L); + item.setAuthorityUnavailableSince(Instant.parse("2026-08-01T00:00:02Z")); + item.setAuthorityUnavailableCount(2); + item.setNextEligibleAt(Instant.parse("2026-08-01T00:00:03Z")); + + ScriptWorkItem saved = repository.insertIfAbsentByTriggerIdentity(item).workItem(); + + assertThat(saved.getPluginActivationEpoch()).isEqualTo(4L); + assertThat(saved.getLifecycleRevision()).isEqualTo(8L); + assertThat(saved.getFailureGeneration()).isEqualTo(3L); + assertThat(saved.getAuthorityUnavailableSince()) + .isEqualTo(Instant.parse("2026-08-01T00:00:02Z")); + assertThat(saved.getAuthorityUnavailableCount()).isEqualTo(2); + assertThat(saved.getNextEligibleAt()).isEqualTo(Instant.parse("2026-08-01T00:00:03Z")); + assertThat(insertSql) + .hasValueSatisfying( + sql -> + assertThat(sql) + .contains( + "plugin_activation_epoch", + "lifecycle_revision", + "failure_generation", + "authority_unavailable_since", + "authority_unavailable_count", + "next_eligible_at")); + } + + @Test + void insertRejectsAConflictingPluginFencePair() { + ScriptWorkItemRepository repository = + new ScriptWorkItemRepository(DSL.using(SQLDialect.POSTGRES)); + ScriptWorkItem item = new ScriptWorkItem(); + item.setPluginActivationEpoch(4L); + + assertThatIllegalArgumentException() + .isThrownBy(() -> repository.insertIfAbsentByTriggerIdentity(item)) + .withMessage( + "plugin_activation_epoch and lifecycle_revision must both be zero or both be positive"); + } + + @Test + void pendingClaimUsesRetryEligibilityAndSkipLocked() { + AtomicReference sql = new AtomicReference<>(); + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + MockDataProvider provider = + context -> { + sql.set(context.sql().toLowerCase(Locale.ROOT)); + return new MockResult[] { + new MockResult(0, resultDsl.newResult(SCRIPT_WORK_ITEMS.fields())) + }; + }; + ScriptWorkItemRepository repository = + new ScriptWorkItemRepository(DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + + assertThat( + repository.findByStatusForUpdateOrderByCreatedAtAscIdAsc( + "PENDING_EVALUATION", PageRequest.of(0, 10))) + .isEmpty(); + assertThat(sql) + .hasValueSatisfying( + statement -> + assertThat(statement) + .contains( + "next_eligible_at", "current_timestamp", "for update", "skip locked")); + } + + @Test + void cancellationClaimUsesBoundedScopeAndRowLock() { + AtomicReference sql = new AtomicReference<>(); + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + MockDataProvider provider = + context -> { + sql.set(context.sql().toLowerCase(Locale.ROOT)); + return new MockResult[] { + new MockResult(0, resultDsl.newResult(SCRIPT_WORK_ITEMS.fields())) + }; + }; + ScriptWorkItemRepository repository = + new ScriptWorkItemRepository(DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + + assertThat( + repository + .findByTenantIdAndScriptPatchVersionAndStatusInForUpdateOrderByCreatedAtAscIdAsc( + "tenant-1", + "patch-1", + "game-1", + "region-1", + List.of("PENDING_EVALUATION", "EVALUATING"))) + .isEmpty(); + assertThat(sql) + .hasValueSatisfying( + statement -> + assertThat(statement) + .contains( + "tenant_id", + "script_patch_version", + "game_instance_id", + "region_id", + "for update", + "fetch next")); + } + + @Test + void replayClaimFencesStatusRowVersionAndFailureGeneration() { + AtomicReference sql = new AtomicReference<>(); + AtomicReference bindings = new AtomicReference<>(); + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + MockDataProvider provider = + context -> { + sql.set(context.sql().toLowerCase(Locale.ROOT)); + bindings.set(context.bindings()); + return new MockResult[] { + new MockResult(0, resultDsl.newResult(SCRIPT_WORK_ITEMS.fields())) + }; + }; + ScriptWorkItemRepository repository = + new ScriptWorkItemRepository(DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + + assertThat( + repository.claimDeadLetterForReplay( + 11L, "tenant-1", 4, 3L, Instant.parse("2026-08-01T00:00:04Z"))) + .isEmpty(); + assertThat(sql) + .hasValueSatisfying( + statement -> + assertThat(statement) + .contains("update", "status", "row_version", "failure_generation") + .satisfies( + sqlText -> + assertThat(sqlText.substring(0, sqlText.indexOf(" returning "))) + .doesNotContain("cancel_reason"))); + assertThat(bindings.get()).contains("PENDING_EVALUATION", "DEAD_LETTERED", 4, 3L); + } + @Test void insertRejectsConflictingOwnerEvidenceAgainstExistingIdentity() { ScriptWorkItemsRecord row = workItemRecord(9L, 4, 7L); @@ -213,6 +387,7 @@ void insertAndHydrateUnpinnedEpochUsesEpochIdentityWithoutRequestId() { ScriptWorkItem saved = repository.insertIfAbsentByTriggerIdentity(item).workItem(); assertThat(saved.getScriptPinEpoch()).isZero(); + assertThat(saved.getFailureGeneration()).isZero(); assertThat(conflictClause(insertSql.get())) .contains("where", "script_pin_epoch", "= 0") .doesNotContain("script_pin_control_plane_request_id"); @@ -304,30 +479,6 @@ void scriptOnlyPluginLookupNormalizesBlankIdentityToCanonicalEmptyValues() { assertThat(bindings.get()).contains("tenant-1", "", ""); } - @Test - void deletingWorkItemsDisposesChildEvidenceBeforeParentRows() { - List sqlStatements = new ArrayList<>(); - MockDataProvider provider = - context -> { - sqlStatements.add(context.sql().toLowerCase(Locale.ROOT)); - return new MockResult[] {new MockResult(1, null)}; - }; - ScriptWorkItemRepository repository = - new ScriptWorkItemRepository(DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); - ScriptWorkItem item = new ScriptWorkItem(); - item.setId(99L); - - repository.deleteAll(List.of(item)); - - assertThat(sqlStatements).hasSize(3); - assertThat(sqlStatements.get(0)) - .startsWith("update") - .contains("script_event_audit") - .contains("work_item_id"); - assertThat(sqlStatements.get(1)).contains("script_handoff_events"); - assertThat(sqlStatements.get(2)).contains("script_work_items"); - } - @Test void statusRetentionDeletesChildrenBeforeMatchingParents() { DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); @@ -337,6 +488,11 @@ void statusRetentionDeletesChildrenBeforeMatchingParents() { String sql = context.sql().toLowerCase(Locale.ROOT); sqlStatements.add(sql); if (sql.startsWith("select")) { + if (sql.contains("script_handoff_events") && !sql.contains("script_work_items")) { + return new MockResult[] { + new MockResult(0, resultDsl.newResult(SCRIPT_HANDOFF_EVENTS.ID)) + }; + } Record1 returned = resultDsl.newRecord(SCRIPT_WORK_ITEMS.ID); returned.set(SCRIPT_WORK_ITEMS.ID, 99L); Result> result = resultDsl.newResult(SCRIPT_WORK_ITEMS.ID); @@ -351,17 +507,27 @@ void statusRetentionDeletesChildrenBeforeMatchingParents() { assertThat(repository.deleteByStatusAndUpdatedAtBefore("HANDED_OFF", Instant.EPOCH)) .isEqualTo(1); - assertThat(sqlStatements).hasSize(4); - assertThat(sqlStatements.get(0)).startsWith("select").contains("for update"); + assertThat(sqlStatements).hasSize(6); + assertThat(sqlStatements.get(0)) + .startsWith("select") + .contains("for update", "script_dead_letter_replay_results", "retention_hold_until"); assertThat(sqlStatements.get(1)) + .startsWith("select") + .contains("script_handoff_events", "for update"); + assertThat(sqlStatements.get(2)) + .startsWith("select") + .contains("script_work_items", "script_dead_letter_replay_results", "retention_hold_until") + .contains("for update"); + assertThat(sqlStatements.get(3)) .startsWith("update") .contains("script_event_audit") .contains("work_item_id"); - assertThat(sqlStatements.get(2)).contains("script_handoff_events"); - assertThat(sqlStatements.get(3)) + assertThat(sqlStatements.get(4)) + .contains("script_handoff_events", "retention_hold_until", "current_timestamp"); + assertThat(sqlStatements.get(5)) .contains("script_work_items") .contains("status") - .contains("updated_at"); + .contains("updated_at", "script_dead_letter_replay_results", "retention_hold_until"); } @Test @@ -373,6 +539,11 @@ void excessStatusRetentionLocksOldestRowsAndRechecksStatus() { String sql = context.sql().toLowerCase(Locale.ROOT); sqlStatements.add(sql); if (sql.startsWith("select")) { + if (sql.contains("script_handoff_events") && !sql.contains("script_work_items")) { + return new MockResult[] { + new MockResult(0, resultDsl.newResult(SCRIPT_HANDOFF_EVENTS.ID)) + }; + } Record1 returned = resultDsl.newRecord(SCRIPT_WORK_ITEMS.ID); returned.set(SCRIPT_WORK_ITEMS.ID, 99L); Result> result = resultDsl.newResult(SCRIPT_WORK_ITEMS.ID); @@ -386,7 +557,7 @@ void excessStatusRetentionLocksOldestRowsAndRechecksStatus() { assertThat(repository.deleteOldestByStatus("HANDED_OFF", 1)).isEqualTo(1); - assertThat(sqlStatements).hasSize(4); + assertThat(sqlStatements).hasSize(6); assertThat(sqlStatements.get(0)) .startsWith("select") .contains("status") @@ -394,11 +565,20 @@ void excessStatusRetentionLocksOldestRowsAndRechecksStatus() { .contains("fetch next") .contains("for update"); assertThat(sqlStatements.get(1)) + .startsWith("select") + .contains("script_handoff_events", "for update"); + assertThat(sqlStatements.get(2)) + .startsWith("select") + .contains("script_work_items", "script_dead_letter_replay_results", "retention_hold_until") + .contains("for update"); + assertThat(sqlStatements.get(3)) .startsWith("update") .contains("script_event_audit") .contains("work_item_id"); - assertThat(sqlStatements.get(2)).contains("script_handoff_events"); - assertThat(sqlStatements.get(3)).contains("script_work_items").contains("status"); + assertThat(sqlStatements.get(4)) + .contains("script_handoff_events", "retention_hold_until", "current_timestamp"); + assertThat(sqlStatements.get(5)) + .contains("script_work_items", "status", "script_dead_letter_replay_results"); } @Test @@ -411,6 +591,93 @@ void deadLetterCleanupFailsClosedUntilRecoveryAwareRetentionEvidenceExists() { assertThat(repository.deleteOldestByStatus("DEAD_LETTERED", 1)).isZero(); } + @Test + void statusRetentionSkipsChildDeletionWhenEligibilityChangesAfterChildLock() { + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + List sqlStatements = new ArrayList<>(); + MockDataProvider provider = + context -> { + String sql = context.sql().toLowerCase(Locale.ROOT); + sqlStatements.add(sql); + if (sql.startsWith("select") + && sql.contains("script_handoff_events") + && !sql.contains("script_work_items")) { + return new MockResult[] { + new MockResult(0, resultDsl.newResult(SCRIPT_HANDOFF_EVENTS.ID)) + }; + } + if (sqlStatements.size() == 1) { + Record1 returned = resultDsl.newRecord(SCRIPT_WORK_ITEMS.ID); + returned.set(SCRIPT_WORK_ITEMS.ID, 99L); + Result> result = resultDsl.newResult(SCRIPT_WORK_ITEMS.ID); + result.add(returned); + return new MockResult[] {new MockResult(1, result)}; + } + return new MockResult[] {new MockResult(0, resultDsl.newResult(SCRIPT_WORK_ITEMS.ID))}; + }; + ScriptWorkItemRepository repository = + new ScriptWorkItemRepository(DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + + assertThat(repository.deleteByStatusAndUpdatedAtBefore("HANDED_OFF", Instant.EPOCH)).isZero(); + assertThat(sqlStatements).hasSize(3); + assertThat(sqlStatements.get(1)).contains("script_handoff_events", "for update"); + assertThat(sqlStatements.get(2)) + .contains("script_work_items", "script_dead_letter_replay_results", "retention_hold_until") + .contains("for update"); + } + + @Test + void terminalCleanupRequiresReceiptAndActiveHandoffHoldProof() { + AtomicReference sql = new AtomicReference<>(); + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + MockDataProvider provider = + context -> { + sql.set(context.sql().toLowerCase(Locale.ROOT)); + return new MockResult[] {new MockResult(0, resultDsl.newResult(SCRIPT_WORK_ITEMS.ID))}; + }; + ScriptWorkItemRepository repository = + new ScriptWorkItemRepository(DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + + assertThat(repository.deleteByStatusAndUpdatedAtBefore("HANDED_OFF", Instant.EPOCH)).isZero(); + assertThat(sql) + .hasValueSatisfying( + statement -> + assertThat(statement) + .contains( + "script_work_items", + "script_dead_letter_replay_results", + "script_handoff_events", + "retention_hold_until", + "current_timestamp")); + } + + @Test + void deadLetterBlockedMetricDoesNotUseChildAbsenceAsDeletionProof() { + AtomicReference sql = new AtomicReference<>(); + DSLContext resultDsl = DSL.using(SQLDialect.POSTGRES); + MockDataProvider provider = + context -> { + sql.set(context.sql().toLowerCase(Locale.ROOT)); + Field countField = DSL.field("count", Integer.class); + Result> result = resultDsl.newResult(countField); + Record1 countRow = resultDsl.newRecord(countField); + countRow.set(countField, 0); + result.add(countRow); + return new MockResult[] {new MockResult(1, result)}; + }; + ScriptWorkItemRepository repository = + new ScriptWorkItemRepository(DSL.using(new MockConnection(provider), SQLDialect.POSTGRES)); + + assertThat(repository.countTerminalRowsBlockedByEvidence("DEAD_LETTERED", Instant.EPOCH)) + .isZero(); + assertThat(sql) + .hasValueSatisfying( + statement -> + assertThat(statement) + .contains("script_work_items", "status", "updated_at") + .doesNotContain("script_event_audit", "script_handoff_events")); + } + @Test void deadLetterListingAppliesOptionalFiltersBeforeLimit() { AtomicReference sql = new AtomicReference<>(); From 8879a176828807141cb5d6cd524d8b2e3198b6e6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 21 Sep 2026 11:29:47 +1200 Subject: [PATCH 02/68] Restore execution replay and queue recovery behavior --- .../service/ScriptWorkItemService.java | 32 +- .../AutomationPatchControlPlaneService.java | 22 +- .../impl/AutomationQueueServiceImpl.java | 106 +- ...riptGameplayCommandHandoffServiceImpl.java | 6 + .../ScriptWorkItemExecutionServiceImpl.java | 391 ++++++- .../impl/ScriptWorkItemServiceImpl.java | 689 +++++++++--- ...tingServiceApplicationIntegrationTest.java | 500 ++++++++- .../impl/AutomationQueueServiceImplTest.java | 126 ++- ...nScriptingControlPlaneGrpcServiceTest.java | 56 +- ...GameplayCommandHandoffServiceImplTest.java | 3 + ...criptWorkItemExecutionServiceImplTest.java | 736 ++++++++++++- .../impl/ScriptWorkItemServiceImplTest.java | 992 +++++++++++++++--- 12 files changed, 3280 insertions(+), 379 deletions(-) diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/ScriptWorkItemService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/ScriptWorkItemService.java index a8975a4dc8..f0a3c2e31d 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/ScriptWorkItemService.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/ScriptWorkItemService.java @@ -276,5 +276,35 @@ record ReplayDeadLettersCommand( } } - record ReplayResult(long replayedCount, long rejectedCount) {} + record ReplayItemResult( + String workItemId, + String outcome, + String rejectionReason, + String failureReason, + long failureGeneration) { + public ReplayItemResult( + String workItemId, String outcome, String rejectionReason, long failureGeneration) { + this(workItemId, outcome, rejectionReason, "", failureGeneration); + } + + public ReplayItemResult(String workItemId, String outcome, String rejectionReason) { + this(workItemId, outcome, rejectionReason, "", 0L); + } + } + + record ReplayResult( + long replayedCount, + long rejectedCount, + List results, + String requestFingerprint) { + public ReplayResult { + results = results == null ? List.of() : List.copyOf(results); + requestFingerprint = requestFingerprint == null ? "" : requestFingerprint; + } + + /** Compatibility constructor for callers that consume only aggregate counts. */ + public ReplayResult(long replayedCount, long rejectedCount) { + this(replayedCount, rejectedCount, List.of(), ""); + } + } } diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java index f60281fc94..e5c1ee96cc 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java @@ -40,6 +40,7 @@ import net.firedevops.firemud.automationscripting.v1.ListScriptTimerAuditEventsRequest; import net.firedevops.firemud.automationscripting.v1.ListScriptTimerAuditEventsResponse; import net.firedevops.firemud.automationscripting.v1.PluginPublicationLink; +import net.firedevops.firemud.automationscripting.v1.ReplayDeadLetteredWorkItemResult; import net.firedevops.firemud.automationscripting.v1.ReplayDeadLetteredWorkItemsRequest; import net.firedevops.firemud.automationscripting.v1.ReplayDeadLetteredWorkItemsResponse; import net.firedevops.firemud.automationscripting.v1.ScriptDeadLetterEntry; @@ -450,10 +451,23 @@ ReplayDeadLetteredWorkItemsResponse replayDeadLetteredWorkItems( request.getControlPlaneRequestId(), request.getActorPrincipal(), request.getReason())); - return ReplayDeadLetteredWorkItemsResponse.newBuilder() - .setReplayedCount(result.replayedCount()) - .setRejectedCount(result.rejectedCount()) - .build(); + ReplayDeadLetteredWorkItemsResponse.Builder response = + ReplayDeadLetteredWorkItemsResponse.newBuilder() + .setReplayedCount(result.replayedCount()) + .setRejectedCount(result.rejectedCount()) + .setRequestFingerprint(result.requestFingerprint()); + result.results().stream() + .map( + item -> + ReplayDeadLetteredWorkItemResult.newBuilder() + .setWorkItemId(item.workItemId()) + .setOutcome(item.outcome()) + .setRejectionReason(item.rejectionReason()) + .setFailureReason(item.failureReason()) + .setFailureGeneration(item.failureGeneration()) + .build()) + .forEach(response::addResults); + return response.build(); } CancelPendingWorkItemsForPatchResponse cancelPendingWorkItemsForPatch( diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationQueueServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationQueueServiceImpl.java index 14ac2ba77a..ef2e68c129 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationQueueServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationQueueServiceImpl.java @@ -8,18 +8,20 @@ import jakarta.annotation.PostConstruct; import java.time.Instant; import java.util.Collection; -import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; -import lombok.RequiredArgsConstructor; import net.firedevops.firemud.automationscripting.entity.ScriptWorkItem; import net.firedevops.firemud.automationscripting.repository.ScriptWorkItemRepository; import net.firedevops.firemud.automationscripting.service.AutomationQueueService; import net.firedevops.firemud.automationscripting.service.AutomationQueueWorkItemPointer; import net.firedevops.firemud.automationscripting.service.redis.AutomationRedisKeys; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.PageRequest; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; @@ -28,33 +30,67 @@ /** Redis-backed implementation of {@link AutomationQueueService}. */ @Service -@RequiredArgsConstructor @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Service dependency is not exposed") public class AutomationQueueServiceImpl implements AutomationQueueService { + private static final Logger LOGGER = LoggerFactory.getLogger(AutomationQueueServiceImpl.class); private static final int POINTER_SCHEMA_VERSION = 1; - private static final Collection INDEXABLE_STATUSES = + private static final Collection INDEXABLE_STATUSES = List.of("PENDING_EVALUATION"); + private static final Collection INSPECTABLE_STATUSES = List.of("PENDING_EVALUATION", "EVALUATING"); private final RedisTemplate redisTemplate; private final MeterRegistry meterRegistry; private final ObjectMapper objectMapper; private final ScriptWorkItemRepository workItemRepository; + private final int drainPointerBudget; + + /** + * The per-tick event ceiling also bounds direct per-entity queue drains. Redis is a derived + * index, so a drain must leave any suffix available for the next execution sweep. + */ + AutomationQueueServiceImpl( + RedisTemplate redisTemplate, + MeterRegistry meterRegistry, + ObjectMapper objectMapper, + ScriptWorkItemRepository workItemRepository) { + this(redisTemplate, meterRegistry, objectMapper, workItemRepository, 50); + } + + @Autowired + public AutomationQueueServiceImpl( + RedisTemplate redisTemplate, + MeterRegistry meterRegistry, + ObjectMapper objectMapper, + ScriptWorkItemRepository workItemRepository, + @Value("${automation.tick-max-events:50}") int drainPointerBudget) { + this.redisTemplate = redisTemplate; + this.meterRegistry = meterRegistry; + this.objectMapper = objectMapper; + this.workItemRepository = workItemRepository; + this.drainPointerBudget = drainPointerBudget; + } private ListOperations listOps; private Counter enqueueCounter; private Counter drainCounter; private Counter rebuildCounter; private Counter inspectionCounter; + private Counter malformedEntriesCounter; private AtomicLong orphanedEntriesGauge = new AtomicLong(); private AtomicLong oldestEntryAgeSecondsGauge = new AtomicLong(); @PostConstruct void init() { + if (drainPointerBudget <= 0) { + throw new IllegalArgumentException("automation.tick-max-events must be positive"); + } this.listOps = redisTemplate.opsForList(); this.enqueueCounter = meterRegistry.counter("automation_queue_enqueued_total"); this.drainCounter = meterRegistry.counter("automation_queue_drained_total"); this.rebuildCounter = meterRegistry.counter("automation_queue_rebuilt_total"); this.inspectionCounter = meterRegistry.counter("automation_queue_health_inspections_total"); + this.malformedEntriesCounter = + meterRegistry.counter("automation_queue_malformed_entries_total"); Gauge.builder("automation_queue_orphaned_entries_total", orphanedEntriesGauge, AtomicLong::get) .register(meterRegistry); Gauge.builder( @@ -86,16 +122,19 @@ public void enqueueWorkItem(ScriptWorkItem workItem) { public List drainWorkItems( String tenantId, String gameInstanceId, String entityId) { String key = AutomationRedisKeys.automationQueue(tenantId, gameInstanceId, entityId); - List raw = listOps.range(key, 0, -1); - redisTemplate.delete(key); - if (raw == null) { - return Collections.emptyList(); - } LinkedHashMap deduped = new LinkedHashMap<>(); - raw.stream() - .map(Object::toString) - .map(this::deserialize) - .forEach(pointer -> deduped.putIfAbsent(pointer.outboxWorkItemId(), pointer)); + // LPOP is atomic with the producer's RPUSH. LRANGE followed by DELETE could + // delete a pointer enqueued between those two operations. + Object entry; + int poppedPointers = 0; + while (poppedPointers < drainPointerBudget && (entry = listOps.leftPop(key)) != null) { + poppedPointers++; + AutomationQueueWorkItemPointer pointer = deserializeOrNull(entry, key); + if (pointer == null) { + continue; + } + deduped.putIfAbsent(pointer.outboxWorkItemId(), pointer); + } drainCounter.increment(deduped.size()); return List.copyOf(deduped.values()); } @@ -115,16 +154,19 @@ public List drainIndexedWorkItemPointers( return List.of(); } LinkedHashMap deduped = new LinkedHashMap<>(); + int poppedPointers = 0; for (String queueKey : queueKeys.stream().sorted().limit(maxQueues).toList()) { - List raw = listOps.range(queueKey, 0, -1); - redisTemplate.delete(queueKey); - if (raw == null) { - continue; - } - for (Object entry : raw) { - AutomationQueueWorkItemPointer pointer = deserialize(entry.toString()); - deduped.putIfAbsent(pointer.outboxWorkItemId(), pointer); - if (deduped.size() >= maxPointers) { + // Pop one entry at a time: unlike range+delete, this leaves the unconsumed + // suffix in Redis when the bounded result is full. Each LPOP is atomic with + // an enqueue's RPUSH, so a producer cannot have its new pointer discarded. + Object entry; + while ((entry = listOps.leftPop(queueKey)) != null) { + poppedPointers++; + AutomationQueueWorkItemPointer pointer = deserializeOrNull(entry, queueKey); + if (pointer != null) { + deduped.putIfAbsent(pointer.outboxWorkItemId(), pointer); + } + if (poppedPointers >= maxPointers) { drainCounter.increment(deduped.size()); return List.copyOf(deduped.values()); } @@ -180,7 +222,8 @@ public QueueHealthSnapshot inspectProjectionHealth(int maxQueues, long staleAfte } raw.stream() .map(Object::toString) - .map(this::deserialize) + .map(entry -> deserializeOrNull(entry, queueKey)) + .filter(java.util.Objects::nonNull) .forEach(pointer -> pointers.putIfAbsent(pointer.outboxWorkItemId(), pointer)); } Map itemsById = @@ -198,7 +241,7 @@ public QueueHealthSnapshot inspectProjectionHealth(int maxQueues, long staleAfte long ageSeconds = Math.max(0L, java.time.Duration.between(item.getCreatedAt(), now).getSeconds()); oldestEntryAgeSeconds = Math.max(oldestEntryAgeSeconds, ageSeconds); - if (!INDEXABLE_STATUSES.contains(item.getStatus()) || ageSeconds > staleAfterSeconds) { + if (!INSPECTABLE_STATUSES.contains(item.getStatus()) || ageSeconds > staleAfterSeconds) { orphanedEntries++; } } @@ -225,6 +268,18 @@ private AutomationQueueWorkItemPointer deserialize(String payload) { } } + private AutomationQueueWorkItemPointer deserializeOrNull(Object entry, String queueKey) { + try { + return deserialize(entry.toString()); + } catch (RuntimeException ex) { + malformedEntriesCounter.increment(); + LOGGER.warn( + "Discarding malformed automation queue pointer from key {} (reason=deserialization_failed)", + queueKey); + return null; + } + } + private boolean ensurePointerIndexed(ScriptWorkItem workItem) { String queueKey = AutomationRedisKeys.automationQueue( @@ -233,7 +288,8 @@ private boolean ensurePointerIndexed(ScriptWorkItem workItem) { if (raw != null && raw.stream() .map(Object::toString) - .map(this::deserialize) + .map(entry -> deserializeOrNull(entry, queueKey)) + .filter(java.util.Objects::nonNull) .anyMatch(pointer -> pointer.outboxWorkItemId() == workItem.getId())) { return false; } diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java index 3a5d3e207a..fb4628b890 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java @@ -753,6 +753,12 @@ private void applyOutcome( now); return; } + // A terminal failure is a distinct dead-letter transition unless this item was + // already terminal. Replay moves it back to PENDING_EVALUATION first, so the + // next terminal failure advances the generation exactly once. + if (!STATUS_DEAD_LETTERED.equals(workItem.getStatus())) { + workItem.setFailureGeneration(Math.addExact(workItem.getFailureGeneration(), 1L)); + } workItem.setStatus(STATUS_DEAD_LETTERED); String failureReason = ScriptHandoffOutcomeSupport.canonicalInfrastructureReason(result); workItem.setCancelReason(failureReason); diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java index ac3a7d1ad4..4dc895c868 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java @@ -1,17 +1,25 @@ package net.firedevops.firemud.automationscripting.service.impl; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.net.ConnectException; +import java.net.SocketTimeoutException; +import java.sql.SQLException; +import java.sql.SQLRecoverableException; +import java.sql.SQLTransientException; +import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; +import net.firedevops.firemud.automationscripting.client.GameSessionControlPlaneClient; import net.firedevops.firemud.automationscripting.config.ScriptOutputProperties; +import net.firedevops.firemud.automationscripting.entity.PluginRuntimeState; import net.firedevops.firemud.automationscripting.entity.ScriptDefinition; import net.firedevops.firemud.automationscripting.entity.ScriptWorkItem; +import net.firedevops.firemud.automationscripting.repository.PluginRuntimeStateRepository; import net.firedevops.firemud.automationscripting.repository.ScriptDefinitionRepository; import net.firedevops.firemud.automationscripting.repository.ScriptEventAuditRepository; import net.firedevops.firemud.automationscripting.repository.ScriptWorkItemRepository; @@ -26,21 +34,21 @@ import net.firedevops.firemud.automationscripting.service.quota.ScriptDryRunCapacityService; import net.firedevops.firemud.automationscripting.service.quota.ScriptReadinessCapacityService; import net.firedevops.firemud.automationscripting.service.quota.ScriptTenantBudgetService; +import net.firedevops.firemud.automationscripting.v1.PluginState; import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.gamesession.v1.GetGameInstanceRuntimeStateResponse; +import org.jooq.exception.DataAccessException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; import tools.jackson.core.JacksonException; import tools.jackson.databind.JsonNode; import tools.jackson.databind.ObjectMapper; @Service -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected collaborators are retained internally by Spring services.") public class ScriptWorkItemExecutionServiceImpl implements ScriptWorkItemExecutionService { private static final Logger LOGGER = LoggerFactory.getLogger(ScriptWorkItemExecutionServiceImpl.class); @@ -51,6 +59,11 @@ public class ScriptWorkItemExecutionServiceImpl implements ScriptWorkItemExecuti private static final String STAGE_DSL_EVAL = "DSL_EVAL"; private static final String OUTCOME_HANDOFF_ACCEPTED = "handoff_accepted"; private static final String OUTCOME_SANDBOX_ERROR = "sandbox_error"; + private static final String OUTCOME_AUTHORITY_UNAVAILABLE_EXHAUSTED = + "authority_unavailable_exhausted"; + private static final Duration AUTHORITY_UNAVAILABLE_RETRY_DELAY = Duration.ofSeconds(30); + private static final Duration AUTHORITY_UNAVAILABLE_MAX_AGE = Duration.ofMinutes(10); + private static final int MAX_AUTHORITY_UNAVAILABLE_OUTCOMES = 10; private static final String PRIORITY_HIGH = "high"; private static final String PRIORITY_NORMAL = "normal"; private static final String PRIORITY_BACKGROUND = "background"; @@ -72,6 +85,9 @@ public class ScriptWorkItemExecutionServiceImpl implements ScriptWorkItemExecuti private final ObjectMapper objectMapper; private final MeterRegistry meterRegistry; private final AutomationQueueService automationQueueService; + private final GameSessionControlPlaneClient gameSessionControlPlaneClient; + private final PluginRuntimeStateRepository pluginRuntimeStateRepository; + private final TransactionTemplate transactionTemplate; public ScriptWorkItemExecutionServiceImpl( ScriptWorkItemService workItemService, @@ -98,10 +114,47 @@ public ScriptWorkItemExecutionServiceImpl( new SimpleMeterRegistry(), null, null, + null, + null, null); } - @org.springframework.beans.factory.annotation.Autowired + /** Compatibility constructor for focused tests that provide readiness collaborators. */ + public ScriptWorkItemExecutionServiceImpl( + ScriptWorkItemService workItemService, + ScriptDefinitionRepository scriptDefinitionRepository, + ScriptGameplayCommandHandoffService handoffService, + ScriptWorkItemRepository workItemRepository, + ScriptEventAuditRepository auditRepository, + ScriptPatchInstanceRolloutProjectionService rolloutProjectionService, + ScriptOutputProperties outputProperties, + ScriptTenantBudgetService tenantBudgetService, + ScriptDryRunCapacityService dryRunCapacityService, + ObjectMapper objectMapper, + MeterRegistry meterRegistry, + AutomationQueueService automationQueueService, + ScriptPatchReadinessProjectionService readinessProjectionService, + ScriptReadinessCapacityService readinessCapacityService) { + this( + workItemService, + scriptDefinitionRepository, + handoffService, + workItemRepository, + auditRepository, + rolloutProjectionService, + outputProperties, + tenantBudgetService, + dryRunCapacityService, + objectMapper, + meterRegistry, + automationQueueService, + readinessProjectionService, + readinessCapacityService, + null, + null); + } + + /** Compatibility constructor for focused tests that provide readiness collaborators. */ public ScriptWorkItemExecutionServiceImpl( AutomationQueueService automationQueueService, ScriptWorkItemService workItemService, @@ -131,7 +184,48 @@ public ScriptWorkItemExecutionServiceImpl( meterRegistry, automationQueueService, readinessProjectionService, - readinessCapacityService); + readinessCapacityService, + null, + null); + } + + @org.springframework.beans.factory.annotation.Autowired + public ScriptWorkItemExecutionServiceImpl( + AutomationQueueService automationQueueService, + ScriptWorkItemService workItemService, + ScriptDefinitionRepository scriptDefinitionRepository, + ScriptGameplayCommandHandoffService handoffService, + ScriptWorkItemRepository workItemRepository, + ScriptEventAuditRepository auditRepository, + ScriptPatchInstanceRolloutProjectionService rolloutProjectionService, + ScriptOutputProperties outputProperties, + ScriptTenantBudgetService tenantBudgetService, + ScriptDryRunCapacityService dryRunCapacityService, + ScriptReadinessCapacityService readinessCapacityService, + ScriptPatchReadinessProjectionService readinessProjectionService, + ObjectMapper objectMapper, + MeterRegistry meterRegistry, + GameSessionControlPlaneClient gameSessionControlPlaneClient, + PluginRuntimeStateRepository pluginRuntimeStateRepository, + org.springframework.transaction.PlatformTransactionManager transactionManager) { + this( + workItemService, + scriptDefinitionRepository, + handoffService, + workItemRepository, + auditRepository, + rolloutProjectionService, + outputProperties, + tenantBudgetService, + dryRunCapacityService, + objectMapper, + meterRegistry, + automationQueueService, + readinessProjectionService, + readinessCapacityService, + gameSessionControlPlaneClient, + pluginRuntimeStateRepository, + transactionManager == null ? null : new TransactionTemplate(transactionManager)); } public ScriptWorkItemExecutionServiceImpl( @@ -160,6 +254,8 @@ public ScriptWorkItemExecutionServiceImpl( meterRegistry, null, null, + null, + null, null); } @@ -190,6 +286,8 @@ public ScriptWorkItemExecutionServiceImpl( meterRegistry, automationQueueService, null, + null, + null, null); } @@ -207,7 +305,47 @@ public ScriptWorkItemExecutionServiceImpl( MeterRegistry meterRegistry, AutomationQueueService automationQueueService, ScriptPatchReadinessProjectionService readinessProjectionService, - ScriptReadinessCapacityService readinessCapacityService) { + ScriptReadinessCapacityService readinessCapacityService, + GameSessionControlPlaneClient gameSessionControlPlaneClient, + PluginRuntimeStateRepository pluginRuntimeStateRepository) { + this( + workItemService, + scriptDefinitionRepository, + handoffService, + workItemRepository, + auditRepository, + rolloutProjectionService, + outputProperties, + tenantBudgetService, + dryRunCapacityService, + objectMapper, + meterRegistry, + automationQueueService, + readinessProjectionService, + readinessCapacityService, + gameSessionControlPlaneClient, + pluginRuntimeStateRepository, + null); + } + + private ScriptWorkItemExecutionServiceImpl( + ScriptWorkItemService workItemService, + ScriptDefinitionRepository scriptDefinitionRepository, + ScriptGameplayCommandHandoffService handoffService, + ScriptWorkItemRepository workItemRepository, + ScriptEventAuditRepository auditRepository, + ScriptPatchInstanceRolloutProjectionService rolloutProjectionService, + ScriptOutputProperties outputProperties, + ScriptTenantBudgetService tenantBudgetService, + ScriptDryRunCapacityService dryRunCapacityService, + ObjectMapper objectMapper, + MeterRegistry meterRegistry, + AutomationQueueService automationQueueService, + ScriptPatchReadinessProjectionService readinessProjectionService, + ScriptReadinessCapacityService readinessCapacityService, + GameSessionControlPlaneClient gameSessionControlPlaneClient, + PluginRuntimeStateRepository pluginRuntimeStateRepository, + TransactionTemplate transactionTemplate) { this.workItemService = workItemService; this.scriptDefinitionRepository = scriptDefinitionRepository; this.handoffService = handoffService; @@ -222,24 +360,47 @@ public ScriptWorkItemExecutionServiceImpl( this.meterRegistry = meterRegistry; this.automationQueueService = automationQueueService; this.readinessProjectionService = readinessProjectionService; + this.gameSessionControlPlaneClient = gameSessionControlPlaneClient; + this.pluginRuntimeStateRepository = pluginRuntimeStateRepository; + this.transactionTemplate = transactionTemplate; } @Override - @Transactional public ExecutionBatchResult processPendingWorkItems(int maxItems) { List claimed = claimWorkItems(maxItems); int completedCount = 0; int failedCount = 0; for (ScriptWorkItem workItem : claimed) { - if (processClaimedWorkItem(workItem)) { - completedCount++; - } else { + try { + if (processOneWorkItemInTransaction(workItem)) { + completedCount++; + } else { + failedCount++; + } + } catch (RuntimeException ex) { + // The claim is already EVALUATING, but this item lacks enough stage/effect evidence for + // an automatic disposition. Leave it unresolved until the target lease/recovery owner + // exists, while ensuring one bad item cannot abort the rest of this claimed batch. + LOGGER.error( + "Unexpected exception processing claimed script work item id={}; leaving unresolved", + workItem.getId(), + ex); failedCount++; } } return new ExecutionBatchResult(claimed.size(), completedCount, failedCount); } + /** Keeps each durable work-item transition and its remote calls in its own transaction. */ + private boolean processOneWorkItemInTransaction(ScriptWorkItem workItem) { + if (transactionTemplate == null) { + // Focused unit-test constructors intentionally have no transaction manager. + return processClaimedWorkItem(workItem); + } + Boolean result = transactionTemplate.execute(status -> processClaimedWorkItem(workItem)); + return Boolean.TRUE.equals(result); + } + private List claimWorkItems(int maxItems) { if (automationQueueService == null) { return workItemService.claimPendingForEvaluation(maxItems); @@ -273,6 +434,25 @@ private List claimWorkItems(int maxItems) { private boolean processClaimedWorkItem(ScriptWorkItem workItem) { Instant now = Instant.now(); + if (authorityUnavailableRetryExpired(workItem, now)) { + deadLetter( + workItem, + STAGE_ADMISSION, + OUTCOME_AUTHORITY_UNAVAILABLE_EXHAUSTED, + OUTCOME_AUTHORITY_UNAVAILABLE_EXHAUSTED, + now); + return false; + } + String fenceFailure = validateCurrentExecutionFences(workItem); + if (fenceFailure != null) { + if (isTerminalFenceFailure(fenceFailure)) { + cancel(workItem, STAGE_ADMISSION, "stale_execution_fenced", fenceFailure, now); + } else { + requeueAfterAuthorityUnavailable(workItem, fenceFailure, now); + } + return false; + } + clearAuthorityUnavailableRetryState(workItem); if (!workItem.isDryRun() && ScriptQuotaClasses.consumesLiveTenantBudget(workItem.getQuotaClass()) && !tenantBudgetService.tryReserve( @@ -312,6 +492,82 @@ private boolean processClaimedWorkItem(ScriptWorkItem workItem) { return evaluateClaimedWorkItem(workItem, now); } + /** + * Final Automation-side admission fence. Queue claims are intentionally not authority: the exact + * owner tuple is reread immediately before definition evaluation and any gameplay handoff. + * Missing pre-fence evidence is rejected, which keeps legacy rows fail closed. + */ + private String validateCurrentExecutionFences(ScriptWorkItem workItem) { + if (isOnLoad(workItem)) { + // Tenant-readiness onLoad is pre-instance-pin work and has no runtime pin fence. + return null; + } + String localFenceFailure = + ScriptWorkItemFenceEvaluationSupport.validateRuntimeIdentity(workItem); + if (localFenceFailure != null) { + return localFenceFailure; + } + if (gameSessionControlPlaneClient == null) { + // Compatibility constructors are used by isolated evaluator tests. The Spring production + // constructor always supplies both authority collaborators and therefore takes the strict + // branch below; keeping this seam local avoids making unit fixtures model remote authority. + return pluginRuntimeStateRepository == null + ? null + : "script_pin_authority_collaborator_unavailable"; + } + final GetGameInstanceRuntimeStateResponse runtime; + runtime = + gameSessionControlPlaneClient.getGameInstanceRuntimeState( + workItem.getTenantId(), workItem.getGameInstanceId(), workItem.getRegionId()); + String runtimeFailure = + ScriptWorkItemFenceEvaluationSupport.validateRuntimeState(workItem, runtime); + if (runtimeFailure != null) { + return runtimeFailure; + } + String pluginFailure = + ScriptWorkItemFenceEvaluationSupport.validateCapturedPluginFence(workItem); + if (pluginFailure != null) { + return pluginFailure; + } + if (ScriptWorkItemFenceEvaluationSupport.normalize(workItem.getPluginId()).isBlank()) { + return null; + } + if (pluginRuntimeStateRepository == null) { + return "plugin_lifecycle_collaborator_unavailable"; + } + String pluginId = ScriptWorkItemFenceEvaluationSupport.normalize(workItem.getPluginId()); + Optional plugin; + try { + plugin = + pluginRuntimeStateRepository.findByTenantIdAndGameInstanceIdAndPluginId( + workItem.getTenantId(), workItem.getGameInstanceId(), pluginId); + } catch (DataAccessException ex) { + if (isRepositoryUnavailable(ex)) { + return "plugin_lifecycle_collaborator_unavailable"; + } + return "plugin_lifecycle_evidence_unavailable"; + } + PluginState pluginState = null; + String activePluginVersionId = ""; + long pluginActivationEpoch = 0L; + long lifecycleRevision = 0L; + if (plugin.isPresent()) { + var state = plugin.orElseThrow(); + activePluginVersionId = state.getActivePluginVersionId(); + if (state.getPluginState() != null) { + try { + pluginState = PluginState.valueOf(state.getPluginState()); + } catch (IllegalArgumentException ex) { + pluginState = null; + } + } + pluginActivationEpoch = state.getPluginActivationEpoch(); + lifecycleRevision = state.getLifecycleRevision(); + } + return ScriptWorkItemFenceEvaluationSupport.validateCurrentPluginFence( + workItem, activePluginVersionId, pluginState, pluginActivationEpoch, lifecycleRevision); + } + private boolean evaluateClaimedWorkItem(ScriptWorkItem workItem, Instant now) { final long tenantId; try { @@ -370,6 +626,20 @@ private boolean evaluateClaimedWorkItem(ScriptWorkItem workItem, Instant now) { return true; } + // DSL evaluation is not the effect boundary. Re-read every authoritative execution fence + // after evaluation and immediately before the first gameplay handoff so a repin, plugin ABA, + // lifecycle transition, or policy revocation that won during evaluation cannot emit effects. + String handoffFenceFailure = validateCurrentExecutionFences(workItem); + if (handoffFenceFailure != null) { + if (isTerminalFenceFailure(handoffFenceFailure)) { + cancel(workItem, STAGE_ADMISSION, "stale_execution_fenced", handoffFenceFailure, now); + } else { + requeueAfterAuthorityUnavailable(workItem, handoffFenceFailure, now); + } + return false; + } + clearAuthorityUnavailableRetryState(workItem); + ScriptGameplayCommandHandoffService.HandoffResult firstRejectedHandoff = null; handoffService.beginAggregateFanout(workItem); try { @@ -414,6 +684,97 @@ private void requeueAfterRetryableHandoff(ScriptWorkItem workItem) { AutomationQueuePublicationSupport.enqueueAfterCommit(automationQueueService, workItem, LOGGER); } + private void requeueAfterAuthorityUnavailable( + ScriptWorkItem workItem, String reason, Instant now) { + Instant firstUnavailableAt = workItem.getAuthorityUnavailableSince(); + if (firstUnavailableAt == null) { + firstUnavailableAt = now; + } + int priorCount = Math.max(0, workItem.getAuthorityUnavailableCount()); + int nextCount = + priorCount >= MAX_AUTHORITY_UNAVAILABLE_OUTCOMES + ? MAX_AUTHORITY_UNAVAILABLE_OUTCOMES + : priorCount + 1; + workItem.setAuthorityUnavailableSince(firstUnavailableAt); + workItem.setAuthorityUnavailableCount(nextCount); + if (nextCount >= MAX_AUTHORITY_UNAVAILABLE_OUTCOMES + || !now.isBefore(firstUnavailableAt.plus(AUTHORITY_UNAVAILABLE_MAX_AGE))) { + deadLetter( + workItem, + STAGE_ADMISSION, + OUTCOME_AUTHORITY_UNAVAILABLE_EXHAUSTED, + OUTCOME_AUTHORITY_UNAVAILABLE_EXHAUSTED, + now); + return; + } + workItem.setStatus("PENDING_EVALUATION"); + workItem.setCancelReason(reason); + workItem.setNextEligibleAt(now.plus(AUTHORITY_UNAVAILABLE_RETRY_DELAY)); + workItem.setUpdatedAt(now); + workItemRepository.save(workItem); + rolloutProjectionService.refreshForWorkItem(workItem); + // Do not immediately republish while the authority is unavailable: that creates a hot loop + // against the same unavailable dependency. The durable pending row is picked up by the next + // executor scan once authority recovers. + } + + /** Clears an outage budget after a fresh fence read succeeds. */ + private void clearAuthorityUnavailableRetryState(ScriptWorkItem workItem) { + if (workItem.getAuthorityUnavailableSince() == null + && workItem.getAuthorityUnavailableCount() == 0 + && workItem.getNextEligibleAt() == null) { + return; + } + workItem.setAuthorityUnavailableSince(null); + workItem.setAuthorityUnavailableCount(0); + workItem.setNextEligibleAt(null); + workItemRepository.save(workItem); + } + + private static boolean isRepositoryUnavailable(DataAccessException exception) { + Throwable cause = exception; + while (cause != null) { + if (cause instanceof SQLTransientException + || cause instanceof SQLRecoverableException + || cause instanceof ConnectException + || cause instanceof SocketTimeoutException) { + return true; + } + if (cause instanceof SQLException sqlException) { + String sqlState = sqlException.getSQLState(); + if (sqlState != null && sqlState.startsWith("08")) { + return true; + } + } + cause = cause.getCause(); + } + return false; + } + + private static boolean authorityUnavailableRetryExpired(ScriptWorkItem workItem, Instant now) { + Instant firstUnavailableAt = workItem.getAuthorityUnavailableSince(); + return firstUnavailableAt != null + && !now.isBefore(firstUnavailableAt.plus(AUTHORITY_UNAVAILABLE_MAX_AGE)); + } + + private static boolean isTerminalFenceFailure(String reason) { + return switch (reason) { + case "script_patch_version_mismatch", + "script_pin_epoch_mismatch", + "script_pin_epoch_unavailable", + "runtime_scope_missing", + "runtime_scope_changed", + "plugin_disabled", + "plugin_version_mismatch", + "plugin_activation_epoch_mismatch", + "plugin_binding_mismatch", + "plugin_lifecycle_revision_mismatch", + "plugin_lifecycle_evidence_unavailable" -> + true; + default -> false; + }; + } + private static long requireWorkItemId(ScriptWorkItem workItem) { if (workItem.getId() == null) { throw new IllegalArgumentException("work_item_id is required for dry-run capacity"); @@ -781,8 +1142,12 @@ private static String render(String template, Map variables) { private void deadLetter( ScriptWorkItem workItem, String stage, String outcome, String reason, Instant now) { + if (!STATUS_DEAD_LETTERED.equals(workItem.getStatus())) { + workItem.setFailureGeneration(Math.addExact(workItem.getFailureGeneration(), 1L)); + } workItem.setStatus(STATUS_DEAD_LETTERED); workItem.setCancelReason(reason); + workItem.setNextEligibleAt(null); workItem.setUpdatedAt(now); workItemRepository.save(workItem); rolloutProjectionService.refreshForWorkItem(workItem); @@ -795,6 +1160,7 @@ private void cancel( ScriptWorkItem workItem, String stage, String outcome, String reason, Instant now) { workItem.setStatus(STATUS_CANCELED); workItem.setCancelReason(reason); + workItem.setNextEligibleAt(null); workItem.setUpdatedAt(now); workItemRepository.save(workItem); rolloutProjectionService.refreshForWorkItem(workItem); @@ -807,6 +1173,7 @@ private void markTerminalSuccess( ScriptWorkItem workItem, String stage, String outcome, String reason, Instant now) { workItem.setStatus(STATUS_HANDED_OFF); workItem.setCancelReason(null); + workItem.setNextEligibleAt(null); workItem.setUpdatedAt(now); workItemRepository.save(workItem); rolloutProjectionService.refreshForWorkItem(workItem); diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java index 0450ccb384..6386a0f62b 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java @@ -1,17 +1,29 @@ package net.firedevops.firemud.automationscripting.service.impl; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.micrometer.core.instrument.Gauge; +import io.micrometer.core.instrument.MeterRegistry; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.time.temporal.ChronoUnit; +import java.util.ArrayList; import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import net.firedevops.firemud.automationscripting.client.GameDesignControlPlaneClient; +import net.firedevops.firemud.automationscripting.client.GameSessionControlPlaneClient; import net.firedevops.firemud.automationscripting.config.ScriptOutboxProperties; -import net.firedevops.firemud.automationscripting.entity.ScriptEventIngressAudit; import net.firedevops.firemud.automationscripting.entity.ScriptHandoffEvent; import net.firedevops.firemud.automationscripting.entity.ScriptWorkItem; +import net.firedevops.firemud.automationscripting.repository.ScriptDeadLetterReplayRepository; import net.firedevops.firemud.automationscripting.repository.ScriptEventAuditRepository; import net.firedevops.firemud.automationscripting.repository.ScriptEventIngressAuditRepository; import net.firedevops.firemud.automationscripting.repository.ScriptHandoffEventRepository; @@ -29,6 +41,7 @@ import net.firedevops.firemud.gamedesign.v1.GetPublishedScriptPatchVersionResponse; import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; +import net.firedevops.firemud.gamesession.v1.GetGameInstanceRuntimeStateResponse; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -44,13 +57,15 @@ public class ScriptWorkItemServiceImpl implements ScriptWorkItemService { private static final String STATUS_CANCELED = "CANCELED"; private static final String STATUS_HANDED_OFF = "HANDED_OFF"; private static final String STATUS_DEAD_LETTERED = "DEAD_LETTERED"; - private static final String STATUS_FAILED = "FAILED"; private static final String STATUS_HANDOFF_IN_FLIGHT = "HANDOFF_IN_FLIGHT"; private static final List CANCELABLE_STATUSES = List.of(STATUS_PENDING_EVALUATION); private static final List ACTIVE_DRAIN_STATUSES = List.of(STATUS_EVALUATING, STATUS_HANDOFF_IN_FLIGHT); private static final List DRAIN_RELEVANT_STATUSES = List.of(STATUS_PENDING_EVALUATION, STATUS_EVALUATING, STATUS_HANDOFF_IN_FLIGHT); + private static final int CANCELLATION_PAGE_SIZE = 100; + private final AtomicLong retentionBlockedRows = new AtomicLong(); + private final MeterRegistry meterRegistry; private final ScriptWorkItemRepository workItemRepository; private final ScriptEventAuditRepository auditRepository; @@ -63,6 +78,8 @@ public class ScriptWorkItemServiceImpl implements ScriptWorkItemService { private final PluginRuntimeStateService pluginRuntimeStateService; private final GameDesignControlPlaneClient gameDesignControlPlaneClient; private final ScriptPatchReadinessProjectionService readinessProjectionService; + private final ScriptDeadLetterReplayRepository replayRepository; + private final GameSessionControlPlaneClient gameSessionControlPlaneClient; @org.springframework.beans.factory.annotation.Autowired public ScriptWorkItemServiceImpl( @@ -76,7 +93,10 @@ public ScriptWorkItemServiceImpl( ScriptPatchInstanceRolloutProjectionService rolloutProjectionService, PluginRuntimeStateService pluginRuntimeStateService, GameDesignControlPlaneClient gameDesignControlPlaneClient, - ScriptPatchReadinessProjectionService readinessProjectionService) { + ScriptPatchReadinessProjectionService readinessProjectionService, + ScriptDeadLetterReplayRepository replayRepository, + GameSessionControlPlaneClient gameSessionControlPlaneClient, + MeterRegistry meterRegistry) { this.workItemRepository = workItemRepository; this.auditRepository = auditRepository; this.ingressAuditRepository = ingressAuditRepository; @@ -88,58 +108,69 @@ public ScriptWorkItemServiceImpl( this.pluginRuntimeStateService = pluginRuntimeStateService; this.gameDesignControlPlaneClient = gameDesignControlPlaneClient; this.readinessProjectionService = readinessProjectionService; + this.replayRepository = replayRepository; + this.gameSessionControlPlaneClient = gameSessionControlPlaneClient; + this.meterRegistry = meterRegistry; + Gauge.builder("automation_retention_blocked_rows", retentionBlockedRows, AtomicLong::get) + .register(meterRegistry); } @Override @Transactional public long cancelPendingForPatch(CancelPendingForPatchCommand command) { - String normalizedTenantId = normalizeRegionId(command.tenantId()); + String normalizedTenantId = normalizeText(command.tenantId()); requireText(normalizedTenantId, "tenant_id"); requireText(command.scriptPatchVersion(), "script_patch_version"); - String normalizedGameInstanceId = normalizeRegionId(command.gameInstanceId()); - String normalizedRegionId = normalizeRegionId(command.regionId()); - List candidates = - workItemRepository - .findByTenantIdAndScriptPatchVersionAndStatusInOrderByCreatedAtAscIdAsc( - normalizedTenantId, command.scriptPatchVersion(), CANCELABLE_STATUSES) - .stream() - .filter( - item -> - normalizedGameInstanceId.isBlank() - || item.getGameInstanceId().equals(normalizedGameInstanceId)) - .filter( - item -> - normalizedRegionId.isBlank() || item.getRegionId().equals(normalizedRegionId)) - .toList(); - return cancelCandidates(candidates, command.reason()); + String normalizedGameInstanceId = normalizeText(command.gameInstanceId()); + String normalizedRegionId = normalizeText(command.regionId()); + long canceled = 0L; + while (true) { + List candidates = + workItemRepository + .findByTenantIdAndScriptPatchVersionAndStatusInForUpdateOrderByCreatedAtAscIdAsc( + normalizedTenantId, + command.scriptPatchVersion(), + normalizedGameInstanceId, + normalizedRegionId, + CANCELABLE_STATUSES); + if (candidates.isEmpty()) { + return canceled; + } + canceled += cancelCandidates(candidates, command.reason()); + if (candidates.size() < CANCELLATION_PAGE_SIZE) { + return canceled; + } + } } @Override @Transactional public long cancelPendingForPluginVersion(CancelPendingForPluginVersionCommand command) { - String normalizedTenantId = normalizeRegionId(command.tenantId()); + String normalizedTenantId = normalizeText(command.tenantId()); requireText(normalizedTenantId, "tenant_id"); requireText(command.pluginId(), "plugin_id"); requireText(command.pluginVersionId(), "plugin_version_id"); - String normalizedGameInstanceId = normalizeRegionId(command.gameInstanceId()); - String normalizedRegionId = normalizeRegionId(command.regionId()); - List candidates = - workItemRepository - .findByTenantIdAndPluginIdAndPluginVersionIdAndStatusInOrderByCreatedAtAscIdAsc( - normalizedTenantId, - command.pluginId(), - command.pluginVersionId(), - CANCELABLE_STATUSES) - .stream() - .filter( - item -> - normalizedGameInstanceId.isBlank() - || item.getGameInstanceId().equals(normalizedGameInstanceId)) - .filter( - item -> - normalizedRegionId.isBlank() || item.getRegionId().equals(normalizedRegionId)) - .toList(); - return cancelCandidates(candidates, command.reason()); + String normalizedGameInstanceId = normalizeText(command.gameInstanceId()); + String normalizedRegionId = normalizeText(command.regionId()); + long canceled = 0L; + while (true) { + List candidates = + workItemRepository + .findByTenantIdAndPluginIdAndPluginVersionIdAndStatusInForUpdateOrderByCreatedAtAscIdAsc( + normalizedTenantId, + command.pluginId(), + command.pluginVersionId(), + normalizedGameInstanceId, + normalizedRegionId, + CANCELABLE_STATUSES); + if (candidates.isEmpty()) { + return canceled; + } + canceled += cancelCandidates(candidates, command.reason()); + if (candidates.size() < CANCELLATION_PAGE_SIZE) { + return canceled; + } + } } private long cancelCandidates(List candidates, String rawReason) { @@ -160,7 +191,7 @@ public List claimPendingForEvaluation(int maxItems) { } Instant now = Instant.now(); List items = - workItemRepository.findByStatusOrderByCreatedAtAscIdAsc( + workItemRepository.findByStatusForUpdateOrderByCreatedAtAscIdAsc( STATUS_PENDING_EVALUATION, PageRequest.of(0, maxItems)); items.forEach( item -> { @@ -183,7 +214,7 @@ public List claimPendingForEvaluation(List workItemIds, in } Instant now = Instant.now(); List items = - workItemRepository.findByIdInAndStatusOrderByCreatedAtAscIdAsc( + workItemRepository.findByIdInAndStatusForUpdateOrderByCreatedAtAscIdAsc( workItemIds.stream().distinct().toList(), STATUS_PENDING_EVALUATION, PageRequest.of(0, maxItems)); @@ -201,6 +232,11 @@ public List claimPendingForEvaluation(List workItemIds, in @Transactional public TerminalCleanupResult cleanupTerminalWorkItems() { Instant now = Instant.now(); + // HANDED_OFF and CANCELED retain their established status-specific cleanup contract. A + // DEAD_LETTERED row is different: the current schema has no recovery aggregate, complete + // child ledger, or rollback/receipt horizon that can prove the whole bundle is disposable. + // Keep its parent and all supporting replay/audit/handoff evidence until that owner contract + // exists. In particular, do not turn configured age or row-count knobs into a guessed TTL. long handedOffDeleted = workItemRepository.deleteByStatusAndUpdatedAtBefore( STATUS_HANDED_OFF, @@ -209,11 +245,18 @@ public TerminalCleanupResult cleanupTerminalWorkItems() { workItemRepository.deleteByStatusAndUpdatedAtBefore( STATUS_CANCELED, now.minus(outboxProperties.getCanceledRetentionDays(), ChronoUnit.DAYS)); - long deadLetteredDeleted = - workItemRepository.deleteByStatusAndUpdatedAtBefore( - STATUS_DEAD_LETTERED, - now.minus(outboxProperties.getDeadLetterMaxAgeSeconds(), ChronoUnit.SECONDS)); - deadLetteredDeleted += deleteExcessDeadLetters(); + long deadLetteredDeleted = 0L; + long blocked = + workItemRepository.countTerminalRowsBlockedByEvidence( + STATUS_HANDED_OFF, + now.minus(outboxProperties.getHandedOffRetentionDays(), ChronoUnit.DAYS)) + + workItemRepository.countTerminalRowsBlockedByEvidence( + STATUS_CANCELED, + now.minus(outboxProperties.getCanceledRetentionDays(), ChronoUnit.DAYS)) + + workItemRepository.countTerminalRowsBlockedByEvidence( + STATUS_DEAD_LETTERED, + now.minus(outboxProperties.getDeadLetterMaxAgeSeconds(), ChronoUnit.SECONDS)); + retentionBlockedRows.set(blocked); return new TerminalCleanupResult(handedOffDeleted, canceledDeleted, deadLetteredDeleted); } @@ -265,15 +308,16 @@ public List listPatchStatuses( @Transactional(readOnly = true) public AutomationDrainStatusSummary getAutomationDrainStatus( String tenantId, String gameInstanceId, String regionId) { - String normalizedTenantId = normalizeRegionId(tenantId); + String normalizedTenantId = normalizeText(tenantId); requireText(normalizedTenantId, "tenant_id"); - String normalizedGameInstanceId = normalizeRegionId(gameInstanceId); + String normalizedGameInstanceId = normalizeText(gameInstanceId); requireText(normalizedGameInstanceId, "game_instance_id"); - String normalizedRegionId = normalizeRegionId(regionId); + String normalizedRegionId = normalizeText(regionId); Instant now = Instant.now(); Optional admissionStateLookup = automationAdmissionStateService.findState( normalizedTenantId, normalizedGameInstanceId, normalizedRegionId); + boolean statePresent = admissionStateLookup.isPresent(); AutomationAdmissionStateService.AdmissionStateSummary admissionState = admissionStateLookup.orElseGet( () -> @@ -298,14 +342,9 @@ public AutomationDrainStatusSummary getAutomationDrainStatus( normalizedRegionId, DRAIN_RELEVANT_STATUSES); List countedWorkItems = - "PAUSED_FOR_ROLLBACK".equals(admissionState.mode()) - ? scopedWorkItems.stream() - .filter( - item -> - item.getAdmissionEpoch() <= 0 - || item.getAdmissionEpoch() < admissionState.admissionEpoch()) - .toList() - : scopedWorkItems; + scopedWorkItems.stream() + .filter(item -> isEligibleForDrainStatus(item, admissionState)) + .toList(); long activeExecutionCount = countedWorkItems.stream() .filter(item -> ACTIVE_DRAIN_STATUSES.contains(item.getStatus())) @@ -325,7 +364,7 @@ public AutomationDrainStatusSummary getAutomationDrainStatus( normalizedTenantId, normalizedGameInstanceId, normalizedRegionId, - admissionStateLookup.isPresent(), + statePresent, admissionState.mode(), admissionState.admissionEpoch(), admissionState.controlPlaneRequestId(), @@ -339,6 +378,15 @@ public AutomationDrainStatusSummary getAutomationDrainStatus( now.toEpochMilli()); } + private static boolean isEligibleForDrainStatus( + ScriptWorkItem item, AutomationAdmissionStateService.AdmissionStateSummary admissionState) { + if ("PAUSED_FOR_ROLLBACK".equals(admissionState.mode())) { + return item.getAdmissionEpoch() <= 0 + || item.getAdmissionEpoch() < admissionState.admissionEpoch(); + } + return item.getAdmissionEpoch() == admissionState.admissionEpoch(); + } + @Override @Transactional(readOnly = true) public Optional getPatchInstanceRolloutStatus( @@ -445,13 +493,14 @@ public List listHandoffEvents( long changedAfterMs, long changedBeforeMs, int limit) { - requireText(tenantId, "tenant_id"); + String normalizedTenantId = normalizeText(tenantId); + requireText(normalizedTenantId, "tenant_id"); int boundedLimit = limit <= 0 ? 100 : Math.min(limit, 500); RoutingBundleSupport.RoutingBundle routingBundle = RoutingBundleSupport.normalize(worldSlug, realmSlug, pointerVersion); return handoffEventRepository .findEvents( - tenantId, + normalizedTenantId, blankToEmpty(gameInstanceId), blankToEmpty(scriptPatchVersion), parseOptionalWorkItemId(workItemId), @@ -477,7 +526,7 @@ public List listHandoffEvents( PageRequest.of(0, boundedLimit)) .stream() .map(ScriptWorkItemServiceImpl::toHandoffSummary) - .map(summary -> withPublication(tenantId, summary)) + .map(summary -> withPublication(normalizedTenantId, summary)) .toList(); } @@ -485,50 +534,266 @@ public List listHandoffEvents( @Transactional(readOnly = true) public List listDeadLetters( String tenantId, String gameInstanceId, String scriptPatchVersion, int limit) { - requireText(tenantId, "tenant_id"); + String normalizedTenantId = normalizeText(tenantId); + requireText(normalizedTenantId, "tenant_id"); int boundedLimit = Math.min(Math.max(limit <= 0 ? 50 : limit, 1), 500); - String normalizedGameInstanceId = normalizeRegionId(gameInstanceId); - String normalizedScriptPatchVersion = normalizeRegionId(scriptPatchVersion); + String normalizedGameInstanceId = normalizeText(gameInstanceId); + String normalizedScriptPatchVersion = normalizeText(scriptPatchVersion); return workItemRepository .findDeadLettersByTenantIdAndFiltersOrderByUpdatedAtDescIdDesc( - tenantId, + normalizedTenantId, normalizedGameInstanceId, normalizedScriptPatchVersion, STATUS_DEAD_LETTERED, PageRequest.of(0, boundedLimit)) .stream() .map(ScriptWorkItemServiceImpl::toDeadLetterSummary) - .map(summary -> withPublication(tenantId, summary)) + .map(summary -> withPublication(normalizedTenantId, summary)) .toList(); } @Override @Transactional public ReplayResult replayDeadLetters(ReplayDeadLettersCommand command) { - String normalizedTenantId = normalizeRegionId(command.tenantId()); + validateReplayCommand(command); + String normalizedTenantId = normalizeText(command.tenantId()); requireText(normalizedTenantId, "tenant_id"); - int boundedLimit = Math.min(Math.max(command.limit() <= 0 ? 50 : command.limit(), 1), 100); + int boundedLimit = command.workItemIds().size(); Instant now = Instant.now(); String reason = normalizeReplayReason(command.reason()); + String fingerprint = replayRequestFingerprint(command); + ScriptDeadLetterReplayRepository.ReplayRequest durableRequest = null; + Map priorResults = Map.of(); + if (replayRepository != null) { + durableRequest = + replayRepository.insertOrGet( + normalizedTenantId, + normalizeText(command.controlPlaneRequestId()), + fingerprint, + normalizeText(command.actorPrincipal()), + reason, + now); + if (!fingerprint.equals(durableRequest.requestFingerprint())) { + throw new IllegalArgumentException( + "control_plane_request_id already records a different replay request"); + } + priorResults = + replayRepository.findResults(durableRequest.id()).stream() + .collect( + Collectors.toMap( + ScriptDeadLetterReplayRepository.ReplayItem::requestedWorkItemId, + item -> item)); + if ("COMPLETED".equals(durableRequest.status())) { + return replayResultFromDurable(command, durableRequest, priorResults); + } + } List candidates = selectReplayCandidates(command, normalizedTenantId, boundedLimit); - long replayed = 0L; - long rejected = 0L; - for (ScriptWorkItem item : candidates) { - if (!eligibleForReplay(item)) { - rejected++; + Map byId = + candidates.stream().collect(Collectors.toMap(ScriptWorkItem::getId, item -> item)); + List results = new ArrayList<>(); + Map> runtimeStateCache = + new HashMap<>(); + for (String requestedId : command.workItemIds()) { + long requestedLongId = parseWorkItemId(requestedId); + ScriptDeadLetterReplayRepository.ReplayItem prior = priorResults.get(requestedLongId); + if (prior != null) { + results.add(toReplayItemResult(requestedId, prior)); + continue; + } + ScriptWorkItem item = byId.get(requestedLongId); + if (item == null) { + results.add(new ReplayItemResult(requestedId, "rejected", "not_found_or_not_owned", 0L)); + persistReplayResult( + durableRequest, + requestedLongId, + "rejected", + "not_found_or_not_owned", + null, + OriginalFailureEvidence.EMPTY, + now); + continue; + } + // Read the mutable failure evidence before the claim changes the work-item status. The + // immutable replay result is the generation-bound receipt that survives later execution + // updates to both the work item and its audit row. + OriginalFailureEvidence originalFailure = originalFailureEvidence(item); + if (!STATUS_DEAD_LETTERED.equals(item.getStatus())) { + String reasonForCurrentStatus = + switch (blankToEmpty(item.getStatus())) { + case STATUS_PENDING_EVALUATION, STATUS_EVALUATING, STATUS_HANDOFF_IN_FLIGHT -> + "recovery_in_progress"; + default -> "work_item_not_dead_lettered"; + }; + results.add( + new ReplayItemResult( + requestedId, "rejected", reasonForCurrentStatus, item.getFailureGeneration())); + persistReplayResult( + durableRequest, + requestedLongId, + "rejected", + reasonForCurrentStatus, + item, + originalFailure, + now); continue; } - item.setStatus(STATUS_PENDING_EVALUATION); - item.setCancelReason(""); - item.setUpdatedAt(now); - workItemRepository.save(item); + String replayRejection = replayEligibilityReason(item, runtimeStateCache); + if (replayRejection != null) { + results.add( + new ReplayItemResult( + requestedId, "rejected", replayRejection, item.getFailureGeneration())); + persistReplayResult( + durableRequest, + requestedLongId, + "rejected", + replayRejection, + item, + originalFailure, + now); + continue; + } + if (!originalFailure.isComplete()) { + // A dead-letter row without both immutable failure dimensions cannot be safely replayed: + // accepting it would lose the original stage/reason as soon as later execution updates + // the mutable work item or audit row. Keep the row untouched and persist only the bounded + // rejection receipt. + results.add( + new ReplayItemResult( + requestedId, + "rejected", + "stage_evidence_unavailable", + item.getFailureGeneration())); + persistReplayResult( + durableRequest, + requestedLongId, + "rejected", + "stage_evidence_unavailable", + item, + originalFailure, + now); + continue; + } + Optional claimed = + workItemRepository.claimDeadLetterForReplay( + item.getId(), + item.getTenantId(), + item.getRowVersion(), + item.getFailureGeneration(), + now); + if (claimed.isEmpty()) { + results.add( + new ReplayItemResult( + requestedId, "rejected", "recovery_in_progress", item.getFailureGeneration())); + persistReplayResult( + durableRequest, + requestedLongId, + "rejected", + "recovery_in_progress", + item, + originalFailure, + now); + continue; + } + item = claimed.orElseThrow(); refreshReadinessProjectionIfNeeded(item); rolloutProjectionService.refreshForWorkItem(item); - markReplayQueued(item.getId(), reason, now); - replayed++; + results.add( + new ReplayItemResult(requestedId, "retried_evaluation", "", item.getFailureGeneration())); + persistReplayResult( + durableRequest, requestedLongId, "retried_evaluation", "", item, originalFailure, now); + } + ReplayCounts counts = replayCounts(results); + if (durableRequest != null) { + boolean completionWon = + replayRepository.complete(durableRequest.id(), counts.replayed(), counts.rejected(), now); + if (!completionWon) { + Optional completedRequest = + replayRepository.findRequest( + normalizedTenantId, normalizeText(command.controlPlaneRequestId())); + if (completedRequest.filter(request -> "COMPLETED".equals(request.status())).isPresent()) { + return replayResultFromDurable( + command, + completedRequest.orElseThrow(), + replayRepository.findResults(durableRequest.id()).stream() + .collect( + Collectors.toMap( + ScriptDeadLetterReplayRepository.ReplayItem::requestedWorkItemId, + item -> item))); + } + } + } + return new ReplayResult(counts.replayed(), counts.rejected(), results, fingerprint); + } + + private static void validateReplayCommand(ReplayDeadLettersCommand command) { + if (command == null) { + throw new IllegalArgumentException("replay_request_required"); + } + if (command.workItemIds() == null || command.workItemIds().isEmpty()) { + throw new IllegalArgumentException("invalid_work_item_ids"); + } + if (command.workItemIds().size() > 100) { + throw new IllegalArgumentException("work_item_ids_limit_exceeded"); + } + Set ids = new HashSet<>(); + Set parsedIds = new HashSet<>(); + for (String id : command.workItemIds()) { + if (id == null || id.isBlank() || !ids.add(id.strip())) { + throw new IllegalArgumentException("invalid_work_item_ids"); + } + if (!parsedIds.add(parseWorkItemId(id))) { + throw new IllegalArgumentException("invalid_work_item_ids"); + } + } + if (!blankToEmpty(command.gameInstanceId()).isBlank() + || !blankToEmpty(command.regionId()).isBlank() + || !blankToEmpty(command.scriptPatchVersion()).isBlank() + || command.createdAfterMs() > 0 + || command.createdBeforeMs() > 0) { + throw new IllegalArgumentException("replay_filters_require_preview"); + } + if (blankToEmpty(command.controlPlaneRequestId()).isBlank()) { + throw new IllegalArgumentException("control_plane_request_id is required"); + } + } + + private static String replayRequestFingerprint(ReplayDeadLettersCommand command) { + List normalizedWorkItemIds = + command.workItemIds().stream() + // Work-item IDs are numeric identities. Canonicalize accepted alternate spellings + // (for example, 01 and +1) before sorting and hashing so an exact logical retry does + // not become an idempotency conflict. + .map(id -> Long.toString(parseWorkItemId(id))) + .sorted() + .toList(); + // replayDeadLetteredWorkItems/v1 uses UTF-8 byte-length framing. The version label is part of + // the preimage so a future encoding change cannot silently reinterpret retained fingerprints. + StringBuilder canonical = new StringBuilder(); + appendReplayFingerprintSegment(canonical, "replayDeadLetteredWorkItems/v1"); + appendReplayFingerprintSegment(canonical, normalizeText(command.tenantId())); + appendReplayFingerprintSegment(canonical, Integer.toString(normalizedWorkItemIds.size())); + normalizedWorkItemIds.forEach(id -> appendReplayFingerprintSegment(canonical, id)); + appendReplayFingerprintSegment(canonical, normalizeText(command.controlPlaneRequestId())); + appendReplayFingerprintSegment(canonical, normalizeText(command.actorPrincipal())); + appendReplayFingerprintSegment(canonical, normalizeReplayReason(command.reason())); + try { + byte[] digest = + MessageDigest.getInstance("SHA-256") + .digest(canonical.toString().getBytes(StandardCharsets.UTF_8)); + StringBuilder fingerprint = new StringBuilder(digest.length * 2); + for (byte value : digest) { + fingerprint.append(String.format("%02x", value)); + } + return fingerprint.toString(); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is required for replay request identity", e); } - return new ReplayResult(replayed, rejected); + } + + private static void appendReplayFingerprintSegment(StringBuilder canonical, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + canonical.append(bytes.length).append(':').append(value); } private PatchInstanceRolloutSummary withPublication( @@ -740,7 +1005,7 @@ private static String blankToEmpty(String value) { return value == null ? "" : value; } - private static String normalizeRegionId(String value) { + private static String normalizeText(String value) { return value == null || value.isBlank() ? "" : value.strip(); } @@ -852,7 +1117,6 @@ private List selectReplayCandidates( .map(workItemRepository::findById) .flatMap(Optional::stream) .filter(item -> normalizedTenantId.equals(item.getTenantId())) - .filter(item -> STATUS_DEAD_LETTERED.equals(item.getStatus())) .filter(item -> matchesReplayFilters(item, command)) .toList(); } @@ -865,8 +1129,8 @@ private List selectReplayCandidates( } private boolean matchesReplayFilters(ScriptWorkItem item, ReplayDeadLettersCommand command) { - String normalizedGameInstanceId = normalizeRegionId(command.gameInstanceId()); - String normalizedRegionId = normalizeRegionId(command.regionId()); + String normalizedGameInstanceId = normalizeText(command.gameInstanceId()); + String normalizedRegionId = normalizeText(command.regionId()); return (normalizedGameInstanceId.isBlank() || item.getGameInstanceId().equals(normalizedGameInstanceId)) && (normalizedRegionId.isBlank() || item.getRegionId().equals(normalizedRegionId)) @@ -879,72 +1143,173 @@ private boolean matchesReplayFilters(ScriptWorkItem item, ReplayDeadLettersComma || item.getCreatedAt().toEpochMilli() <= command.createdBeforeMs()); } - private boolean eligibleForReplay(ScriptWorkItem item) { + private String replayEligibilityReason( + ScriptWorkItem item, + Map> runtimeStateCache) { if ("onLoad".equals(item.getEventType())) { - return eligibleForOnLoadReplay(item); + return "onload_not_replayable"; + } + String localFenceFailure = ScriptWorkItemFenceEvaluationSupport.validateRuntimeIdentity(item); + if (localFenceFailure != null) { + return localFenceFailure; + } + if (gameSessionControlPlaneClient == null) { + return "script_pin_authority_collaborator_unavailable"; + } + RuntimeScopeKey runtimeScopeKey = + new RuntimeScopeKey(item.getTenantId(), item.getGameInstanceId(), item.getRegionId()); + Optional cachedRuntime = + runtimeStateCache.computeIfAbsent( + runtimeScopeKey, + ignored -> { + try { + return Optional.ofNullable( + gameSessionControlPlaneClient.getGameInstanceRuntimeState( + item.getTenantId(), item.getGameInstanceId(), item.getRegionId())); + } catch (RuntimeException ex) { + return Optional.empty(); + } + }); + if (cachedRuntime.isEmpty()) { + return "script_pin_authority_unavailable"; + } + GetGameInstanceRuntimeStateResponse runtime = cachedRuntime.orElseThrow(); + String runtimeFailure = + ScriptWorkItemFenceEvaluationSupport.validateRuntimeState(item, runtime); + if (runtimeFailure != null) { + return runtimeFailure; + } + String capturedPluginFailure = + ScriptWorkItemFenceEvaluationSupport.validateCapturedPluginFence(item); + if (capturedPluginFailure != null) { + return capturedPluginFailure; + } + if (ScriptWorkItemFenceEvaluationSupport.normalize(item.getPluginId()).isBlank()) { + return null; + } + if (pluginRuntimeStateService == null) { + return "plugin_lifecycle_collaborator_unavailable"; } - return eligibleForRuntimeReplay(item); + String pluginId = ScriptWorkItemFenceEvaluationSupport.normalize(item.getPluginId()); + var plugin = + pluginRuntimeStateService.getStatus(item.getTenantId(), item.getGameInstanceId(), pluginId); + return ScriptWorkItemFenceEvaluationSupport.validateCurrentPluginFence( + item, + plugin.map(PluginRuntimeStateService.PluginRuntimeStatus::activePluginVersionId).orElse(""), + plugin.map(PluginRuntimeStateService.PluginRuntimeStatus::pluginState).orElse(null), + plugin.map(PluginRuntimeStateService.PluginRuntimeStatus::pluginActivationEpoch).orElse(0L), + plugin.map(PluginRuntimeStateService.PluginRuntimeStatus::lifecycleRevision).orElse(0L)); } - private boolean eligibleForOnLoadReplay(ScriptWorkItem item) { - return readinessProjectionService - .getProjection(item.getTenantId(), item.getScriptPatchVersion()) - .filter(summary -> summary.status() == ScriptPatchStatus.SCRIPT_PATCH_STATUS_FAILED) - .filter(summary -> summary.supersededByScriptPatchVersion().isBlank()) - .isPresent(); + private void persistReplayResult( + ScriptDeadLetterReplayRepository.ReplayRequest request, + long requestedWorkItemId, + String outcome, + String rejectionReason, + ScriptWorkItem item, + OriginalFailureEvidence originalFailure, + Instant now) { + if (request == null) { + return; + } + replayRepository.saveResult( + request.id(), + requestedWorkItemId, + item == null ? null : item.getId(), + outcome, + rejectionReason, + "", + item == null ? 0L : item.getScriptPinEpoch(), + item == null ? 0L : item.getPluginActivationEpoch(), + item == null ? 0L : item.getLifecycleRevision(), + item == null ? 0L : item.getFailureGeneration(), + originalFailure.stage(), + originalFailure.reason(), + now); } - private boolean eligibleForRuntimeReplay(ScriptWorkItem item) { - Optional runtime = - scriptPatchPinProjectionService - .getPinConvergence(item.getTenantId(), item.getGameInstanceId()) - .summary(); - if (runtime.isEmpty() || runtime.get().projectionStale()) { - return false; + private OriginalFailureEvidence originalFailureEvidence(ScriptWorkItem item) { + if (item == null || item.getId() == null) { + return OriginalFailureEvidence.EMPTY; } - if (item.getScriptPinEpoch() <= 0 - || runtime.get().scriptPinEpoch() <= 0 - || !item.getScriptPatchVersion().equals(runtime.get().observedPinnedScriptPatchVersion()) - || item.getScriptPinEpoch() != runtime.get().scriptPinEpoch() - || blankToEmpty(item.getScriptPinControlPlaneRequestId()).isBlank() - || blankToEmpty(runtime.get().lastObservedControlPlaneRequestId()).isBlank() - || !item.getScriptPinControlPlaneRequestId() - .equals(runtime.get().lastObservedControlPlaneRequestId())) { - return false; + String workItemReason = blankToEmpty(item.getCancelReason()); + return auditRepository + .findByWorkItemId(item.getId()) + .map( + audit -> { + String auditReason = blankToEmpty(audit.getFinalReason()); + boolean consistent = + auditReason.isBlank() + || workItemReason.isBlank() + || auditReason.equals(workItemReason); + return new OriginalFailureEvidence( + blankToEmpty(audit.getFinalStage()), + firstNonBlank(auditReason, workItemReason), + consistent); + }) + .orElse(new OriginalFailureEvidence("", workItemReason, true)); + } + + private static String firstNonBlank(String preferred, String fallback) { + return preferred != null && !preferred.isBlank() ? preferred : blankToEmpty(fallback); + } + + private ReplayResult replayResultFromDurable( + ReplayDeadLettersCommand command, + ScriptDeadLetterReplayRepository.ReplayRequest request, + Map persisted) { + List results = + command.workItemIds().stream() + .map( + id -> { + ScriptDeadLetterReplayRepository.ReplayItem result = + persisted.get(parseWorkItemId(id)); + return result == null + ? new ReplayItemResult(id, "rejected", "replay_result_missing", 0L) + : toReplayItemResult(id, result); + }) + .toList(); + ReplayCounts counts = replayCounts(results); + return new ReplayResult( + counts.replayed(), counts.rejected(), results, request.requestFingerprint()); + } + + private static ReplayCounts replayCounts(List results) { + long replayed = + results.stream() + .filter( + result -> + "retried_evaluation".equals(result.outcome()) + || "resumed_dispatch".equals(result.outcome())) + .count(); + long rejected = results.stream().filter(result -> "rejected".equals(result.outcome())).count(); + return new ReplayCounts(replayed, rejected); + } + + private record ReplayCounts(long replayed, long rejected) {} + + private static ReplayItemResult toReplayItemResult( + String requestedId, ScriptDeadLetterReplayRepository.ReplayItem stored) { + String outcome = blankToEmpty(stored.outcome()); + String rejectionReason = normalizeText(stored.rejectionReason()); + String failureReason = normalizeText(stored.failureReason()); + if ("retried_evaluation".equals(outcome) + || "resumed_dispatch".equals(outcome) + || "already_recovered".equals(outcome) + || "recovery_failed".equals(outcome)) { + return new ReplayItemResult( + requestedId, outcome, rejectionReason, failureReason, stored.failureGeneration()); } - String pluginId = blankToEmpty(item.getPluginId()); - String pluginVersionId = blankToEmpty(item.getPluginVersionId()); - if (pluginId.isBlank()) { - Optional audit = - ingressAuditRepository - .findByTenantIdAndGameInstanceIdAndRegionIdAndRegionEpochAndEntityIdAndPlayableStateScopeAndEventTypeAndEventSchemaVersionAndScriptPatchVersionAndScriptPinEpochAndScriptPinControlPlaneRequestIdAndScriptEventIdAndDryRunAndSourceService( - item.getTenantId(), - item.getGameInstanceId(), - item.getRegionId(), - item.getRegionEpoch(), - item.getEntityId(), - blankToEmpty(item.getPlayableStateScope()), - item.getEventType(), - item.getEventSchemaVersion(), - item.getScriptPatchVersion(), - item.getScriptPinEpoch(), - item.getScriptPinControlPlaneRequestId(), - item.getScriptEventId(), - item.isDryRun(), - blankToEmpty(item.getSourceService())); - if (audit.isEmpty() - || audit.get().getPluginId() == null - || audit.get().getPluginId().isBlank()) { - return true; - } - pluginId = audit.get().getPluginId(); - pluginVersionId = blankToEmpty(audit.get().getPluginVersionId()); + if ("retried_evaluation_unknown".equals(outcome)) { + return new ReplayItemResult( + requestedId, "rejected", "stage_evidence_unavailable", "", stored.failureGeneration()); } - String requiredPluginVersionId = pluginVersionId; - return pluginRuntimeStateService - .getStatus(item.getTenantId(), item.getGameInstanceId(), pluginId) - .map(status -> status.activePluginVersionId().equals(requiredPluginVersionId)) - .orElse(false); + return new ReplayItemResult( + requestedId, + "rejected", + rejectionReason.isBlank() ? "stage_evidence_unavailable" : rejectionReason, + "", + stored.failureGeneration()); } private void refreshReadinessProjectionIfNeeded(ScriptWorkItem item) { @@ -968,29 +1333,6 @@ private void refreshReadinessProjectionsIfNeeded(List items) { }); } - private void markReplayQueued(Long workItemId, String reason, Instant now) { - auditRepository - .findByWorkItemId(workItemId) - .ifPresent( - audit -> { - audit.setFinalStage("REPLAY"); - audit.setFinalOutcome("requeued"); - audit.setFinalReason(reason); - audit.setUpdatedAt(now); - auditRepository.save(audit); - }); - } - - private long deleteExcessDeadLetters() { - long deadLetteredCount = workItemRepository.countByStatus(STATUS_DEAD_LETTERED); - long excess = deadLetteredCount - outboxProperties.getDeadLetterMaxRows(); - if (excess <= 0) { - return 0; - } - int batchSize = Math.toIntExact(Math.min(excess, Integer.MAX_VALUE)); - return workItemRepository.deleteOldestByStatus(STATUS_DEAD_LETTERED, batchSize); - } - private void cancel(ScriptWorkItem item, String reason, Instant now) { item.setStatus(STATUS_CANCELED); item.setCancelReason(reason); @@ -1007,12 +1349,27 @@ private void cancel(ScriptWorkItem item, String reason, Instant now) { }); } + private record RuntimeScopeKey(String tenantId, String gameInstanceId, String regionId) {} + + private record OriginalFailureEvidence(String stage, String reason, boolean consistent) { + private static final OriginalFailureEvidence EMPTY = new OriginalFailureEvidence("", "", true); + + private OriginalFailureEvidence { + stage = blankToEmpty(stage); + reason = blankToEmpty(reason); + } + + private boolean isComplete() { + return consistent && !stage.isBlank() && !reason.isBlank(); + } + } + private static String normalizeReason(String reason) { return reason == null || reason.isBlank() ? "operator_cancel" : reason; } private static String normalizeReplayReason(String reason) { - return reason == null || reason.isBlank() ? "operator_replay" : reason; + return reason == null || reason.isBlank() ? "operator_replay" : reason.strip(); } private static void requireText(String value, String fieldName) { diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/AutomationScriptingServiceApplicationIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/AutomationScriptingServiceApplicationIntegrationTest.java index 87056605e0..1862ef9978 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/AutomationScriptingServiceApplicationIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/AutomationScriptingServiceApplicationIntegrationTest.java @@ -1,19 +1,51 @@ package net.firedevops.firemud.automationscripting; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collection; import java.util.List; import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.automationscripting.dto.ScriptDefinitionDto; +import net.firedevops.firemud.automationscripting.entity.ScriptDefinition; +import net.firedevops.firemud.automationscripting.entity.ScriptEventBinding; +import net.firedevops.firemud.automationscripting.entity.ScriptEventIngressAudit; +import net.firedevops.firemud.automationscripting.entity.ScriptHandoffEvent; +import net.firedevops.firemud.automationscripting.entity.ScriptWorkItem; +import net.firedevops.firemud.automationscripting.mapper.ScriptDefinitionMapper; +import net.firedevops.firemud.automationscripting.repository.ScriptDefinitionRepository; +import net.firedevops.firemud.automationscripting.repository.ScriptEventBindingRepository; +import net.firedevops.firemud.automationscripting.repository.ScriptEventIngressAuditRepository; +import net.firedevops.firemud.automationscripting.repository.ScriptHandoffEventRepository; +import net.firedevops.firemud.automationscripting.repository.ScriptWorkItemRepository; +import net.firedevops.firemud.automationscripting.service.impl.BuiltInScriptEventRegistryService; +import net.firedevops.firemud.automationscripting.service.impl.ScriptDefinitionServiceImpl; +import net.firedevops.firemud.common.saga.SagaException; +import net.firedevops.firemud.common.saga.SagaRunner; import net.firedevops.firemud.common.security.JwtUtil; import net.firedevops.firemud.test.GatewayTestProperties; import net.firedevops.firemud.test.HttpTestSupport; import net.firedevops.firemud.test.NoGrpcServerTestConfiguration; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.mapstruct.factory.Mappers; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; @@ -63,6 +95,34 @@ static void configure(DynamicPropertyRegistry registry) { @LocalServerPort private int port; + private final List barrierExecutors = new ArrayList<>(); + + @AfterEach + void shutdownBarrierExecutors() { + barrierExecutors.forEach(ExecutorService::shutdownNow); + barrierExecutors.clear(); + } + + private ExecutorService barrierExecutor() { + ExecutorService executor = Executors.newFixedThreadPool(2); + barrierExecutors.add(executor); + return executor; + } + + @Autowired private ScriptWorkItemRepository scriptWorkItemRepository; + + @Autowired private ScriptEventIngressAuditRepository scriptEventIngressAuditRepository; + + @Autowired private ScriptDefinitionRepository scriptDefinitionRepository; + + @Autowired private ScriptEventBindingRepository scriptEventBindingRepository; + + @Autowired private DSLContext dsl; + + @Autowired private SagaRunner sagaRunner; + + @Autowired private ScriptHandoffEventRepository scriptHandoffEventRepository; + @Test void pingEndpointReturnsPong() { String body = HttpTestSupport.getBodyUnchecked("http://localhost:" + port + "/ping"); @@ -103,19 +163,447 @@ void unsupportedFormationRestRoutesRejectCrossTenantSelectorsByBeingAbsent() thr void removedFactionRestEndpointReturnsNotFound() throws Exception { String token = JWT_UTIL.generateToken( - "automation-test", Map.of("globalRoles", java.util.List.of("platformAdmin"))); + "automation-test", Map.of("scopedRoles", Map.of("1", List.of("tenantAdmin")))); HttpRequest request = HttpRequest.newBuilder( - URI.create( - "http://localhost:" - + port - + "/factions/1/reputation?tenantId=1&characterId=2&gameInstanceId=GI-1&playableStateScope=NOPE&delta=1")) + URI.create("http://localhost:" + port + "/formations/7/members?tenantId=2")) .header("Authorization", "Bearer " + token) - .method("PATCH", HttpRequest.BodyPublishers.noBody()) + .GET() .build(); HttpResponse response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); assertThat(response.statusCode()).isEqualTo(404); } + + @Test + void concurrentPostgresTriggerIdentityInsertReturnsOneWinnerAndOneExistingRow() throws Exception { + String scriptEventId = "event-concurrent-" + UUID.randomUUID(); + ScriptWorkItem first = concurrentIdentityWorkItem(scriptEventId); + ScriptWorkItem second = concurrentIdentityWorkItem(scriptEventId); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = barrierExecutor(); + CompletableFuture left = + CompletableFuture.supplyAsync(() -> insertAfterBarrier(first, ready, start), executor); + CompletableFuture right = + CompletableFuture.supplyAsync(() -> insertAfterBarrier(second, ready, start), executor); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + ScriptWorkItemRepository.IdempotentInsertResult leftResult = left.get(30, TimeUnit.SECONDS); + ScriptWorkItemRepository.IdempotentInsertResult rightResult = right.get(30, TimeUnit.SECONDS); + + assertThat( + List.of(leftResult, rightResult).stream() + .filter(ScriptWorkItemRepository.IdempotentInsertResult::inserted)) + .hasSize(1); + assertThat(leftResult.workItem().getId()).isEqualTo(rightResult.workItem().getId()); + } + + @Test + void concurrentPostgresNullableIngressIdentityInsertReturnsOneWinnerAndOneExistingRow() + throws Exception { + String scriptEventId = "event-nullable-" + UUID.randomUUID(); + ScriptEventIngressAudit first = concurrentNullableIngressAudit(scriptEventId); + ScriptEventIngressAudit second = concurrentNullableIngressAudit(scriptEventId); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = barrierExecutor(); + CompletableFuture left = + CompletableFuture.supplyAsync( + () -> insertIngressAfterBarrier(first, ready, start), executor); + CompletableFuture right = + CompletableFuture.supplyAsync( + () -> insertIngressAfterBarrier(second, ready, start), executor); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + var leftResult = left.get(30, TimeUnit.SECONDS); + var rightResult = right.get(30, TimeUnit.SECONDS); + + assertThat(List.of(leftResult, rightResult).stream().filter(result -> result.inserted())) + .hasSize(1); + assertThat(leftResult.audit().getId()).isEqualTo(rightResult.audit().getId()); + } + + @Test + void updateScriptRetryAndChangedInputReuseOneStableDefinitionRow() { + String name = "script-definition-" + UUID.randomUUID(); + ScriptDefinition initial = scriptDefinition(name, "{}"); + ScriptDefinition first = scriptDefinitionRepository.save(initial); + + ScriptDefinition exactRetry = scriptDefinition(name, "{}"); + ScriptDefinition retried = scriptDefinitionRepository.save(exactRetry); + assertThat(retried.getId()).isEqualTo(first.getId()); + assertThat(first.getRowVersion()).isZero(); + assertThat(retried.getRowVersion()).isEqualTo(first.getRowVersion()); + + ScriptDefinition changed = scriptDefinitionRepository.save(scriptDefinition(name, "{\"v\":2}")); + assertThat(changed.getId()).isEqualTo(first.getId()); + assertThat(changed.getRowVersion()).isEqualTo(first.getRowVersion() + 1); + assertThat( + scriptDefinitionRepository + .findByTenantIdAndScriptVersionAndName(1L, "patch-definition", name) + .orElseThrow() + .getDefinition()) + .isEqualTo("{\"v\":2}"); + } + + @Test + void concurrentPostgresDefinitionRetriesReturnOneStableIdentity() throws Exception { + String name = "script-definition-concurrent-" + UUID.randomUUID(); + ScriptDefinition left = scriptDefinition(name, "{\"retry\":true}"); + ScriptDefinition right = scriptDefinition(name, "{\"retry\":true}"); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = barrierExecutor(); + CompletableFuture leftResult = + CompletableFuture.supplyAsync( + () -> saveDefinitionAfterBarrier(left, ready, start), executor); + CompletableFuture rightResult = + CompletableFuture.supplyAsync( + () -> saveDefinitionAfterBarrier(right, ready, start), executor); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + assertThat(leftResult.get(30, TimeUnit.SECONDS).getId()) + .isEqualTo(rightResult.get(30, TimeUnit.SECONDS).getId()); + assertThat( + scriptDefinitionRepository.findByTenantIdAndScriptVersionAndName( + 1L, "patch-definition", name)) + .isPresent(); + } + + @Test + void postgresBindingCompensationRestoresLogicalBindings() { + String name = "script-binding-compensation-" + UUID.randomUUID(); + ScriptDefinition originalDefinition = scriptDefinition(name, "{\"original\":true}"); + ScriptDefinition savedDefinition = scriptDefinitionRepository.save(originalDefinition); + ScriptEventBinding originalBinding = scriptBinding(name, "original-scope"); + ScriptEventBinding savedBinding = scriptEventBindingRepository.save(originalBinding); + int originalDefinitionRowVersion = savedDefinition.getRowVersion(); + AtomicReference> bindingsObservedAfterDelete = new AtomicReference<>(); + AtomicReference failForwardReplacement = new AtomicReference<>(true); + + ScriptEventBindingRepository failingBindingRepository = + new ScriptEventBindingRepository(dsl) { + @Override + public List saveAll(Collection entities) { + if (failForwardReplacement.getAndSet(false)) { + bindingsObservedAfterDelete.set( + findByTenantIdAndScriptPatchVersionAndScriptIdOrderByEventTypeAscEventSchemaVersionAscPriorityAscBindingIdAscIdAsc( + 1L, "patch-definition", name)); + throw new IllegalStateException("binding replacement failed"); + } + return super.saveAll(entities); + } + }; + ScriptDefinitionServiceImpl service = + new ScriptDefinitionServiceImpl( + scriptDefinitionRepository, + failingBindingRepository, + Mappers.getMapper(ScriptDefinitionMapper.class), + sagaRunner, + new BuiltInScriptEventRegistryService()); + + ScriptDefinitionDto update = + new ScriptDefinitionDto( + null, + 1L, + name, + "patch-definition", + "{\"replacement\":true}", + List.of( + new ScriptDefinitionDto.EventBindingDto( + "onCommand", + "v1", + "ACTION_TAG", + "replacement-scope", + 0, + "normal", + false, + "binding-replacement"))); + + assertThatThrownBy(() -> service.updateScript(update)).isInstanceOf(SagaException.class); + assertThat(bindingsObservedAfterDelete.get()).isNotNull().isEmpty(); + + List restoredBindings = + scriptEventBindingRepository + .findByTenantIdAndScriptPatchVersionOrderByEventTypeAscEventSchemaVersionAscPriorityAscScriptIdAsc( + 1L, "patch-definition") + .stream() + .filter(binding -> name.equals(binding.getScriptId())) + .toList(); + assertThat(restoredBindings).hasSize(1); + ScriptEventBinding restoredBinding = restoredBindings.get(0); + assertThat(restoredBinding) + .usingRecursiveComparison() + .ignoringFields("id", "rowVersion") + .isEqualTo(savedBinding); + assertThat(restoredBinding.getBindingId()).isEqualTo(savedBinding.getBindingId()); + + ScriptDefinition restoredDefinition = + scriptDefinitionRepository + .findByTenantIdAndScriptVersionAndName(1L, "patch-definition", name) + .orElseThrow(); + assertThat(restoredDefinition.getId()).isEqualTo(savedDefinition.getId()); + assertThat(restoredDefinition.getDefinition()).isEqualTo("{\"original\":true}"); + assertThat(restoredDefinition.getRowVersion()).isGreaterThan(originalDefinitionRowVersion); + + ScriptDefinition staleDefinition = scriptDefinition(name, "{\"stale\":true}"); + staleDefinition.setId(restoredDefinition.getId()); + staleDefinition.setRowVersion(originalDefinitionRowVersion); + assertThatThrownBy(() -> scriptDefinitionRepository.save(staleDefinition)) + .isInstanceOf(org.springframework.dao.OptimisticLockingFailureException.class); + } + + @Test + void concurrentPostgresHandoffCreationReturnsOneStableLogicalChild() throws Exception { + ScriptWorkItem workItem = concurrentIdentityWorkItem(); + workItem.setScriptPatchVersion("patch-handoff-" + UUID.randomUUID()); + workItem.setScriptEventId("event-handoff-" + UUID.randomUUID()); + ScriptWorkItem savedWorkItem = scriptWorkItemRepository.save(workItem); + ScriptHandoffEvent first = handoffEvent(savedWorkItem); + ScriptHandoffEvent second = handoffEvent(savedWorkItem); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = barrierExecutor(); + CompletableFuture left = + CompletableFuture.supplyAsync(() -> saveHandoffAfterBarrier(first, ready, start), executor); + CompletableFuture right = + CompletableFuture.supplyAsync( + () -> saveHandoffAfterBarrier(second, ready, start), executor); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + ScriptHandoffEvent leftResult = left.get(30, TimeUnit.SECONDS); + ScriptHandoffEvent rightResult = right.get(30, TimeUnit.SECONDS); + assertThat(leftResult.getId()).isEqualTo(rightResult.getId()); + Optional persisted = + scriptHandoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal( + savedWorkItem.getTenantId(), savedWorkItem.getId(), 0); + assertThat(persisted).isPresent(); + assertThat(persisted.orElseThrow().getId()).isEqualTo(leftResult.getId()); + } + + private ScriptDefinition saveDefinitionAfterBarrier( + ScriptDefinition definition, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + try { + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("definition concurrency test did not start"); + } + return scriptDefinitionRepository.save(definition); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("definition concurrency test interrupted", e); + } + } + + private static ScriptDefinition scriptDefinition(String name, String definition) { + ScriptDefinition result = new ScriptDefinition(); + result.setTenantId(1L); + result.setName(name); + result.setScriptVersion("patch-definition"); + result.setDefinition(definition); + return result; + } + + private static ScriptEventBinding scriptBinding(String scriptId, String targetScopeId) { + ScriptEventBinding binding = new ScriptEventBinding(); + binding.setTenantId(1L); + binding.setScriptPatchVersion("patch-definition"); + binding.setBindingId("binding-" + targetScopeId); + binding.setEventType("onCommand"); + binding.setEventSchemaVersion("v1"); + binding.setScriptId(scriptId); + binding.setTargetScopeType("ACTION_TAG"); + binding.setTargetScopeId(targetScopeId); + binding.setPriority(0); + binding.setPriorityTag("normal"); + binding.setEnabled(true); + return binding; + } + + private ScriptHandoffEvent saveHandoffAfterBarrier( + ScriptHandoffEvent event, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + try { + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("handoff concurrency test did not start"); + } + return scriptHandoffEventRepository.save(event); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("handoff concurrency test interrupted", e); + } + } + + private static ScriptHandoffEvent handoffEvent(ScriptWorkItem workItem) { + ScriptHandoffEvent event = new ScriptHandoffEvent(); + event.setEventId("handoff-event-" + workItem.getId()); + event.setTenantId(workItem.getTenantId()); + event.setGameInstanceId(workItem.getGameInstanceId()); + event.setScriptPatchVersion(workItem.getScriptPatchVersion()); + event.setScriptId(workItem.getScriptId()); + event.setWorkItemId(workItem.getId()); + event.setCommandOrdinal(0); + event.setAutomationDispatchId("dispatch-" + workItem.getId()); + event.setTargetEntityId("entity-1"); + event.setEmittedCommandText("look"); + event.setHandoffOutcome("enqueued"); + event.setHandoffReason("game_session_accepted"); + event.setObservedAt(Instant.now()); + return event; + } + + private ScriptEventIngressAuditRepository.IdempotentInsertResult insertIngressAfterBarrier( + ScriptEventIngressAudit audit, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + try { + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("nullable ingress concurrency test did not start"); + } + return scriptEventIngressAuditRepository.insertIfAbsentByIdentity(audit); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("nullable ingress concurrency test interrupted", e); + } + } + + private static ScriptEventIngressAudit concurrentNullableIngressAudit(String scriptEventId) { + ScriptEventIngressAudit audit = new ScriptEventIngressAudit(); + audit.setTenantId("1"); + audit.setGameInstanceId(null); + audit.setRegionId(null); + audit.setRegionEpoch(null); + audit.setEntityId(null); + audit.setPlayableStateScope(""); + audit.setWorldSlug(""); + audit.setRealmSlug(""); + audit.setPointerVersion(""); + audit.setEventType("onCommand"); + audit.setEventSchemaVersion("v1"); + audit.setScriptPatchVersion("patch-nullable-ingress"); + audit.setScriptEventId(scriptEventId); + audit.setSourceService("integration-test"); + audit.setTriggerMode("EVENT"); + audit.setSourceKind("GAMEPLAY_EVENT"); + audit.setSourceState("TRIGGER_ADMITTED"); + audit.setAdmitted(true); + audit.setAdmissionOutcome("ADMITTED"); + audit.setAdmissionReason("test"); + audit.setCreatedAt(Instant.now()); + return audit; + } + + @Test + void concurrentPostgresDeadLetterReplayClaimHasOneWinnerAndOneRecoveryInProgress() + throws Exception { + ScriptWorkItem item = concurrentReplayWorkItem(); + ScriptWorkItem saved = scriptWorkItemRepository.save(item); + int expectedRowVersion = saved.getRowVersion(); + long expectedFailureGeneration = saved.getFailureGeneration(); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = barrierExecutor(); + CompletableFuture> left = + CompletableFuture.supplyAsync( + () -> + claimAfterBarrier( + saved, expectedRowVersion, expectedFailureGeneration, ready, start), + executor); + CompletableFuture> right = + CompletableFuture.supplyAsync( + () -> + claimAfterBarrier( + saved, expectedRowVersion, expectedFailureGeneration, ready, start), + executor); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + Optional leftResult = left.get(30, TimeUnit.SECONDS); + Optional rightResult = right.get(30, TimeUnit.SECONDS); + + assertThat(List.of(leftResult, rightResult).stream().filter(Optional::isPresent)).hasSize(1); + Optional winner = leftResult.isPresent() ? leftResult : rightResult; + assertThat(winner).isPresent(); + assertThat(winner.orElseThrow().getStatus()).isEqualTo("PENDING_EVALUATION"); + } + + private Optional claimAfterBarrier( + ScriptWorkItem item, + int expectedRowVersion, + long expectedFailureGeneration, + CountDownLatch ready, + CountDownLatch start) { + ready.countDown(); + try { + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("replay concurrency test did not start"); + } + return scriptWorkItemRepository.claimDeadLetterForReplay( + item.getId(), + item.getTenantId(), + expectedRowVersion, + expectedFailureGeneration, + Instant.now()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("replay concurrency test interrupted", e); + } + } + + private static ScriptWorkItem concurrentReplayWorkItem() { + ScriptWorkItem item = concurrentIdentityWorkItem(); + item.setGameInstanceId("concurrent-replay-game"); + item.setScriptEventId("event-replay-" + UUID.randomUUID()); + item.setStatus("DEAD_LETTERED"); + item.setFailureGeneration(7L); + item.setScriptPinEpoch(1L); + item.setCreatedAt(Instant.now()); + item.setUpdatedAt(Instant.now()); + return item; + } + + private ScriptWorkItemRepository.IdempotentInsertResult insertAfterBarrier( + ScriptWorkItem item, CountDownLatch ready, CountDownLatch start) { + ready.countDown(); + try { + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("concurrency test did not start"); + } + return scriptWorkItemRepository.insertIfAbsentByTriggerIdentity(item); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("concurrency test interrupted", e); + } + } + + private static ScriptWorkItem concurrentIdentityWorkItem() { + return concurrentIdentityWorkItem("event-concurrent-" + UUID.randomUUID()); + } + + private static ScriptWorkItem concurrentIdentityWorkItem(String scriptEventId) { + ScriptWorkItem item = new ScriptWorkItem(); + item.setTenantId("1"); + item.setGameInstanceId("concurrent-game"); + item.setRegionId("region-1"); + item.setRegionEpoch(1L); + item.setEntityId(""); + item.setPlayableStateScope(""); + item.setWorldSlug(""); + item.setRealmSlug(""); + item.setPointerVersion(""); + item.setScriptId("script-concurrent"); + item.setEventType("onCommand"); + item.setEventSchemaVersion("v1"); + item.setScriptPatchVersion("patch-concurrent"); + item.setScriptEventId(scriptEventId); + item.setDryRun(false); + item.setSourceService("integration-test"); + item.setTriggerMode("EVENT"); + item.setPayloadJson("{}"); + item.setCreatedAt(Instant.now()); + item.setUpdatedAt(Instant.now()); + return item; + } } diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationQueueServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationQueueServiceImplTest.java index 57e5d5de24..0e639eef4c 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationQueueServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationQueueServiceImplTest.java @@ -1,7 +1,9 @@ package net.firedevops.firemud.automationscripting.service.impl; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -9,12 +11,14 @@ import java.time.Instant; import java.util.List; import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.automationscripting.entity.ScriptWorkItem; import net.firedevops.firemud.automationscripting.repository.ScriptWorkItemRepository; import net.firedevops.firemud.automationscripting.service.AutomationQueueService; import net.firedevops.firemud.automationscripting.service.AutomationQueueWorkItemPointer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; import org.springframework.data.domain.PageRequest; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisTemplate; @@ -25,6 +29,7 @@ class AutomationQueueServiceImplTest { private RedisTemplate redisTemplate; private ListOperations listOps; private ScriptWorkItemRepository workItemRepository; + private SimpleMeterRegistry meterRegistry; private AutomationQueueService service; @BeforeEach @@ -32,10 +37,11 @@ void setup() { redisTemplate = mock(RedisTemplate.class); listOps = mock(ListOperations.class); workItemRepository = mock(ScriptWorkItemRepository.class); + meterRegistry = new SimpleMeterRegistry(); when(redisTemplate.opsForList()).thenReturn(listOps); service = new AutomationQueueServiceImpl( - redisTemplate, new SimpleMeterRegistry(), new ObjectMapper(), workItemRepository); + redisTemplate, meterRegistry, new ObjectMapper(), workItemRepository); ((AutomationQueueServiceImpl) service).init(); } @@ -58,12 +64,12 @@ void enqueueWorkItemPushesVersionedPointerToRedis() { } @Test - void drainWorkItemsRetrievesDeserializedPointersAndDeletesQueue() { - when(listOps.range("automation:queue:{tenant:tenant-1:instance:instance-1}:entity-1", 0, -1)) + void drainWorkItemsRetrievesDeserializedPointersWithoutDeletingConcurrentEnqueues() { + when(listOps.leftPop("automation:queue:{tenant:tenant-1:instance:instance-1}:entity-1")) .thenReturn( - List.of( - "{\"schemaVersion\":1,\"outboxWorkItemId\":41,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-1\",\"scriptEventId\":\"event-1\"}", - "{\"schemaVersion\":1,\"outboxWorkItemId\":42,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-2\",\"scriptEventId\":\"event-2\"}")); + "{\"schemaVersion\":1,\"outboxWorkItemId\":41,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-1\",\"scriptEventId\":\"event-1\"}", + "{\"schemaVersion\":1,\"outboxWorkItemId\":42,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-2\",\"scriptEventId\":\"event-2\"}", + (Object) null); List drained = service.drainWorkItems("tenant-1", "instance-1", "entity-1"); @@ -72,16 +78,15 @@ void drainWorkItemsRetrievesDeserializedPointersAndDeletesQueue() { .containsExactly( new AutomationQueueWorkItemPointer(1, 41L, "instance-1", "patch-1", "event-1"), new AutomationQueueWorkItemPointer(1, 42L, "instance-1", "patch-2", "event-2")); - verify(redisTemplate).delete("automation:queue:{tenant:tenant-1:instance:instance-1}:entity-1"); } @Test void drainWorkItemsDedupesRepeatedPointersByWorkItemId() { - when(listOps.range("automation:queue:{tenant:tenant-1:instance:instance-1}:entity-1", 0, -1)) + when(listOps.leftPop("automation:queue:{tenant:tenant-1:instance:instance-1}:entity-1")) .thenReturn( - List.of( - "{\"schemaVersion\":1,\"outboxWorkItemId\":41,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-1\",\"scriptEventId\":\"event-1\"}", - "{\"schemaVersion\":1,\"outboxWorkItemId\":41,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-1\",\"scriptEventId\":\"event-1\"}")); + "{\"schemaVersion\":1,\"outboxWorkItemId\":41,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-1\",\"scriptEventId\":\"event-1\"}", + "{\"schemaVersion\":1,\"outboxWorkItemId\":41,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-1\",\"scriptEventId\":\"event-1\"}", + (Object) null); List drained = service.drainWorkItems("tenant-1", "instance-1", "entity-1"); @@ -92,21 +97,56 @@ void drainWorkItemsDedupesRepeatedPointersByWorkItemId() { } @Test - void drainIndexedWorkItemPointersScansQueueKeysAndDeletesDrainedProjections() { + void drainWorkItemsStopsAtConfiguredTickPointerBudget() { + String queueKey = "automation:queue:{tenant:tenant-1:instance:instance-1}:entity-1"; + AtomicInteger popCount = new AtomicInteger(); + when(listOps.leftPop(queueKey)) + .thenAnswer( + invocation -> { + int index = popCount.getAndIncrement(); + return index < 50 ? pointerJson(41L + index) : null; + }); + + List drained = + service.drainWorkItems("tenant-1", "instance-1", "entity-1"); + + assertThat(drained).hasSize(50); + assertThat( + drained.stream() + .map(AutomationQueueWorkItemPointer::outboxWorkItemId) + .distinct() + .count()) + .isEqualTo(50L); + verify(listOps, org.mockito.Mockito.times(50)).leftPop(queueKey); + } + + @Test + void rejectsNonPositiveTickPointerBudgetDuringInitialization() { + AutomationQueueServiceImpl invalidService = + new AutomationQueueServiceImpl( + redisTemplate, meterRegistry, new ObjectMapper(), workItemRepository, 0); + + assertThatThrownBy(invalidService::init) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("automation.tick-max-events must be positive"); + } + + @Test + void drainIndexedWorkItemPointersScansQueueKeysWithoutDeletingDrainedProjections() { when(redisTemplate.keys("automation:queue:*")) .thenReturn( Set.of( "automation:queue:{tenant:tenant-1:instance:instance-1}:entity-2", "automation:queue:{tenant:tenant-1:instance:instance-1}:entity-1")); - when(listOps.range("automation:queue:{tenant:tenant-1:instance:instance-1}:entity-1", 0, -1)) + when(listOps.leftPop("automation:queue:{tenant:tenant-1:instance:instance-1}:entity-1")) .thenReturn( - List.of( - "{\"schemaVersion\":1,\"outboxWorkItemId\":41,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-1\",\"scriptEventId\":\"event-1\"}", - "{\"schemaVersion\":1,\"outboxWorkItemId\":41,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-1\",\"scriptEventId\":\"event-1\"}")); - when(listOps.range("automation:queue:{tenant:tenant-1:instance:instance-1}:entity-2", 0, -1)) + "{\"schemaVersion\":1,\"outboxWorkItemId\":41,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-1\",\"scriptEventId\":\"event-1\"}", + "{\"schemaVersion\":1,\"outboxWorkItemId\":41,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-1\",\"scriptEventId\":\"event-1\"}", + (Object) null); + when(listOps.leftPop("automation:queue:{tenant:tenant-1:instance:instance-1}:entity-2")) .thenReturn( - List.of( - "{\"schemaVersion\":1,\"outboxWorkItemId\":42,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-2\",\"scriptEventId\":\"event-2\"}")); + "{\"schemaVersion\":1,\"outboxWorkItemId\":42,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-2\",\"scriptEventId\":\"event-2\"}", + (Object) null); List drained = service.drainIndexedWorkItemPointers(10, 10); @@ -114,8 +154,42 @@ void drainIndexedWorkItemPointersScansQueueKeysAndDeletesDrainedProjections() { .containsExactly( new AutomationQueueWorkItemPointer(1, 41L, "instance-1", "patch-1", "event-1"), new AutomationQueueWorkItemPointer(1, 42L, "instance-1", "patch-2", "event-2")); - verify(redisTemplate).delete("automation:queue:{tenant:tenant-1:instance:instance-1}:entity-1"); - verify(redisTemplate).delete("automation:queue:{tenant:tenant-1:instance:instance-1}:entity-2"); + verify(redisTemplate, never()).delete(Mockito.anyString()); + } + + @Test + void drainIndexedWorkItemPointersLeavesSuffixWhenPointerBoundIsReached() { + String queueKey = "automation:queue:{tenant:tenant-1:instance:instance-1}:entity-1"; + when(redisTemplate.keys("automation:queue:*")).thenReturn(Set.of(queueKey)); + when(listOps.leftPop(queueKey)) + .thenReturn( + "{\"schemaVersion\":1,\"outboxWorkItemId\":41,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-1\",\"scriptEventId\":\"event-1\"}", + "{\"schemaVersion\":1,\"outboxWorkItemId\":42,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-1\",\"scriptEventId\":\"event-2\"}"); + + List drained = service.drainIndexedWorkItemPointers(10, 1); + + assertThat(drained) + .containsExactly( + new AutomationQueueWorkItemPointer(1, 41L, "instance-1", "patch-1", "event-1")); + verify(listOps).leftPop(queueKey); + } + + @Test + void drainIndexedWorkItemPointersCountsMalformedEntriesTowardPointerBound() { + String queueKey = "automation:queue:{tenant:tenant-1:instance:instance-1}:entity-1"; + when(redisTemplate.keys("automation:queue:*")).thenReturn(Set.of(queueKey)); + when(listOps.leftPop(queueKey)) + .thenReturn( + "not-json", + "{\"schemaVersion\":1,\"outboxWorkItemId\":41,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-1\",\"scriptEventId\":\"event-1\"}", + "{\"schemaVersion\":1,\"outboxWorkItemId\":42,\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-1\",\"scriptEventId\":\"event-2\"}"); + + List drained = service.drainIndexedWorkItemPointers(10, 1); + + assertThat(drained).isEmpty(); + assertThat(meterRegistry.get("automation_queue_malformed_entries_total").counter().count()) + .isEqualTo(1.0); + verify(listOps).leftPop(queueKey); } @Test @@ -123,7 +197,7 @@ void rebuildPendingWorkItemIndexRepublishesOnlyMissingPointers() { ScriptWorkItem missing = workItem(41L, "entity-1"); ScriptWorkItem existing = workItem(42L, "entity-2"); when(workItemRepository.findByStatusInOrderByCreatedAtAscIdAsc( - List.of("PENDING_EVALUATION", "EVALUATING"), PageRequest.of(0, 10))) + List.of("PENDING_EVALUATION"), PageRequest.of(0, 10))) .thenReturn(List.of(missing, existing)); when(listOps.range("automation:queue:{tenant:tenant-1:instance:instance-1}:entity-1", 0, -1)) .thenReturn(List.of()); @@ -194,4 +268,12 @@ private static ScriptWorkItem workItem(long id, String entityId) { workItem.setStatus("PENDING_EVALUATION"); return workItem; } + + private static String pointerJson(long id) { + return "{\"schemaVersion\":1,\"outboxWorkItemId\":" + + id + + ",\"gameInstanceId\":\"instance-1\",\"scriptPatchVersion\":\"patch-1\",\"scriptEventId\":\"event-" + + id + + "\"}"; + } } diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java index b1fed6909b..8aa0cfc276 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java @@ -1979,7 +1979,18 @@ void replaysDeadLettersThroughWorkItemService() { SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); Mockito.when(workItemService.replayDeadLetters(Mockito.any())) - .thenReturn(new ScriptWorkItemService.ReplayResult(2L, 1L)); + .thenReturn( + new ScriptWorkItemService.ReplayResult( + 2L, + 1L, + List.of( + new ScriptWorkItemService.ReplayItemResult( + "77", "retried_evaluation", "", "", 4L), + new ScriptWorkItemService.ReplayItemResult( + "88", "resumed_dispatch", "", "", 5L), + new ScriptWorkItemService.ReplayItemResult( + "99", "rejected", "recovery_in_progress", "", 6L)), + "replay-fingerprint")); AutomationScriptingControlPlaneGrpcService service = newService( workItemService, @@ -2001,6 +2012,49 @@ void replaysDeadLettersThroughWorkItemService() { assertThat(ref.get().hasError()).isFalse(); assertThat(ref.get().getReplayedCount()).isEqualTo(2L); assertThat(ref.get().getRejectedCount()).isEqualTo(1L); + assertThat(ref.get().getRequestFingerprint()).isEqualTo("replay-fingerprint"); + assertThat(ref.get().getResultsList()).hasSize(3); + assertThat(ref.get().getResults(0).getWorkItemId()).isEqualTo("77"); + assertThat(ref.get().getResults(0).getOutcome()).isEqualTo("retried_evaluation"); + assertThat(ref.get().getResults(0).getFailureGeneration()).isEqualTo(4L); + assertThat(ref.get().getResults(1).getWorkItemId()).isEqualTo("88"); + assertThat(ref.get().getResults(1).getOutcome()).isEqualTo("resumed_dispatch"); + assertThat(ref.get().getResults(1).getFailureGeneration()).isEqualTo(5L); + assertThat(ref.get().getResults(2).getWorkItemId()).isEqualTo("99"); + assertThat(ref.get().getResults(2).getOutcome()).isEqualTo("rejected"); + assertThat(ref.get().getResults(2).getRejectionReason()).isEqualTo("recovery_in_progress"); + assertThat(ref.get().getResults(2).getFailureGeneration()).isEqualTo(6L); + } + + @Test + void mapsEmptyReplayResultListWithoutFabricatingItems() { + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + Mockito.when(workItemService.replayDeadLetters(Mockito.any())) + .thenReturn(new ScriptWorkItemService.ReplayResult(0L, 0L, List.of(), "empty-fingerprint")); + AutomationScriptingControlPlaneGrpcService service = + newService( + workItemService, + Mockito.mock(PluginRuntimeStateService.class), + admissionStateService(), + Mockito.mock(ScriptPatchPinProjectionService.class)); + AtomicReference ref = new AtomicReference<>(); + + service.replayDeadLetteredWorkItems( + ReplayDeadLetteredWorkItemsRequest.newBuilder() + .setTenantId("1") + .setGameInstanceId("game-1") + .addWorkItemIds("77") + .setControlPlaneRequestId("request-empty") + .setReason("retry") + .build(), + observer(ref)); + + assertThat(ref.get().hasError()).isFalse(); + assertThat(ref.get().getReplayedCount()).isZero(); + assertThat(ref.get().getRejectedCount()).isZero(); + assertThat(ref.get().getResultsList()).isEmpty(); + assertThat(ref.get().getRequestFingerprint()).isEqualTo("empty-fingerprint"); } @Test diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java index aaae6cd906..3ee075304b 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java @@ -743,6 +743,8 @@ void malformedAcceptedGameSessionOutcomeIsRejectedWithoutAggregateAcceptance() { assertThat(result.accepted()).isFalse(); assertThat(result.errorCode()).isEqualTo("REMOTE_RESPONSE_INVALID"); + assertThat(item.getStatus()).isEqualTo("DEAD_LETTERED"); + assertThat(item.getFailureGeneration()).isEqualTo(1L); assertThat(result.outcome()).isEqualTo("REMOTE_REJECTED"); assertThat(audit.getFinalStage()).isEqualTo("TICK_HANDOFF"); assertThat(audit.getFinalOutcome()).isEqualTo("infrastructure_error"); @@ -877,6 +879,7 @@ void malformedLocalRuntimeOwnerFailsClosedBeforeLocalEnqueue() { ArgumentCaptor workItemCaptor = ArgumentCaptor.forClass(ScriptWorkItem.class); verify(workItemRepository).save(workItemCaptor.capture()); assertThat(workItemCaptor.getValue().getStatus()).isEqualTo("DEAD_LETTERED"); + assertThat(workItemCaptor.getValue().getFailureGeneration()).isEqualTo(1L); assertThat(workItemCaptor.getValue().getCancelReason()).isEqualTo("remote_response_invalid"); } diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java index e17eeed426..ec2b132e4a 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java @@ -6,15 +6,21 @@ import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.sql.SQLException; +import java.sql.SQLTransientConnectionException; +import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Stream; +import net.firedevops.firemud.automationscripting.client.GameSessionControlPlaneClient; import net.firedevops.firemud.automationscripting.config.ScriptOutputProperties; +import net.firedevops.firemud.automationscripting.entity.PluginRuntimeState; import net.firedevops.firemud.automationscripting.entity.ScriptDefinition; import net.firedevops.firemud.automationscripting.entity.ScriptEventAudit; import net.firedevops.firemud.automationscripting.entity.ScriptWorkItem; +import net.firedevops.firemud.automationscripting.repository.PluginRuntimeStateRepository; import net.firedevops.firemud.automationscripting.repository.ScriptDefinitionRepository; import net.firedevops.firemud.automationscripting.repository.ScriptEventAuditRepository; import net.firedevops.firemud.automationscripting.repository.ScriptWorkItemRepository; @@ -29,6 +35,9 @@ import net.firedevops.firemud.automationscripting.service.quota.ScriptDryRunCapacityService; import net.firedevops.firemud.automationscripting.service.quota.ScriptReadinessCapacityService; import net.firedevops.firemud.automationscripting.service.quota.ScriptTenantBudgetService; +import net.firedevops.firemud.gamesession.v1.GetGameInstanceRuntimeStateResponse; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.jooq.exception.DataAccessException; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -43,6 +52,562 @@ import tools.jackson.databind.ObjectMapper; class ScriptWorkItemExecutionServiceImplTest { + @Test + void requeuesWorkWhenRuntimeAuthorityIsUnavailable() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptDefinitionRepository definitionRepository = + Mockito.mock(ScriptDefinitionRepository.class); + ScriptGameplayCommandHandoffService handoffService = + Mockito.mock(ScriptGameplayCommandHandoffService.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + AutomationQueueService automationQueueService = Mockito.mock(AutomationQueueService.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenReturn( + GetGameInstanceRuntimeStateResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("UNAVAILABLE").build()) + .build()); + ScriptWorkItem item = workItem(); + item.setScriptPinEpoch(3L); + when(workItemService.claimPendingForEvaluation(10)).thenReturn(List.of(item)); + when(workItemRepository.save(item)).thenReturn(item); + + ScriptWorkItemExecutionService service = + new ScriptWorkItemExecutionServiceImpl( + workItemService, + definitionRepository, + handoffService, + workItemRepository, + auditRepository, + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + new ScriptOutputProperties(), + allowingTenantBudgetService(), + allowingDryRunCapacityService(), + new ObjectMapper(), + new SimpleMeterRegistry(), + automationQueueService, + null, + null, + gameSessionClient, + Mockito.mock(PluginRuntimeStateRepository.class)); + + ScriptWorkItemExecutionService.ExecutionBatchResult result = + service.processPendingWorkItems(10); + + assertThat(result.failedCount()).isEqualTo(1); + assertThat(item.getStatus()).isEqualTo("PENDING_EVALUATION"); + assertThat(item.getCancelReason()).isEqualTo("script_pin_authority_unavailable"); + verify(definitionRepository, Mockito.never()) + .findByTenantIdAndScriptVersionAndName( + Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + verify(handoffService, Mockito.never()).handoff(Mockito.any(), Mockito.any()); + verify(automationQueueService, Mockito.never()).enqueueWorkItem(Mockito.any()); + } + + @Test + void authorityUnavailableRetryRecordsDurableEligibilityAndFirstOutcome() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenReturn( + GetGameInstanceRuntimeStateResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("UNAVAILABLE").build()) + .build()); + ScriptWorkItem item = workItem(); + item.setScriptPinEpoch(3L); + when(workItemService.claimPendingForEvaluation(1)).thenReturn(List.of(item)); + when(workItemRepository.save(item)).thenAnswer(invocation -> invocation.getArgument(0)); + + ScriptWorkItemExecutionService service = + fenceExecutionService( + workItemService, + workItemRepository, + auditRepository, + gameSessionClient, + Mockito.mock(PluginRuntimeStateRepository.class)); + + Instant before = Instant.now(); + ScriptWorkItemExecutionService.ExecutionBatchResult result = service.processPendingWorkItems(1); + + assertThat(result.failedCount()).isEqualTo(1); + assertThat(item.getStatus()).isEqualTo("PENDING_EVALUATION"); + assertThat(item.getAuthorityUnavailableCount()).isEqualTo(1); + assertThat(item.getAuthorityUnavailableSince()).isNotNull().isBetween(before, Instant.now()); + assertThat(item.getNextEligibleAt()).isNotNull().isAfter(Instant.now().plusSeconds(29)); + } + + @Test + void clearsAuthorityUnavailableRetryStateAfterFenceRecovers() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenReturn(runtimeStateResponse()); + ScriptWorkItem item = workItem(); + item.setScriptPinEpoch(3L); + item.setAuthorityUnavailableSince(Instant.now().minus(Duration.ofSeconds(1))); + item.setAuthorityUnavailableCount(3); + item.setNextEligibleAt(Instant.now().minus(Duration.ofSeconds(1))); + when(workItemService.claimPendingForEvaluation(1)).thenReturn(List.of(item)); + when(workItemRepository.save(item)).thenAnswer(invocation -> invocation.getArgument(0)); + + ScriptWorkItemExecutionService service = + fenceExecutionService( + workItemService, + workItemRepository, + auditRepository, + gameSessionClient, + Mockito.mock(PluginRuntimeStateRepository.class)); + + service.processPendingWorkItems(1); + + assertThat(item.getAuthorityUnavailableSince()).isNull(); + assertThat(item.getAuthorityUnavailableCount()).isZero(); + assertThat(item.getNextEligibleAt()).isNull(); + assertThat(item.getStatus()).isEqualTo("DEAD_LETTERED"); + } + + @Test + void doesNotTreatUnexpectedGameSessionFailureAsAuthorityRetry() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenThrow(new IllegalStateException("unexpected client failure")); + ScriptWorkItem item = workItem(); + item.setScriptPinEpoch(3L); + when(workItemService.claimPendingForEvaluation(1)).thenReturn(List.of(item)); + + ScriptWorkItemExecutionService service = + fenceExecutionService( + workItemService, + workItemRepository, + auditRepository, + gameSessionClient, + Mockito.mock(PluginRuntimeStateRepository.class)); + + ScriptWorkItemExecutionService.ExecutionBatchResult result = service.processPendingWorkItems(1); + + assertThat(result.failedCount()).isEqualTo(1); + assertThat(item.getStatus()).isEqualTo("EVALUATING"); + assertThat(item.getAuthorityUnavailableCount()).isZero(); + verify(workItemRepository, Mockito.never()).save(Mockito.any()); + } + + @Test + void retriesWhenPluginRepositoryReportsTransientConnectionFailure() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + PluginRuntimeStateRepository pluginRuntimeStateRepository = + Mockito.mock(PluginRuntimeStateRepository.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenReturn(runtimeStateResponse()); + when(pluginRuntimeStateRepository.findByTenantIdAndGameInstanceIdAndPluginId( + "1", "7", "plugin-1")) + .thenThrow( + new DataAccessException( + "plugin lookup unavailable", new SQLTransientConnectionException("offline"))); + ScriptWorkItem item = pluginWorkItem(); + when(workItemService.claimPendingForEvaluation(1)).thenReturn(List.of(item)); + when(workItemRepository.save(item)).thenAnswer(invocation -> invocation.getArgument(0)); + + ScriptWorkItemExecutionService service = + fenceExecutionService( + workItemService, + workItemRepository, + auditRepository, + gameSessionClient, + pluginRuntimeStateRepository); + + service.processPendingWorkItems(1); + + assertThat(item.getStatus()).isEqualTo("PENDING_EVALUATION"); + assertThat(item.getCancelReason()).isEqualTo("plugin_lifecycle_collaborator_unavailable"); + assertThat(item.getAuthorityUnavailableCount()).isEqualTo(1); + } + + @Test + void terminalizesNonAvailabilityPluginRepositoryFailureWithoutRetry() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + PluginRuntimeStateRepository pluginRuntimeStateRepository = + Mockito.mock(PluginRuntimeStateRepository.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenReturn(runtimeStateResponse()); + when(pluginRuntimeStateRepository.findByTenantIdAndGameInstanceIdAndPluginId( + "1", "7", "plugin-1")) + .thenThrow( + new DataAccessException("invalid plugin query", new SQLException("syntax", "42601"))); + ScriptWorkItem item = pluginWorkItem(); + when(workItemService.claimPendingForEvaluation(1)).thenReturn(List.of(item)); + when(workItemRepository.save(item)).thenAnswer(invocation -> invocation.getArgument(0)); + + ScriptWorkItemExecutionService service = + fenceExecutionService( + workItemService, + workItemRepository, + auditRepository, + gameSessionClient, + pluginRuntimeStateRepository); + + service.processPendingWorkItems(1); + + assertThat(item.getStatus()).isEqualTo("CANCELED"); + assertThat(item.getCancelReason()).isEqualTo("plugin_lifecycle_evidence_unavailable"); + assertThat(item.getAuthorityUnavailableCount()).isZero(); + } + + @Test + void authorityUnavailableRetryDeadLettersAtOutcomeLimitWithDurableEvidence() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenReturn( + GetGameInstanceRuntimeStateResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("UNAVAILABLE").build()) + .build()); + ScriptWorkItem item = workItem(); + item.setScriptPinEpoch(3L); + item.setAuthorityUnavailableSince(Instant.now().minus(Duration.ofSeconds(1))); + item.setAuthorityUnavailableCount(9); + when(workItemService.claimPendingForEvaluation(1)).thenReturn(List.of(item)); + when(workItemRepository.save(item)).thenAnswer(invocation -> invocation.getArgument(0)); + + ScriptWorkItemExecutionService service = + fenceExecutionService( + workItemService, + workItemRepository, + auditRepository, + gameSessionClient, + Mockito.mock(PluginRuntimeStateRepository.class)); + + ScriptWorkItemExecutionService.ExecutionBatchResult result = service.processPendingWorkItems(1); + + assertThat(result.failedCount()).isEqualTo(1); + assertThat(item.getStatus()).isEqualTo("DEAD_LETTERED"); + assertThat(item.getCancelReason()).isEqualTo("authority_unavailable_exhausted"); + assertThat(item.getAuthorityUnavailableCount()).isEqualTo(10); + assertThat(item.getNextEligibleAt()).isNull(); + verify(workItemRepository).save(item); + } + + @Test + void authorityUnavailableRetryDeadLettersWhenFirstOutcomeExceedsAgeBound() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + ScriptWorkItem item = workItem(); + item.setAuthorityUnavailableSince(Instant.now().minus(Duration.ofMinutes(10).plusSeconds(1))); + item.setAuthorityUnavailableCount(1); + when(workItemService.claimPendingForEvaluation(1)).thenReturn(List.of(item)); + when(workItemRepository.save(item)).thenAnswer(invocation -> invocation.getArgument(0)); + + ScriptWorkItemExecutionService service = + fenceExecutionService( + workItemService, + workItemRepository, + auditRepository, + gameSessionClient, + Mockito.mock(PluginRuntimeStateRepository.class)); + + ScriptWorkItemExecutionService.ExecutionBatchResult result = service.processPendingWorkItems(1); + + assertThat(result.failedCount()).isEqualTo(1); + assertThat(item.getStatus()).isEqualTo("DEAD_LETTERED"); + assertThat(item.getCancelReason()).isEqualTo("authority_unavailable_exhausted"); + assertThat(item.getAuthorityUnavailableCount()).isEqualTo(1); + Mockito.verifyNoInteractions(gameSessionClient); + } + + @Test + void rejectsRuntimeAuthorityForDifferentTenantBeforeEvaluation() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptWorkItem item = workItem(); + item.setScriptPinEpoch(3L); + when(workItemService.claimPendingForEvaluation(10)).thenReturn(List.of(item)); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + when(workItemRepository.save(item)).thenReturn(item); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenReturn( + GetGameInstanceRuntimeStateResponse.newBuilder() + .setRuntimeState( + net.firedevops.firemud.gamesession.v1.GameInstanceRuntimeState.newBuilder() + .setTenantId("tenant-2") + .setGameInstanceId("7") + .setRegionId("region-1") + .setRegionEpoch(12L)) + .build()); + + ScriptWorkItemExecutionService service = + new ScriptWorkItemExecutionServiceImpl( + workItemService, + Mockito.mock(ScriptDefinitionRepository.class), + Mockito.mock(ScriptGameplayCommandHandoffService.class), + workItemRepository, + Mockito.mock(ScriptEventAuditRepository.class), + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + new ScriptOutputProperties(), + allowingTenantBudgetService(), + allowingDryRunCapacityService(), + new ObjectMapper(), + new SimpleMeterRegistry(), + null, + null, + null, + gameSessionClient, + Mockito.mock(PluginRuntimeStateRepository.class)); + + service.processPendingWorkItems(10); + + assertThat(item.getStatus()).isEqualTo("CANCELED"); + assertThat(item.getCancelReason()).isEqualTo("runtime_scope_changed"); + } + + @Test + void rejectsMissingRuntimeScopeBeforeAuthorityLookup() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptWorkItem item = workItem(); + item.setTenantId(null); + item.setScriptPinEpoch(3L); + when(workItemService.claimPendingForEvaluation(10)).thenReturn(List.of(item)); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + when(workItemRepository.save(item)).thenReturn(item); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + + ScriptWorkItemExecutionService service = + new ScriptWorkItemExecutionServiceImpl( + workItemService, + Mockito.mock(ScriptDefinitionRepository.class), + Mockito.mock(ScriptGameplayCommandHandoffService.class), + workItemRepository, + Mockito.mock(ScriptEventAuditRepository.class), + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + new ScriptOutputProperties(), + allowingTenantBudgetService(), + allowingDryRunCapacityService(), + new ObjectMapper(), + new SimpleMeterRegistry(), + null, + null, + null, + gameSessionClient, + Mockito.mock(PluginRuntimeStateRepository.class)); + + service.processPendingWorkItems(10); + + assertThat(item.getStatus()).isEqualTo("CANCELED"); + assertThat(item.getCancelReason()).isEqualTo("runtime_scope_missing"); + Mockito.verifyNoInteractions(gameSessionClient); + } + + @Test + void rejectsMissingScriptPinEpochAsTerminalBeforeAuthorityLookup() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptWorkItem item = workItem(); + item.setScriptPinEpoch(0L); + when(workItemService.claimPendingForEvaluation(10)).thenReturn(List.of(item)); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + when(workItemRepository.save(item)).thenReturn(item); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + + ScriptWorkItemExecutionService service = + new ScriptWorkItemExecutionServiceImpl( + workItemService, + Mockito.mock(ScriptDefinitionRepository.class), + Mockito.mock(ScriptGameplayCommandHandoffService.class), + workItemRepository, + Mockito.mock(ScriptEventAuditRepository.class), + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + new ScriptOutputProperties(), + allowingTenantBudgetService(), + allowingDryRunCapacityService(), + new ObjectMapper(), + new SimpleMeterRegistry(), + null, + null, + null, + gameSessionClient, + Mockito.mock(PluginRuntimeStateRepository.class)); + + ScriptWorkItemExecutionService.ExecutionBatchResult result = + service.processPendingWorkItems(10); + + assertThat(result.failedCount()).isEqualTo(1); + assertThat(item.getStatus()).isEqualTo("CANCELED"); + assertThat(item.getCancelReason()).isEqualTo("script_pin_epoch_unavailable"); + verify(workItemRepository).save(item); + Mockito.verifyNoInteractions(gameSessionClient); + } + + @Test + void rejectsMissingPluginLifecycleEvidenceAsTerminalBeforeEvaluation() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptWorkItem item = workItem(); + item.setScriptPinEpoch(3L); + item.setPluginId("plugin-1"); + item.setPluginVersionId("plugin-version-1"); + when(workItemService.claimPendingForEvaluation(10)).thenReturn(List.of(item)); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + when(workItemRepository.save(item)).thenReturn(item); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenReturn( + GetGameInstanceRuntimeStateResponse.newBuilder() + .setRuntimeState( + net.firedevops.firemud.gamesession.v1.GameInstanceRuntimeState.newBuilder() + .setTenantId("1") + .setGameInstanceId("7") + .setRegionId("region-1") + .setRegionEpoch(12L) + .setPinnedScriptPatchVersion("patch-1") + .setScriptPinEpoch(3L)) + .build()); + + ScriptWorkItemExecutionService service = + new ScriptWorkItemExecutionServiceImpl( + workItemService, + Mockito.mock(ScriptDefinitionRepository.class), + Mockito.mock(ScriptGameplayCommandHandoffService.class), + workItemRepository, + Mockito.mock(ScriptEventAuditRepository.class), + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + new ScriptOutputProperties(), + allowingTenantBudgetService(), + allowingDryRunCapacityService(), + new ObjectMapper(), + new SimpleMeterRegistry(), + null, + null, + null, + gameSessionClient, + Mockito.mock(PluginRuntimeStateRepository.class)); + + ScriptWorkItemExecutionService.ExecutionBatchResult result = + service.processPendingWorkItems(10); + + assertThat(result.failedCount()).isEqualTo(1); + assertThat(item.getStatus()).isEqualTo("CANCELED"); + assertThat(item.getCancelReason()).isEqualTo("plugin_lifecycle_evidence_unavailable"); + verify(workItemRepository).save(item); + verify(gameSessionClient).getGameInstanceRuntimeState("1", "7", "region-1"); + } + + @Test + void terminalizesCapturedPluginBindingMismatchBeforeEvaluation() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + ScriptEventAudit audit = new ScriptEventAudit(); + PluginRuntimeStateRepository pluginRuntimeStateRepository = + Mockito.mock(PluginRuntimeStateRepository.class); + ScriptWorkItem item = workItem(); + item.setScriptPinEpoch(3L); + item.setPluginId("plugin-1"); + when(workItemService.claimPendingForEvaluation(10)).thenReturn(List.of(item)); + when(workItemRepository.save(item)).thenReturn(item); + when(auditRepository.findByWorkItemId(99L)).thenReturn(Optional.of(audit)); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenReturn(runtimeStateResponse()); + + ScriptWorkItemExecutionService service = + fenceExecutionService( + workItemService, + workItemRepository, + auditRepository, + gameSessionClient, + pluginRuntimeStateRepository); + + ScriptWorkItemExecutionService.ExecutionBatchResult result = + service.processPendingWorkItems(10); + + assertThat(result.failedCount()).isEqualTo(1); + assertThat(item.getStatus()).isEqualTo("CANCELED"); + assertThat(item.getCancelReason()).isEqualTo("plugin_binding_mismatch"); + assertThat(audit.getFinalStage()).isEqualTo("ADMISSION"); + assertThat(audit.getFinalOutcome()).isEqualTo("stale_execution_fenced"); + assertThat(audit.getFinalReason()).isEqualTo("plugin_binding_mismatch"); + verify(auditRepository).save(audit); + Mockito.verifyNoInteractions(pluginRuntimeStateRepository); + } + + @Test + void terminalizesCurrentPluginLifecycleMismatchBeforeEvaluation() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + PluginRuntimeStateRepository pluginRuntimeStateRepository = + Mockito.mock(PluginRuntimeStateRepository.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + ScriptEventAudit audit = new ScriptEventAudit(); + ScriptWorkItem item = workItem(); + item.setScriptPinEpoch(3L); + item.setPluginId("plugin-1"); + item.setPluginVersionId("plugin-version-1"); + item.setPluginActivationEpoch(4L); + item.setLifecycleRevision(8L); + when(workItemService.claimPendingForEvaluation(10)).thenReturn(List.of(item)); + when(workItemRepository.save(item)).thenReturn(item); + when(auditRepository.findByWorkItemId(99L)).thenReturn(Optional.of(audit)); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenReturn(runtimeStateResponse()); + PluginRuntimeState currentState = new PluginRuntimeState(); + currentState.setPluginState( + net.firedevops.firemud.automationscripting.v1.PluginState.PLUGIN_STATE_ENABLED.name()); + currentState.setActivePluginVersionId("plugin-version-1"); + currentState.setPluginActivationEpoch(4L); + currentState.setLifecycleRevision(9L); + when(pluginRuntimeStateRepository.findByTenantIdAndGameInstanceIdAndPluginId( + "1", "7", "plugin-1")) + .thenReturn(Optional.of(currentState)); + + ScriptWorkItemExecutionService service = + fenceExecutionService( + workItemService, + workItemRepository, + auditRepository, + gameSessionClient, + pluginRuntimeStateRepository); + + ScriptWorkItemExecutionService.ExecutionBatchResult result = + service.processPendingWorkItems(10); + + assertThat(result.failedCount()).isEqualTo(1); + assertThat(item.getStatus()).isEqualTo("CANCELED"); + assertThat(item.getCancelReason()).isEqualTo("plugin_binding_mismatch"); + assertThat(audit.getFinalStage()).isEqualTo("ADMISSION"); + assertThat(audit.getFinalOutcome()).isEqualTo("stale_execution_fenced"); + assertThat(audit.getFinalReason()).isEqualTo("plugin_binding_mismatch"); + verify(auditRepository).save(audit); + } + @Test void claimsQueueIndexedWorkItemsBeforeFallingBackToDurableScan() { AutomationQueueService automationQueueService = Mockito.mock(AutomationQueueService.class); @@ -177,6 +742,62 @@ void processesClaimedWorkItemAndHandsOffRenderedCommands() { assertThat(audit.getFinalReason()).isEqualTo("commands_handed_off"); } + @Test + void unexpectedItemFailureDoesNotAbortLaterClaimedItems() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptDefinitionRepository definitionRepository = + Mockito.mock(ScriptDefinitionRepository.class); + ScriptGameplayCommandHandoffService handoffService = + Mockito.mock(ScriptGameplayCommandHandoffService.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptWorkItem first = workItem(); + ScriptWorkItem second = workItem(); + second.setId(100L); + ScriptDefinition definition = new ScriptDefinition(); + definition.setDefinition("{\"emitCommands\":[{\"commandText\":\"LOOK\"}]}"); + when(workItemService.claimPendingForEvaluation(10)).thenReturn(List.of(first, second)); + when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) + .thenReturn(Optional.of(definition)); + when(workItemRepository.save(Mockito.any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + when(handoffService.handoff(Mockito.any(), Mockito.any())) + .thenAnswer( + invocation -> { + ScriptWorkItem item = invocation.getArgument(0); + if (item == first) { + throw new IllegalStateException("unexpected handoff failure"); + } + second.setStatus("HANDED_OFF"); + return new ScriptGameplayCommandHandoffService.HandoffResult( + true, "ENQUEUED", "auto-2", "", "", ""); + }); + + ScriptWorkItemExecutionService service = + new ScriptWorkItemExecutionServiceImpl( + workItemService, + definitionRepository, + handoffService, + workItemRepository, + Mockito.mock(ScriptEventAuditRepository.class), + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + new ScriptOutputProperties(), + allowingTenantBudgetService(), + allowingDryRunCapacityService(), + new ObjectMapper()); + + ScriptWorkItemExecutionService.ExecutionBatchResult result = + service.processPendingWorkItems(10); + + assertThat(result.claimedCount()).isEqualTo(2); + assertThat(result.completedCount()).isEqualTo(1); + assertThat(result.failedCount()).isEqualTo(1); + assertThat(first.getStatus()).isEqualTo("EVALUATING"); + assertThat(second.getStatus()).isEqualTo("HANDED_OFF"); + verify(workItemRepository).save(second); + verify(workItemRepository, Mockito.never()).save(first); + verify(handoffService, Mockito.times(2)).handoff(Mockito.any(), Mockito.any()); + } + @Test void retryableHandoffRequeuesAndPublishesPointerAfterCommit() { ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); @@ -318,12 +939,57 @@ void rejectedHandoffWithNonTerminalWorkItemFailsClosed() { assertThat(fixture.result().failedCount()).isEqualTo(1); assertThat(fixture.item().getStatus()).isEqualTo("DEAD_LETTERED"); + assertThat(fixture.item().getFailureGeneration()) + .isEqualTo(fixture.initialFailureGeneration() + 1L); assertThat(fixture.item().getCancelReason()).isEqualTo("remote_response_invalid"); assertThat(fixture.audit().getFinalStage()).isEqualTo("TICK_HANDOFF"); assertThat(fixture.audit().getFinalOutcome()).isEqualTo("infrastructure_error"); assertThat(fixture.audit().getFinalReason()).isEqualTo("remote_response_invalid"); } + @Test + void deadLetterGenerationAdvancesOncePerDistinctTransition() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptDefinitionRepository definitionRepository = + Mockito.mock(ScriptDefinitionRepository.class); + ScriptGameplayCommandHandoffService handoffService = + Mockito.mock(ScriptGameplayCommandHandoffService.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + ScriptWorkItem item = workItem(); + ScriptEventAudit audit = new ScriptEventAudit(); + when(workItemService.claimPendingForEvaluation(1)) + .thenReturn(List.of(item), List.of(item), List.of(item)); + when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) + .thenReturn(Optional.empty()); + when(auditRepository.findByWorkItemId(99L)).thenReturn(Optional.of(audit)); + when(workItemRepository.save(Mockito.any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + ScriptWorkItemExecutionService service = + new ScriptWorkItemExecutionServiceImpl( + workItemService, + definitionRepository, + handoffService, + workItemRepository, + auditRepository, + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + new ScriptOutputProperties(), + allowingTenantBudgetService(), + allowingDryRunCapacityService(), + new ObjectMapper(), + new SimpleMeterRegistry()); + + service.processPendingWorkItems(1); + assertThat(item.getFailureGeneration()).isEqualTo(1L); + + item.setStatus("PENDING_EVALUATION"); + service.processPendingWorkItems(1); + assertThat(item.getFailureGeneration()).isEqualTo(2L); + + service.processPendingWorkItems(1); + assertThat(item.getFailureGeneration()).isEqualTo(2L); + } + @Test void defersOutcomeMetricUntilTransactionCommit() { TransactionSynchronizationManager.initSynchronization(); @@ -1429,8 +2095,6 @@ private void assertMalformedDefinitionAndContinuesBatch( ScriptPatchReadinessProjectionService readinessProjectionService = Mockito.mock(ScriptPatchReadinessProjectionService.class); ScriptWorkItem malformed = workItem(); - malformed.setGameInstanceId(""); - malformed.setRegionId(""); malformed.setEntityId(""); malformed.setEventType(eventType); malformed.setScriptId("malformed-script"); @@ -1438,8 +2102,6 @@ private void assertMalformedDefinitionAndContinuesBatch( onLoad ? ScriptQuotaClasses.PUBLISH_READINESS : ScriptQuotaClasses.STANDARD_RUNTIME); ScriptWorkItem valid = workItem(); valid.setId(100L); - valid.setGameInstanceId(""); - valid.setRegionId(""); valid.setEntityId(""); valid.setEventType(eventType); valid.setScriptId("valid-script"); @@ -2068,8 +2730,14 @@ private static ExecutionFixture executeDefinition( allowingDryRunCapacityService(), new ObjectMapper(), meterRegistry); + long initialFailureGeneration = item.getFailureGeneration(); return new ExecutionFixture( - item, audit, handoffService, meterRegistry, service.processPendingWorkItems(10)); + item, + audit, + handoffService, + meterRegistry, + initialFailureGeneration, + service.processPendingWorkItems(10)); } private static io.micrometer.core.instrument.Counter outcomeCounter( @@ -2147,8 +2815,14 @@ private static ExecutionFixture executeDefinitionWithRejectedHandoff( allowingDryRunCapacityService(), new ObjectMapper(), meterRegistry); + long initialFailureGeneration = item.getFailureGeneration(); return new ExecutionFixture( - item, audit, handoffService, meterRegistry, service.processPendingWorkItems(10)); + item, + audit, + handoffService, + meterRegistry, + initialFailureGeneration, + service.processPendingWorkItems(10)); } private record ExecutionFixture( @@ -2156,6 +2830,7 @@ private record ExecutionFixture( ScriptEventAudit audit, ScriptGameplayCommandHandoffService handoffService, SimpleMeterRegistry meterRegistry, + long initialFailureGeneration, ScriptWorkItemExecutionService.ExecutionBatchResult result) {} private static ScriptTenantBudgetService allowingTenantBudgetService() { @@ -2202,6 +2877,44 @@ private static ScriptReadinessCapacityService denyingReadinessCapacityService() return service; } + private static ScriptWorkItemExecutionService fenceExecutionService( + ScriptWorkItemService workItemService, + ScriptWorkItemRepository workItemRepository, + ScriptEventAuditRepository auditRepository, + GameSessionControlPlaneClient gameSessionClient, + PluginRuntimeStateRepository pluginRuntimeStateRepository) { + return new ScriptWorkItemExecutionServiceImpl( + workItemService, + Mockito.mock(ScriptDefinitionRepository.class), + Mockito.mock(ScriptGameplayCommandHandoffService.class), + workItemRepository, + auditRepository, + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + new ScriptOutputProperties(), + allowingTenantBudgetService(), + allowingDryRunCapacityService(), + new ObjectMapper(), + new SimpleMeterRegistry(), + null, + null, + null, + gameSessionClient, + pluginRuntimeStateRepository); + } + + private static GetGameInstanceRuntimeStateResponse runtimeStateResponse() { + return GetGameInstanceRuntimeStateResponse.newBuilder() + .setRuntimeState( + net.firedevops.firemud.gamesession.v1.GameInstanceRuntimeState.newBuilder() + .setTenantId("1") + .setGameInstanceId("7") + .setRegionId("region-1") + .setRegionEpoch(12L) + .setPinnedScriptPatchVersion("patch-1") + .setScriptPinEpoch(3L)) + .build(); + } + private static ScriptWorkItem workItem() { ScriptWorkItem item = new ScriptWorkItem(); item.setId(99L); @@ -2219,9 +2932,20 @@ private static ScriptWorkItem workItem() { item.setSourceKind("GAMEPLAY_EVENT"); item.setSourceService("game-session-service"); item.setPayloadJson("{\"commandName\":\"LOOK\"}"); + item.setScriptPinEpoch(3L); item.setStatus("EVALUATING"); item.setCreatedAt(Instant.EPOCH); item.setUpdatedAt(Instant.EPOCH); return item; } + + private static ScriptWorkItem pluginWorkItem() { + ScriptWorkItem item = workItem(); + item.setScriptPinEpoch(3L); + item.setPluginId("plugin-1"); + item.setPluginVersionId("plugin-version-1"); + item.setPluginActivationEpoch(4L); + item.setLifecycleRevision(8L); + return item; + } } diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java index b1d2ef8488..73ab8f9c6e 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java @@ -7,15 +7,24 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import io.micrometer.core.instrument.MeterRegistry; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.lang.reflect.Method; import java.time.Instant; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Optional; +import java.util.stream.IntStream; import net.firedevops.firemud.automationscripting.client.GameDesignControlPlaneClient; +import net.firedevops.firemud.automationscripting.client.GameSessionControlPlaneClient; import net.firedevops.firemud.automationscripting.config.ScriptOutboxProperties; import net.firedevops.firemud.automationscripting.entity.ScriptEventAudit; -import net.firedevops.firemud.automationscripting.entity.ScriptEventIngressAudit; import net.firedevops.firemud.automationscripting.entity.ScriptHandoffEvent; import net.firedevops.firemud.automationscripting.entity.ScriptWorkItem; +import net.firedevops.firemud.automationscripting.repository.ScriptDeadLetterReplayRepository; import net.firedevops.firemud.automationscripting.repository.ScriptEventAuditRepository; import net.firedevops.firemud.automationscripting.repository.ScriptEventIngressAuditRepository; import net.firedevops.firemud.automationscripting.repository.ScriptHandoffEventRepository; @@ -26,7 +35,6 @@ import net.firedevops.firemud.automationscripting.service.ScriptPatchPinProjectionService; import net.firedevops.firemud.automationscripting.service.ScriptPatchReadinessProjectionService; import net.firedevops.firemud.automationscripting.service.ScriptWorkItemService; -import net.firedevops.firemud.automationscripting.v1.PluginState; import net.firedevops.firemud.automationscripting.v1.ScriptPatchInstanceRolloutStatus; import net.firedevops.firemud.automationscripting.v1.ScriptPatchStatus; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; @@ -34,6 +42,8 @@ import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.PublishedScriptPatchVersion; +import net.firedevops.firemud.gamesession.v1.GameInstanceRuntimeState; +import net.firedevops.firemud.gamesession.v1.GetGameInstanceRuntimeStateResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.NullAndEmptySource; @@ -42,6 +52,74 @@ import org.springframework.data.domain.PageRequest; class ScriptWorkItemServiceImplTest { + @Test + void replayFingerprintIsFixedLengthAndCanonicalAcrossIdOrderAndBoundaryWhitespace() + throws Exception { + List ids = + IntStream.rangeClosed(1, 100) + .mapToObj(String::valueOf) + .collect(java.util.stream.Collectors.toCollection(ArrayList::new)); + ScriptWorkItemService.ReplayDeadLettersCommand first = + new ScriptWorkItemService.ReplayDeadLettersCommand( + " tenant-1 ", "", "", ids, "", 0L, 0L, 100, " request-1 ", " operator ", " retry "); + List reordered = new ArrayList<>(ids); + Collections.reverse(reordered); + ScriptWorkItemService.ReplayDeadLettersCommand equivalent = + new ScriptWorkItemService.ReplayDeadLettersCommand( + "tenant-1", "", "", reordered, "", 0L, 0L, 100, "request-1", "operator", "retry"); + + Method fingerprint = + ScriptWorkItemServiceImpl.class.getDeclaredMethod( + "replayRequestFingerprint", ScriptWorkItemService.ReplayDeadLettersCommand.class); + fingerprint.setAccessible(true); + String firstDigest = (String) fingerprint.invoke(null, first); + String equivalentDigest = (String) fingerprint.invoke(null, equivalent); + + assertThat(firstDigest).hasSize(64).matches("[0-9a-f]{64}"); + assertThat(equivalentDigest).isEqualTo(firstDigest); + } + + @Test + void replayFingerprintUsesVersionedByteFramingAndCanonicalNumericIds() throws Exception { + ScriptWorkItemService.ReplayDeadLettersCommand unicodeTenant = + new ScriptWorkItemService.ReplayDeadLettersCommand( + "tenant-µ", "", "", List.of("01"), "", 0L, 0L, 1, "request-1", "operator", "retry"); + ScriptWorkItemService.ReplayDeadLettersCommand canonicalNumericId = + new ScriptWorkItemService.ReplayDeadLettersCommand( + "tenant-µ", "", "", List.of("1"), "", 0L, 0L, 1, "request-1", "operator", "retry"); + ScriptWorkItemService.ReplayDeadLettersCommand reorderedIds = + new ScriptWorkItemService.ReplayDeadLettersCommand( + "tenant-µ", "", "", List.of("2", "1"), "", 0L, 0L, 2, "request-1", "operator", "retry"); + ScriptWorkItemService.ReplayDeadLettersCommand orderedIds = + new ScriptWorkItemService.ReplayDeadLettersCommand( + "tenant-µ", "", "", List.of("1", "2"), "", 0L, 0L, 2, "request-1", "operator", "retry"); + ScriptWorkItemService.ReplayDeadLettersCommand differentId = + new ScriptWorkItemService.ReplayDeadLettersCommand( + "tenant-µ", "", "", List.of("12"), "", 0L, 0L, 1, "request-1", "operator", "retry"); + ScriptWorkItemService.ReplayDeadLettersCommand nulInActor = + new ScriptWorkItemService.ReplayDeadLettersCommand( + "tenant-1", "", "", List.of("1"), "", 0L, 0L, 1, "request-1", "ops\u0000x", "retry"); + ScriptWorkItemService.ReplayDeadLettersCommand nulShiftedToReason = + new ScriptWorkItemService.ReplayDeadLettersCommand( + "tenant-1", "", "", List.of("1"), "", 0L, 0L, 1, "request-1", "ops", "x\u0000retry"); + + assertThat(replayFingerprint(unicodeTenant)) + .isEqualTo("a76bf79431c5510c7118c0d96fc3e8206ef84381058b9eb20c08d3c45e5deecf"); + assertThat(replayFingerprint(canonicalNumericId)).isEqualTo(replayFingerprint(unicodeTenant)); + assertThat(replayFingerprint(reorderedIds)).isEqualTo(replayFingerprint(orderedIds)); + assertThat(replayFingerprint(orderedIds)).isNotEqualTo(replayFingerprint(differentId)); + assertThat(replayFingerprint(nulInActor)).isNotEqualTo(replayFingerprint(nulShiftedToReason)); + } + + private static String replayFingerprint(ScriptWorkItemService.ReplayDeadLettersCommand command) + throws Exception { + Method fingerprint = + ScriptWorkItemServiceImpl.class.getDeclaredMethod( + "replayRequestFingerprint", ScriptWorkItemService.ReplayDeadLettersCommand.class); + fingerprint.setAccessible(true); + return (String) fingerprint.invoke(null, command); + } + private static ScriptEventIngressAuditRepository ingressAuditRepository() { return Mockito.mock(ScriptEventIngressAuditRepository.class); } @@ -156,49 +234,453 @@ private static ScriptWorkItemService service( rolloutProjectionService, pluginRuntimeStateService, gameDesignControlPlaneClient, - readinessProjectionService); + readinessProjectionService, + null, + null, + new SimpleMeterRegistry()); + } + + private static ScriptWorkItemService service( + ScriptWorkItemRepository workItemRepository, + ScriptEventAuditRepository auditRepository, + ScriptEventIngressAuditRepository ingressAuditRepository, + ScriptHandoffEventRepository handoffEventRepository, + ScriptOutboxProperties outboxProperties, + AutomationAdmissionStateService automationAdmissionStateService, + ScriptPatchPinProjectionService scriptPatchPinProjectionService, + ScriptPatchInstanceRolloutProjectionService rolloutProjectionService, + PluginRuntimeStateService pluginRuntimeStateService, + GameDesignControlPlaneClient gameDesignControlPlaneClient, + ScriptPatchReadinessProjectionService readinessProjectionService, + MeterRegistry meterRegistry) { + return new ScriptWorkItemServiceImpl( + workItemRepository, + auditRepository, + ingressAuditRepository, + handoffEventRepository, + outboxProperties, + automationAdmissionStateService, + scriptPatchPinProjectionService, + rolloutProjectionService, + pluginRuntimeStateService, + gameDesignControlPlaneClient, + readinessProjectionService, + null, + null, + meterRegistry); } @Test - void replayDirectIdsNormalizesPaddedTenant() { + void rejectsDirectReplayWhenRuntimeAuthorityUnavailableAfterTenantNormalization() { ScriptWorkItem item = replayableRuntimeWorkItem(90L); + item.setScriptPinEpoch(1L); ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); when(workItemRepository.findById(90L)).thenReturn(Optional.of(item)); - when(workItemRepository.save(item)).thenReturn(item); ScriptWorkItemService service = replayService(workItemRepository); ScriptWorkItemService.ReplayResult result = service.replayDeadLetters( new ScriptWorkItemService.ReplayDeadLettersCommand( - " 1 ", "", "", List.of("90"), "", 0L, 0L, 10, "", "", "")); + " 1 ", "", "", List.of("90"), "", 0L, 0L, 10, "req-90", "", "")); - assertThat(result.replayedCount()).isEqualTo(1L); - assertThat(result.rejectedCount()).isZero(); - assertThat(item.getStatus()).isEqualTo("PENDING_EVALUATION"); + assertThat(result.replayedCount()).isZero(); + assertThat(result.rejectedCount()).isEqualTo(1L); + assertThat(result.results()) + .singleElement() + .satisfies( + replay -> + assertThat(replay.rejectionReason()) + .isEqualTo("script_pin_authority_collaborator_unavailable")); + assertThat(item.getStatus()).isEqualTo("DEAD_LETTERED"); verify(workItemRepository).findById(90L); } @Test - void replayTenantQueryNormalizesPaddedTenant() { - ScriptWorkItem item = replayableRuntimeWorkItem(91L); + void replayCountsOnlyCanonicalRetriedOutcome() { ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); - when(workItemRepository.findByTenantIdAndStatusOrderByUpdatedAtDescIdDesc( - "1", "DEAD_LETTERED", PageRequest.of(0, 10))) - .thenReturn(List.of(item)); - when(workItemRepository.save(item)).thenReturn(item); - ScriptWorkItemService service = replayService(workItemRepository); + ScriptDeadLetterReplayRepository replayRepository = + Mockito.mock(ScriptDeadLetterReplayRepository.class); + when(replayRepository.insertOrGet( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any())) + .thenAnswer( + invocation -> + new ScriptDeadLetterReplayRepository.ReplayRequest( + 1L, invocation.getArgument(2), "RUNNING", 0L, 0L)); + when(replayRepository.findResults(1L)) + .thenReturn( + List.of( + new ScriptDeadLetterReplayRepository.ReplayItem( + 90L, "retried_evaluation_unknown", "legacy_reason", 1L, 0L, 0L, 1L))); + ScriptWorkItemService service = + new ScriptWorkItemServiceImpl( + workItemRepository, + Mockito.mock(ScriptEventAuditRepository.class), + ingressAuditRepository(), + Mockito.mock(ScriptHandoffEventRepository.class), + outboxProperties(), + admissionStateService(), + Mockito.mock(ScriptPatchPinProjectionService.class), + rolloutProjectionService(), + Mockito.mock(PluginRuntimeStateService.class), + gameDesignClient(), + readinessProjectionService(), + replayRepository, + Mockito.mock(GameSessionControlPlaneClient.class), + new SimpleMeterRegistry()); ScriptWorkItemService.ReplayResult result = service.replayDeadLetters( new ScriptWorkItemService.ReplayDeadLettersCommand( - " 1 ", "", "", List.of(), "", 0L, 0L, 10, "", "", "")); + "1", "", "", List.of("90"), "", 0L, 0L, 10, "req-90", "admin", "retry")); + + assertThat(result.replayedCount()).isZero(); + assertThat(result.rejectedCount()).isEqualTo(1L); + assertThat(result.results()) + .singleElement() + .satisfies( + item -> { + assertThat(item.outcome()).isEqualTo("rejected"); + assertThat(item.rejectionReason()).isEqualTo("stage_evidence_unavailable"); + assertThat(item.failureReason()).isEmpty(); + }); + } + + @Test + void replayRetainsOriginalFailureEvidenceWithoutRewritingAudit() { + ScriptWorkItem item = replayableRuntimeWorkItem(95L); + item.setCancelReason("GAME_SESSION_UNAVAILABLE"); + item.setFailureGeneration(2L); + ScriptWorkItem claimed = replayableRuntimeWorkItem(95L); + claimed.setStatus("PENDING_EVALUATION"); + claimed.setCancelReason("GAME_SESSION_UNAVAILABLE"); + claimed.setFailureGeneration(2L); + + ScriptEventAudit audit = new ScriptEventAudit(); + audit.setFinalStage("TICK_HANDOFF"); + audit.setFinalOutcome("authority_unavailable_exhausted"); + audit.setFinalReason("GAME_SESSION_UNAVAILABLE"); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + when(auditRepository.findByWorkItemId(95L)).thenReturn(Optional.of(audit)); + + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + when(workItemRepository.findById(95L)).thenReturn(Optional.of(item)); + when(workItemRepository.claimDeadLetterForReplay( + Mockito.eq(95L), + Mockito.eq("1"), + Mockito.eq(item.getRowVersion()), + Mockito.eq(2L), + Mockito.any(Instant.class))) + .thenReturn(Optional.of(claimed)); + + ScriptDeadLetterReplayRepository replayRepository = + Mockito.mock(ScriptDeadLetterReplayRepository.class); + when(replayRepository.insertOrGet( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(Instant.class))) + .thenAnswer( + invocation -> + new ScriptDeadLetterReplayRepository.ReplayRequest( + 7L, invocation.getArgument(2), "RUNNING", 0L, 0L)); + when(replayRepository.findResults(7L)).thenReturn(List.of()); + when(replayRepository.complete( + Mockito.eq(7L), Mockito.eq(1L), Mockito.eq(0L), Mockito.any(Instant.class))) + .thenReturn(true); + java.util.concurrent.atomic.AtomicReference originalStage = + new java.util.concurrent.atomic.AtomicReference<>(); + java.util.concurrent.atomic.AtomicReference originalReason = + new java.util.concurrent.atomic.AtomicReference<>(); + Mockito.doAnswer( + invocation -> { + originalStage.set(invocation.getArgument(10)); + originalReason.set(invocation.getArgument(11)); + return null; + }) + .when(replayRepository) + .saveResult( + Mockito.anyLong(), + Mockito.anyLong(), + Mockito.any(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyLong(), + Mockito.anyLong(), + Mockito.anyLong(), + Mockito.anyLong(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(Instant.class)); + + ScriptPatchPinProjectionService pinProjectionService = + Mockito.mock(ScriptPatchPinProjectionService.class); + when(pinProjectionService.getPinConvergence("1", "game-1")) + .thenReturn( + new ScriptPatchPinProjectionService.PinConvergenceLookup( + Optional.of( + new ScriptPatchPinProjectionService.PinConvergenceSummary( + "1", "game-1", "patch-1", 1L, "req-1", 100L, 100L, 0L, false, "", 0L, "", + "", "")), + "", + "")); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "game-1", "region-1")) + .thenReturn( + GetGameInstanceRuntimeStateResponse.newBuilder() + .setRuntimeState( + GameInstanceRuntimeState.newBuilder() + .setTenantId("1") + .setGameInstanceId("game-1") + .setPinnedScriptPatchVersion("patch-1") + .setScriptPinEpoch(1L) + .setRegionId("region-1") + .setRegionEpoch(3L) + .build()) + .build()); + + ScriptWorkItemService service = + new ScriptWorkItemServiceImpl( + workItemRepository, + auditRepository, + ingressAuditRepository(), + Mockito.mock(ScriptHandoffEventRepository.class), + outboxProperties(), + admissionStateService(), + pinProjectionService, + rolloutProjectionService(), + Mockito.mock(PluginRuntimeStateService.class), + gameDesignClient(), + readinessProjectionService(), + replayRepository, + gameSessionClient, + new SimpleMeterRegistry()); + + ScriptWorkItemService.ReplayResult result = + service.replayDeadLetters( + new ScriptWorkItemService.ReplayDeadLettersCommand( + "1", "", "", List.of("95"), "", 0L, 0L, 10, "req-95", "admin", "retry")); assertThat(result.replayedCount()).isEqualTo(1L); - assertThat(result.rejectedCount()).isZero(); - assertThat(item.getStatus()).isEqualTo("PENDING_EVALUATION"); - verify(workItemRepository) - .findByTenantIdAndStatusOrderByUpdatedAtDescIdDesc( - "1", "DEAD_LETTERED", PageRequest.of(0, 10)); + assertThat(originalStage).hasValue("TICK_HANDOFF"); + assertThat(originalReason).hasValue("GAME_SESSION_UNAVAILABLE"); + assertThat(item.getCancelReason()).isEqualTo("GAME_SESSION_UNAVAILABLE"); + assertThat(claimed.getCancelReason()).isEqualTo("GAME_SESSION_UNAVAILABLE"); + assertThat(audit.getFinalStage()).isEqualTo("TICK_HANDOFF"); + assertThat(audit.getFinalReason()).isEqualTo("GAME_SESSION_UNAVAILABLE"); + verify(auditRepository, never()).save(Mockito.any(ScriptEventAudit.class)); + } + + @Test + void rejectsReplayWithoutOriginalFailureEvidenceBeforeClaim() { + ScriptWorkItem item = replayableRuntimeWorkItem(96L); + item.setCancelReason(""); + item.setFailureGeneration(3L); + ScriptWorkItem contradictory = replayableRuntimeWorkItem(97L); + contradictory.setCancelReason("WORK_ITEM_REASON"); + contradictory.setFailureGeneration(4L); + + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + when(workItemRepository.findById(96L)).thenReturn(Optional.of(item)); + when(workItemRepository.findById(97L)).thenReturn(Optional.of(contradictory)); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + when(auditRepository.findByWorkItemId(96L)).thenReturn(Optional.empty()); + ScriptEventAudit contradictoryAudit = new ScriptEventAudit(); + contradictoryAudit.setFinalStage("TICK_HANDOFF"); + contradictoryAudit.setFinalReason("AUDIT_REASON"); + when(auditRepository.findByWorkItemId(97L)).thenReturn(Optional.of(contradictoryAudit)); + + ScriptDeadLetterReplayRepository replayRepository = + Mockito.mock(ScriptDeadLetterReplayRepository.class); + when(replayRepository.insertOrGet( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(Instant.class))) + .thenAnswer( + invocation -> + new ScriptDeadLetterReplayRepository.ReplayRequest( + 8L, invocation.getArgument(2), "RUNNING", 0L, 0L)); + when(replayRepository.findResults(8L)).thenReturn(List.of()); + when(replayRepository.complete( + Mockito.eq(8L), Mockito.eq(0L), Mockito.eq(2L), Mockito.any(Instant.class))) + .thenReturn(true); + + ScriptPatchPinProjectionService pinProjectionService = + Mockito.mock(ScriptPatchPinProjectionService.class); + when(pinProjectionService.getPinConvergence("1", "game-1")) + .thenReturn( + new ScriptPatchPinProjectionService.PinConvergenceLookup( + Optional.of( + new ScriptPatchPinProjectionService.PinConvergenceSummary( + "1", "game-1", "patch-1", 1L, "req-1", 100L, 100L, 0L, false, "", 0L, "", + "", "")), + "", + "")); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "game-1", "region-1")) + .thenReturn( + GetGameInstanceRuntimeStateResponse.newBuilder() + .setRuntimeState( + GameInstanceRuntimeState.newBuilder() + .setTenantId("1") + .setGameInstanceId("game-1") + .setPinnedScriptPatchVersion("patch-1") + .setScriptPinEpoch(1L) + .setRegionId("region-1") + .setRegionEpoch(3L) + .build()) + .build()); + + ScriptWorkItemService service = + new ScriptWorkItemServiceImpl( + workItemRepository, + auditRepository, + ingressAuditRepository(), + Mockito.mock(ScriptHandoffEventRepository.class), + outboxProperties(), + admissionStateService(), + pinProjectionService, + rolloutProjectionService(), + Mockito.mock(PluginRuntimeStateService.class), + gameDesignClient(), + readinessProjectionService(), + replayRepository, + gameSessionClient, + new SimpleMeterRegistry()); + + ScriptWorkItemService.ReplayResult result = + service.replayDeadLetters( + new ScriptWorkItemService.ReplayDeadLettersCommand( + "1", "", "", List.of("96", "97"), "", 0L, 0L, 10, "req-96-97", "admin", "retry")); + + assertThat(result.replayedCount()).isZero(); + assertThat(result.rejectedCount()).isEqualTo(2L); + assertThat(result.results()) + .extracting(ScriptWorkItemService.ReplayItemResult::rejectionReason) + .containsExactly("stage_evidence_unavailable", "stage_evidence_unavailable"); + assertThat(item.getStatus()).isEqualTo("DEAD_LETTERED"); + assertThat(contradictory.getStatus()).isEqualTo("DEAD_LETTERED"); + verify(workItemRepository, never()) + .claimDeadLetterForReplay( + Mockito.anyLong(), + Mockito.anyString(), + Mockito.anyInt(), + Mockito.anyLong(), + Mockito.any(Instant.class)); + verify(replayRepository, Mockito.times(2)) + .saveResult( + Mockito.eq(8L), + Mockito.anyLong(), + Mockito.any(), + Mockito.eq("rejected"), + Mockito.eq("stage_evidence_unavailable"), + Mockito.eq(""), + Mockito.eq(1L), + Mockito.eq(0L), + Mockito.eq(0L), + Mockito.anyLong(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any(Instant.class)); + } + + @Test + void replayAggregateCountsAreDerivedFromPerItemOutcomes() { + ScriptDeadLetterReplayRepository replayRepository = + Mockito.mock(ScriptDeadLetterReplayRepository.class); + when(replayRepository.insertOrGet( + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.any())) + .thenAnswer( + invocation -> + new ScriptDeadLetterReplayRepository.ReplayRequest( + 1L, invocation.getArgument(2), "COMPLETED", 1L, 4L)); + when(replayRepository.findResults(1L)) + .thenReturn( + List.of( + new ScriptDeadLetterReplayRepository.ReplayItem( + 90L, "retried_evaluation", "", 1L, 0L, 0L, 1L), + new ScriptDeadLetterReplayRepository.ReplayItem( + 91L, "resumed_dispatch", "", 1L, 0L, 0L, 1L), + new ScriptDeadLetterReplayRepository.ReplayItem( + 92L, "already_recovered", "", 1L, 0L, 0L, 1L), + new ScriptDeadLetterReplayRepository.ReplayItem( + 93L, "recovery_failed", "", 1L, 0L, 0L, 1L), + new ScriptDeadLetterReplayRepository.ReplayItem( + 94L, "rejected", "stage_evidence_unavailable", 1L, 0L, 0L, 1L))); + ScriptWorkItemService service = + new ScriptWorkItemServiceImpl( + Mockito.mock(ScriptWorkItemRepository.class), + Mockito.mock(ScriptEventAuditRepository.class), + ingressAuditRepository(), + Mockito.mock(ScriptHandoffEventRepository.class), + outboxProperties(), + admissionStateService(), + Mockito.mock(ScriptPatchPinProjectionService.class), + rolloutProjectionService(), + Mockito.mock(PluginRuntimeStateService.class), + gameDesignClient(), + readinessProjectionService(), + replayRepository, + Mockito.mock(GameSessionControlPlaneClient.class), + new SimpleMeterRegistry()); + + ScriptWorkItemService.ReplayResult result = + service.replayDeadLetters( + new ScriptWorkItemService.ReplayDeadLettersCommand( + "1", + "", + "", + List.of("90", "91", "92", "93", "94"), + "", + 0L, + 0L, + 10, + "req-mixed", + "admin", + "retry")); + + assertThat(result.replayedCount()).isEqualTo(2L); + assertThat(result.rejectedCount()).isEqualTo(1L); + assertThat(result.results()) + .extracting(ScriptWorkItemService.ReplayItemResult::outcome) + .containsExactly( + "retried_evaluation", + "resumed_dispatch", + "already_recovered", + "recovery_failed", + "rejected"); + } + + @Test + void rejectsTenantReplayWithoutExplicitWorkItemIds() { + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptWorkItemService service = replayService(workItemRepository); + + assertThatThrownBy( + () -> + service.replayDeadLetters( + new ScriptWorkItemService.ReplayDeadLettersCommand( + " 1 ", "", "", List.of(), "", 0L, 0L, 10, "req-91", "", ""))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("invalid_work_item_ids"); + verifyNoInteractions(workItemRepository); } @ParameterizedTest @@ -215,8 +697,13 @@ void cancelsPendingPatchWorkAndUpdatesAuditOutcome(String gameInstanceId) { ScriptEventAudit audit = new ScriptEventAudit(); ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); - when(workItemRepository.findByTenantIdAndScriptPatchVersionAndStatusInOrderByCreatedAtAscIdAsc( - "1", "patch-1", List.of("PENDING_EVALUATION"))) + when(workItemRepository + .findByTenantIdAndScriptPatchVersionAndStatusInForUpdateOrderByCreatedAtAscIdAsc( + Mockito.eq("1"), + Mockito.eq("patch-1"), + Mockito.anyString(), + Mockito.anyString(), + Mockito.eq(List.of("PENDING_EVALUATION")))) .thenReturn(List.of(item)); when(auditRepository.findByWorkItemId(42L)).thenReturn(Optional.of(audit)); ScriptWorkItemService service = @@ -260,8 +747,9 @@ void refreshesReadinessProjectionWhenCancelingPendingOnLoadWork() { ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); ScriptPatchReadinessProjectionService readinessProjectionService = Mockito.mock(ScriptPatchReadinessProjectionService.class); - when(workItemRepository.findByTenantIdAndScriptPatchVersionAndStatusInOrderByCreatedAtAscIdAsc( - "1", "patch-1", List.of("PENDING_EVALUATION"))) + when(workItemRepository + .findByTenantIdAndScriptPatchVersionAndStatusInForUpdateOrderByCreatedAtAscIdAsc( + "1", "patch-1", "", "", List.of("PENDING_EVALUATION"))) .thenReturn(List.of(item)); when(auditRepository.findByWorkItemId(43L)).thenReturn(Optional.of(audit)); ScriptWorkItemService service = @@ -292,6 +780,7 @@ void refreshesReadinessProjectionWhenCancelingPendingOnLoadWork() { @ValueSource(strings = {"game-1", " game-1 ", " "}) @NullAndEmptySource void cancelsPendingPluginVersionWorkAndUpdatesAuditOutcome(String gameInstanceId) { + String normalizedGameInstanceId = gameInstanceId == null ? "" : gameInstanceId.strip(); ScriptWorkItem item = new ScriptWorkItem(); item.setId(43L); item.setTenantId("1"); @@ -305,8 +794,13 @@ void cancelsPendingPluginVersionWorkAndUpdatesAuditOutcome(String gameInstanceId ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); when(workItemRepository - .findByTenantIdAndPluginIdAndPluginVersionIdAndStatusInOrderByCreatedAtAscIdAsc( - "1", "plugin-1", "plugin-v1", List.of("PENDING_EVALUATION"))) + .findByTenantIdAndPluginIdAndPluginVersionIdAndStatusInForUpdateOrderByCreatedAtAscIdAsc( + "1", + "plugin-1", + "plugin-v1", + normalizedGameInstanceId, + "", + List.of("PENDING_EVALUATION"))) .thenReturn(List.of(item)); when(auditRepository.findByWorkItemId(43L)).thenReturn(Optional.of(audit)); ScriptWorkItemService service = @@ -325,14 +819,7 @@ void cancelsPendingPluginVersionWorkAndUpdatesAuditOutcome(String gameInstanceId long canceled = service.cancelPendingForPluginVersion( new ScriptWorkItemService.CancelPendingForPluginVersionCommand( - " 1 ", - "plugin-1", - "plugin-v1", - gameInstanceId, - " region-1 ", - "req-1", - "admin", - "")); + " 1 ", "plugin-1", "plugin-v1", gameInstanceId, "", "req-1", "admin", "")); assertThat(canceled).isEqualTo(1L); assertThat(item.getStatus()).isEqualTo("CANCELED"); @@ -343,13 +830,62 @@ void cancelsPendingPluginVersionWorkAndUpdatesAuditOutcome(String gameInstanceId verify(auditRepository).save(audit); } + @Test + void cancellationContinuesAcrossBoundedPagesUntilNoEligibleRowsRemain() { + List firstPage = + IntStream.rangeClosed(1, 100).mapToObj(id -> cancelableWorkItem(id, "patch-1")).toList(); + List secondPage = List.of(cancelableWorkItem(101L, "patch-1")); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + when(workItemRepository + .findByTenantIdAndScriptPatchVersionAndStatusInForUpdateOrderByCreatedAtAscIdAsc( + "tenant-1", "patch-1", "game-1", "region-1", List.of("PENDING_EVALUATION"))) + .thenReturn(firstPage, secondPage, List.of()); + ScriptWorkItemService service = + service( + workItemRepository, + auditRepository, + ingressAuditRepository(), + Mockito.mock(ScriptHandoffEventRepository.class), + outboxProperties(), + admissionStateService(), + Mockito.mock(ScriptPatchPinProjectionService.class), + rolloutProjectionService(), + Mockito.mock(PluginRuntimeStateService.class), + gameDesignClient()); + + long canceled = + service.cancelPendingForPatch( + new ScriptWorkItemService.CancelPendingForPatchCommand( + "tenant-1", "patch-1", "game-1", "region-1", "req-1", "admin", "rollback")); + + assertThat(canceled).isEqualTo(101L); + assertThat(firstPage).allSatisfy(item -> assertThat(item.getStatus()).isEqualTo("CANCELED")); + assertThat(secondPage).allSatisfy(item -> assertThat(item.getStatus()).isEqualTo("CANCELED")); + verify(workItemRepository, Mockito.times(2)).saveAll(Mockito.anyCollection()); + verify(workItemRepository, Mockito.times(2)) + .findByTenantIdAndScriptPatchVersionAndStatusInForUpdateOrderByCreatedAtAscIdAsc( + "tenant-1", "patch-1", "game-1", "region-1", List.of("PENDING_EVALUATION")); + } + + private static ScriptWorkItem cancelableWorkItem(long id, String scriptPatchVersion) { + ScriptWorkItem item = new ScriptWorkItem(); + item.setId(id); + item.setTenantId("tenant-1"); + item.setGameInstanceId("game-1"); + item.setRegionId("region-1"); + item.setScriptPatchVersion(scriptPatchVersion); + item.setStatus("PENDING_EVALUATION"); + return item; + } + @Test void claimsPendingItemsForEvaluationInStableOrder() { ScriptWorkItem item = new ScriptWorkItem(); item.setStatus("PENDING_EVALUATION"); ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); - when(workItemRepository.findByStatusOrderByCreatedAtAscIdAsc( + when(workItemRepository.findByStatusForUpdateOrderByCreatedAtAscIdAsc( "PENDING_EVALUATION", PageRequest.of(0, 10))) .thenReturn(List.of(item)); when(workItemRepository.saveAll(List.of(item))).thenReturn(List.of(item)); @@ -400,7 +936,7 @@ void claimsPendingWorkItemsByQueuePointerIds() { item.setId(99L); ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); - when(workItemRepository.findByIdInAndStatusOrderByCreatedAtAscIdAsc( + when(workItemRepository.findByIdInAndStatusForUpdateOrderByCreatedAtAscIdAsc( List.of(99L, 100L), "PENDING_EVALUATION", PageRequest.of(0, 10))) .thenReturn(List.of(item)); when(workItemRepository.saveAll(List.of(item))).thenReturn(List.of(item)); @@ -434,10 +970,6 @@ void cleansTerminalOutboxRowsUsingConfiguredRetentionWindows() { .thenReturn(2L); when(workItemRepository.deleteByStatusAndUpdatedAtBefore(Mockito.eq("CANCELED"), Mockito.any())) .thenReturn(3L); - when(workItemRepository.deleteByStatusAndUpdatedAtBefore( - Mockito.eq("DEAD_LETTERED"), Mockito.any())) - .thenReturn(5L); - when(workItemRepository.countByStatus("DEAD_LETTERED")).thenReturn(100000L); ScriptWorkItemService service = service( workItemRepository, @@ -455,24 +987,81 @@ void cleansTerminalOutboxRowsUsingConfiguredRetentionWindows() { assertThat(result.handedOffDeleted()).isEqualTo(2L); assertThat(result.canceledDeleted()).isEqualTo(3L); - assertThat(result.deadLetteredDeleted()).isEqualTo(5L); - assertThat(result.totalDeleted()).isEqualTo(10L); + assertThat(result.deadLetteredDeleted()).isZero(); + assertThat(result.totalDeleted()).isEqualTo(5L); verify(workItemRepository) .deleteByStatusAndUpdatedAtBefore(Mockito.eq("HANDED_OFF"), Mockito.any()); verify(workItemRepository) .deleteByStatusAndUpdatedAtBefore(Mockito.eq("CANCELED"), Mockito.any()); - verify(workItemRepository) + verify(workItemRepository, never()) .deleteByStatusAndUpdatedAtBefore(Mockito.eq("DEAD_LETTERED"), Mockito.any()); } @Test - void deletesOldestDeadLettersWhenRowCapIsExceeded() { + void updatesRetentionBlockedRowsGaugeToCurrentBlockedPopulation() { + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + when(workItemRepository.countTerminalRowsBlockedByEvidence(Mockito.anyString(), Mockito.any())) + .thenReturn(2L, 2L, 2L, 0L, 0L, 0L); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + ScriptWorkItemService service = + service( + workItemRepository, + auditRepository, + ingressAuditRepository(), + Mockito.mock(ScriptHandoffEventRepository.class), + outboxProperties(), + admissionStateService(), + Mockito.mock(ScriptPatchPinProjectionService.class), + rolloutProjectionService(), + Mockito.mock(PluginRuntimeStateService.class), + gameDesignClient(), + readinessProjectionService(), + meterRegistry); + + service.cleanupTerminalWorkItems(); + assertThat(meterRegistry.get("automation_retention_blocked_rows").gauge().value()) + .isEqualTo(6.0); + + service.cleanupTerminalWorkItems(); + assertThat(meterRegistry.get("automation_retention_blocked_rows").gauge().value()).isZero(); + } + + @Test + void doesNotDisposeReplayEvidenceWithoutARecoveryAwareHorizon() { + ScriptDeadLetterReplayRepository replayRepository = + Mockito.mock(ScriptDeadLetterReplayRepository.class); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + ScriptWorkItemService service = + new ScriptWorkItemServiceImpl( + Mockito.mock(ScriptWorkItemRepository.class), + Mockito.mock(ScriptEventAuditRepository.class), + ingressAuditRepository(), + Mockito.mock(ScriptHandoffEventRepository.class), + outboxProperties(), + admissionStateService(), + Mockito.mock(ScriptPatchPinProjectionService.class), + rolloutProjectionService(), + Mockito.mock(PluginRuntimeStateService.class), + gameDesignClient(), + readinessProjectionService(), + replayRepository, + Mockito.mock(GameSessionControlPlaneClient.class), + meterRegistry); + + service.cleanupTerminalWorkItems(); + + verifyNoInteractions(replayRepository); + assertThat(meterRegistry.find("automation_retention_disposed_total").counter()).isNull(); + } + + @Test + void doesNotScanOrDeleteDeadLettersForAgeOrRowCap() { ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); ScriptOutboxProperties properties = outboxProperties(); - properties.setDeadLetterMaxRows(2); - when(workItemRepository.countByStatus("DEAD_LETTERED")).thenReturn(5L); - when(workItemRepository.deleteOldestByStatus("DEAD_LETTERED", 3)).thenReturn(2L); + properties.setDeadLetterMaxRows(1); + when(workItemRepository.countByStatus("DEAD_LETTERED")).thenReturn(2L); ScriptWorkItemService service = service( workItemRepository, @@ -486,10 +1075,8 @@ void deletesOldestDeadLettersWhenRowCapIsExceeded() { Mockito.mock(PluginRuntimeStateService.class), gameDesignClient()); - ScriptWorkItemService.TerminalCleanupResult result = service.cleanupTerminalWorkItems(); - - assertThat(result.deadLetteredDeleted()).isEqualTo(2L); - verify(workItemRepository).deleteOldestByStatus("DEAD_LETTERED", 3); + assertThat(service.cleanupTerminalWorkItems().deadLetteredDeleted()).isZero(); + verify(workItemRepository, never()).countByStatus("DEAD_LETTERED"); } @Test @@ -757,6 +1344,117 @@ void reportsAutomationDrainStatusForScopedWorkItems() { assertThat(summary.observedAtMs()).isPositive(); } + @Test + void normalAutomationDrainStatusCountsOnlyCurrentAdmissionEpoch() { + ScriptWorkItem currentEvaluating = + workItem("patch-1", "EVALUATING", Instant.ofEpochMilli(120L)); + currentEvaluating.setAdmissionEpoch(2L); + currentEvaluating.setCreatedAt(Instant.ofEpochMilli(120L)); + ScriptWorkItem currentPending = + workItem("patch-1", "PENDING_EVALUATION", Instant.ofEpochMilli(130L)); + currentPending.setAdmissionEpoch(2L); + currentPending.setCreatedAt(Instant.ofEpochMilli(130L)); + ScriptWorkItem priorHandoff = + workItem("patch-1", "HANDOFF_IN_FLIGHT", Instant.ofEpochMilli(100L)); + priorHandoff.setAdmissionEpoch(1L); + priorHandoff.setCreatedAt(Instant.ofEpochMilli(100L)); + ScriptWorkItem futureEvaluating = workItem("patch-1", "EVALUATING", Instant.ofEpochMilli(90L)); + futureEvaluating.setAdmissionEpoch(3L); + futureEvaluating.setCreatedAt(Instant.ofEpochMilli(90L)); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + AutomationAdmissionStateService admissionStateService = + Mockito.mock(AutomationAdmissionStateService.class); + when(admissionStateService.findState("1", "game-1", "region-1")) + .thenReturn( + Optional.of( + new AutomationAdmissionStateService.AdmissionStateSummary( + "1", "game-1", "region-1", "NORMAL", 2L, "", "", 100L))); + when(workItemRepository.findByScopeAndStatusesOrderByCreatedAtAscIdAsc( + "1", + "game-1", + "region-1", + List.of("PENDING_EVALUATION", "EVALUATING", "HANDOFF_IN_FLIGHT"))) + .thenReturn(List.of(currentEvaluating, currentPending, priorHandoff, futureEvaluating)); + ScriptWorkItemService service = + service( + workItemRepository, + auditRepository, + ingressAuditRepository(), + Mockito.mock(ScriptHandoffEventRepository.class), + outboxProperties(), + admissionStateService, + Mockito.mock(ScriptPatchPinProjectionService.class), + rolloutProjectionService(), + Mockito.mock(PluginRuntimeStateService.class), + gameDesignClient()); + + ScriptWorkItemService.AutomationDrainStatusSummary summary = + service.getAutomationDrainStatus("1", "game-1", "region-1"); + + assertThat(summary.activeExecutionCount()).isEqualTo(1L); + assertThat(summary.oldestActiveExecutionStartedAtMs()).isEqualTo(120L); + assertThat(summary.pendingCancelableWorkItemCount()).isEqualTo(1L); + } + + @Test + void pausedAutomationDrainStatusCountsLegacyAndPriorEpochsOnly() { + ScriptWorkItem legacyPending = + workItem("patch-1", "PENDING_EVALUATION", Instant.ofEpochMilli(130L)); + legacyPending.setAdmissionEpoch(0L); + legacyPending.setCreatedAt(Instant.ofEpochMilli(130L)); + ScriptWorkItem priorEvaluating = workItem("patch-1", "EVALUATING", Instant.ofEpochMilli(110L)); + priorEvaluating.setAdmissionEpoch(1L); + priorEvaluating.setCreatedAt(Instant.ofEpochMilli(110L)); + ScriptWorkItem priorHandoff = + workItem("patch-1", "HANDOFF_IN_FLIGHT", Instant.ofEpochMilli(120L)); + priorHandoff.setAdmissionEpoch(-1L); + priorHandoff.setCreatedAt(Instant.ofEpochMilli(120L)); + ScriptWorkItem currentEvaluating = workItem("patch-1", "EVALUATING", Instant.ofEpochMilli(90L)); + currentEvaluating.setAdmissionEpoch(2L); + currentEvaluating.setCreatedAt(Instant.ofEpochMilli(90L)); + ScriptWorkItem futurePending = + workItem("patch-1", "PENDING_EVALUATION", Instant.ofEpochMilli(80L)); + futurePending.setAdmissionEpoch(3L); + futurePending.setCreatedAt(Instant.ofEpochMilli(80L)); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + AutomationAdmissionStateService admissionStateService = + Mockito.mock(AutomationAdmissionStateService.class); + when(admissionStateService.findState("1", "game-1", "region-1")) + .thenReturn( + Optional.of( + new AutomationAdmissionStateService.AdmissionStateSummary( + "1", "game-1", "region-1", "PAUSED_FOR_ROLLBACK", 2L, "", "", 100L))); + when(workItemRepository.findByScopeAndStatusesOrderByCreatedAtAscIdAsc( + "1", + "game-1", + "region-1", + List.of("PENDING_EVALUATION", "EVALUATING", "HANDOFF_IN_FLIGHT"))) + .thenReturn( + List.of( + legacyPending, priorEvaluating, priorHandoff, currentEvaluating, futurePending)); + ScriptWorkItemService service = + service( + workItemRepository, + auditRepository, + ingressAuditRepository(), + Mockito.mock(ScriptHandoffEventRepository.class), + outboxProperties(), + admissionStateService, + Mockito.mock(ScriptPatchPinProjectionService.class), + rolloutProjectionService(), + Mockito.mock(PluginRuntimeStateService.class), + gameDesignClient()); + + ScriptWorkItemService.AutomationDrainStatusSummary summary = + service.getAutomationDrainStatus("1", "game-1", "region-1"); + + assertThat(summary.activeExecutionCount()).isEqualTo(2L); + assertThat(summary.oldestActiveExecutionStartedAtMs()).isEqualTo(110L); + assertThat(summary.pendingCancelableWorkItemCount()).isEqualTo(1L); + } + @Test void reportsZeroedAutomationDrainStatusWhenScopedWorkIsEmpty() { ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); @@ -1755,13 +2453,12 @@ void normalizesPartialRoutingBundleFilterAndSummaryForHandoffEvents() { } @ParameterizedTest - @ValueSource(strings = {"game-1", " game-1 ", " "}) @NullAndEmptySource - void replaysEligibleDeadLetteredWorkItem(String gameInstanceId) { + void rejectsReplayForMissingGameInstanceId(String gameInstanceId) { ScriptWorkItem item = workItem("patch-1", "DEAD_LETTERED", Instant.ofEpochMilli(300)); item.setId(77L); item.setTenantId("1"); - item.setGameInstanceId("game-1"); + item.setGameInstanceId(gameInstanceId); item.setRegionId("region-1"); item.setRegionEpoch(3L); item.setScriptPinEpoch(1L); @@ -1774,10 +2471,6 @@ void replaysEligibleDeadLetteredWorkItem(String gameInstanceId) { item.setCreatedAt(Instant.ofEpochMilli(100)); item.setCancelReason("GAME_SESSION_UNAVAILABLE"); ScriptEventAudit audit = new ScriptEventAudit(); - ScriptEventIngressAudit ingressAudit = new ScriptEventIngressAudit(); - ingressAudit.setPluginId(""); - ScriptPatchPinProjectionService pinProjectionService = - Mockito.mock(ScriptPatchPinProjectionService.class); PluginRuntimeStateService pluginRuntimeStateService = Mockito.mock(PluginRuntimeStateService.class); ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); @@ -1786,32 +2479,6 @@ void replaysEligibleDeadLetteredWorkItem(String gameInstanceId) { when(workItemRepository.findById(77L)).thenReturn(Optional.of(item)); when(workItemRepository.save(item)).thenReturn(item); when(auditRepository.findByWorkItemId(77L)).thenReturn(Optional.of(audit)); - when(ingressAuditRepository - .findByTenantIdAndGameInstanceIdAndRegionIdAndRegionEpochAndEntityIdAndPlayableStateScopeAndEventTypeAndEventSchemaVersionAndScriptPatchVersionAndScriptPinEpochAndScriptPinControlPlaneRequestIdAndScriptEventIdAndDryRunAndSourceService( - "1", - "game-1", - "region-1", - 3L, - "entity-1", - "", - "onCommand", - "v1", - "patch-1", - 1L, - "req-1", - "event-1", - false, - "game-session-service")) - .thenReturn(Optional.of(ingressAudit)); - when(pinProjectionService.getPinConvergence("1", "game-1")) - .thenReturn( - new ScriptPatchPinProjectionService.PinConvergenceLookup( - Optional.of( - new ScriptPatchPinProjectionService.PinConvergenceSummary( - "1", "game-1", "patch-1", 1L, "req-1", 500L, 501L, 0L, false, "", 0L, "", - "", "")), - "", - "")); ScriptWorkItemService service = service( workItemRepository, @@ -1820,7 +2487,7 @@ void replaysEligibleDeadLetteredWorkItem(String gameInstanceId) { Mockito.mock(ScriptHandoffEventRepository.class), outboxProperties(), admissionStateService(), - pinProjectionService, + Mockito.mock(ScriptPatchPinProjectionService.class), rolloutProjectionService(), pluginRuntimeStateService, gameDesignClient()); @@ -1828,29 +2495,19 @@ void replaysEligibleDeadLetteredWorkItem(String gameInstanceId) { ScriptWorkItemService.ReplayResult result = service.replayDeadLetters( new ScriptWorkItemService.ReplayDeadLettersCommand( - "1", - gameInstanceId, - " region-1 ", - List.of("77"), - "patch-1", - 0L, - 0L, - 10, - "req-1", - "admin", - "retry")); + "1", "", "", List.of("77"), "", 0L, 0L, 10, "req-1", "admin", "retry")); - assertThat(result.replayedCount()).isEqualTo(1L); - assertThat(result.rejectedCount()).isEqualTo(0L); - assertThat(item.getStatus()).isEqualTo("PENDING_EVALUATION"); - assertThat(item.getCancelReason()).isEmpty(); - assertThat(audit.getFinalStage()).isEqualTo("REPLAY"); - assertThat(audit.getFinalOutcome()).isEqualTo("requeued"); - assertThat(audit.getFinalReason()).isEqualTo("retry"); + assertThat(result.replayedCount()).isZero(); + assertThat(result.rejectedCount()).isEqualTo(1L); + assertThat(result.results()) + .singleElement() + .satisfies( + replay -> assertThat(replay.rejectionReason()).isEqualTo("runtime_scope_missing")); + assertThat(item.getStatus()).isEqualTo("DEAD_LETTERED"); } @Test - void replaysPluginOwnedDeadLetterUsingWorkItemPluginIdentityBeforeIngressAuditFallback() { + void rejectsPluginOwnedDeadLetterWhenRuntimeAuthorityIsUnavailable() { ScriptWorkItem item = workItem("patch-1", "DEAD_LETTERED", Instant.ofEpochMilli(300)); item.setId(78L); item.setTenantId("1"); @@ -1867,16 +2524,12 @@ void replaysPluginOwnedDeadLetterUsingWorkItemPluginIdentityBeforeIngressAuditFa item.setScriptEventId("event-2"); item.setSourceService("game-session-service"); item.setCreatedAt(Instant.ofEpochMilli(100)); - ScriptEventAudit audit = new ScriptEventAudit(); - ScriptEventIngressAudit ingressAudit = new ScriptEventIngressAudit(); - ingressAudit.setPluginId(""); ScriptPatchPinProjectionService pinProjectionService = Mockito.mock(ScriptPatchPinProjectionService.class); PluginRuntimeStateService pluginRuntimeStateService = Mockito.mock(PluginRuntimeStateService.class); ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); - ScriptEventIngressAuditRepository ingressAuditRepository = ingressAuditRepository(); when(workItemRepository.findById(78L)).thenReturn(Optional.of(item)); when(workItemRepository.save(item)).thenReturn(item); when(auditRepository.findByWorkItemId(78L)).thenReturn(Optional.of(audit)); @@ -1926,7 +2579,7 @@ void replaysPluginOwnedDeadLetterUsingWorkItemPluginIdentityBeforeIngressAuditFa service( workItemRepository, auditRepository, - ingressAuditRepository, + ingressAuditRepository(), Mockito.mock(ScriptHandoffEventRepository.class), outboxProperties(), admissionStateService(), @@ -1938,21 +2591,12 @@ void replaysPluginOwnedDeadLetterUsingWorkItemPluginIdentityBeforeIngressAuditFa ScriptWorkItemService.ReplayResult result = service.replayDeadLetters( new ScriptWorkItemService.ReplayDeadLettersCommand( - "1", - "game-1", - "region-1", - List.of("78"), - "patch-1", - 0L, - 0L, - 10, - "req-1", - "admin", - "retry")); + "1", "", "", List.of("78"), "", 0L, 0L, 10, "req-1", "admin", "retry")); - assertThat(result.replayedCount()).isEqualTo(1L); - assertThat(result.rejectedCount()).isEqualTo(0L); - verify(pluginRuntimeStateService).getStatus("1", "game-1", "plugin-1"); + assertThat(result.replayedCount()).isZero(); + assertThat(result.rejectedCount()).isEqualTo(1L); + assertThat(item.getStatus()).isEqualTo("DEAD_LETTERED"); + verify(pluginRuntimeStateService, Mockito.never()).getStatus("1", "game-1", "plugin-1"); } @Test @@ -2019,7 +2663,7 @@ void rejectsReplayWhenPinnedPatchDoesNotMatch() { ScriptWorkItemService.ReplayResult result = service.replayDeadLetters( new ScriptWorkItemService.ReplayDeadLettersCommand( - "1", "game-1", "", List.of("77"), "", 0L, 0L, 10, "", "", "")); + "1", "", "", List.of("77"), "", 0L, 0L, 10, "req-77", "", "")); assertThat(result.replayedCount()).isEqualTo(0L); assertThat(result.rejectedCount()).isEqualTo(1L); @@ -2027,7 +2671,7 @@ void rejectsReplayWhenPinnedPatchDoesNotMatch() { } @Test - void replaysFailedOnLoadDeadLetterWhenReadinessProjectionMatches() { + void rejectsOnLoadDeadLetterWithCanonicalReplayReason() { ScriptWorkItem item = workItem("patch-1", "DEAD_LETTERED", Instant.ofEpochMilli(300)); item.setId(88L); item.setTenantId("1"); @@ -2071,15 +2715,20 @@ void replaysFailedOnLoadDeadLetterWhenReadinessProjectionMatches() { ScriptWorkItemService.ReplayResult result = service.replayDeadLetters( new ScriptWorkItemService.ReplayDeadLettersCommand( - "1", "", "", List.of("88"), "patch-1", 0L, 0L, 10, "req-1", "admin", "retry")); + "1", "", "", List.of("88"), "", 0L, 0L, 10, "req-1", "admin", "retry")); - assertThat(result.replayedCount()).isEqualTo(1L); - assertThat(result.rejectedCount()).isEqualTo(0L); - assertThat(item.getStatus()).isEqualTo("PENDING_EVALUATION"); - assertThat(item.getCancelReason()).isEmpty(); - verify(readinessProjectionService).refreshFromOnLoadWorkItems("1", "patch-1"); - assertThat(audit.getFinalStage()).isEqualTo("REPLAY"); - assertThat(audit.getFinalOutcome()).isEqualTo("requeued"); + assertThat(result.replayedCount()).isZero(); + assertThat(result.rejectedCount()).isEqualTo(1L); + assertThat(result.results()) + .singleElement() + .satisfies( + replay -> { + assertThat(replay.outcome()).isEqualTo("rejected"); + assertThat(replay.rejectionReason()).isEqualTo("onload_not_replayable"); + }); + assertThat(item.getStatus()).isEqualTo("DEAD_LETTERED"); + verify(readinessProjectionService, Mockito.never()) + .refreshFromOnLoadWorkItems(Mockito.anyString(), Mockito.anyString()); } @Test @@ -2122,7 +2771,7 @@ void rejectsReplayForSupersededOnLoadDeadLetter() { ScriptWorkItemService.ReplayResult result = service.replayDeadLetters( new ScriptWorkItemService.ReplayDeadLettersCommand( - "1", "", "", List.of("89"), "patch-old", 0L, 0L, 10, "", "", "")); + "1", "", "", List.of("89"), "", 0L, 0L, 10, "req-89", "", "")); assertThat(result.replayedCount()).isEqualTo(0L); assertThat(result.rejectedCount()).isEqualTo(1L); @@ -2157,6 +2806,77 @@ void replayRejectsNonPositiveWorkItemIdBeforeRepositoryRead() { Mockito.verifyNoInteractions(workItemRepository); } + @Test + void replayRejectsDistinctTextualIdsThatParseToTheSameWorkItem() { + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptWorkItemService service = + service( + workItemRepository, + Mockito.mock(ScriptEventAuditRepository.class), + ingressAuditRepository(), + Mockito.mock(ScriptHandoffEventRepository.class), + outboxProperties(), + admissionStateService(), + Mockito.mock(ScriptPatchPinProjectionService.class), + rolloutProjectionService(), + Mockito.mock(PluginRuntimeStateService.class), + gameDesignClient()); + + assertThatThrownBy( + () -> + service.replayDeadLetters( + new ScriptWorkItemService.ReplayDeadLettersCommand( + "1", "", "", List.of("01", "1"), "", 0L, 0L, 10, "req-duplicate", "", ""))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("invalid_work_item_ids"); + Mockito.verifyNoInteractions(workItemRepository); + } + + @Test + void replayEligibilityRejectsRuntimeScopeMismatchBeforeFenceComparison() throws Exception { + ScriptWorkItem item = replayableRuntimeWorkItem(92L); + item.setScriptPinEpoch(1L); + GameSessionControlPlaneClient gameSessionControlPlaneClient = + Mockito.mock(GameSessionControlPlaneClient.class); + when(gameSessionControlPlaneClient.getGameInstanceRuntimeState("1", "game-1", "region-1")) + .thenReturn( + GetGameInstanceRuntimeStateResponse.newBuilder() + .setRuntimeState( + GameInstanceRuntimeState.newBuilder() + .setTenantId("other-tenant") + .setGameInstanceId("game-1") + .setPinnedScriptPatchVersion("patch-1") + .setScriptPinEpoch(1L) + .setRegionId("region-1") + .setRegionEpoch(3L) + .build()) + .build()); + ScriptWorkItemServiceImpl service = + new ScriptWorkItemServiceImpl( + Mockito.mock(ScriptWorkItemRepository.class), + Mockito.mock(ScriptEventAuditRepository.class), + ingressAuditRepository(), + Mockito.mock(ScriptHandoffEventRepository.class), + outboxProperties(), + admissionStateService(), + Mockito.mock(ScriptPatchPinProjectionService.class), + rolloutProjectionService(), + Mockito.mock(PluginRuntimeStateService.class), + gameDesignClient(), + readinessProjectionService(), + Mockito.mock(ScriptDeadLetterReplayRepository.class), + gameSessionControlPlaneClient, + new SimpleMeterRegistry()); + + Method eligibility = + ScriptWorkItemServiceImpl.class.getDeclaredMethod( + "replayEligibilityReason", ScriptWorkItem.class, Map.class); + eligibility.setAccessible(true); + + assertThat(eligibility.invoke(service, item, new HashMap<>())) + .isEqualTo("runtime_scope_changed"); + } + private static ScriptWorkItem workItem(String patchVersion, String status, Instant updatedAt) { ScriptWorkItem item = new ScriptWorkItem(); item.setTenantId("1"); From b158b0282f2dc9bd75de6ebdd0abea4904355132 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 21 Sep 2026 11:30:41 +1200 Subject: [PATCH 03/68] Document durable replay and Entity receipt boundaries --- .../automation-scripting-service/api-contracts.md | 2 +- .../automation-scripting-service/operations.md | 2 +- .../entity-management-service/api-contracts.md | 2 +- .../entity-management-service/operations.md | 2 +- .../entity-management-service/runtime-and-data.md | 3 ++- ...rchitecture-scripting-control-plane-operations.md | 4 ++-- ...ystem-architecture-scripting-runtime-execution.md | 8 ++++---- .../v1/automation_scripting_service.proto | 12 ++++++++++++ 8 files changed, 24 insertions(+), 11 deletions(-) diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md index 81845f5d58..f0accc0140 100644 --- a/design/architecture/microservices/automation-scripting-service/api-contracts.md +++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md @@ -220,7 +220,7 @@ The service exposes control-plane read and lifecycle surfaces for script patch v Dead-letter replay selection, eligibility, claim, and recovery-result semantics are canonical in [Scripting Control Plane Operations](../../system-architecture-scripting-control-plane-operations.md#replaydeadletteredworkitems); the endpoint entry and rules below retain the direct API shape and Automation-local implementation gap. -- `ReplayDeadLetteredWorkItems(tenantId, workItemIds, controlPlaneRequestId, actorPrincipal, reason)` – **Target mutation contract:** requires a non-empty bounded explicit parent `workItemIds` list. `scriptPatchVersion`, `createdAfterMs`, `createdBeforeMs`, and `limit` are listing/preview selectors, not mutation inputs; filter-only and mixed requests that supply any of them must be rejected. **Current implementation gap:** the proto/service still exposes optional `gameInstanceId`/`regionId` scope fields, permits an empty ID list, falls back to tenant-wide dead-letter selection, and applies those filters both with and without explicit IDs; it requeues eligible parent rows as `PENDING_EVALUATION` and returns aggregate counts only, without per-item `failureGeneration`, `outcome`, or `rejectionReason` results and without proving stage-specific recovery. **Target-state only:** descriptor references and filter-based selection remain deferred; evaluation-stage recovery retries with the original work-item and `scriptEventId`, frozen payload/manifest, exact compiled graph, exact admitted tuple, and captured plugin `(pluginActivationEpoch, lifecycleRevision)` when applicable, preserving the original logical trigger/work-item identity. It allocates no dispatch or command-child identity before a winning descriptor/outbox commit; if commands emit, that commit allocates and persists one `automationDispatchId`, while a valid zero-command evaluation creates no dispatch identity. Post-evaluation recovery resumes stored evaluated output and unfinished child dispatches without re-entering the DSL or generic admission, reusing their existing identities and creating no replacement dispatch identity. The exact current `{scriptPatchVersion, scriptPinEpoch}` tuple, plugin identity/version/binding, captured plugin `(pluginActivationEpoch, lifecycleRevision)`, runtime region/epoch, and routing bundle including playable-state scope must match; the same patch under a new epoch is ineligible. Same-request retries return persisted per-row outcomes under the canonical [operator replay contract](../../system-architecture-scripting-control-plane-operations.md#replaydeadletteredworkitems). +- `ReplayDeadLetteredWorkItems(tenantId, workItemIds, controlPlaneRequestId, actorPrincipal, reason)` – **Target mutation contract:** requires a non-empty bounded explicit parent `workItemIds` list. `scriptPatchVersion`, `createdAfterMs`, `createdBeforeMs`, and `limit` are listing/preview selectors, not mutation inputs; filter-only and mixed requests that supply any of them must be rejected. **Current implementation:** the adapter requires a non-empty explicit ID list and returns durable per-item outcomes with the canonical request fingerprint; it still exposes legacy scope/filter fields, requeues eligible non-`onLoad` rows as `PENDING_EVALUATION`, rejects tenant-readiness `onLoad` rows with `onload_not_replayable`, and does not yet prove stage-specific recovery. **Target-state only:** descriptor references and filter-based selection remain deferred; evaluation-stage recovery retries with the original work-item and `scriptEventId`, frozen payload/manifest, exact compiled graph, exact admitted tuple, and captured plugin `(pluginActivationEpoch, lifecycleRevision)` when applicable, preserving the original logical trigger/work-item identity. It allocates no dispatch or command-child identity before a winning descriptor/outbox commit; if commands emit, that commit allocates and persists one `automationDispatchId`, while a valid zero-command evaluation creates no dispatch identity. Post-evaluation recovery resumes stored evaluated output and unfinished child dispatches without re-entering the DSL or generic admission, reusing their existing identities and creating no replacement dispatch identity. The exact current `{scriptPatchVersion, scriptPinEpoch}` tuple, plugin identity/version/binding, captured plugin `(pluginActivationEpoch, lifecycleRevision)`, runtime region/epoch, and routing bundle including playable-state scope must match; the same patch under a new epoch is ineligible. Same-request retries return persisted per-row outcomes under the canonical [operator replay contract](../../system-architecture-scripting-control-plane-operations.md#replaydeadletteredworkitems). Target-state replay claim and scope rules for `ReplayDeadLetteredWorkItems`: diff --git a/design/architecture/microservices/automation-scripting-service/operations.md b/design/architecture/microservices/automation-scripting-service/operations.md index 244589727b..22e7d6e1d8 100644 --- a/design/architecture/microservices/automation-scripting-service/operations.md +++ b/design/architecture/microservices/automation-scripting-service/operations.md @@ -40,7 +40,7 @@ Pin-transition orchestration rules: - Promotion and rollback orchestration follow the durable state machine in [Scripting Rollout and Rollback](../../system-architecture-scripting-rollout-and-rollback.md#pin-transition-orchestration-state-machine-required). This service must resume its idempotent participation from the last durable owner state rather than restarting or accidentally unpausing. - **Current fresh-schema timer consequence:** runtime materialization creates missing unpinned `script_schedule_instances` rows via `ScriptScheduleInstanceServiceImpl`/`ScriptScheduleInstanceRepository.saveAll`, with `scriptPinEpoch=0` and no owner request identity. On the next runtime tick or wall-clock observation, the scheduler treats that incomplete tuple as fenced, sets `materializationStatus=FENCED`, clears the retained due point and runtime-progress fields, and emits no timer work or audit. A later complete Game Session pin/runtime reconciliation rematerializes the schedule; wall-clock timers are seeded from the pin-observation time, while tick-aligned timers wait for fresh runtime progress. Operators should reconcile the owner tuple before treating the timer as active. - **Target-state drain mapping:** `GetAutomationDrainStatus` is diagnostic cleanup-progress evidence, not a resume gate. A fresh response for the current `{tenantId, gameInstanceId, regionId?}` scope, `admissionEpoch`, and exact `scriptPinEpoch` reports the current `activeExecutionCount` and `pendingCancelableWorkItemCount`; both counts being zero means counted cleanup is complete for that exact scope, `admissionEpoch`, and `scriptPinEpoch`, but remains diagnostic and is not a resume gate. `activeExecutionCount` is exactly current-epoch `EXECUTING` pre-DSL triggers plus `HANDOFF_IN_FLIGHT` evaluated descriptors, and `pendingCancelableWorkItemCount` is exactly current-epoch `PENDING_EVALUATION` pre-DSL triggers plus `PENDING`/`INDEXED` evaluated descriptors. Terminal states, rows from another scope or epoch, and derived queue pointers are excluded. Nonzero counts report current counted work, while Automation resume remains gated by exact target-artifact convergence and schedule reconciliation; missing, stale, or other-epoch pin evidence cannot prove cleanup completion. -- **Current fail-closed counts:** while `PAUSED_FOR_ROLLBACK`, the live projection restricts persisted current `script_work_items` to rows whose `workItem.admissionEpoch <= 0` or `workItem.admissionEpoch < current admissionEpoch`, excluding positive current-epoch rows; within that set it counts `EVALUATING`, including unresolved stale rows, and `HANDOFF_IN_FLIGHT` as active and `PENDING_EVALUATION` as pending. In normal mode it counts the corresponding scoped rows without that admission-epoch filter. The current query does not filter or group by `scriptPinEpoch`, so a response can aggregate mixed pin epochs and cannot prove cleanup for one exact epoch. The current work-item model now persists the exact positive `scriptPinEpoch` captured at admission; the separate `PENDING`/`INDEXED` descriptor layer and its richer recovery semantics remain target-only. These counts are diagnostic only, not authoritative target cleanup completion; any unresolved count, stale response, or mixed/earlier-epoch response cannot prove cleanup completion or authorize resume. +- **Current fail-closed counts:** the live projection selects the counted admission-epoch set by mode: `NORMAL` includes only rows whose `workItem.admissionEpoch` equals the current `admissionEpoch`, while `PAUSED_FOR_ROLLBACK` includes rows whose `workItem.admissionEpoch <= 0` or `workItem.admissionEpoch < current admissionEpoch`, excluding positive current-epoch rows. Within that set it counts `EVALUATING`, including unresolved stale rows, and `HANDOFF_IN_FLIGHT` as active and `PENDING_EVALUATION` as pending. The current query does not filter or group by `scriptPinEpoch`, so a response can aggregate mixed pin epochs and cannot prove cleanup for one exact epoch. The separate `PENDING`/`INDEXED` descriptor layer remains target-only, while the current work-item model persists the exact positive `scriptPinEpoch` captured at admission. These counts are diagnostic only, not authoritative target cleanup completion; any unresolved count, stale response, or earlier-epoch response cannot prove cleanup completion or authorize resume. - During target-state `DRAINING`, `PENDING_EVALUATION` is durably canceled without entering the DSL. `EXECUTING` is resolved only after reading the descriptor-commit marker: if committed, cancellation never resumes or re-dispatches a child; `PENDING` and `INDEXED` children compare-and-set to `CANCELED` with durable `cancelReason`, `finalStage=WORK_ITEM_PERSIST`, and `finalOutcome=canceled`; `HANDOFF_IN_FLIGHT` fences further retry and reconciles the durable downstream outcome (remaining active/unresolved when ambiguous); and `HANDED_OFF`, `CANCELED`, or `DEAD_LETTERED` children retain their outcome and no-op. An explicitly canceled uncommitted trigger becomes terminal `CANCELED` with `finalStage=DSL_EVAL` and `finalOutcome=canceled`, while only the distinct expired-stale recovery-owner path makes an uncommitted trigger terminal `DEAD_LETTERED` with `finalReason=stale_execution_fenced`. The current live projection remains `EVALUATING` and retains unresolved stale rows as active; the status, reason, and audit mapping are defined in [Scripting Runtime Execution](../../system-architecture-scripting-runtime-execution.md#pre-dsl-trigger-and-evaluated-descriptor-boundary). **Target-state exact-epoch admission:** For instance-scoped script admission, a bounded-fresh observed Game Session pin/epoch projection may admit work. If that projection is absent or stale, Automation must perform a bounded refresh from authoritative Game Session `GetPinnedScriptPatchVersion` before admission; refresh failure fails closed. A mismatched exact tuple also fails closed, and no stale or local projection override may admit work. Current ordinary instance-scoped gameplay/runtime ingress carries `scriptPinControlPlaneRequestId` with the patch and positive epoch, persists that owner evidence on the event claim and admitted handler work, and compares it with current owner/observed state; absent, partial, or mismatched owner evidence fails closed. Tenant-readiness `onLoad` remains the explicit pre-instance exception and omits all instance pin-owner fields. The stronger target lifecycle carries the same evidence through every local and remote handoff, recovery, and final-effect boundary; remote source/target binding and complete final-effect proof remain gaps. For plugin-backed work, the owner-local ADR 0119 lifecycle fence also applies at admission and final execution: `ENABLED` requires the exact current `lifecycleRevision`, only normal `DRAINING` may finish work admitted by a winning CAS before its drain barrier using the immediately preceding `ENABLED` revision, and a committed forced interruption or emergency revocation provides no predecessor exception. A successful semantic `UNPINNED` owner result remains the explicit no-script-configured case. The service may continue ordinary non-script runtime work while scoped script admission is unavailable. Cleanup of displaced work is bounded and asynchronous; cleanup completion is not the epoch-fence correctness barrier. Operators must use owner pin/history reads together with the Automation convergence projection and must not repair or purge rows by direct SQL. diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index af572c5721..65246b825b 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -171,7 +171,7 @@ Only entities approved by the `EntityVisibilityPolicy` are returned; hidden NPCs Under [ADR 0112](../../decisions/adr-0112-typed-bounded-gameplay-effect-extension.md), Entity Management is the canonical owner of actor/effect mutation, resource costs, and cooldown state. It accepts only a validated typed plan or registered effect operation resolved by the owning server-side gameplay path from the exact release-pinned typed effect declaration/reference and digest, preserves the operation/effect replay identity and request digest, and never parses script text, executes caller-supplied DML, or reconstructs targeting policy from a partial request. -`ApplyActorCondition` is the first mutation contract for the same actor-state table. The current implementation validates the concrete mTLS caller and method allowlist, `PlayerExecutionContext`, and playable-state scope before creating an `actor_active_conditions` row with `conditionKey`, `stackCount`, `sourceType`, `sourceId`, optional `expiresAt`, and optional caller-supplied `effectPayloadJson`; accepting that payload directly, and allowing `QueryActorState` to evaluate it into gameplay-visible state, is the transitional gap identified above. Until the target typed request exists, callers using the current wire contract must keep a supplied `sourceId` unique tenant-wide per intended operation/effect because it is also the durable replay marker key. Within that operation, the actor-condition table lookup is narrower—`{tenantId, playableStateKey, characterId, sourceType, sourceId}`—and returns the first matching source row without comparing changed `effectPayloadJson` values. The target contract carries a dedicated `effectId` as the operation-level replay identity under `{tenantId, effectId}`, while `sourceId` remains authored/source provenance and may legitimately recur across separate applications. Target-state replay behavior (not currently enforced by this transitional request) is: a completed duplicate with the same canonical request payload returns the original serialized `ApplyActorConditionResponse` without another condition mutation; an in-progress duplicate returns conflict, payload or operation reuse returns invalid argument, and an unreadable stored response fails internally. Until dedicated `effectId`, canonical request-digest, and stored-response enforcement are live, clients must not rely on those outcomes or on changed-payload conflict detection. This is intended for gameplay-owned actions such as the first transient `blocking` state as well as later spells, consumables, and scripted effects. Reads ignore expired rows and the scheduled expiry sweep removes elapsed rows; callers must still treat the mutation response as the authoritative applied state for that request. +`ApplyActorCondition` is the first mutation contract for the same actor-state table. The current implementation validates the concrete mTLS caller and method allowlist, `PlayerExecutionContext`, and playable-state scope before creating an `actor_active_conditions` row with `conditionKey`, `stackCount`, `sourceType`, `sourceId`, optional `expiresAt`, and optional caller-supplied `effectPayloadJson`; accepting that payload directly, and allowing `QueryActorState` to evaluate it into gameplay-visible state, is the transitional gap identified above. Until the target typed request exists, callers using the current wire contract must keep a supplied `sourceId` unique tenant-wide per intended operation/effect because it is also the durable replay marker key. Within that operation, the actor-condition table lookup is narrower—`{tenantId, playableStateKey, characterId, sourceType, sourceId}`—and returns the first matching source row without comparing changed `effectPayloadJson` values. The target contract carries a dedicated `effectId` as the operation-level replay identity under `{tenantId, effectId}`, while `sourceId` remains authored/source provenance and may legitimately recur across separate applications. Target-state replay behavior (not currently enforced by this transitional request) is: a completed duplicate with the same canonical request payload returns the original serialized `ApplyActorConditionResponse` without another condition mutation; an in-progress duplicate returns conflict, payload or operation reuse returns invalid argument, and an unreadable stored response fails internally. Until dedicated `effectId`, canonical request-digest, and stored-response enforcement are live, clients must not rely on those outcomes or on changed-payload conflict detection. This is intended for gameplay-owned actions such as the first transient `blocking` state as well as later spells, consumables, and scripted effects. Reads ignore expired rows, so an expired effect is not restored; the scheduled default-30-second sweep then globally and without a batch bound deletes elapsed `actor_active_conditions` rows. The sweep does not delete separate `entity_mutation_effects` receipts, which `ApplyActorCondition` checks before mutation, but a receipt-retention guarantee across the replay/restore horizon remains unproved. Current behavior makes no concrete duplicate-application or S2-loss claim; target proof still requires explicit S1/S2 classification, dependent-reference/hold checks, and typed target, request-digest, and concurrency enforcement. Callers must still treat the mutation response as the authoritative applied state for that request. Condition and item-template effect payloads are an internal persisted contract in this first slice. They may contain a top-level `modifiers` array whose entries include `operation`, `target_key`, `value`, optional `scope_kind`, optional `scope_key`, and optional `priority`; supported operations currently match the shared evaluator primitives: `ADD`, `MULTIPLY`, `CLAMP_MIN`, `CLAMP_MAX`, `GRANT_FLAG`, and `GRANT_CONDITION`. diff --git a/design/architecture/microservices/entity-management-service/operations.md b/design/architecture/microservices/entity-management-service/operations.md index e7d3c27e54..01ba084089 100644 --- a/design/architecture/microservices/entity-management-service/operations.md +++ b/design/architecture/microservices/entity-management-service/operations.md @@ -20,7 +20,7 @@ Replacement operations use the stable `playableStateNamespaceId` and owner-resol - `liveness` is process-local only. - `readiness` is truthful local readiness for the currently implemented entity-query slice and must fail when the service cannot safely answer room/entity lookup traffic with its required local persistence/cache/bootstrap state. - Logging, metrics, and tracing follow the standard [Logging & Monitoring](../../system-architecture-logging-monitoring.md) pipeline. -- `entity.actor-condition.expiry-interval-seconds` controls the scheduled active-condition expiry sweep. The default is 30 seconds and removes rows whose `expires_at` has elapsed; gameplay reads also ignore expired rows, so the sweep is cleanup and convergence rather than the sole correctness guard. +- `entity.actor-condition.expiry-interval-seconds` controls the scheduled actor-condition expiry sweep. The default is 30 seconds, and the sweep globally and without a batch bound deletes rows whose `expires_at` has elapsed. Gameplay reads filter those rows before evaluating state, so an expired effect is not restored. The sweep targets only `actor_active_conditions`; separate `entity_mutation_effects` receipts remain and are checked by `ApplyActorCondition` before mutation, but a receipt-retention guarantee across the replay/restore horizon is unproved. No concrete duplicate-application or S2-loss claim is made. Target proof still requires explicit S1/S2 classification, dependent-reference/hold checks, a safe watermark, and typed target, request-digest, and concurrency enforcement; expiry is not itself a retention or disposal decision. ## Tick Locking 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 201f2354c5..a1c5ba24ba 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -13,6 +13,7 @@ This document defines Entity Management’s runtime model, persistence ownership - 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 isolated marker transaction, followed by real PostgreSQL concurrent first-apply/replay proof. Until then replay readiness remains blocked. - Character updates are also not currently optimistic CAS: `CharacterRepository` increments `version` but updates by row ID without the old-version and tenant predicates or an affected-row conflict check. Concurrent progression/last-login writes can therefore overwrite each other. The target requires tenant- and namespace-bound version CAS with stale-write failure and focused concurrent proof; the current `@Transactional` service methods do not establish that invariant. - Current `jOOQ + Flyway` adoption and focused persistence proof remain implementation work. +- The current actor-condition expiry job runs every 30 seconds by default and invokes a global, unbounded delete for rows whose `expires_at` has elapsed, without tenant/namespace/instance predicates or a batch bound. Reads filter expired rows before evaluating state, so expired gameplay effects are not restored. The deletion targets only `actor_active_conditions`; it does not delete the separate `entity_mutation_effects` receipt that `ApplyActorCondition` checks before mutation. No concrete duplicate-application or S2-loss claim is made from this path. The target still requires explicit S1/S2 classification, a replay/restore horizon, dependent-reference/hold checks, a receipt-retention guarantee, a safe watermark, and typed target, request-digest, and concurrency proof under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md); expiry is not itself disposal eligibility. - Realm-authored actor entry remains partial: legacy creation and actor rows still expose fixed RPG-oriented fields, policy/descriptor/template resolution and auto-provision idempotency are incomplete, and synthetic-ID/fork-copy proof gaps remain. These target rules do not claim runtime convergence. - The live runtime-instance cleanup path currently deletes room-ground inventory, item stacks, item instances, and container instances by `(tenantId, gameInstanceId)` alone. It does not apply namespace, scope, and holder/container closure or prove S3 classification, so its cleanup acknowledgement is unsafe for replacement until owner-local classification, fencing, and focused proof are complete. - The live Entity schema does not yet represent the target namespace-stable identity for durable S1/S2 state: `characters` and `actor_resource_states` retain legacy `playable_state_key`, while `inventory`, `character_friend`, `character_equipment`, and durable holder/containment rows omit `playableStateNamespaceId` (and some omit `tenant_id` entirely). The current repositories consequently cannot enforce the target `{tenantId, playableStateNamespaceId, domainObjectId}` identity at the SQL boundary. A convergent migration, legacy-row disposition/backfill evidence, namespace-aware repository predicates, and focused isolation proof remain required; until those are complete, legacy `playable_state_key` rows (including `character_friend` associations reached through them) are not namespace-isolated proof and cutover readers must not treat them as namespace-backed survivor state. This does not change the target contract above. @@ -299,7 +300,7 @@ See [Versioning & Runtime Configuration](../../system-architecture-versioning-ru - `item` table stores equipment, consumables, and quest objects. - Many-to-many tables define inventory and equipment relationships, including container contents and room/ground inventory. Room/ground inventory is modeled as items whose container references a synthetic room-ground container entity keyed by `(tenantId, gameInstanceId, roomInstanceId)` so limits such as max items on the ground or special container rules can be enforced consistently without cross-instance collisions. - Actor gameplay state is persisted separately from the legacy character stat columns. `actor_resource_states` stores current/base/max resource values with source provenance, while `actor_active_conditions` stores active condition keys, stack counts, source provenance, start/expiry timestamps, and effect payload JSON. Reads merge baseline character stat fields with persisted resource rows so later mutation/effect slices can converge on the new state model without removing the bootstrap character fields first. -- The first shared effect-evaluation seam is an in-process Entity Management service that evaluates typed resource modifiers and granted states deterministically. Active condition payloads and equipped item-template payloads are `CONTINUOUS` effect sources: they contribute while their source exists and never write derived values into current resources during reads. When an attached source changes a bounded-resource maximum, its attach, detach, refresh, expiry, or replacement mutation performs the one idempotent capacity normalization using the declaration override or resolved tenant/game `actorState.capacityChangePolicy` captured by that mutation. Evaluation reads never normalize current state. Gameplay-attested `ApplyActorCondition` calls are the first `INSTANT` mutation path, creating active condition/action-state rows through the same internal mutation service under an idempotent effect id. A scheduled Entity Management job also expires elapsed active-condition rows on a bounded cadence. Player command wiring remains future work. +- The first shared effect-evaluation seam is an in-process Entity Management service that evaluates typed resource modifiers and granted states deterministically. Active condition payloads and equipped item-template payloads are `CONTINUOUS` effect sources: they contribute while their source exists and never write derived values into current resources during reads. When an attached source changes a bounded-resource maximum, its attach, detach, refresh, expiry, or replacement mutation performs the one idempotent capacity normalization using the declaration override or resolved tenant/game `actorState.capacityChangePolicy` captured by that mutation. Evaluation reads never normalize current state. Gameplay-attested `ApplyActorCondition` calls are the first `INSTANT` mutation path, creating active condition/action-state rows through the same internal mutation service under an idempotent effect id. A scheduled Entity Management job globally and without a batch bound deletes elapsed active-condition rows on the default 30-second cadence; read-time filtering prevents expired effects from being restored before cleanup. The job does not delete separate `entity_mutation_effects` receipts, which are checked before mutation, but receipt-retention and typed replay/concurrency proof remain target gaps. Player command wiring remains future work. - Target-state active-condition rows are condition instances with stable instance ids, frozen definition/release snapshots, source provenance, stack counts, expiry, and applied-effect snapshots. Condition-definition DML, not source-id coincidence, selects `REPLACE`, `REFRESH`, `STACK`, or `PARALLEL` reapplication behavior and its duration policy. Typed removal resolves exact keys, authored tags, or permitted sources in deterministic definition priority and instance-id order; it must not expose raw row or payload deletion to player-facing callers. - Target only: World Management will own character/NPC location and instance-membership rows and their authoritative reads/writes; those tables and paths are not present in the current implementation. Entity Management owns and persists item instances and inventories, but must not add competing actor-location fields or tables. - Entity graphs cache inventory relationships for fast lookups. diff --git a/design/architecture/system-architecture-scripting-control-plane-operations.md b/design/architecture/system-architecture-scripting-control-plane-operations.md index 050c0c23ff..e0962c9044 100644 --- a/design/architecture/system-architecture-scripting-control-plane-operations.md +++ b/design/architecture/system-architecture-scripting-control-plane-operations.md @@ -18,7 +18,7 @@ Separately, a terminal pre-DSL `DEAD_LETTERED` row with no committed descriptor ## Implementation Status -This section records current behavior only. The current Automation claim boundary is `PENDING_EVALUATION` -> `EVALUATING`; it has no recovery owner, evaluation lease expiry/fencing generation, or descriptor-commit marker/status, and its recovery behavior is unimplemented and unverified. The current replay mutation still accepts optional `gameInstanceId`/`regionId` scope fields and empty-ID selection, selects parent `workItemIds`, requeues eligible `script_work_items` rows as `PENDING_EVALUATION`, and returns aggregate counts instead of target per-row recovery results; it does not select independent command descriptors or prove post-evaluation recovery. Current `CancelPendingWorkItemsForPluginVersion` accepts only tenant/plugin-version/instance/region plus request/audit fields and returns aggregate `canceledCount`; it does not accept the target activation/script tuples or explicit work-item IDs, return per-parent results, or reconcile evaluated descriptors and children, so the richer cancellation contract below is target-only. `GetAutomationPinConvergence` currently serves the durable `ScriptPatchPinProjection`/`script_patch_pin_projections` view with the observed patch/epoch tuple and last observed owner request identity; it does not expose `observedConvergenceAttemptGeneration`, so attempt-bound convergence proof remains unavailable. While `PAUSED_FOR_ROLLBACK`, current `GetAutomationDrainStatus` first restricts the counted set to rows whose `workItem.admissionEpoch <= 0` or `workItem.admissionEpoch < current admissionEpoch`, excluding positive current-epoch rows; within that set `activeExecutionCount` counts `EVALUATING` and `HANDOFF_IN_FLIGHT`, including unresolved stale `EVALUATING`, and `pendingCancelableWorkItemCount` counts `PENDING_EVALUATION`. Normal mode counts the corresponding scoped rows without that epoch filter. The target mapping instead uses current-epoch pre-DSL and evaluated-descriptor counts. Current terminal-row cleanup is retention-based; the target terminal-evidence purge rule is not current trigger-state recovery and does not establish that the current cleanup preserves an `EVALUATED_COMMITTED` marker, audit, or replay causation. The emergency component-revocation workflow below is also target-only, unimplemented, and unproved; current runtime checks do not establish authoritative affected-scope discovery, durable containment convergence, or the complete pre-effect revocation fence. These implementation facts are a cleanup-projection gap; they do not relax the target exact-artifact convergence and schedule-reconciliation gates for Automation admission. +This section records current behavior only. The current Automation claim boundary is `PENDING_EVALUATION` -> `EVALUATING`; it has no recovery owner, evaluation lease expiry/fencing generation, or descriptor-commit marker/status, and its recovery behavior is unimplemented and unverified. The current replay mutation still accepts optional `gameInstanceId`/`regionId` scope fields and empty-ID selection, selects parent `workItemIds`, requeues eligible `script_work_items` rows as `PENDING_EVALUATION`, and returns aggregate counts instead of target per-row recovery results; it does not select independent command descriptors or prove post-evaluation recovery. Current `CancelPendingWorkItemsForPluginVersion` accepts only tenant/plugin-version/instance/region plus request/audit fields and returns aggregate `canceledCount`; it does not accept the target activation/script tuples or explicit work-item IDs, return per-parent results, or reconcile evaluated descriptors and children, so the richer cancellation contract below is target-only. `GetAutomationPinConvergence` currently serves the durable `ScriptPatchPinProjection`/`script_patch_pin_projections` view with the observed patch/epoch tuple and last observed owner request identity; it does not expose `observedConvergenceAttemptGeneration`, so attempt-bound convergence proof remains unavailable. Current `GetAutomationDrainStatus` selects its counted set by mode: `NORMAL` includes only rows whose `workItem.admissionEpoch` equals the current `admissionEpoch`; `PAUSED_FOR_ROLLBACK` includes rows whose `workItem.admissionEpoch <= 0` or `workItem.admissionEpoch < current admissionEpoch`, excluding positive current-epoch rows. Within that set `activeExecutionCount` counts `EVALUATING` and `HANDOFF_IN_FLIGHT`, including unresolved stale `EVALUATING`, and `pendingCancelableWorkItemCount` counts `PENDING_EVALUATION`. The current query does not filter or group by `scriptPinEpoch`, so a response can aggregate mixed pin epochs and cannot prove cleanup for one exact epoch. The target mapping instead uses current-epoch pre-DSL and evaluated-descriptor counts. Current terminal-row cleanup is retention-based; the target terminal-evidence purge rule is not current trigger-state recovery and does not establish that the current cleanup preserves an `EVALUATED_COMMITTED` marker, audit, or replay causation. The emergency component-revocation workflow below is also target-only, unimplemented, and unproved; current runtime checks do not establish authoritative affected-scope discovery, durable containment convergence, or the complete pre-effect revocation fence. These implementation facts are a cleanup-projection gap; they do not relax the target exact-artifact convergence and schedule-reconciliation gates for Automation admission. ## Table of Contents @@ -160,7 +160,7 @@ Semantics: - Read-only. - The response identifies the exact requested scope: omitted or blank `regionId` selects only the durable empty/unscoped row and never aggregates regional rows. A regional recovery must enumerate the complete affected scope set from the authoritative durable PostgreSQL/runtime owner inventory and issue exact-scope Set/readback pairs for every regional and unscoped scope that exists; unavailable or incomplete inventory fails closed. - A missing exact admission row is returned as an explicit diagnostic/default (`statePresent=false`, `NORMAL`, epoch `0`, no request ID, and `NOT_FOUND` outcome) and is not created or persisted by this read. Recovery accepts only a durable successful Set acknowledgement (`APPLIED` or `ALREADY_APPLIED`) whose request ID, exact scope, target mode, fingerprint, epoch, and outcome match the requested tuple; counts or a successful RPC response alone do not authorize progression. -- Reports whether any pre-pause executions or already-persisted work remain in the rollback scope after the current `admissionEpoch` took effect. +- The counted set is mode-dependent: `NORMAL` includes only rows whose `workItem.admissionEpoch` equals the current `admissionEpoch`; `PAUSED_FOR_ROLLBACK` includes legacy rows with `workItem.admissionEpoch <= 0` and rows from an earlier epoch (`workItem.admissionEpoch < current admissionEpoch`). Active and pending counts retain their existing status classifications after this epoch filter. - For authoritative pause/resume readback, the returned tenant, instance, and optional region scope must match the requested scope, `admissionMode` must match the requested mode, `admissionEpoch` must be current for that scope, and `observedAt` must be fresh. Missing, stale, earlier-epoch, or contradictory readback is diagnostic only and cannot authorize workflow advancement or completion. The microservice-local API contract documents the same projection; Automation's durable admission state remains the authority. - Rollback orchestration uses this API to expose asynchronous cleanup progress. Drain counts do not gate Automation resumption or ordinary gameplay ticks; the [Pin Convergence Acknowledgment Predicate](./system-architecture-scripting-rollout-and-rollback.md#pin-convergence-acknowledgment-predicate), including fresh exact-tuple acknowledgments from `GetAutomationPinConvergence` and `GetGameSessionPinConvergence`, exact target-artifact convergence, and schedule reconciliation are the admission gates. For a scope with applicable plugin-backed admission, fresh signer-policy convergence is an additional admission gate: missing, stale, revoked, or otherwise fail-closed signer evidence keeps plugin admission blocked and cannot be replaced by drain counts. A cached, stale, or earlier-epoch response remains diagnostic rather than convergence evidence, and bounded cleanup may remain pending after `COMPLETED` under the displaced exact epoch fence. diff --git a/design/architecture/system-architecture-scripting-runtime-execution.md b/design/architecture/system-architecture-scripting-runtime-execution.md index 0210546402..4ad0097679 100644 --- a/design/architecture/system-architecture-scripting-runtime-execution.md +++ b/design/architecture/system-architecture-scripting-runtime-execution.md @@ -76,7 +76,7 @@ The current evaluator supports a bounded emitted-command collection per work ite That current-boundary execution format is intentionally narrow but no longer raw-text-only: script definitions may expose `emitCommands` at the top level or under `eventHandlers..emitCommands`, and each emitted command may currently carry either direct `commandText` or a structured `commandAlias` plus templated `arguments`, along with an optional target entity or bounded `targetEntityIds[]` list, optional explicit target runtime scope (`targetGameInstanceId`, `targetRegionId`, `targetRegionEpoch`), `requiresSoloTick`, and optional `dueTickId`. The evaluator may expand `targetEntityIds[]` locally and attempt one command per listed target. If no target is present, the command targets the triggering work item's entity; if explicit target runtime scope is absent, the command defaults to the triggering work item's owned gameplay scope. Each resulting command receives a local ordinal and is attempted through the handoff service, but this local expansion is not the target-state multi-target fan-out contract: the live wire does not carry the complete per-target identity or target `playableStateScope`, so complete handoff identity, scope validation, deduplication, and end-to-end progress remain unproved. Command nodes may also carry bounded `when` / `unless` predicate maps over durable work-item metadata and flat primitive payload fields; target-state command ordinals and optional `targetPlayableStateScope` distinguish emitted commands after handoff identity is widened. Template substitution is still limited to durable work-item metadata and flat primitive payload fields such as `{{payload.commandName}}`. Richer graph execution and broader DSL semantics remain target-state work above this first production evaluator path. -The current claim boundary is the atomic PostgreSQL transition from `PENDING_EVALUATION` to `EVALUATING`; the existing Game Session lease rules govern region-owned tick execution, not Automation work-item claims. The current implementation has no evaluation lease expiry, fencing generation, descriptor-commit marker, or recovery owner. While `PAUSED_FOR_ROLLBACK`, its `GetAutomationDrainStatus` implementation restricts the counted set to rows whose `workItem.admissionEpoch <= 0` or `workItem.admissionEpoch < current admissionEpoch`, excluding positive current-epoch rows; within that set `activeExecutionCount` counts `EVALUATING` and `HANDOFF_IN_FLIGHT`, including unresolved stale `EVALUATING`, and `pendingCancelableWorkItemCount` counts `PENDING_EVALUATION`. Normal mode counts the corresponding scoped rows without that epoch filter. These are current implementation gaps: the current runtime retains unresolved work and keeps the Automation admission barrier closed; ordinary gameplay ticks continue except within a separately declared unfenced-effect workflow. It cannot safely resume or promise terminal audit from lease age alone. The target mapping and recovery behavior are defined below, and current tooling must not infer reclaim, terminalization, or re-entry to the DSL. +The current claim boundary is the atomic PostgreSQL transition from `PENDING_EVALUATION` to `EVALUATING`; the existing Game Session lease rules govern region-owned tick execution, not Automation work-item claims. The current implementation has no evaluation lease expiry, fencing generation, descriptor-commit marker, or recovery owner. Its `GetAutomationDrainStatus` projection selects the counted epoch set by mode: `NORMAL` includes only rows whose `workItem.admissionEpoch` equals the current `admissionEpoch`, while `PAUSED_FOR_ROLLBACK` includes rows whose `workItem.admissionEpoch <= 0` or `workItem.admissionEpoch < current admissionEpoch`, excluding positive current-epoch rows. Within that set `activeExecutionCount` counts `EVALUATING` and `HANDOFF_IN_FLIGHT`, including unresolved stale `EVALUATING`, and `pendingCancelableWorkItemCount` counts `PENDING_EVALUATION`. These are current implementation gaps: the current runtime retains unresolved work and keeps the Automation admission barrier closed; ordinary gameplay ticks continue except within a separately declared unfenced-effect workflow. It cannot safely resume or promise terminal audit from lease age alone. The target mapping and recovery behavior are defined below, and current tooling must not infer reclaim, terminalization, or re-entry to the DSL. The current `onLoad` implementation slice is tenant-readiness work limited to configuration/runtime metadata validation and warming recomputable in-process caches. It does not perform per-entity setup or create handler-owned durable shared state. Platform-owned execution, readiness, and `script_event_audit` metadata remains required bookkeeping and is not a handler-created effect. The current implementation also lacks stale-`ONLOAD_RUNNING` generation recovery; that gap must not be handled by re-entering the same DSL execution. @@ -181,9 +181,9 @@ For plugin-owned schedule-derived work, rebuilding a due candidate or firing cla - Outbox scanning for rebuild and cancellation must be bounded and backpressured (pagination, time windows, per-tenant limits) so it cannot become an unbounded full-table scan on large tenants. - Outbox retention must be explicitly defined for `HANDED_OFF`, `CANCELED`, and `DEAD_LETTERED` records. Payload compaction or deletion waits until every child is terminal and the longest downstream replay, rollback-diagnosis, command-status, and audit horizon has elapsed; retained identity, digest, and disposition evidence must still prevent a duplicate logical dispatch. - The canonical defaults are owned by [Automation & Scripting Service Configuration](./microservices/automation-scripting-service/configuration.md): `SCRIPT_OUTBOX_HANDED_OFF_RETENTION_DAYS`, `SCRIPT_OUTBOX_CANCELED_RETENTION_DAYS`, `SCRIPT_DEAD_LETTER_MAX_AGE_SECONDS`, `SCRIPT_OUTBOX_TERMINAL_CLEANUP_INTERVAL_SECONDS`, `SCRIPT_OUTBOX_EXECUTION_INTERVAL_SECONDS`, and `SCRIPT_OUTBOX_EXECUTION_BATCH_SIZE`. `SCRIPT_OUTBOX_QUEUE_REBUILD_INTERVAL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_REBUILD_BATCH_SIZE` are target-only settings for a future owner-gated rebuild and have no current scheduled binding. -- The current Automation & Scripting implementation wires those retention knobs into a scheduled cleanup job for terminal `script_work_items`: `HANDED_OFF` and `CANCELED` rows expire by status-specific retention days. The `DEAD_LETTERED` max-age and row-count knobs remain configured, but both automatic deletion paths fail closed and retain every dead-letter parent until recovery-aware whole-bundle eligibility can be proved. The target retention policy covers those terminal dead-lettered records and their complete supporting evidence. +- The current Automation & Scripting implementation wires the handed-off and canceled retention knobs into a scheduled cleanup job for terminal `script_work_items`. Dead-letter age and row-cap settings remain diagnostic only: cleanup does not select, scan, or delete `DEAD_LETTERED` parents, replay request/result receipts, or their supporting audit/handoff evidence because the current implementation still lacks the recovery-aware whole-bundle and rollback-diagnosis horizon. Dependency references, retention holds, or retained replay/evidence rows can block deletion, and the target retention policy still covers terminal dead-lettered records once that proof exists. - **Target-state only:** The derived queue contract is a projection only: queue drains dedupe repeated parent pointer envelopes by `outboxWorkItemId`, and a bounded rebuild republishes missing queue pointers only from evaluated descriptors in `PENDING` or `INDEXED` status. Rebuild and handoff must apply an explicit status gate before treating a row as evaluated command work. Projection or Redis arrival order is not replay order: the executor selects durable rows by their canonical status and complete identity, and a rebuild must not advance, reorder, or replay a descriptor merely because its pointer was observed first. Pre-DSL `PENDING_EVALUATION` and `EXECUTING` rows are never published to or consumed from the evaluated-command queue; a separate pre-DSL projection may route evaluator work. Redis never becomes authoritative, and reindexing `EXECUTING` rows must not reclaim or replay them. The target descriptor rebuild and lease/fencing recovery contract above remain current implementation gaps. -- The scheduled queue-rebuild hook and its configuration have been removed/disabled because the current `rebuildPendingWorkItemIndex` helper remains unsafe and has no stale, owner, or compare-and-set reconciliation gate. Its current status gate still selects both `PENDING_EVALUATION` and `EVALUATING`, and its Redis-existence check and append remain separate operations, so it is not a supported recovery operation. The current executor catches queue-pointer discovery failures and falls back to a bounded durable `PENDING_EVALUATION` scan, and supplements a short queue batch with a durable scan when capacity remains; however, the Redis drain deletes an entire list before enforcing its pointer cap, so an over-cap list can lose its unreturned suffix and neither fallback nor rebuild immediately recovers those deleted pointers. Consequently, safe owner-reconciled rebuild and any safe reset/recovery operation remain unavailable; queue reset/resume must fail closed. Target pre-DSL recovery permits `PENDING_EVALUATION` plus only owner-reconciled/reclaimed safe non-stale `EVALUATING`; target `PENDING`/`INDEXED` descriptor rebuild is unavailable because the separate evaluated descriptor status layer is not currently persisted. These current pointers are not evaluated-command queue entries or evidence of descriptor replay. Containment and the remaining implementation/proof gap are defined in [Current Queue-Rebuild Concurrency Gap](#current-queue-rebuild-concurrency-gap) and remain owned by the Automation queue owner. +- The scheduled queue-rebuild hook and its configuration have been removed/disabled because the current `rebuildPendingWorkItemIndex` helper remains unsafe and has no stale, owner, or compare-and-set reconciliation gate. Its current status gate selects only `PENDING_EVALUATION`, but its Redis-existence check and append remain separate operations, so it is not a supported recovery operation. The current executor catches queue-pointer discovery failures and falls back to a bounded durable `PENDING_EVALUATION` scan, and supplements a short queue batch with a durable scan when capacity remains. Redis drains now use bounded one-at-a-time `LPOP`, preserving any unconsumed suffix for the next sweep; this does not make rebuild publication atomic or safe. Consequently, safe owner-reconciled rebuild and any safe reset/recovery operation remain unavailable; queue reset/resume must fail closed. Target pre-DSL recovery permits `PENDING_EVALUATION` plus only owner-reconciled/reclaimed safe non-stale `EVALUATING`; target `PENDING`/`INDEXED` descriptor rebuild is unavailable because the separate evaluated descriptor status layer is not currently persisted. These current pointers are not evaluated-command queue entries or evidence of descriptor replay. Containment and the remaining implementation/proof gap are defined in [Current Queue-Rebuild Concurrency Gap](#current-queue-rebuild-concurrency-gap) and remain owned by the Automation queue owner. - Target purge follows the [normative terminal descriptor evidence rule](./system-architecture-scripting-normative-contract-tables.md#terminal-descriptor-evidence-purge-target-state): under an `EVALUATED_COMMITTED` parent it may remove descriptor/outbox/evaluated-output evidence only after every child under that parent is terminal (`HANDED_OFF`, `CANCELED`, or `DEAD_LETTERED`) and every eligible evidence item is retention-eligible. A fully canceled required-child set therefore follows the same retention-gated purge path; purge does not create or transition a dead-letter recovery aggregate or create replay eligibility. The purge transaction atomically removes all eligible evidence and persists an explicit durable `descriptorEvidencePurgedAt` marker on the retained parent. If any sibling is `PENDING`, `INDEXED`, `HANDOFF_IN_FLIGHT`, otherwise nonterminal, or not retention-eligible, the entire parent purge is rejected and no marker is written. A marked parent is non-recoverable and non-replayable, and consumers reject it deterministically rather than treating missing children as recoverable. It preserves the trigger marker, corresponding `script_event_audit`, and replay-causation evidence, and rejects active/nonterminal trigger or descriptor work. - Operator-facing replay, purge, and convergence tooling must treat those retention windows as the supported diagnosis horizon rather than inventing ad hoc cleanup timing. @@ -211,7 +211,7 @@ Current legacy single-row marker: when the current executor completes a live non **Target-state `GetAutomationDrainStatus` mapping:** for the current scope and `admissionEpoch`, `activeExecutionCount` is exactly the sum of `EXECUTING` pre-DSL triggers and `HANDOFF_IN_FLIGHT` evaluated descriptors; an `EVALUATED_COMMITTED` trigger itself contributes zero. `pendingCancelableWorkItemCount` is exactly the sum of `PENDING_EVALUATION` pre-DSL triggers and `PENDING`/`INDEXED` evaluated descriptors, including descriptors committed by an `EVALUATED_COMMITTED` trigger. Terminal states, including required `CANCELED` children and their settled parent audit, another scope or epoch, and derived queue pointers do not contribute. These counts expose asynchronous cleanup progress only; they do not gate Automation resumption or ordinary gameplay ticks, and no cleanup path enters or re-enters the DSL. -`PENDING` and `INDEXED` are target descriptor states; the current implementation does not persist them as separate statuses or persist `EVALUATED_COMMITTED`. **Current projection mapping:** while `PAUSED_FOR_ROLLBACK`, the live projection first restricts its counted set to rows whose `workItem.admissionEpoch <= 0` or `workItem.admissionEpoch < current admissionEpoch`, excluding positive current-epoch rows; within that set it counts `EVALUATING`, including unresolved stale rows, and `HANDOFF_IN_FLIGHT` as active and `PENDING_EVALUATION` as pending. Normal mode counts the corresponding scoped rows without that epoch filter. Until the implementation converges, drain and rebuild projections must report that gap rather than presenting `PENDING_EVALUATION` or `EVALUATING` as evaluated command work; unresolved counts remain diagnostic cleanup backlog and do not gate ordinary ticks or target Automation resumption. +`PENDING` and `INDEXED` are target descriptor states; the current implementation does not persist them as separate statuses or persist `EVALUATED_COMMITTED`. **Current projection mapping:** the live projection selects the counted epoch set by mode: `NORMAL` includes only rows whose `workItem.admissionEpoch` equals the current `admissionEpoch`, while `PAUSED_FOR_ROLLBACK` includes rows whose `workItem.admissionEpoch <= 0` or `workItem.admissionEpoch < current admissionEpoch`, excluding positive current-epoch rows. Within that set it counts `EVALUATING`, including unresolved stale rows, and `HANDOFF_IN_FLIGHT` as active and `PENDING_EVALUATION` as pending. Until the implementation converges, drain and rebuild projections must report that gap rather than presenting `PENDING_EVALUATION` or `EVALUATING` as evaluated command work; unresolved counts remain diagnostic cleanup backlog and do not gate ordinary ticks or target Automation resumption. ### Operator Replay of DEAD_LETTERED Work diff --git a/protos/automation-scripting/v1/automation_scripting_service.proto b/protos/automation-scripting/v1/automation_scripting_service.proto index 3f8377211b..24e2eea8a2 100644 --- a/protos/automation-scripting/v1/automation_scripting_service.proto +++ b/protos/automation-scripting/v1/automation_scripting_service.proto @@ -330,6 +330,18 @@ message ReplayDeadLetteredWorkItemsResponse { int64 replayed_count = 1; int64 rejected_count = 2; shared.v1.ErrorDetail error = 3; + // Durable per-item outcomes, in the same order as the selected work-item IDs. + repeated ReplayDeadLetteredWorkItemResult results = 4; + // The canonical request fingerprint used for idempotent replay readback. + string request_fingerprint = 5; +} + +message ReplayDeadLetteredWorkItemResult { + string work_item_id = 1; + string outcome = 2; + string rejection_reason = 3; + string failure_reason = 4; + int64 failure_generation = 5; } enum TriggerMode { From 3e76249c920516ad84025e0ea379710d19298f96 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 21 Sep 2026 11:47:54 +1200 Subject: [PATCH 04/68] style: align combined replay test imports --- .../service/impl/ScriptWorkItemServiceImplTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java index 77b1341e71..d86a4f43fb 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java @@ -36,9 +36,9 @@ import net.firedevops.firemud.automationscripting.service.ScriptPatchPinProjectionService; import net.firedevops.firemud.automationscripting.service.ScriptPatchReadinessProjectionService; import net.firedevops.firemud.automationscripting.service.ScriptWorkItemService; +import net.firedevops.firemud.automationscripting.v1.PluginState; import net.firedevops.firemud.automationscripting.v1.ScriptPatchInstanceRolloutStatus; import net.firedevops.firemud.automationscripting.v1.ScriptPatchStatus; -import net.firedevops.firemud.automationscripting.v1.PluginState; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedScriptPatchVersionResponse; import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; From 341362d42d2873a7ab4ba9d165f13aae9a5d4c0e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 21 Sep 2026 11:59:21 +1200 Subject: [PATCH 05/68] docs: preserve replay cleanup and handoff boundaries --- .../automation-scripting-service/api-contracts.md | 2 +- ...em-architecture-scripting-rollout-and-rollback.md | 2 ++ .../automation-and-scheduler-runtime.md | 12 +++++++----- .../shared-runtime-contracts-and-persistence.md | 1 + 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md index f0accc0140..374f4330ee 100644 --- a/design/architecture/microservices/automation-scripting-service/api-contracts.md +++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md @@ -79,7 +79,7 @@ Expected response: ### Work-Item Identifier Naming -On the current public Automation & Scripting API, `workItemId` and `workItemIds` are aliases for the canonical persisted `outboxWorkItemId` parent identifiers. The aliases carry the same identifier values and do not define a second work-item identity. `automationWorkItemId` remains the current Game Session wire name for that same parent identifier at the handoff boundary. **Target-state mutation contract:** Replay and purge mutations are bounded to explicit work-item IDs; descriptor references carrying the complete Command-Handoff Identity remain deferred until a separate accepted contract. **Current replay gap:** `ReplayDeadLetteredWorkItems` still exposes optional scope fields, permits an empty ID list, falls back to tenant-wide dead-letter selection, and applies filters both with and without explicit IDs, as detailed in the endpoint entry below. +On the current public Automation & Scripting API, `workItemId` and `workItemIds` are aliases for the canonical persisted `outboxWorkItemId` parent identifiers. The aliases carry the same identifier values and do not define a second work-item identity. `automationWorkItemId` remains the current Game Session wire name for that same parent identifier at the handoff boundary. **Target-state mutation contract:** Replay and purge mutations are bounded to explicit work-item IDs; descriptor references carrying the complete Command-Handoff Identity remain deferred until a separate accepted contract. **Current replay gap:** `ReplayDeadLetteredWorkItems` still exposes optional scope fields and applies filters both with and without explicit IDs, as detailed in the endpoint entry below; the service rejects an empty ID list before selection. Generic replay rejects tenant-readiness `onLoad` rows with `onload_not_replayable`, with focused proof in `ScriptWorkItemServiceImplTest`. ## Event Ingress Contract diff --git a/design/architecture/system-architecture-scripting-rollout-and-rollback.md b/design/architecture/system-architecture-scripting-rollout-and-rollback.md index e2182f6224..153e5b8562 100644 --- a/design/architecture/system-architecture-scripting-rollout-and-rollback.md +++ b/design/architecture/system-architecture-scripting-rollout-and-rollback.md @@ -10,6 +10,8 @@ Before any promotion or rollback admission barrier, the orchestrator resolves th ## Implementation Status +The live Game Session handoff still lacks complete per-command Trigger Identity propagation; the detailed current fallback is recorded in [Command Identity and Live Handoff Boundary](#command-identity-and-live-handoff-boundary). Bounded local multi-command and multi-target fan-out is live, but complete durable child/target identity and end-to-end handoff/dedup proof remain incomplete, so current fan-out is not target-conformant. + Automation currently claims work through `PENDING_EVALUATION` to `EVALUATING`; its implementation lacks the target lease/fencing-generation recovery and separate evaluated descriptor/outbox boundary. The target state mapping and recovery owner are canonical in [Scripting Runtime Execution](./system-architecture-scripting-runtime-execution.md#current-state-mapping-drain-and-rebuild-rules). While `PAUSED_FOR_ROLLBACK`, current `GetAutomationDrainStatus` restricts its counted set to rows whose `workItem.admissionEpoch <= 0` or `workItem.admissionEpoch < current admissionEpoch`, excluding positive current-epoch rows; within that set `activeExecutionCount` counts `EVALUATING` and `HANDOFF_IN_FLIGHT`, including unresolved stale `EVALUATING`, and `pendingCancelableWorkItemCount` counts `PENDING_EVALUATION`. Normal mode counts the corresponding scoped rows without that epoch filter. This is a current projection gap, not permission to infer a reclaim. Metric schemas come from [Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix); audit and handoff diagnostics come from the [Scripting & Automation Observability Contract](./system-architecture-scripting-observability-contract.md). The current exact-owner boundary is narrower than the target workflow: Game Session's pin owner persists the exact `(scriptPatchVersion, scriptPinEpoch, scriptPinControlPlaneRequestId)` tuple, and Automation work-item plus handoff-audit persistence retains that evidence. `scriptPinControlPlaneRequestId` is the persisted owner-evidence projection of the successful Game Session pin mutation's API `controlPlaneRequestId`; it is not a second request identity. Later convergence and reconciliation operations use their own operation-scoped `controlPlaneRequestId` values and the separate `convergenceAttemptGeneration`, and never overwrite the persisted pin-owner evidence. For local instance-scoped Automation, `EnqueueAutomationCommandIfAbsentRequest` carries the complete tuple, Game Session compares it before admission or duplicate replay, durable tick staging/replay locks and rechecks it, and final gameplay execution rechecks the persisted tuple. `ScheduleRemoteFollowupRequest` carries the source epoch and owner-request evidence, but the receiving remote path does not yet persist or compare that evidence at the complete source/target and final-effect fences. Those target gates remain separate and must not be inferred from the completed local path; current remote handoff diagnosis uses the narrower fallback documented in [Scripting Runtime Execution](./system-architecture-scripting-runtime-execution.md#current-implementation-status). 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 1d66f84f1d..b8a19d631c 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -14,15 +14,17 @@ Current residual: the legacy NPC formation REST controllers are removed and `/fo The current Automation queue reset/rebuild/resume path is unavailable and must fail closed regardless of the observed status mix; a non-atomic status preflight cannot authorize the target PENDING-only workflow. The owner-reconciled target recovery and its proof remain outstanding. -Terminal cleanup disposes aged child audit and handoff evidence before deleting each eligible `HANDED_OFF` or `CANCELED` parent `script_work_items` row in the same transaction; the non-cascading foreign keys therefore cannot strand that parent cleanup on a constraint violation. Automatic `DEAD_LETTERED` age- and row-cap deletion now fails closed because the live schema cannot prove whole-bundle recovery disposition or evidence-retention eligibility. Repository unit proof covers the child-first SQL order and fail-closed dead-letter paths; PostgreSQL retention cases exist but require Docker/Testcontainers and remain unexecuted in the current local environment. +Execution claims commit `PENDING_EVALUATION -> EVALUATING` before the per-item processing transaction. The production Game Session client maps ordinary runtime transport failures to an unavailable response and bounded backoff; an unexpected exception after the claim still leaves the row `EVALUATING` and the batch logs it without unsafe requeue. There is no durable evaluation-owner lease, stage/descriptor marker, or complete child ledger to distinguish a pre-effect crash from uncertain handoff. Stale evaluation-owner reconciliation, fencing, and PostgreSQL crash/concurrency proof remain recovery gaps; age alone cannot authorize retry or cleanup. -The `xmax = 0` insert discriminator used by the `ScriptWorkItem` and `ScriptEventAudit` repositories remains without PostgreSQL integration proof; current unit/mock evidence does not establish INSERT-versus-conflict-update behavior against PostgreSQL. +Terminal cleanup locks and rechecks each eligible `HANDED_OFF` or `CANCELED` parent and its handoff children, detaches retained audit links, then deletes only unheld handoff children and eligible parents in one transaction. A retained replay result or active handoff hold blocks parent deletion; replay results and audit evidence are not age-disposed by this cleanup. Automatic `DEAD_LETTERED` age- and row-cap deletion fails closed because the live schema cannot prove whole-bundle recovery disposition or evidence-retention eligibility. V4 now persists a monotonic failure-generation field and immutable replay request/result receipts, but the recovery aggregate, complete expected-child ledger, and recovery/rollback-diagnosis horizon remain incomplete. Repository unit proof covers the child-first SQL order and fail-closed dead-letter paths; PostgreSQL retention cases exist but require Docker/Testcontainers and remain unexecuted in the current local environment. + +The `xmax = 0` insert discriminator used by the `ScriptWorkItem` and `ScriptEventAudit` repositories has PostgreSQL integration cases for INSERT-versus-conflict-update behavior in [AutomationClaimAndRetentionRepositoryIntegrationTest](../../../services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java); those Testcontainers cases compile but are skipped locally without Docker, so executed PostgreSQL proof remains outstanding. Bootstrap/dev `UpdateScript` now uses one PostgreSQL upsert for the durable `(tenantId, scriptPatchVersion, scriptId)` definition identity, preserving explicit-ID CAS for internal callers and replacing bindings within the service transaction. Focused repository unit proof executes; PostgreSQL cases for one-statement persistence, concurrent definition identity, complete binding replacement, and rollback are compiled but skipped without Docker. They are not executed database proof. This bounded upload path does not satisfy the separate production publication/readiness contract. ### Script-transition reconciliation -The accepted transition family does not promote the current implementation to complete. Exact patch/epoch propagation is present through the live instance-bound admission, schedule, replay, and timer/audit paths; local Game Session Automation admission, duplicate replay, durable tick staging/replay, and final gameplay-effect tuple enforcement are implemented and recorded below. Remote handoff source/target dual-tuple propagation and binding, projection freshness, complete command identity, and remote final-effect fencing remain implementation/proof gaps; current Automation pin projections and rollout rows are diagnostic/read-model state and cannot authorize an operation. Automation-owned plugin activation/lifecycle fences are not yet persisted and propagated through current plugin work, status, scheduler, handoff, retry, replay, and recovery surfaces, and same-version re-enable/same-epoch lifecycle proof remains open. In particular, the current scheduler `TimerFiringCandidate` has no captured `pluginActivationEpoch`, so plugin-owned `scheduleCandidateId` and derived `scriptEventId` cannot yet change on disable/re-enable; the scheduler/service model must add and persist that captured epoch before the target identity rule is live. Automation's target `failureGeneration` is likewise not yet persisted or propagated through dead-letter readback, recovery results, claims, and success evidence. Current properties still lack the target upper-bound validation for `SCRIPT_PIN_PROJECTION_STALE_THRESHOLD_MS`; the [Automation & Scripting configuration contract](../../architecture/microservices/automation-scripting-service/configuration.md#service-specific-variables) owns the numeric range and freshness-SLO relationship. These gaps remain separate from the region/region-epoch and plugin-binding fences tracked below; those fences do not substitute for final exact-epoch enforcement. +The accepted transition family does not promote the current implementation to complete. Exact patch/epoch propagation is present through the live instance-bound admission, schedule, replay, and timer/audit paths; local Game Session Automation admission, duplicate replay, durable tick staging/replay, and final gameplay-effect tuple enforcement are implemented and recorded below. Remote handoff source/target dual-tuple propagation and binding, projection freshness, complete command identity, and remote final-effect fencing remain implementation/proof gaps; current Automation pin projections and rollout rows are diagnostic/read-model state and cannot authorize an operation. Automation-owned plugin activation/lifecycle fences are not yet persisted and propagated through current plugin work, status, scheduler, handoff, retry, replay, and recovery surfaces, and same-version re-enable/same-epoch lifecycle proof remains open. In particular, the current scheduler `TimerFiringCandidate` has no captured `pluginActivationEpoch`, so plugin-owned `scheduleCandidateId` and derived `scriptEventId` cannot yet change on disable/re-enable; the scheduler/service model must add and persist that captured epoch before the target identity rule is live. V4 now persists Automation's monotonic `failureGeneration` and replay request/result receipts, but those fields are not yet propagated through complete dead-letter readback, recovery claims/attempts, success evidence, or the expected-child ledger; the recovery-aware retention horizon therefore remains open. Current properties still lack the target upper-bound validation for `SCRIPT_PIN_PROJECTION_STALE_THRESHOLD_MS`; the [Automation & Scripting configuration contract](../../architecture/microservices/automation-scripting-service/configuration.md#service-specific-variables) owns the numeric range and freshness-SLO relationship. These gaps remain separate from the region/region-epoch and plugin-binding fences tracked below; those fences do not substitute for final exact-epoch enforcement. Local Game Session Automation command fencing is implemented for the complete `(scriptPatchVersion, scriptPinEpoch, scriptPinControlPlaneRequestId)` tuple: admission and duplicate replay compare against the locked current `GameInstance`, durable tick staging/replay locks and rechecks the tuple and retains it in the sealed manifest, and final execution rechecks the persisted tuple. Non-script player commands retain their existing path. Remote Automation follow-ups retain their separate legacy source/target contract, but target-side `trigger_script_event` execution is deterministically disabled until complete source/target tuple-plus-owner binding is implemented and proven. The combined three-service `check -PfullCheck` recorded Automation 713 unit tests executed and 20 integration tests skipped; the current Game Session exact-head check records 1,591 unit tests total (1,574 executed and 17 skipped), 125 integration tests total (18 executed and 107 skipped), and 38 cross-service tests total (1 executed and 37 skipped); and Game Design 132 unit tests executed with 9 integration tests skipped. Focused exact-pin and forward-migration tests were also forced to rerun successfully. PostgreSQL/Testcontainers-backed migration and integration cases that remain skipped are not local runtime proof. @@ -105,7 +107,7 @@ Current status: `VersionServiceImpl.publishScriptPatchVersion` in Game Design ca The bounded readiness correction serializes tenant `begin` and refresh mutations, retains an existing readiness identity on retry without restarting `onLoad`, schedule refresh, or Temporal tracking, and installs a partial unique index for one active tenant candidate. Retained duplicate active rows fail V2 migration rather than being rewritten. Focused unit tests pass, but the two new PostgreSQL concurrency/duplicate-migration cases are unexecuted here; empty-notification, manifest, base/request binding, generation-CAS, and recovery gaps remain with 5B-Publication and the named Automation owners. -Current gaps remain: `ReplayDeadLetteredWorkItems` can requeue `onLoad`, stale `ONLOAD_RUNNING` work remains unreclaimed, and focused proof for readiness-owner recovery is missing. Target ownership, recovery, terminalization, and identity rules are defined by [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md) and the [scripting normative contract tables](../../architecture/system-architecture-scripting-normative-contract-tables.md#table-2-script_event_audit-stages-and-outcomes). +Current generic dead-letter replay rejects `onLoad` with `onload_not_replayable`; stale `ONLOAD_RUNNING` work remains unreclaimed, and focused proof for readiness-owner recovery is missing. Target ownership, recovery, terminalization, and identity rules are defined by [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md) and the [scripting normative contract tables](../../architecture/system-architecture-scripting-normative-contract-tables.md#table-2-script_event_audit-stages-and-outcomes). Publish workflow state is also exposed through canonical control-plane reads; Temporal workflow identity does not create a parallel operator state model. @@ -132,7 +134,7 @@ The current execution policy has bounded terminal cleanup, serialized-work-item Quota-denied handlers are audited without creating work items, and budget-denied live work uses `tenant_budget_exceeded`. For this readiness path, the target `EXECUTING` transition is the execution state of `script_work_items`; the separate patch-readiness projection remains `ONLOAD_RUNNING` until it reaches `READY` or `FAILED`. -Target readiness ownership, at-most-once stale terminalization, and exclusion from generic dead-letter replay are defined by [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md) and the [normative contract tables](../../architecture/system-architecture-scripting-normative-contract-tables.md#table-2-script_event_audit-stages-and-outcomes). Current generic replay can still requeue `onLoad`, stale `ONLOAD_RUNNING` work remains unreclaimed, and focused readiness-owner recovery proof is missing. +Target readiness ownership, at-most-once stale terminalization, and exclusion from generic dead-letter replay are defined by [ADR 0115](../../architecture/decisions/adr-0115-manifest-complete-onload-readiness-without-durable-game-initialization.md) and the [normative contract tables](../../architecture/system-architecture-scripting-normative-contract-tables.md#table-2-script_event_audit-stages-and-outcomes). Generic replay now rejects `onLoad`, but stale `ONLOAD_RUNNING` work remains unreclaimed and focused readiness-owner recovery proof is missing. Implementation status: the manifest classifies `onLoad` as `PUBLISH_READINESS`; live work persists `quotaClass`, charges ordinary per-script/tenant budgets only for `STANDARD_RUNTIME`, and reserves separate `script.readiness.*` capacity after claim. Capacity exhaustion currently moves work through `EVALUATING` to `CANCELED` with `onload_budget_exceeded` and maps the readiness projection to legacy `ROLLED_BACK`; this is stage/state drift because target denial must occur before `EXECUTING` and record `FAILED` at `ADMISSION`. Instance-bound ingress/work-item/audit paths persist and deduplicate the exact `scriptPatchVersion`/`scriptPinEpoch` tuple with paired request evidence, retain plugin/binding identity, and prevent same-version/different-epoch reuse. Stale recovery preserves the original Trigger Identity and `scriptEventId` without DSL re-entry; tenant-readiness `onLoad` uses the pre-instance identity ``. The canceled outbox row remains subject to configured terminal cleanup. diff --git a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md index ca01ec3d34..a0e753d2b8 100644 --- a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md +++ b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md @@ -41,6 +41,7 @@ The following current-state findings refine the existing partial/drift status; o - `SF-2.1`: Account V22/V23 canonicalize retained `accounts.email` values and validate a new check without proven rolling- or rollback-compatibility with older binaries. Before affected deployment, Account needs service- and environment-specific no-overlap and retained-data evidence or a forward-compatible rollout path, plus old-era and mixed-binary proof. No existing deployment state is inferred; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). - `SF-2.1`: Account implements bounded owner-local cleanup of expired password-reset, email-verification, and email-login-challenge SQL rows with per-family deleted counts and oldest-expired-row lag. Focused unit coverage exists for cleanup orchestration; individual PostgreSQL integration-case execution is not recorded in the available validation evidence. Atomic token consumption, session revocation, and complete ADR 0163 retention classes, horizons, blockers, holds, and cross-service proof remain open; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). This tracker records owner-local status only and does not alter the normative retention contract. - `SF-1.2` / `SF-2.1`: Entity runtime-instance cleanup deletes item/container families by `(tenantId, gameInstanceId)` without namespace/scope/holder closure or proven S3 classification. Cleanup acknowledgement and its fencing/classification proof remain unsafe. See [Entity Runtime and Data](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status). +- `SF-2.1`: Entity actor-condition expiry defaults to 30 seconds and globally deletes elapsed rows without a batch bound; read-time filtering prevents expired gameplay effects from being restored. The cleanup targets `actor_active_conditions` only; the separate `entity_mutation_effects` receipt is checked before `ApplyActorCondition` mutation and is not deleted by this sweep, but a receipt-retention guarantee across the replay/restore horizon remains unproved. No concrete duplicate-application or S2-loss claim is made. Target gaps remain explicit S1/S2 classification, replay/restore horizon, dependent references/holds, safe watermark, and typed target/request-digest/concurrency proof. See [Entity Runtime and Data](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status) and [Entity Operations](../../architecture/microservices/entity-management-service/operations.md#operational-notes). - `SF-2.1`: World’s historical `world_event` replacement has no recorded retained-row mapping/backfill evidence, and legacy tenant/version migrations use sentinel defaults without hierarchy/version-graph evidence. Affected retained-data disposition or a verified no-data boundary remains open; see [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). - `SF-2.1`: World V22 directly renames `room_instance` and `room_instance_exit` columns without proven rolling- or rollback-compatibility with older binaries. Before affected deployment, World needs service- and environment-specific no-overlap and retained-data evidence or a forward-compatible rollout path, plus old-era and mixed-binary proof. No existing deployment state is inferred; see [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). - `SF-1.5` / `SF-2.4`: `common-saga` dependency and migration-location wiring is broad through base service conventions, including services without Saga workflows. No finite repository-wide Saga-adopter registry or machine-enforced adopter opt-in is currently established from accepted workflow ownership and canonical service documents, so adopter selection and conformance proof remain incomplete; see [Shared Libraries](../../architecture/system-architecture-shared-libraries.md#implementation-status). From 3458c93a9d5cad7f5f1a2478f69f81855992a7d7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 22 Sep 2026 15:42:52 +1200 Subject: [PATCH 06/68] style(automation): normalize replay merge formatting --- .../system-architecture-scripting-runtime-execution.md | 2 +- .../service/impl/ScriptWorkItemExecutionServiceImplTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/design/architecture/system-architecture-scripting-runtime-execution.md b/design/architecture/system-architecture-scripting-runtime-execution.md index a4f24e2bdd..6e621f0da8 100644 --- a/design/architecture/system-architecture-scripting-runtime-execution.md +++ b/design/architecture/system-architecture-scripting-runtime-execution.md @@ -183,7 +183,7 @@ For plugin-owned schedule-derived work, rebuilding a due candidate or firing cla - The canonical defaults are owned by [Automation & Scripting Service Configuration](./microservices/automation-scripting-service/configuration.md): `SCRIPT_OUTBOX_HANDED_OFF_RETENTION_DAYS`, `SCRIPT_OUTBOX_CANCELED_RETENTION_DAYS`, `SCRIPT_DEAD_LETTER_MAX_AGE_SECONDS`, `SCRIPT_OUTBOX_TERMINAL_CLEANUP_INTERVAL_SECONDS`, `SCRIPT_OUTBOX_EXECUTION_INTERVAL_SECONDS`, and `SCRIPT_OUTBOX_EXECUTION_BATCH_SIZE`. `SCRIPT_OUTBOX_QUEUE_REBUILD_INTERVAL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_REBUILD_BATCH_SIZE` are target-only settings for a future owner-gated rebuild and have no current scheduled binding. - The current Automation & Scripting implementation wires the handed-off and canceled retention knobs into a scheduled cleanup job for terminal `script_work_items`. Dead-letter age and row-cap settings remain diagnostic only: cleanup does not select, scan, or delete `DEAD_LETTERED` parents, replay request/result receipts, or their supporting audit/handoff evidence because the current implementation still lacks the recovery-aware whole-bundle and rollback-diagnosis horizon. Dependency references, retention holds, or retained replay/evidence rows can block deletion, and the target retention policy still covers terminal dead-lettered records once that proof exists. - **Target-state only:** The derived queue contract is a projection only: queue drains dedupe repeated parent pointer envelopes by `outboxWorkItemId`, and a bounded rebuild republishes missing queue pointers only from evaluated descriptors in `PENDING` or `INDEXED` status. Rebuild and handoff must apply an explicit status gate before treating a row as evaluated command work. Projection or Redis arrival order is not replay order: the executor selects durable rows by their canonical status and complete identity, and a rebuild must not advance, reorder, or replay a descriptor merely because its pointer was observed first. Pre-DSL `PENDING_EVALUATION` and `EXECUTING` rows are never published to or consumed from the evaluated-command queue; a separate pre-DSL projection may route evaluator work. Redis never becomes authoritative, and reindexing `EXECUTING` rows must not reclaim or replay them. The target descriptor rebuild and lease/fencing recovery contract above remain current implementation gaps. - - The scheduled queue-rebuild hook and its configuration have been removed/disabled because the current `rebuildPendingWorkItemIndex` helper remains unsafe and has no stale, owner, or compare-and-set reconciliation gate. Its current status gate selects only `PENDING_EVALUATION`, but its Redis-existence check and append remain separate operations, so it is not a supported recovery operation. The current executor catches queue-pointer discovery failures and falls back to a bounded durable `PENDING_EVALUATION` scan, and supplements a short queue batch with a durable scan when capacity remains. Redis drains now use bounded one-at-a-time `LPOP`, preserving any unconsumed suffix for the next sweep; this does not make rebuild publication atomic or safe. Consequently, safe owner-reconciled rebuild and any safe reset/recovery operation remain unavailable; queue reset/resume must fail closed. Target pre-DSL recovery permits `PENDING_EVALUATION` plus only an `EVALUATING` row whose owner has proved the lease stale or explicitly released ownership through one fenced compare-and-set covering status, owner, freshness, and fence transition; non-stale, unresolved, or ambiguous ownership remains unrecoverable. Target `PENDING`/`INDEXED` descriptor rebuild is unavailable because the separate evaluated descriptor status layer is not currently persisted. These current pointers are not evaluated-command queue entries or evidence of descriptor replay. Containment and the remaining implementation/proof gap are defined in [Current Queue-Rebuild Concurrency Gap](#current-queue-rebuild-concurrency-gap) and remain owned by the Automation queue owner. +- The scheduled queue-rebuild hook and its configuration have been removed/disabled because the current `rebuildPendingWorkItemIndex` helper remains unsafe and has no stale, owner, or compare-and-set reconciliation gate. Its current status gate selects only `PENDING_EVALUATION`, but its Redis-existence check and append remain separate operations, so it is not a supported recovery operation. The current executor catches queue-pointer discovery failures and falls back to a bounded durable `PENDING_EVALUATION` scan, and supplements a short queue batch with a durable scan when capacity remains. Redis drains now use bounded one-at-a-time `LPOP`, preserving any unconsumed suffix for the next sweep; this does not make rebuild publication atomic or safe. Consequently, safe owner-reconciled rebuild and any safe reset/recovery operation remain unavailable; queue reset/resume must fail closed. Target pre-DSL recovery permits `PENDING_EVALUATION` plus only an `EVALUATING` row whose owner has proved the lease stale or explicitly released ownership through one fenced compare-and-set covering status, owner, freshness, and fence transition; non-stale, unresolved, or ambiguous ownership remains unrecoverable. Target `PENDING`/`INDEXED` descriptor rebuild is unavailable because the separate evaluated descriptor status layer is not currently persisted. These current pointers are not evaluated-command queue entries or evidence of descriptor replay. Containment and the remaining implementation/proof gap are defined in [Current Queue-Rebuild Concurrency Gap](#current-queue-rebuild-concurrency-gap) and remain owned by the Automation queue owner. - Target purge follows the [normative terminal descriptor evidence rule](./system-architecture-scripting-normative-contract-tables.md#terminal-descriptor-evidence-purge-target-state): under an `EVALUATED_COMMITTED` parent it may remove descriptor/outbox/evaluated-output evidence only after every child under that parent is terminal (`HANDED_OFF`, `CANCELED`, or `DEAD_LETTERED`) and every eligible evidence item is retention-eligible. A fully canceled required-child set therefore follows the same retention-gated purge path; purge does not create or transition a dead-letter recovery aggregate or create replay eligibility. The purge transaction atomically removes all eligible evidence and persists an explicit durable `descriptorEvidencePurgedAt` marker on the retained parent. If any sibling is `PENDING`, `INDEXED`, `HANDOFF_IN_FLIGHT`, otherwise nonterminal, or not retention-eligible, the entire parent purge is rejected and no marker is written. A marked parent is non-recoverable and non-replayable, and consumers reject it deterministically rather than treating missing children as recoverable. It preserves the trigger marker, corresponding `script_event_audit`, and replay-causation evidence, and rejects active/nonterminal trigger or descriptor work. - Operator-facing replay, purge, and convergence tooling must treat those retention windows as the supported diagnosis horizon rather than inventing ad hoc cleanup timing. diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java index c91ff8b514..cdf86a3099 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java @@ -36,10 +36,10 @@ import net.firedevops.firemud.automationscripting.service.quota.ScriptDryRunCapacityService; import net.firedevops.firemud.automationscripting.service.quota.ScriptReadinessCapacityService; import net.firedevops.firemud.automationscripting.service.quota.ScriptTenantBudgetService; +import net.firedevops.firemud.automationscripting.v1.PluginState; import net.firedevops.firemud.gamesession.v1.GetGameInstanceRuntimeStateResponse; import net.firedevops.firemud.shared.v1.ErrorDetail; import org.jooq.exception.DataAccessException; -import net.firedevops.firemud.automationscripting.v1.PluginState; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; From 59946f45d710bb86213a27180a5fa74ae5ad4ba1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 22 Sep 2026 15:46:17 +1200 Subject: [PATCH 07/68] test(automation): reconcile lifecycle retry proof with V4 batching --- ...criptWorkItemExecutionServiceImplTest.java | 27 ++++++++----------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java index cdf86a3099..a43cad384a 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java @@ -1,7 +1,6 @@ package net.firedevops.firemud.automationscripting.service.impl; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -221,7 +220,7 @@ void retriesWhenPluginRepositoryReportsTransientConnectionFailure() { .thenThrow( new DataAccessException( "plugin lookup unavailable", new SQLTransientConnectionException("offline"))); - ScriptWorkItem item = pluginWorkItem(); + ScriptWorkItem item = replayPluginWorkItem(); when(workItemService.claimPendingForEvaluation(1)).thenReturn(List.of(item)); when(workItemRepository.save(item)).thenAnswer(invocation -> invocation.getArgument(0)); @@ -255,7 +254,7 @@ void terminalizesNonAvailabilityPluginRepositoryFailureWithoutRetry() { "1", "7", "plugin-1")) .thenThrow( new DataAccessException("invalid plugin query", new SQLException("syntax", "42601"))); - ScriptWorkItem item = pluginWorkItem(); + ScriptWorkItem item = replayPluginWorkItem(); when(workItemService.claimPendingForEvaluation(1)).thenReturn(List.of(item)); when(workItemRepository.save(item)).thenAnswer(invocation -> invocation.getArgument(0)); @@ -903,10 +902,9 @@ void missingCurrentPluginAuthorityRetriesWithoutTerminalWrites() { allowingTenantBudgetService(), pluginRepository); - assertThatThrownBy(() -> service.processPendingWorkItems(1)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("authority_unavailable"); + ScriptWorkItemExecutionService.ExecutionBatchResult result = service.processPendingWorkItems(1); + assertThat(result.failedCount()).isEqualTo(1); assertThat(item.getStatus()).isEqualTo(originalStatus); verify(workItemRepository, Mockito.never()).save(Mockito.any()); verify(auditRepository, Mockito.never()).findByWorkItemId(Mockito.anyLong()); @@ -943,10 +941,9 @@ void malformedCurrentPluginAuthorityRetriesWithoutTerminalWrites(String pluginSt allowingTenantBudgetService(), pluginRepository); - assertThatThrownBy(() -> service.processPendingWorkItems(1)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("authority_unavailable"); + ScriptWorkItemExecutionService.ExecutionBatchResult result = service.processPendingWorkItems(1); + assertThat(result.failedCount()).isEqualTo(1); assertThat(item.getStatus()).isEqualTo("EVALUATING"); verify(workItemRepository, Mockito.never()).save(Mockito.any()); verify(auditRepository, Mockito.never()).findByWorkItemId(Mockito.anyLong()); @@ -981,10 +978,9 @@ void invalidCurrentPluginEvidenceRetriesWithoutTerminalWrites() { allowingTenantBudgetService(), pluginRepository); - assertThatThrownBy(() -> service.processPendingWorkItems(1)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("authority_unavailable"); + ScriptWorkItemExecutionService.ExecutionBatchResult result = service.processPendingWorkItems(1); + assertThat(result.failedCount()).isEqualTo(1); assertThat(item.getStatus()).isEqualTo("EVALUATING"); verify(workItemRepository, Mockito.never()).save(Mockito.any()); verify(auditRepository, Mockito.never()).findByWorkItemId(Mockito.anyLong()); @@ -1016,10 +1012,9 @@ void missingInjectedPluginAuthorityRetriesWithoutTerminalWrites() { allowingDryRunCapacityService(), new ObjectMapper()); - assertThatThrownBy(() -> service.processPendingWorkItems(1)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("authority_unavailable"); + ScriptWorkItemExecutionService.ExecutionBatchResult result = service.processPendingWorkItems(1); + assertThat(result.failedCount()).isEqualTo(1); assertThat(item.getStatus()).isEqualTo("EVALUATING"); verify(workItemRepository, Mockito.never()).save(Mockito.any()); verify(auditRepository, Mockito.never()).findByWorkItemId(Mockito.anyLong()); @@ -3477,7 +3472,7 @@ private static ScriptWorkItem workItem() { return item; } - private static ScriptWorkItem pluginWorkItem() { + private static ScriptWorkItem replayPluginWorkItem() { ScriptWorkItem item = workItem(); item.setScriptPinEpoch(3L); item.setPluginId("plugin-1"); From 0586c69004af1b14382aec700306904a70461b60 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 22 Sep 2026 18:54:25 +1200 Subject: [PATCH 08/68] fix(automation): retain incomplete handoff evidence --- .../design-alignment/README.md | 2 +- .../ScriptHandoffEventRepository.java | 86 +++++++++++------- .../repository/ScriptWorkItemRepository.java | 19 +++- ...AndRetentionRepositoryIntegrationTest.java | 90 +++++++++++++++++++ .../ScriptHandoffEventRepositoryTest.java | 3 + .../ScriptWorkItemRepositoryTest.java | 5 ++ 6 files changed, 170 insertions(+), 35 deletions(-) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 8705498099..93d8461aec 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -43,7 +43,7 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | 5A | API, message, identifier, tenant, time, and authorization primitives | Complete (corpus review; implementation gaps remain) | [#2813](https://github.com/benhook1013/FireMUD/pull/2813) | Three fresh whole-section passes each covered 17/17 substantive allocated sources: 8, 15, and 12 raw observations. The corrected-state third pass confirmed 12 useful already-owned handoffs, no new unowned root, and taper. The shared-library Redis status claim and conflicting operator incident/revocation guidance were corrected. gRPC outcomes, Account runtime-read exposure, numeric IDs, gameplay attestation, JWT/workload identity, Gateway connect-carrier and route inventory, and script-fence gaps remain with their service/shared-runtime owners; Redis role clients and descriptor foundation belong to 5C, and operator binding enforcement/readback plus terminal-reissuance design belong to 6D. This status does not claim those capabilities are implemented. | | 5B-Schema | SQL/Flyway/jOOQ, schema and identifier migration | Broad review tapered; merge proof pending | [#2826](https://github.com/benhook1013/FireMUD/pull/2826) | Six fresh whole-unit cycles reached two corrected-state dry cycles after the accepted Schema fixes. Retained-row adjudication, mixed-binary deployment evidence, and Docker-backed PostgreSQL proof remain explicit limits. Dependent #2827 carries the separately reviewed Automation lifecycle/fence successor and is not additional Schema scope. | | 5B-Publication | Durable version/publication/readiness state | Broad review tapered; merge proof pending | [#2828](https://github.com/benhook1013/FireMUD/pull/2828) | Cycles 1–4 were productive and corrected the accepted findings through V27. Fresh whole-unit Cycles 5 and 6 each returned 12 raw observations with zero new useful Publication obligations, establishing two consecutive corrected-state dry cycles. Live mounted-certificate/Temporal owner calls, mixed PostgreSQL upgrade/concurrency proof, version-scoped Automation content, exact Game Design template/asset mapping, readiness notification, and dedicated ability-schema attestation remain open. | -| 5B-Retention | Retention classes, cleanup, horizons, contraction | Draft candidate; fresh broad review pending | [#2829](https://github.com/benhook1013/FireMUD/pull/2829) | V4 execution/replay/retention work is preserved behind Publication; no substantive fresh Retention review has begun on the linearized candidate. | +| 5B-Retention | Retention classes, cleanup, horizons, contraction | Broad review active; Cycle 1 productive | [#2829](https://github.com/benhook1013/FireMUD/pull/2829) | Fresh whole-unit Cycle 1 returned 12 observations with one useful Retention obligation. Cleanup now fails closed when any handoff child has an incomplete durable outcome, including sibling-bundle and parent-correlation proof. Replay-receipt horizons, recovery-aware dead-letter cleanup, cross-owner retention classes, and Docker-backed PostgreSQL proof remain open. | | 5C | Redis roles and cache/rate-limit semantics | Queued | — | — | | 5D | Idempotency, outbox, replay, saga, and workflow patterns | Queued | — | — | | 6A | Gateway routes, traffic planes, sharding, and close taxonomy | Queued | — | — | diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepository.java index ce2f75f8c9..b3f6124008 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepository.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepository.java @@ -51,49 +51,71 @@ public long deleteExpiredRetentionEvidence(Instant safeWatermark, Instant now) { LocalDateTime cutoff = toLocalDateTime(safeWatermark); OffsetDateTime current = toOffsetDateTime(now); var candidates = SCRIPT_HANDOFF_EVENTS.as("retention_candidates"); + var siblings = SCRIPT_HANDOFF_EVENTS.as("retention_siblings"); + Condition noIncompleteSibling = + notExists( + org.jooq + .impl + .DSL + .selectOne() + .from(siblings) + .where( + siblings + .TENANT_ID + .eq(candidates.TENANT_ID) + .and(siblings.WORK_ITEM_ID.eq(candidates.WORK_ITEM_ID)) + .and(incompleteHandoffOutcome(siblings.HANDOFF_OUTCOME)))); + Condition noIneligibleParent = + notExists( + org.jooq + .impl + .DSL + .selectOne() + .from(SCRIPT_WORK_ITEMS) + .where( + SCRIPT_WORK_ITEMS + .TENANT_ID + .eq(candidates.TENANT_ID) + .and(SCRIPT_WORK_ITEMS.ID.eq(candidates.WORK_ITEM_ID)) + .and( + SCRIPT_WORK_ITEMS + .STATUS + .notIn( + AutomationScriptingJooqRepositorySupport + .TERMINAL_WORK_ITEM_STATUSES) + .or(SCRIPT_WORK_ITEMS.STATUS.eq("DEAD_LETTERED"))))); + Condition candidateEligibility = + candidates + .TENANT_ID + .isNotNull() + .and(candidates.OBSERVED_AT.lt(cutoff)) + .and(RETENTION_HOLD_UNTIL.isNull().or(RETENTION_HOLD_UNTIL.le(current))) + .and(nonBlankHandoffOutcome(candidates.HANDOFF_OUTCOME)) + .and(noIncompleteSibling) + .and(noIneligibleParent); return dsl.deleteFrom(SCRIPT_HANDOFF_EVENTS) .where( row(SCRIPT_HANDOFF_EVENTS.ID, SCRIPT_HANDOFF_EVENTS.TENANT_ID) .in( dsl.select(candidates.ID, candidates.TENANT_ID) .from(candidates) - .where( - candidates - .TENANT_ID - .isNotNull() - .and(candidates.OBSERVED_AT.lt(cutoff)) - .and( - RETENTION_HOLD_UNTIL - .isNull() - .or(RETENTION_HOLD_UNTIL.le(current))) - .and( - notExists( - org.jooq - .impl - .DSL - .selectOne() - .from(SCRIPT_WORK_ITEMS) - .where( - SCRIPT_WORK_ITEMS - .TENANT_ID - .eq(candidates.TENANT_ID) - .and( - SCRIPT_WORK_ITEMS.ID.eq( - candidates.WORK_ITEM_ID)) - .and( - SCRIPT_WORK_ITEMS - .STATUS - .notIn( - AutomationScriptingJooqRepositorySupport - .TERMINAL_WORK_ITEM_STATUSES) - .or( - SCRIPT_WORK_ITEMS.STATUS.eq( - "DEAD_LETTERED"))))))) + .where(candidateEligibility) .orderBy(candidates.EVENT_ID.asc()) .limit(RETENTION_DELETE_BATCH_SIZE))) .execute(); } + /** Retention only disposes a handoff after its durable outcome has meaningful content. */ + private static Condition nonBlankHandoffOutcome(Field outcome) { + return outcome.isNotNull().and(incompleteHandoffOutcome(outcome).not()); + } + + private static Condition incompleteHandoffOutcome(Field outcome) { + return outcome + .isNull() + .or(field("regexp_replace({0}, '[[:space:]]', '', 'g')", String.class, outcome).eq("")); + } + /** Applies or clears the durable owner hold for one tenant-qualified handoff row. */ public boolean setRetentionHold(String tenantId, long handoffId, Instant holdUntil) { return dsl.update(SCRIPT_HANDOFF_EVENTS) diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepository.java index 2f001dedb4..0d921a2d68 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepository.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepository.java @@ -491,8 +491,23 @@ private static Condition noBlockingRetentionEvidence() { .TENANT_ID .eq(SCRIPT_WORK_ITEMS.TENANT_ID) .and(SCRIPT_HANDOFF_EVENTS.WORK_ITEM_ID.eq(SCRIPT_WORK_ITEMS.ID)) - .and(HANDOFF_RETENTION_HOLD_UNTIL.isNotNull()) - .and(HANDOFF_RETENTION_HOLD_UNTIL.gt(CURRENT_OFFSET_TIMESTAMP))))); + .and(handoffBlocksParent())))); + } + + private static Condition handoffBlocksParent() { + Condition incompleteOutcome = + SCRIPT_HANDOFF_EVENTS + .HANDOFF_OUTCOME + .isNull() + .or( + field( + "regexp_replace({0}, '[[:space:]]', '', 'g')", + String.class, SCRIPT_HANDOFF_EVENTS.HANDOFF_OUTCOME) + .eq("")); + return HANDOFF_RETENTION_HOLD_UNTIL + .isNotNull() + .and(HANDOFF_RETENTION_HOLD_UNTIL.gt(CURRENT_OFFSET_TIMESTAMP)) + .or(incompleteOutcome); } /** diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java index 9d93b9b219..175aa3a62b 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java @@ -938,6 +938,96 @@ void deadLetterRowCapLeavesParentWhenChildOutcomeIsIncomplete() { assertThat(dsl.fetchCount(SCRIPT_HANDOFF_EVENTS)).isEqualTo(1); } + @Test + void handedOffAgeRetentionLeavesParentWhenChildOutcomeIsIncomplete() { + ScriptWorkItem parent = workItemRepository.save(retainedWorkItem()); + ScriptHandoffEvent handoff = retainedHandoff(parent.getId()); + handoff.setEventId("incomplete-handed-off-age-handoff"); + handoff.setHandoffOutcome(""); + handoffRepository.save(handoff); + + assertThat(workItemRepository.deleteByStatusAndUpdatedAtBefore("HANDED_OFF", Instant.now())) + .isZero(); + assertThat(dsl.fetchCount(SCRIPT_WORK_ITEMS)).isEqualTo(1); + assertThat(dsl.fetchCount(SCRIPT_HANDOFF_EVENTS)).isEqualTo(1); + } + + @Test + void incompleteChildBlocksOnlyItsCorrelatedParentDuringAgeRetention() { + ScriptWorkItem incompleteParent = workItemRepository.save(retainedWorkItem()); + ScriptHandoffEvent incompleteHandoff = retainedHandoff(incompleteParent.getId()); + incompleteHandoff.setEventId("incomplete-correlated-parent"); + incompleteHandoff.setHandoffOutcome(""); + handoffRepository.save(incompleteHandoff); + + ScriptWorkItem completeParent = retainedWorkItem(); + completeParent.setScriptEventId("complete-correlated-parent"); + completeParent = workItemRepository.save(completeParent); + ScriptHandoffEvent completeHandoff = retainedHandoff(completeParent.getId()); + completeHandoff.setEventId("complete-correlated-child"); + handoffRepository.save(completeHandoff); + + assertThat(workItemRepository.deleteByStatusAndUpdatedAtBefore("HANDED_OFF", Instant.now())) + .isEqualTo(1L); + assertThat(dsl.fetchCount(SCRIPT_WORK_ITEMS)).isEqualTo(1); + assertThat( + dsl.fetchExists(SCRIPT_WORK_ITEMS, SCRIPT_WORK_ITEMS.ID.eq(incompleteParent.getId()))) + .isTrue(); + assertThat( + dsl.fetchExists( + SCRIPT_HANDOFF_EVENTS, SCRIPT_HANDOFF_EVENTS.ID.eq(incompleteHandoff.getId()))) + .isTrue(); + } + + @Test + void canceledRowCapRetentionLeavesParentWhenChildOutcomeIsWhitespace() { + ScriptWorkItem parent = retainedWorkItem(); + parent.setScriptEventId("canceled-incomplete-cap"); + parent.setStatus("CANCELED"); + parent = workItemRepository.save(parent); + ScriptHandoffEvent handoff = retainedHandoff(parent.getId()); + handoff.setEventId("incomplete-canceled-cap-handoff"); + handoff.setHandoffOutcome(" \t "); + handoffRepository.save(handoff); + + assertThat(workItemRepository.deleteOldestByStatus("CANCELED", 1)).isZero(); + assertThat(dsl.fetchCount(SCRIPT_WORK_ITEMS)).isEqualTo(1); + assertThat(dsl.fetchCount(SCRIPT_HANDOFF_EVENTS)).isEqualTo(1); + } + + @Test + void handoffAgeRetentionLeavesBlankOutcomeChildForTerminalParent() { + ScriptWorkItem parent = workItemRepository.save(retainedWorkItem()); + ScriptHandoffEvent handoff = retainedHandoff(parent.getId()); + handoff.setEventId("incomplete-direct-age-handoff"); + handoff.setHandoffOutcome(" \t "); + handoffRepository.save(handoff); + + assertThat(handoffRepository.deleteExpiredRetentionEvidence(Instant.now(), Instant.now())) + .isZero(); + assertThat(dsl.fetchCount(SCRIPT_WORK_ITEMS)).isEqualTo(1); + assertThat(dsl.fetchCount(SCRIPT_HANDOFF_EVENTS)).isEqualTo(1); + } + + @Test + void handoffAgeRetentionLeavesCompleteChildWhenSiblingOutcomeIsIncomplete() { + ScriptWorkItem parent = workItemRepository.save(retainedWorkItem()); + ScriptHandoffEvent complete = retainedHandoff(parent.getId()); + complete.setEventId("complete-sibling-age-handoff"); + handoffRepository.save(complete); + ScriptHandoffEvent incomplete = retainedHandoff(parent.getId()); + incomplete.setEventId("incomplete-sibling-age-handoff"); + incomplete.setCommandOrdinal(1); + incomplete.setAutomationDispatchId("dispatch-2"); + incomplete.setHandoffOutcome(""); + handoffRepository.save(incomplete); + + assertThat(handoffRepository.deleteExpiredRetentionEvidence(Instant.now(), Instant.now())) + .isZero(); + assertThat(dsl.fetchCount(SCRIPT_WORK_ITEMS)).isEqualTo(1); + assertThat(dsl.fetchCount(SCRIPT_HANDOFF_EVENTS)).isEqualTo(2); + } + private void markIngressInProgress(Long id, Instant claimStartedAt, int rowVersion) { dsl.update(SCRIPT_EVENT_INGRESS_AUDIT) .set(SCRIPT_EVENT_INGRESS_AUDIT.SOURCE_STATE, "IN_PROGRESS") diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepositoryTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepositoryTest.java index bb4399b530..0600048c9c 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepositoryTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepositoryTest.java @@ -589,6 +589,9 @@ void retentionCleanupBindsUtcOffsetDateTimeForNullableHoldComparison() { "observed_at", " < ", "retention_hold_until", + "handoff_outcome", + "regexp_replace", + "retention_siblings", "is null", " <= ", "status", diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepositoryTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepositoryTest.java index 912a89bc85..ba54174838 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepositoryTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepositoryTest.java @@ -654,7 +654,12 @@ void terminalCleanupRequiresReceiptAndActiveHandoffHoldProof() { "script_dead_letter_replay_results", "script_handoff_events", "retention_hold_until", + "handoff_outcome", + "regexp_replace", "current_timestamp")); + assertThat(sql.get()) + .contains("script_handoff_events\".\"tenant_id\" = \"script_work_items\".\"tenant_id\"") + .contains("script_handoff_events\".\"work_item_id\" = \"script_work_items\".\"id\""); } @Test From 40a0a95d4338418fe6c679af46a67e79655e5714 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 22 Sep 2026 19:04:52 +1200 Subject: [PATCH 09/68] docs(alignment): record first dry retention cycle --- design/project-management/design-alignment/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 93d8461aec..a5bcfac746 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -43,7 +43,7 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | 5A | API, message, identifier, tenant, time, and authorization primitives | Complete (corpus review; implementation gaps remain) | [#2813](https://github.com/benhook1013/FireMUD/pull/2813) | Three fresh whole-section passes each covered 17/17 substantive allocated sources: 8, 15, and 12 raw observations. The corrected-state third pass confirmed 12 useful already-owned handoffs, no new unowned root, and taper. The shared-library Redis status claim and conflicting operator incident/revocation guidance were corrected. gRPC outcomes, Account runtime-read exposure, numeric IDs, gameplay attestation, JWT/workload identity, Gateway connect-carrier and route inventory, and script-fence gaps remain with their service/shared-runtime owners; Redis role clients and descriptor foundation belong to 5C, and operator binding enforcement/readback plus terminal-reissuance design belong to 6D. This status does not claim those capabilities are implemented. | | 5B-Schema | SQL/Flyway/jOOQ, schema and identifier migration | Broad review tapered; merge proof pending | [#2826](https://github.com/benhook1013/FireMUD/pull/2826) | Six fresh whole-unit cycles reached two corrected-state dry cycles after the accepted Schema fixes. Retained-row adjudication, mixed-binary deployment evidence, and Docker-backed PostgreSQL proof remain explicit limits. Dependent #2827 carries the separately reviewed Automation lifecycle/fence successor and is not additional Schema scope. | | 5B-Publication | Durable version/publication/readiness state | Broad review tapered; merge proof pending | [#2828](https://github.com/benhook1013/FireMUD/pull/2828) | Cycles 1–4 were productive and corrected the accepted findings through V27. Fresh whole-unit Cycles 5 and 6 each returned 12 raw observations with zero new useful Publication obligations, establishing two consecutive corrected-state dry cycles. Live mounted-certificate/Temporal owner calls, mixed PostgreSQL upgrade/concurrency proof, version-scoped Automation content, exact Game Design template/asset mapping, readiness notification, and dedicated ability-schema attestation remain open. | -| 5B-Retention | Retention classes, cleanup, horizons, contraction | Broad review active; Cycle 1 productive | [#2829](https://github.com/benhook1013/FireMUD/pull/2829) | Fresh whole-unit Cycle 1 returned 12 observations with one useful Retention obligation. Cleanup now fails closed when any handoff child has an incomplete durable outcome, including sibling-bundle and parent-correlation proof. Replay-receipt horizons, recovery-aware dead-letter cleanup, cross-owner retention classes, and Docker-backed PostgreSQL proof remain open. | +| 5B-Retention | Retention classes, cleanup, horizons, contraction | Broad review active; Cycle 2 dry | [#2829](https://github.com/benhook1013/FireMUD/pull/2829) | Cycle 1 returned 12 observations with one useful Retention obligation and fixed incomplete handoff-child cleanup. Fresh corrected-state Cycle 2 covered all 12 assigned anchors and returned 12 raw observations with zero new useful obligations, the first dry cycle. Replay-receipt horizons, recovery-aware dead-letter cleanup, cross-owner retention classes, and Docker-backed PostgreSQL proof remain open. | | 5C | Redis roles and cache/rate-limit semantics | Queued | — | — | | 5D | Idempotency, outbox, replay, saga, and workflow patterns | Queued | — | — | | 6A | Gateway routes, traffic planes, sharding, and close taxonomy | Queued | — | — | From 8d898b37c1ef8cf17d30b3f14b70e47567db7667 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 22 Sep 2026 19:15:40 +1200 Subject: [PATCH 10/68] docs(alignment): record retention review taper --- design/project-management/design-alignment/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index a5bcfac746..b7abf1b389 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -24,7 +24,7 @@ This is the sole live corpus section-status index for a fresh whole-corpus revie The preserved 5B implementation work has been rebuilt into #2826 Schema, the dependent #2827 Automation lifecycle/fence successor, #2828 Publication, and #2829 Retention. The superseded #2808, #2678, #2804, and #2679 PRs were closed only after hunk-level no-loss verification; their branches and private ledgers remain historical evidence rather than live section ownership. The replacement stack is based on the independently reviewed non-5B prerequisites #2824 and #2818. Overall 5B is complete only after all three semantic subunits taper and a cross-subunit synthesis is recorded; there is no separate overall 5B status row. -5B synthesis: Queued; evidence — +5B synthesis: Active; paired whole-5B closure review begins from the final tapered #2829 tree. | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | @@ -43,7 +43,7 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | 5A | API, message, identifier, tenant, time, and authorization primitives | Complete (corpus review; implementation gaps remain) | [#2813](https://github.com/benhook1013/FireMUD/pull/2813) | Three fresh whole-section passes each covered 17/17 substantive allocated sources: 8, 15, and 12 raw observations. The corrected-state third pass confirmed 12 useful already-owned handoffs, no new unowned root, and taper. The shared-library Redis status claim and conflicting operator incident/revocation guidance were corrected. gRPC outcomes, Account runtime-read exposure, numeric IDs, gameplay attestation, JWT/workload identity, Gateway connect-carrier and route inventory, and script-fence gaps remain with their service/shared-runtime owners; Redis role clients and descriptor foundation belong to 5C, and operator binding enforcement/readback plus terminal-reissuance design belong to 6D. This status does not claim those capabilities are implemented. | | 5B-Schema | SQL/Flyway/jOOQ, schema and identifier migration | Broad review tapered; merge proof pending | [#2826](https://github.com/benhook1013/FireMUD/pull/2826) | Six fresh whole-unit cycles reached two corrected-state dry cycles after the accepted Schema fixes. Retained-row adjudication, mixed-binary deployment evidence, and Docker-backed PostgreSQL proof remain explicit limits. Dependent #2827 carries the separately reviewed Automation lifecycle/fence successor and is not additional Schema scope. | | 5B-Publication | Durable version/publication/readiness state | Broad review tapered; merge proof pending | [#2828](https://github.com/benhook1013/FireMUD/pull/2828) | Cycles 1–4 were productive and corrected the accepted findings through V27. Fresh whole-unit Cycles 5 and 6 each returned 12 raw observations with zero new useful Publication obligations, establishing two consecutive corrected-state dry cycles. Live mounted-certificate/Temporal owner calls, mixed PostgreSQL upgrade/concurrency proof, version-scoped Automation content, exact Game Design template/asset mapping, readiness notification, and dedicated ability-schema attestation remain open. | -| 5B-Retention | Retention classes, cleanup, horizons, contraction | Broad review active; Cycle 2 dry | [#2829](https://github.com/benhook1013/FireMUD/pull/2829) | Cycle 1 returned 12 observations with one useful Retention obligation and fixed incomplete handoff-child cleanup. Fresh corrected-state Cycle 2 covered all 12 assigned anchors and returned 12 raw observations with zero new useful obligations, the first dry cycle. Replay-receipt horizons, recovery-aware dead-letter cleanup, cross-owner retention classes, and Docker-backed PostgreSQL proof remain open. | +| 5B-Retention | Retention classes, cleanup, horizons, contraction | Broad review tapered; merge proof pending | [#2829](https://github.com/benhook1013/FireMUD/pull/2829) | Cycle 1 returned 12 observations with one useful Retention obligation and fixed incomplete handoff-child cleanup. Fresh corrected-state Cycles 2 and 3 each returned 12 raw observations with zero new useful obligations and complete assigned coverage, establishing two consecutive dry cycles. Replay-receipt horizons, recovery-aware dead-letter cleanup, cross-owner retention classes, and Docker-backed PostgreSQL proof remain open. | | 5C | Redis roles and cache/rate-limit semantics | Queued | — | — | | 5D | Idempotency, outbox, replay, saga, and workflow patterns | Queued | — | — | | 6A | Gateway routes, traffic planes, sharding, and close taxonomy | Queued | — | — | From 9b8c522e6e3a5fc2520266b06c26f4e8f5f2c2d2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 22 Sep 2026 19:33:08 +1200 Subject: [PATCH 11/68] docs(alignment): record first dry 5B closure cycle --- design/project-management/design-alignment/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index b7abf1b389..76de8ebf57 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -24,7 +24,7 @@ This is the sole live corpus section-status index for a fresh whole-corpus revie The preserved 5B implementation work has been rebuilt into #2826 Schema, the dependent #2827 Automation lifecycle/fence successor, #2828 Publication, and #2829 Retention. The superseded #2808, #2678, #2804, and #2679 PRs were closed only after hunk-level no-loss verification; their branches and private ledgers remain historical evidence rather than live section ownership. The replacement stack is based on the independently reviewed non-5B prerequisites #2824 and #2818. Overall 5B is complete only after all three semantic subunits taper and a cross-subunit synthesis is recorded; there is no separate overall 5B status row. -5B synthesis: Active; paired whole-5B closure review begins from the final tapered #2829 tree. +5B synthesis: Active; paired whole-5B closure Cycle 1 independently covered the complete cumulative tree and, after deduplication, returned 13 raw observations with zero new accepted obligations, 12 already-owned/routed obligations, and one rejected race hypothesis. This is the first dry closure cycle. | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | From c204582372e55e52cb174e020f3ce6c61e687615 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 22 Sep 2026 20:06:22 +1200 Subject: [PATCH 12/68] docs(automation): classify plugin lifecycle retention --- .../automation-scripting-service/runtime-and-data.md | 2 ++ .../implementation-tracking/automation-and-scheduler-runtime.md | 2 ++ 2 files changed, 4 insertions(+) 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 b3d28c822c..bdba229f79 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -12,6 +12,8 @@ The current service validates and resolves handlers during admission, persists e Plugin lifecycle mutations use immutable request history keyed by `(tenantId, gameInstanceId, pluginId, controlPlaneRequestId)`, with the operation and canonical request fingerprint stored as bound payload. An exact retry returns the recorded result, while reuse for another operation or changed input fails before state, epoch, revision, lifecycle history, schedule, or notification mutation. Fresh same-target activation, already-`DRAINING`, already-`DISABLED`, and never-active `DISABLE` no-ops store one immutable successful request receipt while leaving runtime state, lifecycle event history, notifications, schedules, and counters unchanged. A new `DRAIN` against a plugin with no active `ENABLED` lifecycle records one immutable `FAILED_PRECONDITION` receipt without changing plugin state. Transient transition or fence-install failures are not terminalized by this receipt slice. V3 assigns a founding `(pluginActivationEpoch, lifecycleRevision)=(1,1)` only to retained runtime rows with a nonblank active version and to retained schedules whose tenant, instance, plugin, version, runtime region, and region epoch match exactly; contradictory executable rows fail migration, and schema/repository guards reject incoherent pairs or an active version at `0/0`, while historical work/audit/handoff evidence remains `0/0` and fenced because its winning admission cannot be reconstructed. Generic plugin-owned ingress also requires the later fence read to remain `ENABLED` before persisting work. Focused service and migration-shape proof executes locally; PostgreSQL receipt/concurrency and retained-data cases require Docker/Testcontainers. +The plugin lifecycle histories are separate ADR 0163 retained families. `plugin_runtime_request_history` is a retry/idempotency-receipt family: its immutable canonical request digest and terminal result must survive every supported client retry, reconnect, replay, restore, and lifecycle-transition recovery horizon. `plugin_runtime_events` is recovery/reconciliation lineage and purpose-bound lifecycle audit evidence: an event is immutable history, but it is not cleanup-eligible while a lifecycle transition, owner reconciliation, rollback diagnosis, supported restore, or related retained runtime evidence may still depend on it. Automation owns both families. Neither family currently has a declared measured minimum horizon, retention-hold mechanism, archive/compaction policy, bounded garbage-collection cadence, safe watermark, or cleanup-lag/oldest-blocker metrics, so both remain retained and ineligible for automatic deletion. A future cleanup slice must establish those fields and dependency inequalities from measured retry/recovery/governance horizons; age alone is never eligibility, and archive storage cannot replace an online receipt needed for exact retry. + 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. 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 8f69d2b377..8c6a2694e4 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -172,6 +172,8 @@ Durable projections include `script_patch_readiness_projections`, `script_patch_ Durable Automation admission acknowledgements and exact-scope read-only diagnostics are implemented for the optional regional selector; recovery remains fail-closed when successful history is unavailable. The normative request/result behavior is owned by [SetAutomationAdmissionMode](../../architecture/system-architecture-scripting-control-plane-api.md#setautomationadmissionmode). Queue reset, workflow integration, and broader admission behavior remain partial. 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. +Plugin lifecycle persistence also has two explicitly classified but not yet cleanup-eligible families. `plugin_runtime_request_history` is an Automation-owned retry/idempotency-receipt family whose digest-bound outcome must remain online through every supported retry, reconnect, replay, restore, and lifecycle-transition recovery horizon. `plugin_runtime_events` is Automation-owned recovery/reconciliation lineage plus purpose-bound lifecycle audit evidence and remains required while transition recovery, owner reconciliation, rollback diagnosis, supported restore, or related retained runtime evidence may depend on it. Neither family currently implements a measured minimum horizon, holds, compaction/archive policy, bounded sweep, safe watermark, or cleanup-lag/oldest-blocker metrics. They therefore remain retained; age alone is not cleanup evidence, and this tracker does not invent a TTL. + The admission-slice proof anchors are the direct [V1 baseline schema test](../../../services/automation-scripting-service/src/test/java/unit/db/migration/V1__baselineTest.java), [admission service test](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationAdmissionStateServiceImplTest.java), [immutable request-history repository test](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/AutomationAdmissionRequestHistoryRepositoryTest.java), and [PostgreSQL integration suite](../../../services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java). Focused JVM proof is executed locally; the Docker-backed cases are present but skipped on a host without Docker and still require execution in CI or another Docker-capable environment. Game Session pin reads remain distinct: `GetPinnedScriptPatchVersion` reports pinned patch provenance, while `GetGameSessionPinConvergence` reports persisted convergence observation and stale signaling; `GetGameInstanceRuntimeState` supplies current ownership and routing. Logging & Admin exposes those canonical reads through tenant-guarded `GET /game-session-pins/{tenantId}/{gameInstanceId}` and `/convergence` routes, with fail-closed tenant/game-instance convergence identity validation. `GetGameplayCommandStatus` and remote runtime reads cross-link script-patch/plugin publication metadata while preserving runtime command and follow-up truth. Operator surfaces consume durable reads and append-only events rather than inferring state from raw tables, logs, or a second scripting state machine. From 78ccccd59be4d9cf4405fd86b4c7e46359b243f1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 22 Sep 2026 20:25:25 +1200 Subject: [PATCH 13/68] docs(review): record productive 5B closure cycle --- design/project-management/design-alignment/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 76de8ebf57..6e1ef14e5e 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -24,7 +24,7 @@ This is the sole live corpus section-status index for a fresh whole-corpus revie The preserved 5B implementation work has been rebuilt into #2826 Schema, the dependent #2827 Automation lifecycle/fence successor, #2828 Publication, and #2829 Retention. The superseded #2808, #2678, #2804, and #2679 PRs were closed only after hunk-level no-loss verification; their branches and private ledgers remain historical evidence rather than live section ownership. The replacement stack is based on the independently reviewed non-5B prerequisites #2824 and #2818. Overall 5B is complete only after all three semantic subunits taper and a cross-subunit synthesis is recorded; there is no separate overall 5B status row. -5B synthesis: Active; paired whole-5B closure Cycle 1 independently covered the complete cumulative tree and, after deduplication, returned 13 raw observations with zero new accepted obligations, 12 already-owned/routed obligations, and one rejected race hypothesis. This is the first dry closure cycle. +5B synthesis: Active; paired whole-5B closure Cycle 1 was dry. Cycle 2 was productive and reset the dry streak: its two independent reviewers produced three accepted obligations after deduplication. The corrected stack now enforces coordinated `Recreate`, roll-forward-only deployment for the incompatible Automation V3 and Game Design V26 migration boundaries; quarantines only V13-marked unattested legacy full versions while preserving bundled and script-only rows; and explicitly classifies the two Automation plugin-history retention families without inventing a cleanup TTL. The corrected cumulative tree is awaiting the third paired closure cycle, which is the instructed report boundary. | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | @@ -42,8 +42,8 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | 4B | Scheduling, quotas, reload, and operational fairness | Queued | — | — | | 5A | API, message, identifier, tenant, time, and authorization primitives | Complete (corpus review; implementation gaps remain) | [#2813](https://github.com/benhook1013/FireMUD/pull/2813) | Three fresh whole-section passes each covered 17/17 substantive allocated sources: 8, 15, and 12 raw observations. The corrected-state third pass confirmed 12 useful already-owned handoffs, no new unowned root, and taper. The shared-library Redis status claim and conflicting operator incident/revocation guidance were corrected. gRPC outcomes, Account runtime-read exposure, numeric IDs, gameplay attestation, JWT/workload identity, Gateway connect-carrier and route inventory, and script-fence gaps remain with their service/shared-runtime owners; Redis role clients and descriptor foundation belong to 5C, and operator binding enforcement/readback plus terminal-reissuance design belong to 6D. This status does not claim those capabilities are implemented. | | 5B-Schema | SQL/Flyway/jOOQ, schema and identifier migration | Broad review tapered; merge proof pending | [#2826](https://github.com/benhook1013/FireMUD/pull/2826) | Six fresh whole-unit cycles reached two corrected-state dry cycles after the accepted Schema fixes. Retained-row adjudication, mixed-binary deployment evidence, and Docker-backed PostgreSQL proof remain explicit limits. Dependent #2827 carries the separately reviewed Automation lifecycle/fence successor and is not additional Schema scope. | -| 5B-Publication | Durable version/publication/readiness state | Broad review tapered; merge proof pending | [#2828](https://github.com/benhook1013/FireMUD/pull/2828) | Cycles 1–4 were productive and corrected the accepted findings through V27. Fresh whole-unit Cycles 5 and 6 each returned 12 raw observations with zero new useful Publication obligations, establishing two consecutive corrected-state dry cycles. Live mounted-certificate/Temporal owner calls, mixed PostgreSQL upgrade/concurrency proof, version-scoped Automation content, exact Game Design template/asset mapping, readiness notification, and dedicated ability-schema attestation remain open. | -| 5B-Retention | Retention classes, cleanup, horizons, contraction | Broad review tapered; merge proof pending | [#2829](https://github.com/benhook1013/FireMUD/pull/2829) | Cycle 1 returned 12 observations with one useful Retention obligation and fixed incomplete handoff-child cleanup. Fresh corrected-state Cycles 2 and 3 each returned 12 raw observations with zero new useful obligations and complete assigned coverage, establishing two consecutive dry cycles. Replay-receipt horizons, recovery-aware dead-letter cleanup, cross-owner retention classes, and Docker-backed PostgreSQL proof remain open. | +| 5B-Publication | Durable version/publication/readiness state | Broad review tapered; closure correction published; merge proof pending | [#2828](https://github.com/benhook1013/FireMUD/pull/2828) | Cycles 1–4 were productive and corrected the accepted findings through V27; corrected-state Cycles 5 and 6 were dry. Whole-5B closure Cycle 2 subsequently added the V28 legacy full-version quarantine and made V26's incompatible participant-scope migration operationally stop-before-start and roll-forward-only. PostgreSQL retained-row execution, live mounted-certificate/Temporal owner calls, version-scoped Automation content, exact Game Design template/asset mapping, readiness notification, and dedicated ability-schema attestation remain open. | +| 5B-Retention | Retention classes, cleanup, horizons, contraction | Broad review tapered; closure correction published; merge proof pending | [#2829](https://github.com/benhook1013/FireMUD/pull/2829) | Cycle 1 fixed incomplete handoff-child cleanup; corrected-state Cycles 2 and 3 were dry. Whole-5B closure Cycle 2 then classified `plugin_runtime_request_history` as retry/idempotency receipt evidence and `plugin_runtime_events` as recovery/reconciliation plus lifecycle-audit evidence. Both remain ineligible for automatic deletion until measured horizons, holds, safe watermarks, bounded sweeps, and metrics exist. Recovery-aware dead-letter cleanup, cross-owner inequalities, and Docker-backed PostgreSQL proof remain open. | | 5C | Redis roles and cache/rate-limit semantics | Queued | — | — | | 5D | Idempotency, outbox, replay, saga, and workflow patterns | Queued | — | — | | 6A | Gateway routes, traffic planes, sharding, and close taxonomy | Queued | — | — | From dce1d8246e3ff2bf9c3bfcb9649ae0e5c4181e6b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 22 Sep 2026 20:48:39 +1200 Subject: [PATCH 14/68] Record whole-5B closure report boundary --- design/project-management/design-alignment/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 6e1ef14e5e..491a711f63 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -24,7 +24,7 @@ This is the sole live corpus section-status index for a fresh whole-corpus revie The preserved 5B implementation work has been rebuilt into #2826 Schema, the dependent #2827 Automation lifecycle/fence successor, #2828 Publication, and #2829 Retention. The superseded #2808, #2678, #2804, and #2679 PRs were closed only after hunk-level no-loss verification; their branches and private ledgers remain historical evidence rather than live section ownership. The replacement stack is based on the independently reviewed non-5B prerequisites #2824 and #2818. Overall 5B is complete only after all three semantic subunits taper and a cross-subunit synthesis is recorded; there is no separate overall 5B status row. -5B synthesis: Active; paired whole-5B closure Cycle 1 was dry. Cycle 2 was productive and reset the dry streak: its two independent reviewers produced three accepted obligations after deduplication. The corrected stack now enforces coordinated `Recreate`, roll-forward-only deployment for the incompatible Automation V3 and Game Design V26 migration boundaries; quarantines only V13-marked unattested legacy full versions while preserving bundled and script-only rows; and explicitly classifies the two Automation plugin-history retention families without inventing a cleanup TTL. The corrected cumulative tree is awaiting the third paired closure cycle, which is the instructed report boundary. +5B synthesis: Active at the three-cycle report boundary; paired whole-5B closure Cycle 1 was dry, Cycle 2 was productive, and corrected-state Cycle 3 was dry. Cycle 2's two independent reviewers produced three accepted obligation families after deduplication. The corrected stack now enforces coordinated `Recreate`, roll-forward-only deployment for the incompatible Automation V3 and Game Design V26 migration boundaries; quarantines only V13-marked unattested legacy full versions while preserving bundled and script-only rows; and explicitly classifies the two Automation plugin-history retention families without inventing a cleanup TTL. Cycle 3's two independent reviewers returned 18 and 19 raw observations with zero new accepted obligations, but this is only the first dry cycle after the Cycle 2 corrections. The required two consecutive corrected-state dry cycles have therefore not established whole-5B closure taper. | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | From 32c8e10525e61f0c6e9735d538d06162cf927b62 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 00:21:29 +1200 Subject: [PATCH 15/68] docs(shared-runtime): reconcile 5C and 5D corpus authority --- design/architecture/decisions/README.md | 1 + ...ting-event-ingress-idempotency-identity.md | 8 +- ...ndoff-reliability-and-success-semantics.md | 14 +- ...9-coordination-redis-ownership-boundary.md | 8 +- ...-session-front-end-and-region-execution.md | 4 +- ...nical-gameplay-command-status-lifecycle.md | 2 +- ...ble-idempotent-operator-write-execution.md | 44 +++-- ...-authority-with-causal-read-composition.md | 4 +- ...patial-mutations-across-split-authority.md | 6 +- ...terministic-fair-entity-tick-scheduling.md | 2 +- ...ution-with-one-logical-terminal-outcome.md | 29 +++- ...-specific-timer-durability-and-recovery.md | 6 +- ...ount-bounds-for-generated-effect-chains.md | 8 +- ...ffect-fanout-and-lightweight-idle-ticks.md | 2 + ...ound-workflow-and-step-retry-identities.md | 2 +- ...ecific-script-timer-clocks-and-recovery.md | 4 +- ...ing-and-authoritative-region-transition.md | 2 +- ...effect-id-allocation-and-replay-binding.md | 120 ++++++++++++++ .../infrastructure/deployment-environments.md | 2 +- .../automation-scripting-service/README.md | 2 +- .../api-contracts.md | 6 +- .../configuration.md | 6 +- .../runtime-and-data.md | 41 +++-- .../sandbox-runtime-design.md | 4 +- .../api-contracts.md | 4 +- .../entity-management-service/operations.md | 26 +-- .../runtime-and-data.md | 8 +- .../game-design-service/modding-framework.md | 10 +- .../game-design-service/operations.md | 20 +++ .../game-design-service/version-control.md | 6 +- .../game-session-service/api-contracts.md | 3 +- .../game-session-service/runtime-and-data.md | 45 +++-- .../logging-admin-service/api-contracts.md | 10 +- .../logging-admin-service/runtime-and-data.md | 4 +- .../world-creation-workflow.md | 16 +- ...system-architecture-identifier-glossary.md | 8 +- .../system-architecture-overview.md | 6 +- ...stem-architecture-redis-cache-reference.md | 11 +- .../system-architecture-redis-cache.md | 11 +- .../system-architecture-redis-cheatsheet.md | 7 +- ...tem-architecture-redis-design-checklist.md | 9 +- ...tem-architecture-redis-incident-runbook.md | 21 ++- .../system-architecture-redis-lua-patterns.md | 25 ++- .../system-architecture-redis-operations.md | 39 +++-- .../system-architecture-redis-ops-access.md | 35 ++-- ...m-architecture-redis-reset-and-recovery.md | 42 +++-- ...m-architecture-redis-usage-and-profiles.md | 29 +++- .../architecture/system-architecture-redis.md | 29 ++-- ...system-architecture-scripting-contracts.md | 8 +- ...rchitecture-scripting-control-plane-api.md | 24 +-- ...ture-scripting-control-plane-operations.md | 4 +- ...rchitecture-scripting-dsl-for-designers.md | 4 +- ...e-scripting-dsl-reference-and-lifecycle.md | 16 +- ...m-architecture-scripting-event-registry.md | 6 +- ...tecture-scripting-examples-and-patterns.md | 18 +- ...ure-scripting-normative-contract-tables.md | 59 ++++--- ...ecture-scripting-observability-contract.md | 16 +- ...hitecture-scripting-operations-cookbook.md | 2 +- ...tecture-scripting-quotas-and-operations.md | 12 +- ...rchitecture-scripting-runtime-execution.md | 56 ++++--- ...itecture-scripting-scheduler-and-timers.md | 79 +++++---- ...ure-spatial-and-ambient-effects-catalog.md | 24 +-- .../system-architecture-temporal-workflows.md | 2 +- ...chitecture-tick-concepts-and-invariants.md | 31 ++-- ...ystem-architecture-tick-execution-flows.md | 65 ++++---- ...chitecture-tick-failures-and-operations.md | 156 ++++++++++-------- ...stem-architecture-tick-incident-runbook.md | 55 +++--- .../architecture/system-architecture-ticks.md | 64 +++---- .../system-architecture-transactions.md | 91 ++++++---- .../design-alignment/README.md | 14 +- .../consequential-decision-inventory.md | 6 +- .../decision-inventory-cross-cutting.md | 4 +- .../design-capability-allocation.md | 8 +- .../automation-and-scheduler-runtime.md | 14 +- ...e-session-runtime-and-tick-coordination.md | 36 +++- .../gameplay-rules-entities-and-effects.md | 13 +- .../world-runtime-and-movement.md | 2 + dev-tools/tests/architecture-doc-contracts.sh | 83 ++++++++-- .../check-design-capability-allocation.py | 9 + .../src/main/resources/openapi.yaml | 5 +- .../src/main/resources/openapi.yaml | 69 +++++++- .../src/main/resources/openapi.yaml | 14 +- .../src/main/resources/openapi.yaml | 24 ++- 83 files changed, 1217 insertions(+), 627 deletions(-) create mode 100644 design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md diff --git a/design/architecture/decisions/README.md b/design/architecture/decisions/README.md index 90a1d6474e..f3e4bacff6 100644 --- a/design/architecture/decisions/README.md +++ b/design/architecture/decisions/README.md @@ -277,6 +277,7 @@ Validation precedence is fixed: first parse every checked queue row and validate | [ADR 0180](./adr-0180-account-owned-hosted-terms-acceptance-gate.md) | Accepted | `AA-1.3` | `AA-1.5`, `AR-1.1`, `AR-1.4`, `AR-1.5`, `EA-3.2`, `PO-1.3`, `SF-2.3` | Account-owned hosted-terms catalog, acceptance evidence, and official-hosted creator mutation gate | | [ADR 0181](./adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) | Accepted | `PO-1.3` | `AA-1.3`, `AA-1.4`, `AA-1.5`, `AR-1.1`, `AR-1.4`, `AR-1.5`, `EA-3.2`, `SF-2.3` | Changed hosted-terms decline, prior-terms continuity, lifecycle-reducing access, and finite transition | | [ADR 0182](./adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md) | Accepted | `PO-3.2` | `PO-3.1`, `PO-4.4`, `SF-1.3`, `PO-1.1` | Separated hosted runtime and certificate-identity lifecycles | +| [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) | Proposed - Pending Human Review | `GR-1.2` | `GR-1.4`, `GR-4.1`, `AS-1.2`, `AS-1.4`, `SF-1.4`, `SF-2.3`, `PO-4.2` | Pending deterministic command-plan and generated-child EffectId allocation and replay binding | Capability identifiers are defined in the [FireMUD Product Capability Taxonomy](../../product/capability-taxonomy.md). diff --git a/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md b/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md index f2e2831bb5..310d3b0d29 100644 --- a/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md +++ b/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md @@ -6,7 +6,7 @@ Superseded by [ADR 0172](./adr-0172-parent-event-and-frozen-handler-execution-id ## Implementation Status -The live `ScriptScheduleInstanceServiceImpl.TimerFiringCandidate.identity()` implementation remains narrower than the canonical scheduler preimage until the target and owner/plugin fields are carried. It currently resolves `playableStateScope` and emits `eventSchemaVersion=v1`, `isDryRun=false`, and `triggerMode=TRIGGER_MODE_CATCH_UP`; those values are explicit inputs even while they remain constant. It has no cross-producer golden-vector proof for the canonical preimage or its numeric formatting rules. See the [automation and scheduler runtime tracker](../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). +The live `ScriptScheduleInstanceServiceImpl.TimerFiringCandidate.identity()` implementation remains narrower than the canonical scheduler preimage until the target and owner/plugin fields are carried. It currently uses resolved `playableStateScope` in the identity preimage and emits `eventSchemaVersion=v1`, `isDryRun=false`, and `triggerMode=TRIGGER_MODE_CATCH_UP`; authoritative `playableStateNamespaceId` identity and separate non-identity scope evidence are target-state. The current values remain explicit preimage inputs even while they are constant. It has no cross-producer golden-vector proof for the canonical preimage or its numeric formatting rules. See the [automation and scheduler runtime tracker](../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). ## Context @@ -16,9 +16,9 @@ Event-ingress RPCs into the Automation & Scripting Service must be idempotent un Automation & Scripting treats event ingress as at-most-once per **Trigger Identity**. The exact endpoint-specific field matrix is owned by [Scripting Normative Contract Tables](../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) so the ADR and runtime contract cannot evolve as competing tuples. -- Gameplay/runtime handler identity includes the applicable `tenantId`, `gameInstanceId`, resolved `playableStateScope`, `regionId`, `regionEpoch`, `entityId`, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptEventId`, and `isDryRun` fields. +- Gameplay/runtime handler identity includes the applicable `tenantId`, `gameInstanceId`, authoritative `playableStateNamespaceId`, `regionId`, `regionEpoch`, `entityId`, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch`, `scriptEventId`, and `isDryRun` fields. The server-derived `playableStateScope` is retained and exact-validated as immutable policy/routing/authorization/fence evidence, not as a uniqueness discriminator. An authoritative scope transition starts a new playable-state lifecycle and namespace; stale presented scope with unchanged authority may reuse the existing identity. - `isDryRun` is always an identity dimension so live and test execution cannot collide. -- Scheduler/timer identity additionally carries its due point and trigger mode. The canonical scheduler preimage fields are serialized in this fixed order: ``. Fields marked `when ...` are omitted, not replaced by empty or sentinel values, when their branch does not apply; `targetScopeType` makes the target selector explicit and `stableOwnerKind` makes the core/plugin owner branch explicit. Thus `scriptEventId` itself is never part of this preimage, and `resumeWindowId` is absent for non-catch-up triggers. `duePoint` is exactly one tagged value: `dueTickId:` for tick-aligned schedules or `dueAt:` for wall-clock timers. Any additional scheduler schema version or trigger mode must become an explicit deterministic-ID input before it is admitted. +- Scheduler/timer identity additionally carries its due point and trigger mode. The canonical scheduler preimage fields are serialized in this fixed order: ``. Fields marked `when ...` are omitted, not replaced by empty or sentinel values, when their branch does not apply; `targetScopeType` makes the target selector explicit and `stableOwnerKind` makes the core/plugin owner branch explicit. The server-derived `playableStateScope` remains immutable policy/routing/authorization/fence evidence and is not a preimage or uniqueness input. Thus `scriptEventId` itself is never part of this preimage, and `resumeWindowId` is absent for non-catch-up triggers. `duePoint` is exactly one tagged value: `dueTickId:` for tick-aligned schedules or `dueAt:` for wall-clock timers. Any additional scheduler schema version or trigger mode must become an explicit deterministic-ID input before it is admitted. - The canonical target preimage is the fixed-order, length-prefixed UTF-8 serialization that `ScriptScheduleInstanceServiceImpl.TimerFiringCandidate.identity()` must implement. Each field is encoded as its UTF-8 byte length rendered as unsigned base-10 ASCII decimal with no leading zeroes, followed by a colon and its unescaped UTF-8 value; fields are concatenated without separators. Numeric identity values therefore use their canonical base-10 ASCII spelling (for example, `0`, `7`, and `-1`), and the prefix length counts UTF-8 bytes rather than Unicode code points. Semantic validation still controls which numeric values are admissible; deterministic decimal serialization does not make an otherwise invalid value valid. Boolean values serialize canonically as lowercase `true` or `false`. Enum values serialize as the contract-declared enum symbol/name, never an ordinal, localized spelling, or other implementation-specific representation. This permits delimiters and arbitrary UTF-8 text without creating tuple collisions. Hash those bytes with SHA-256, encode the digest as lowercase hexadecimal, retain the first 60 hexadecimal characters, and prefix the result with `timer-`. Cross-producer golden vectors must cover empty values, non-ASCII values, delimiters, negative and zero numeric values, both boolean values, representative enum branches, and both tagged due-point branches before this identity is considered proven. - Tenant-readiness `onLoad` follows the explicit non-runtime exception in the normative table and does not invent sentinel runtime, region, or entity identity. - Plugin-trigger identity additionally carries plugin and binding identity where the invocation unit is plugin- or binding-scoped. @@ -27,7 +27,7 @@ Ordinary event-ingress callers must reuse the same full applicable Trigger Ident ## Consequences -- Protos and service contracts must carry enough fields to represent the endpoint-specific Trigger Identity, including runtime scope, dry-run namespace, and due-point or plugin dimensions where applicable. +- Protos and service contracts must carry enough fields to represent the endpoint-specific Trigger Identity, including the playable-state namespace, immutable scope fence evidence, dry-run mode, and due-point or plugin dimensions where applicable. - Audit records (`script_event_audit`) must be keyed by Trigger Identity, not by `scriptEventId` alone. ## Implementation and Proof Obligations diff --git a/design/architecture/decisions/adr-0002-automation-handoff-reliability-and-success-semantics.md b/design/architecture/decisions/adr-0002-automation-handoff-reliability-and-success-semantics.md index 165e689a7e..a611949339 100644 --- a/design/architecture/decisions/adr-0002-automation-handoff-reliability-and-success-semantics.md +++ b/design/architecture/decisions/adr-0002-automation-handoff-reliability-and-success-semantics.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -This decision is partially implemented. Stage-qualified outcomes exist, but the database-save/Redis-stage gap, durable per-dispatch custody, and state-sensitive duplicate handling do not yet satisfy the accepted handoff boundary. See the [automation and scheduler runtime tracker](../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status) for current implementation and proof status. +This decision is partially implemented. Stage-qualified outcomes exist, but durable outbox persistence and queue-pointer publication, durable per-dispatch custody, and state-sensitive duplicate handling do not yet satisfy the accepted handoff boundary. See the [automation and scheduler runtime tracker](../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status) for current implementation and proof status. ## Decision Record @@ -17,23 +17,21 @@ This decision is partially implemented. Stage-qualified outcomes exist, but the ## Context -Scripting produces commands that must flow into the tick system. The historical design included Redis-based staging (`automation:queue:*` and the former `automation:tick:*` path) and internal gRPC handoff to Game Session. The `automation:tick:*` path is retired and not live; current automation stages work through `automation:queue:*` and hands gameplay enqueue to Game Session. Without a clear contract, “success” can mean either “DSL ran” or “effects will happen”, which undermines rollback semantics and operator trust. +Scripting produces commands that must flow into the tick system. The historical design included Redis-based staging (the former `automation:tick:*` path), which is retired and not live; current automation stages work through `automation:queue:*` discovery pointers and hands gameplay enqueue to Game Session. The target design records script work items in a durable PostgreSQL outbox and publishes instance-aware queue pointers in Cache/Rate-Limit Redis. Queue pointers are disposable discovery indexes, not work truth; durable outbox rows and Game Session handoff custody determine recovery and success. The current implementation has narrower work-item persistence and queue-pointer paths, but does not yet prove this accepted durable publication and custody boundary. Without a clear contract, “success” can mean either “DSL ran” or “effects will happen”, which undermines rollback semantics and operator trust. ## Decision - The historical generic label `script_event_audit.finalOutcome=success` is superseded **only as a label** by [ADR 0064](adr-0064-stage-qualified-script-outcomes.md). For a live command-producing handler, `finalStage=TICK_HANDOFF` and `finalOutcome=handoff_accepted` mean every required child dispatch is in Game Session custody: each child is either durably adopted/admitted, or covered by a committed per-child durable re-drive obligation that Game Session owns for outcome convergence. This is not a claim that gameplay effects were applied. The canonical stage-qualified outcomes are defined in the [scripting normative outcome table](../system-architecture-scripting-normative-contract-tables.md#canonical-finaloutcome-values-normative). - `completed_no_commands`, `readiness_success`, and `dry_run_success` remain distinct non-handoff outcomes in their declared branches. -- Local `automation:queue:*` staging is only pending Automation work-item discovery and is not handoff acceptance. A durable remote coordinator or follow-up schedule counts as the per-child re-drive obligation only when Game Session transactionally accepts it under stable identities; acceptance never means that the target tick has executed. +- In the target state, the durable PostgreSQL outbox/work-item row is the pending-work record. An instance-aware `automation:queue:*` pointer in Cache/Rate-Limit Redis is only a disposable discovery index; it is neither handoff acceptance nor work truth. A durable remote coordinator or follow-up schedule counts as the per-child re-drive obligation only when Game Session transactionally accepts it under stable identities; acceptance never means that the target tick has executed. - The pipeline must record stage-aware outcomes so operators can see where a trigger failed to progress (DSL evaluation vs persistence vs handoff/enqueue). -- Duplicate lookup compares the immutable dispatch digest and returns accepted only from a state that proves handoff custody. A received-but-unstaged volatile row must be re-driven, reported pending or not accepted, or exposed as terminal `NOT_APPLIED`; it must never become an unconditional accepted no-op. -- If Redis staging queues are reset/lost, the system must either: - - re-drive delivery from a durable outbox of script work items, or - - record explicit “dropped before tick enqueue” outcomes and never report `handoff_accepted`. +- Duplicate lookup compares the immutable dispatch digest and returns accepted only from a state that proves handoff custody. A received-but-not-yet-handed-off durable outbox/work-item row must be re-driven, reported pending or not accepted, or exposed as terminal `NOT_APPLIED`; it must never become an unconditional accepted no-op because a discovery pointer is absent. +- If `automation:queue:*` discovery pointers in Cache/Rate-Limit Redis are reset or lost, the system must rebuild them from durable PostgreSQL outbox/work-item rows and re-drive delivery; pointer loss is not a dropped-work outcome. If durable outbox persistence fails before Game Session handoff, the system must record an explicit persistence/drop outcome and never report `handoff_accepted`. ## Consequences - The Automation & Scripting Service must have a durable representation of “pending script work items” if the target behavior is “do not drop silently”. -- Any best-effort Redis buffer (`automation:queue:*`) cannot be the sole record of admitted work if `handoff_accepted` implies tick acceptance. +- Any Cache/Rate-Limit Redis discovery pointer (`automation:queue:*`) cannot be the sole record of admitted work if `handoff_accepted` implies tick acceptance. - A handler may be `handoff_accepted` even when one of its commands later becomes `NOT_APPLIED` or `ABANDONED`; the authoritative per-command status explains that later result. ## References diff --git a/design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md b/design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md index 807f6542c8..e657f76f6c 100644 --- a/design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md +++ b/design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md @@ -21,10 +21,10 @@ The architecture already distinguishes ownership from participation, but the bou Coordination Redis ownership is explicit and narrow: - Game Session Service owns gameplay coordination keyspace and schema (for example `tick:*`, `timer:*`, `retry:*`, `session:game:*`, and lease-related prefixes). -- Account Service owns authentication allowlist/session-auth prefixes (`session:auth:*`) and their lifecycle semantics, plus the already accepted `session:connect-token:*` issuance-result projection/cache defined by [ADR 0029](./adr-0029-single-use-gameplay-connect-token-carriage.md). -- Automation & Scripting Service owns automation coordination and cache families with an explicit split: - - Coordination Redis: Automation & Scripting owns the target scheduler/checkpoint boundary represented by `automation:timer:*` and `script-scheduler:*` once implemented. These are reset-tolerant projections rebuilt from durable schedules, trigger-instance rows, and heartbeat progress; durable schedules and trigger-instance de-duplication remain PostgreSQL authority. They are target-state names, not current runtime guarantees. The former `automation:tick:*` staging path is retired, not live, and is not an active owned prefix. - - Cache/Rate-Limit Redis: `automation:queue:*`, `automation:quota:*`, `automation:tenant-budget:*`, `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` best-effort buffers/counters and owner-token leases. These remain distinct from the target Coordination Redis `automation:timer:*` and `script-scheduler:*` projections. +- Account Service owns the exact authentication/session-auth families recorded by the Redis hub: `session:auth:account:*`, `session:auth:tenant:*`, `session:auth:token:*`, and `session:auth:generation:*`, together with their lifecycle semantics. It also owns the separate exact-input `session:connect-token:tenant::account::scope::request:` issuance-result/idempotency family defined by [ADR 0029](./adr-0029-single-use-gameplay-connect-token-carriage.md). No wildcard `session:auth:*` ACL or authority grant is implied. +- Automation & Scripting Service owns automation coordination and cache families with an explicit current-versus-target split: + - Coordination Redis: it owns the target scheduler/checkpoint boundary represented by `automation:timer:*` and `script-scheduler:*` once implemented. These are reset-tolerant projections rebuilt from durable schedules, trigger-instance rows, and heartbeat progress; durable schedules and trigger-instance de-duplication remain PostgreSQL authority. They are target-state names, not current runtime guarantees. The former `automation:tick:*` staging path is retired, not live, and is not an active owned prefix. + - Cache/Rate-Limit Redis: `automation:queue:*` discovery pointers, `automation:quota:*`, `automation:tenant-budget:*`, `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` best-effort buffers/counters and owner-token leases; queue pointers are disposable indexes, not work truth. The test and readiness families remain unsupported for target adoption until each is centrally registered and has slot-safe keying. These remain distinct from the target Coordination Redis `automation:timer:*` and `script-scheduler:*` projections. - Non-owner services may participate only through approved shared helpers and documented prefixes/contracts. Owner-managed bridge contracts are the only approved exception to “write only your own keys”: diff --git a/design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md b/design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md index 8de7c7867b..0b114c491a 100644 --- a/design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md +++ b/design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md @@ -29,7 +29,7 @@ FireMUD adopts a **session front-end + lease-owner execution** model inside the - The session front-end pod must not mutate tick-owned gameplay coordination state for a region it does not own. - When command execution or tick-owned mutation targets a region leased by another pod, the session front-end forwards the request over internal gRPC to the current **lease owner**. - Only the lease owner may stage or commit Redis coordination changes for that region. -- `playableStateScope` is part of the forwarded request identity and must be preserved and validated end to end because it distinguishes the gameplay state/effect scope being acted on. +- `playableStateScope` is exact-validated request evidence/context in the forwarded request and must be preserved end to end because it validates the gameplay state/effect scope being acted on; it is excluded from uniqueness and deduplication identity. - `playableStateScope` is not an additional lease-ownership dimension. Lease ownership remains keyed by ``; the current owner and its fence apply to the region, while the owner validates the forwarded playable-state scope against the authoritative gameplay binding. ## Consequences @@ -44,7 +44,7 @@ FireMUD adopts a **session front-end + lease-owner execution** model inside the Any session front-end to lease-owner forwarding path must implement one canonical contract: -- Every forwarded request carries `tenantId`, `gameInstanceId`, `playableStateScope`, `sessionId`, `characterId`, target `regionId`, command or action identifier, and a monotonic per-session sequencing token so the lease owner can preserve session-local ordering. +- Every forwarded request carries `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `sessionId`, `characterId`, target `regionId`, command or action identifier, and a monotonic per-session sequencing token so the lease owner can preserve session-local ordering. - Every forwarded request carries the lease/epoch fence for the target region. A lease owner must reject requests with a stale or missing fence using an application-level stale-lease error. - The session front-end may retry only idempotent forwarded operations and must not create duplicate tick-owned mutations when a response is ambiguous. - If lease ownership changes before execution starts, the front-end must refresh ownership and retry against the new lease owner. If ownership changes after execution has begun, the in-flight attempt is owned by the executor that accepted the fenced request and later attempts must use the new fence. diff --git a/design/architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md b/design/architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md index 7821327d63..a1e8d8b985 100644 --- a/design/architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md +++ b/design/architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md @@ -54,7 +54,7 @@ Existing values such as `STAGED`, `DRAINED`, and `RETRY_QUEUED` map to lifecycle ### Authority and Convergence -- `GetGameplayCommandStatus` reads the authoritative durable record by `commandId` scoped to `tenantId` and `gameInstanceId`, or by the automation handoff identity `(tenantId, gameInstanceId, regionId, regionEpoch, automationDispatchId)`. The `regionId` and `regionEpoch` routing fields apply to the automation-identity lookup. Redis coordination state is not part of the lookup authority. +- `GetGameplayCommandStatus` reads the authoritative durable record only by the point-lookup key `{tenantId, gameInstanceId, commandId}`. The automation tuple `(tenantId, gameInstanceId, regionId, regionEpoch, automationDispatchId)` is a collection/filter correlation key only, not a point-lookup or uniqueness key: one dispatch may contain multiple emitted commands distinguished by `commandOrdinal` in the complete Command-Handoff Identity defined by the scripting normative contract table. If an automation-correlated status view is exposed, it returns an explicitly bounded collection rather than selecting one authoritative record from that tuple; `regionId` and `regionEpoch` apply only as routing/filter fields. Redis coordination state is not part of the lookup authority. - Status reads require the same caller-bound subject/actor authority recorded at ingress or an explicitly authorized internal/operator route. Possession or collision of a client-generated `commandId` is never status-read authority. - Optional outcome events or streams may reduce observation latency, but they are advisory projections of the same lifecycle. - Every accepted command converges to an explicit terminal result. An `ACCEPTED_VOLATILE` command lost before durable batch binding becomes `LOST_BEFORE_STAGING` with `NOT_APPLIED` rather than remaining indefinitely pending. diff --git a/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md b/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md index 33cdf0c1dc..759316991f 100644 --- a/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md +++ b/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md @@ -31,7 +31,11 @@ Operator writes are low-volume control-plane operations, so one durable intent r ### One Correlated Execution -ADR 0048 is the sole owning definition of `preAuthorizationReservationTuple/v1`; ADR 0047 and the Account issuance API reference this tuple exactly and must not define a variant. Logging and Admin assigns one `controlPlaneRequestId`, computes ADR 0047's versioned canonical `mutationDigest`, and atomically reserves that identifier before issuing an Account authorization reference or forwarding any mutation. `mutationDigest` is only the SHA-256 digest of the normalized action-family schema pair and typed scope, target, expected-version, mutation, and audit-reason values defined by ADR 0047; it is not the idempotency identity. The reservation actor is authority-derived and never caller supplied. For a human reservation, Logging and Admin captures the locally validated `control-ui` subject/account before reservation, sends that exact actor value with the authorization request, and Account compares it with the authenticated `control-ui` subject before issuing; retries preserve that same actor and never derive it from a later Account response. Automation uses the exact authenticated workload identity paired with its versioned automation-policy identity. Logging and Admin may carry validated evidence but may not invent, override, or accept a caller-supplied actor. The immutable `preAuthorizationReservationTuple/v1` contains `controlPlaneRequestId`, this reservation actor identity, applicable automation-policy identity or explicit human no-policy value, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, and every schema-declared bound presence/absence value. `targetOwner` is a schema-bound typed owner-selection value, distinct from `target`; it is immutable after reservation and is not recomputed from current routing or lease ownership. It contains only values known before Account authorization: it does not contain or fabricate an `issuanceKind`, `issuanceOperationId`, authorization-reference fingerprint, authenticated authority tuple, `membershipVersion`, `issuanceFence`, authority scope, source transaction/outbox or event version, projection status/freshness, or issuance-operation identity. The canonical digest is persisted and recomputed as an integrity check and never substitutes for those stored fields. Reservation is a durable compare-and-set: exactly one caller becomes the reservation owner, and the owner token is required for every later tuple-completion write. The reservation is not authorization and does not permit forwarding. +The stable `controlPlaneRequestId` is the sole key for the ADR 0048 orchestration/reservation record and its deduplication, recovery lookup, and correlation. The tagged `actionFamilyRequestIdentity` is carried in the reservation and post-authorization tuples and is used at the applicable Account/domain action-idempotency boundary; it is not a second orchestration or reservation key. In particular, moderation may use `policyIntentRequestId` or `ownerEnforcementRequestId` to select the domain idempotency record while the ADR 0048 record remains keyed by `controlPlaneRequestId`. + +When later moderation wording calls `controlPlaneRequestId` “correlation-only,” that qualification is only for the domain mutation-idempotency lookup; it remains the required ADR 0048 orchestration, reservation, recovery-lookup, deduplication, and correlation key. + +ADR 0048 is the sole owning definition of `preAuthorizationReservationTuple/v1`; ADR 0047 and the Account issuance API reference this tuple exactly and must not define a variant. Logging and Admin assigns the action-family request identity (`controlPlaneRequestId` for non-moderation mutations, `policyIntentRequestId` for local moderation policy intent, or `ownerEnforcementRequestId` for moderation owner-enforcement commands), computes ADR 0047's versioned canonical `mutationDigest`, and atomically reserves and commits the initial `ACCOUNT_AUTHORIZATION/RESERVED` record keyed solely by `controlPlaneRequestId` before issuing an Account authorization reference or forwarding any mutation. The tagged action-family request identity is stored in that record's tuple and is used only at the applicable Account/domain action-idempotency boundary. For moderation flows, `controlPlaneRequestId` is correlation-only at that domain boundary and is never an alias for either dedicated mutation identity. `mutationDigest` is only the SHA-256 digest of the normalized action-family schema pair and typed scope, target, expected-version, mutation, and audit-reason values defined by ADR 0047; it is not the idempotency identity. The reservation actor is authority-derived and never caller-supplied. For a human reservation, Logging and Admin captures the locally validated `control-ui` subject/account before reservation, sends that exact actor value with the authorization request, and Account compares it with the authenticated `control-ui` subject before issuing; retries preserve that same actor and never derive it from a later Account response. Automation uses the exact authenticated workload identity paired with its versioned automation-policy identity. Logging and Admin may carry validated evidence but may not invent, override, or accept a caller-supplied actor. The immutable `preAuthorizationReservationTuple/v1` contains that action-family request identity, this reservation actor identity, applicable automation-policy identity or explicit human no-policy value, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, and every schema-declared bound presence/absence value. `targetOwner` is a schema-bound typed owner-selection value, distinct from `target`; it is immutable after reservation and is not recomputed from current routing or lease ownership. It contains only values known before Account authorization: it does not contain or fabricate an `issuanceKind`, `issuanceOperationId`, authorization-reference fingerprint, authenticated authority tuple, `membershipVersion`, `issuanceFence`, authority scope, source transaction/outbox or event version, projection status/freshness, or issuance-operation identity. The canonical digest is persisted and recomputed as an integrity check and never substitutes for those stored fields. Reservation is a durable compare-and-set: exactly one caller becomes the reservation owner, and the owner token is required for every later tuple-completion write. The reservation is not authorization and does not permit forwarding. The canonical complete `postAuthorizationExecutionTuple` is the immutable tuple created only after Account authorization. It contains the complete pre-authorization tuple plus `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact authenticated workload and actor binding, applicable workload/policy identity, exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, and the exact immutable `authorityEvidenceBundle/v1` defined by reference in ADR 0047. The bundle is complete and canonical; it is authority evidence, not an execution-tuple variant. The post-authorization tuple explicitly includes the immutable typed `targetOwner` and every schema-bound typed presence/absence value; only a value whose absence is declared by the action-family schema may be absent. Every tuple completion, recovery lookup, owner idempotency record, terminal or no-accept/no-commit proof, and conflict comparison carries and compares this exact tuple. No participant may omit, infer, or replace one of these fields from current ownership, routing, caller assertions, or a later authority read. @@ -41,53 +45,57 @@ The reservation-owner claim is itself a durable bounded lease. The record stores The durable record has an explicit `phase` and `state`; `PENDING` is never persisted or returned without its phase. `phase=ACCOUNT_AUTHORIZATION` covers `RESERVED`, `AUTHORIZATION_PENDING`, `AUTHORIZED`, and `NOT_EXECUTED_BEFORE_AUTHORIZATION`; `phase=OWNER_EXECUTION` covers `OWNER_EXECUTION_PENDING`, `FENCE_REJECTED`, `COMMITTED`, `FAILED`, and `NOT_EXECUTED_AFTER_AUTHORIZATION`. Every acquire, renew, expiry, completion, rejection, recovery, lookup, and rearm CAS compares the expected phase and state together with the phase-appropriate tuple, attempt identity, owner identity, and applicable claim/fencing token. Pre-authorization operations compare `preAuthorizationReservationTuple`; the transition to `AUTHORIZED` atomically enriches that tuple into `postAuthorizationExecutionTuple`, and every later owner execution, result lookup, and reconciliation operation compares the post-authorization tuple. Any later rearm starts a new reservation and authorization tuple with a fresh reference. A phase mismatch is an idempotency conflict or stale-fence rejection as applicable; it is never treated as an interchangeable `PENDING` state. -An exact pre-authorization duplicate has the same `preAuthorizationReservationTuple` and reservation claim metadata; it observes the same durable record and waits for the reservation owner to complete it or for the bounded reservation attempt to reach its terminal no-mutation outcome. It must not issue another authorization reference or forward another request. A request with the same `controlPlaneRequestId` but any difference in the phase-appropriate tuple returns canonical `IDEMPOTENCY_CONFLICT` without mutation. Only the current reservation owner with an unexpired matching claim fence, including one fresh claim held by a fenced recovery owner after claim expiry, may atomically enrich the record with the Account-returned `postAuthorizationExecutionTuple`. Reservation state transitions are explicit and phase-qualified: `ACCOUNT_AUTHORIZATION/RESERVED -> ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` is the owner/fence-protected transition required before dispatching the Account authorization request; `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING -> ACCOUNT_AUTHORIZATION/AUTHORIZED` is the owner/fence-protected completion after the original Account response is received or recovered and the full post-authorization tuple is durably stored; `ACCOUNT_AUTHORIZATION/RESERVED` or `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING -> ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` is allowed only when durable phase evidence records that Account authorization cannot complete and durable dispatch evidence proves that no owner-forward call occurred and no owner-forward call can still occur. A `NOT_FOUND` returned by the read-only `RecoverOperatorAuthorizationReference` lookup is only read-only lookup evidence and never satisfies either proof by itself. An ambiguous Account authorization call remains `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`; it never becomes an owner-execution state and no owner-forward call may begin from it. After the original response is recovered, the fenced recovery owner may complete `AUTHORIZED` only while its fresh recovery claim is current and unexpired, then use the bounded handoff and fresh redemption rules for the original reference. Only after the durable `ACCOUNT_AUTHORIZATION/AUTHORIZED -> OWNER_EXECUTION/OWNER_EXECUTION_PENDING` transition, written before the exact reference or mutation is dispatched to the owner, can an ambiguous owner-forward call belong to `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`. That owner-forward ambiguity remains non-replayable and cannot become a phase-inappropriate `NOT_EXECUTED` result without durable no-call/no-commit proof. A stale owner/fence may produce `OWNER_EXECUTION/FENCE_REJECTED` only after the rejecting owner atomically persists its no-accept/no-commit proof; absent or inconsistent proof leaves the request in `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`, non-replayable and non-rearmable. The rejecting owner or one fenced recovery owner may transition a valid `FENCE_REJECTED` to `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` only after validating that proof. A tuple mismatch is `IDEMPOTENCY_CONFLICT`; neither wire outcome is itself rearmable. An expired claim, lost response, missing record after dispatch, or any other ambiguous phase-specific state remains in its applicable phase-specific pending state and is never converted to a phase-inappropriate `NOT_EXECUTED` result. Recovery may not transfer an active reservation claim or issue another reference while a call may still be in flight. After the claim expires, a recovery CAS may assign a new fenced recovery owner solely to call ADR 0047's read-only `RecoverOperatorAuthorizationReference` for `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`, with `preAuthorizationReservationTuple`. That read either returns the original durable Account response or durable absence; it cannot create or replace a reference. A recovered original response permits the atomic `AUTHORIZED` enrichment and subsequent bounded handoff only while the fresh claim is valid; durable absence permits `ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` only after the independent durable phase and dispatch evidence above is present. +An exact pre-authorization duplicate has the same `preAuthorizationReservationTuple` and reservation claim metadata; it observes the same durable record and waits for the reservation owner to complete it or for the bounded reservation attempt to reach its terminal no-mutation outcome. It must not issue another authorization reference or forward another request. At the ADR 0048 orchestration boundary, a request with the same `controlPlaneRequestId` but any difference in the phase-appropriate tuple returns canonical `IDEMPOTENCY_CONFLICT` without mutation. At the applicable Account/domain boundary, reuse of the same tagged action-family request identity with any difference in its domain tuple likewise returns canonical `IDEMPOTENCY_CONFLICT`; a different `controlPlaneRequestId` does not create a second ADR 0048 reservation alias or bypass that domain conflict. Only the current reservation owner with an unexpired matching claim fence, including one fresh claim held by a fenced recovery owner after claim expiry, may atomically enrich the record with the Account-returned `postAuthorizationExecutionTuple`. Reservation state transitions are explicit and phase-qualified: `ACCOUNT_AUTHORIZATION/RESERVED -> ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` is the owner/fence-protected transition required before dispatching the Account authorization request; `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING -> ACCOUNT_AUTHORIZATION/AUTHORIZED` is the owner/fence-protected completion after the original Account response is received or recovered and the full post-authorization tuple is durably stored; `ACCOUNT_AUTHORIZATION/RESERVED` or `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING -> ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` is allowed only when durable phase evidence records that Account authorization cannot complete and durable dispatch evidence proves that no owner-forward call occurred and no owner-forward call can still occur. A `NOT_FOUND` returned by the read-only `RecoverOperatorAuthorizationReference` lookup is only read-only lookup evidence and never satisfies either proof by itself. An ambiguous Account authorization call remains `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`; it never becomes an owner-execution state and no owner-forward call may begin from it. After the original response is recovered, the fenced recovery owner may complete `AUTHORIZED` only while its fresh recovery claim is current and unexpired, then use the bounded handoff and fresh redemption rules for the original reference. Only after the durable `ACCOUNT_AUTHORIZATION/AUTHORIZED -> OWNER_EXECUTION/OWNER_EXECUTION_PENDING` transition, written before the exact reference or mutation is dispatched to the owner, can an ambiguous owner-forward call belong to `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`. That owner-forward ambiguity remains non-replayable and cannot become a phase-inappropriate `NOT_EXECUTED` result without durable no-call/no-commit proof. A stale owner/fence may produce `OWNER_EXECUTION/FENCE_REJECTED` only after the rejecting owner atomically persists its no-accept/no-commit proof; absent or inconsistent proof leaves the request in `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`, non-replayable and non-rearmable. The rejecting owner or one fenced recovery owner may transition a valid `FENCE_REJECTED` to `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` only after validating that proof. A tuple mismatch is `IDEMPOTENCY_CONFLICT`; neither wire outcome is itself rearmable. An expired claim, lost response, missing record after dispatch, or any other ambiguous phase-specific state remains in its applicable phase-specific pending state and is never converted to a phase-inappropriate `NOT_EXECUTED` result. Recovery may not transfer an active reservation claim or issue another reference while a call may still be in flight. After the claim expires, a recovery CAS may assign a new fenced recovery owner solely to call ADR 0047's read-only `RecoverOperatorAuthorizationReference` for `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`, with `preAuthorizationReservationTuple`. That read either returns the original durable Account response or durable absence; it cannot create or replace a reference. A recovered original response permits the atomic `AUTHORIZED` enrichment and subsequent bounded handoff only while the fresh claim is valid; durable absence permits `ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` only after the independent durable phase and dispatch evidence above is present. `ACCOUNT_AUTHORIZATION` is itself the durable pre-authorization recovery record. `RESERVED` carries the reservation claim and fence, `AUTHORIZATION_PENDING` carries the phase-qualified dispatch/response ambiguity and recovery claim/proof, and `NOT_EXECUTED_BEFORE_AUTHORIZATION` is terminal only with durable proof that authorization did not commit and no owner-forward call occurred or can still occur. No Redis owner record, write-ahead record, mutation marker, or effect evidence exists before the durable `ACCOUNT_AUTHORIZATION/AUTHORIZED -> OWNER_EXECUTION/OWNER_EXECUTION_PENDING` transition; Redis presence or absence cannot prove a pre-authorization outcome. `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` has two distinct terminal-proof forms, and neither is inferred from a timeout, `NOT_FOUND`, missing Redis state, or an absent record: -- **Pre-redemption no-redemption proof:** durable handoff and owner evidence prove that the owner call could not be accepted, Account redemption did not succeed and did not consume the reference, and no owner commit or business mutation occurred or can still occur under the attempt's fence. +- **Pre-redemption no-redemption proof:** durable handoff and owner evidence prove that the owner call could not be accepted, no redemption or owner-acceptance operation is in flight or can still complete under the attempt's fence, Account redemption did not succeed and did not consume the reference, the reference is durably non-redeemable for this attempt under that fence, and no owner commit or business mutation occurred or can still occur under the attempt's fence. - **Post-redemption no-acceptance proof:** Account's successful redemption and consumed-reference result are retained, so the proof must not claim no redemption. It instead proves that the owner did not durably accept the business mutation, did not commit an owner result/effect, and did not mutate business state, and that the fenced attempt cannot accept or commit later. -If the redemption outcome, owner acceptance, owner commit, business mutation, or delayed-commit exclusion is ambiguous, the request remains `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`, non-replayable, and non-rearmable. A terminal owner-side result is read-only for the original attempt. It does not support rearm or reuse of the original reference. Repeating the business intent requires a new explicit operator request with a new `controlPlaneRequestId`, a new Logging and Admin reservation, fresh Account authorization, and a new opaque reference. The new owner attempt uses its own complete post-authorization tuple, attempt number, high-entropy `ownerMutationId`, and fenced execution token; the prior terminal result and attempt history remain immutable. A successful redemption consumes the reference, and neither that consumed reference nor a replayed redemption result from the prior attempt can authorize the new attempt. A pre-authorization `ACCOUNT_AUTHORIZATION/RESERVED -> ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` record has no opaque reference and likewise requires a new explicit operator request. A terminal `NOT_EXECUTED` result is proof only for the completed attempt; it is never permission to replay an indeterminate dispatch. +If the redemption outcome, owner acceptance, owner commit, business mutation, delayed-commit exclusion, or reference non-redeemability is ambiguous, the request remains `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`, non-replayable, and non-rearmable. A terminal owner-side result is read-only for the original attempt. It does not support rearm or reuse of the original reference. Repeating the business intent requires a new explicit operator request with a new action-family request identity, a new Logging and Admin reservation, fresh Account authorization, and a new opaque reference. The new owner attempt uses its own complete post-authorization tuple, attempt number, high-entropy `ownerMutationId`, and fenced execution token; the prior terminal result and attempt history remain immutable. A successful redemption consumes the reference, and neither that consumed reference nor a replayed redemption result from the prior attempt can authorize the new attempt. A pre-authorization `ACCOUNT_AUTHORIZATION/RESERVED -> ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` record has no opaque reference and likewise requires a new explicit operator request. A terminal `NOT_EXECUTED` result is proof only for the completed attempt; it is never permission to replay an indeterminate dispatch. ### Fenced Reference Handoff -The original opaque reference is never stored durably by Logging and Admin, the domain owner, or the owner-result record. Account remains the source-of-truth provider and retains the reference in its protected authority record. For an `ACCOUNT_AUTHORIZATION/AUTHORIZED` record produced by a fenced recovery owner, the authorized-to-owner transition must first durably enter `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`; only then may the current domain owner receive the original reference through one bounded handoff from the exact current Logging and Admin reservation owner for the initial owner execution. The request carries the unchanged canonical complete `postAuthorizationExecutionTuple`, including immutable typed `targetOwner`, Account-returned `authorizationReferenceFingerprint`, `controlPlaneRequestId`, `reservationOwnerId`, current positive `reservationClaimFence`, the current domain `ownerId` and owner/gameplay fence, and a fresh high-entropy handoff identity. +The original opaque reference is never stored durably by Logging and Admin, the domain owner, or the owner-result record. Account remains the source-of-truth provider and retains the reference in its protected authority record. For an `ACCOUNT_AUTHORIZATION/AUTHORIZED` record produced by a fenced recovery owner, the authorized-to-owner transition must first durably enter `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`; only then may the current domain owner receive the original reference through one bounded handoff from the exact current Logging and Admin reservation owner for the initial owner execution. The request carries the unchanged canonical complete `postAuthorizationExecutionTuple`, including immutable typed `targetOwner`, Account-returned `authorizationReferenceFingerprint`, the action-family request identity, `reservationOwnerId`, current positive `reservationClaimFence`, the current domain `ownerId` and owner/gameplay fence, and a fresh high-entropy handoff identity. Logging and Admin is the delivery provider, not a second authority: it must hold the exact unexpired reservation owner and claim fence. Only a separately fenced replacement owner of the exact authenticated Logging and Admin mTLS workload may call Account's read-only `RecoverOperatorAuthorizationReference` with `preAuthorizationReservationTuple/v1` and that fresh fence during pre-authorization recovery. The domain owner's `recoveryOwnerId` never calls `RecoverOperatorAuthorizationReference`; it receives the original opaque reference only through this post-authorization handoff after the owner-side claim is current and fenced. When the pre-authorization recovery owner receives the original issued response, it may atomically enrich the record to `ACCOUNT_AUTHORIZATION/AUTHORIZED` under the fresh claim and invoke this bounded handoff to the current domain owner. Account checks `issuanceKind`, immutable typed `targetOwner`, authenticated workload/actor binding, automation-policy identity, authority tuple, membership version, issuance fence, all existing immutable fields, and the reservation owner/fence before returning the original reference. Logging and Admin delivers that reference only over the exact allowlisted mTLS channel to the current domain owner in a bounded, non-durable envelope bound to the handoff identity, full tuple, reference fingerprint, reservation owner/fence, current owner/fence, and an expiry no later than the Account reference expiry. The raw reference is held only in protected in-flight memory and is zeroized after successful redemption, expiry, or failed delivery; no durable recovery copy is created. This handoff is only for the initial owner execution; a consumed reference and its durable redemption result cannot start another owner attempt. -If that Logging and Admin reservation claim has expired on a terminal owner-execution result, that terminal result is not eligible for rearm. A recovery owner may retain and reconcile the historical result read-only, but it cannot transfer reservation ownership, recover or deliver the original reference, redeem it for execution, or allocate a successor owner attempt. This restriction does not apply to an expired `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` claim: a fenced recovery CAS may install a fresh valid claim, recover the original issued response, atomically enrich to `AUTHORIZED`, and use the bounded handoff/fresh redemption path for the initial owner execution. Repeating a terminal owner-execution business intent requires a new explicit operator request with a new `controlPlaneRequestId`, fresh Account authorization, and a new opaque reference; claim expiry never turns an old reference or terminal result into authorization for another actor and never creates a duplicate issuance. +If that Logging and Admin reservation claim has expired on a terminal owner-execution result, that terminal result is not eligible for rearm. A recovery owner may retain and reconcile the historical result read-only, but it cannot transfer reservation ownership, recover or deliver the original reference, redeem it for execution, or allocate a successor owner attempt. This restriction does not apply to an expired `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` claim: a fenced recovery CAS may install a fresh valid claim, recover the original issued response, atomically enrich to `AUTHORIZED`, and use the bounded handoff/fresh redemption path for the initial owner execution. Repeating a terminal owner-execution business intent requires a new explicit operator request with a new action-family request identity, fresh Account authorization, and a new opaque reference; claim expiry never turns an old reference or terminal result into authorization for another actor and never creates a duplicate issuance. -The current domain owner authenticates the delivery provider, rechecks its own current owner/gameplay fence and the unchanged reservation claim fence, and redeems the exact reference with Account before allocating the initial owner attempt. Account redemption must still validate the exact caller workload, tuple, current authority, membership, applicable privilege, and issuance fence; successful redemption consumes the reference and binds the durable redemption result to that attempt. Handoff timeout, provider/owner fence loss, tuple or fingerprint mismatch, expired or revoked reference, Account `NOT_FOUND`, delivery failure, or redemption failure after the authorized-to-owner transition remains `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` until exact durable proof establishes no owner-forward call, no redemption, and no owner commit; only then may it transition to `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION`. The original authorization and consumed reference are never reused after a failed or ambiguous post-authorization handoff. An ambiguous handoff is read-only and non-replayable; it never authorizes business execution, and any later business attempt requires a new explicit operator request, fresh Account authorization, and a new reference. +The current domain owner authenticates the delivery provider, rechecks its own current owner/gameplay fence and the unchanged reservation claim fence, and redeems the exact reference with Account before allocating the initial owner attempt. Account redemption must still validate the exact caller workload, tuple, current authority, membership, applicable privilege, and issuance fence; successful redemption consumes the reference and binds the durable redemption result to that attempt. Handoff timeout, provider/owner fence loss, tuple or fingerprint mismatch, expired or revoked reference, Account `NOT_FOUND`, delivery failure, or redemption failure after the authorized-to-owner transition remains `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` until one of the two applicable terminal-proof forms above is established durably; only then may it transition to `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION`. The original authorization and consumed reference are never reused after a failed or ambiguous post-authorization handoff. An ambiguous handoff is read-only and non-replayable; it never authorizes business execution, and any later business attempt requires a new explicit operator request, fresh Account authorization, and a new reference. -For a forwarded owner-mutation family, after the reservation owner receives the Account authorization reference, it atomically enriches the exact `preAuthorizationReservationTuple/v1` into the canonical complete `postAuthorizationExecutionTuple`. The latter contains the complete pre-authorization tuple plus `issuanceKind`, the `authorizationReferenceFingerprint` returned unchanged by Account for the exact opaque reference, exact authenticated workload and actor binding, applicable workload/policy identity, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, and the exact immutable `authorityEvidenceBundle/v1` defined in ADR 0047. It explicitly retains the immutable typed `targetOwner` from the reservation and every schema-bound typed presence/absence value; no declared value may be dropped during tuple completion. Logging and Admin never derives or recomputes the fingerprint or any authority evidence. Its durable record may retain the operator intent and Account-returned fingerprint; any opaque reference held by Logging and Admin is protected, bounded in-flight delivery material only, not a recovery authority record or competing copy of Account's authority. The workload identity is the exact authenticated Logging and Admin mTLS identity; an automated request also binds `automation_policy_id` and `automation_policy_version`, while a human request has an explicit no-automation-policy value. Schema-bound absent or null values represented by the digest are stored as bound values rather than omitted during tuple completion. If the reservation, initial durable record, or tuple completion cannot be written after a reference may exist, the durable record remains `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` under its applicable claim/recovery rules, and the original request tuple, Account response/reference fingerprint, reservation owner and claim fence, and all returned authority/evidence fields are retained in their owning durable records; the opaque reference itself remains only in Account's protected authority record and bounded in-flight delivery material. It must not be forwarded, reissued, or treated as `NOT_EXECUTED_BEFORE_AUTHORIZATION` until durable proof establishes that no authorization reference exists, cannot still be issued, and no owner-forward call occurred or can still occur. If no reference could have existed and the no-dispatch proof is complete, the pre-authorization terminal outcome may be recorded instead. `controlPlaneRequestId` is the canonical logical request name across HTTP, Java/domain contracts, ADRs, and audit records. Protobuf contracts may use the language-standard wire spelling `control_plane_request_id`, which maps directly to that same identifier; it is not a second idempotency key. +For a forwarded owner-mutation family, after the reservation owner receives the Account authorization reference, it atomically enriches the exact `preAuthorizationReservationTuple/v1` into the canonical complete `postAuthorizationExecutionTuple`. The latter contains the complete pre-authorization tuple plus `issuanceKind`, the `authorizationReferenceFingerprint` returned unchanged by Account for the exact opaque reference, exact authenticated workload and actor binding, applicable workload/policy identity, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, and the exact immutable `authorityEvidenceBundle/v1` defined in ADR 0047. It explicitly retains the immutable typed `targetOwner` from the reservation and every schema-bound typed presence/absence value; no declared value may be dropped during tuple completion. Logging and Admin never derives or recomputes the fingerprint or any authority evidence. Its durable record may retain the operator intent and Account-returned fingerprint; any opaque reference held by Logging and Admin is protected, bounded in-flight delivery material only, not a recovery authority record or competing copy of Account's authority. The workload identity is the exact authenticated Logging and Admin mTLS identity; an automated request also binds `automation_policy_id` and `automation_policy_version`, while a human request has an explicit no-automation-policy value. Schema-bound absent or null values represented by the digest are stored as bound values rather than omitted during tuple completion. The reservation CAS and initial `ACCOUNT_AUTHORIZATION/RESERVED` record are prerequisites to issuance: if that pre-record commit fails, Account issuance must not be attempted, and the request uses the applicable pre-authorization outcome; `AUTHORIZATION_PENDING` is not recorded or returned because no phase record exists. If Account issuance has been dispatched or a reference may exist, but tuple completion cannot be written, the durable record remains `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` under its applicable claim/recovery rules, and the original request tuple, Account response/reference fingerprint, reservation owner and claim fence, and all returned authority/evidence fields are retained in their owning durable records; the opaque reference itself remains only in Account's protected authority record and bounded in-flight delivery material. It must not be forwarded, reissued, or treated as `NOT_EXECUTED_BEFORE_AUTHORIZATION` until durable proof establishes that no authorization reference exists, cannot still be issued, and no owner-forward call occurred or can still occur. If no reference could have existed and the no-dispatch proof is complete, the pre-authorization terminal outcome may be recorded instead. The action-family request identity is canonical across HTTP, Java/domain contracts, ADRs, and audit records; its action-family mapping and moderation correlation rule are defined above. Protobuf contracts may use the language-standard wire spelling `control_plane_request_id`, which maps directly to the non-moderation identifier; it is not a second idempotency key. -For a forwarded owner-mutation family, Account first issues the applicable opaque bounded operator authorization reference defined by ADR 0047. A human request uses the typed Account `IssueHumanOperatorAuthorizationReference` path and requires the current `control-ui` identity; its reference is bound to the `human_operator` issuance kind, current token `jti`, account generation, role-assurance result, applicable `tenant_generation` or `target_tenant_generation`, any required `privileged_control` predicate, exact authenticated workload and actor binding, complete applicable authority tuple, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, exact tenant/scope, immutable typed `targetOwner`, action family, `actionFamilySchemaId`, `actionFamilySchemaVersion`, actor, `controlPlaneRequestId`, `mutationDigest`, issue time, and expiry. An unattended request uses the typed Account `IssueAutomationOperatorAuthorizationReference` path with `exact_mtls_workload_plus_versioned_automation_policy`; the current automation branch is restricted to tenant-scoped action families that require no `privileged_control`, and its reference is bound to the `automation_operator` issuance kind, exact Logging and Admin workload mTLS identity, `automation_policy_id`, `automation_policy_version`, exact `tenant_generation`, complete applicable authority tuple, independent applicable `membershipVersion` when applicable, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, exact tenant/scope, immutable typed `targetOwner`, action family, `actionFamilySchemaId`, `actionFamilySchemaVersion`, `controlPlaneRequestId`, `mutationDigest`, issue time, and expiry. It carries no user account, end-user token, `control-ui` identity, global-role authority, or human elevation. Logging and Admin forwards that reference and its unchanged generation, evidence-bundle, predicate evidence, reservation owner, claim fence, immutable typed `targetOwner`, and every schema-bound typed presence/absence value with the typed request, digest, schema pair, exact scope, and same request identifier to the authoritative domain owner. The owner: +For a forwarded owner-mutation family, Account first issues the applicable opaque bounded operator authorization reference defined by ADR 0047. A human request uses the typed Account `IssueHumanOperatorAuthorizationReference` path and requires the current `control-ui` identity; its reference is bound to the `human_operator` issuance kind, current token `jti`, account generation, role-assurance result, applicable `tenant_generation` or `target_tenant_generation`, any required `privileged_control` predicate, exact authenticated workload and actor binding, complete applicable authority tuple, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, exact tenant/scope, immutable typed `targetOwner`, action family, `actionFamilySchemaId`, `actionFamilySchemaVersion`, actor, the action-family request identity, `mutationDigest`, issue time, and expiry. An unattended request uses the typed Account `IssueAutomationOperatorAuthorizationReference` path with `exact_mtls_workload_plus_versioned_automation_policy`; the current automation branch is restricted to tenant-scoped action families that require no `privileged_control`, and its reference is bound to the `automation_operator` issuance kind, exact Logging and Admin workload mTLS identity, `automation_policy_id`, `automation_policy_version`, exact `tenant_generation`, complete applicable authority tuple, independent applicable `membershipVersion` when applicable, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, exact tenant/scope, immutable typed `targetOwner`, action family, `actionFamilySchemaId`, `actionFamilySchemaVersion`, the action-family request identity, `mutationDigest`, issue time, and expiry. It carries no user account, end-user token, `control-ui` identity, global-role authority, or human elevation. Logging and Admin forwards that reference and its unchanged generation, evidence-bundle, predicate evidence, reservation owner, claim fence, immutable typed `targetOwner`, and every schema-bound typed presence/absence value with the typed request, digest, schema pair, exact scope, and same request identifier to the authoritative domain owner. The owner: - authenticates the immediate caller with the exact Logging and Admin workload mTLS identity, redeems the matching human or unattended reference with Account, and recomputes the canonical mutation digest before any new execution; -- compares the canonical complete `postAuthorizationExecutionTuple` (`controlPlaneRequestId`, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact authenticated workload and actor binding, applicable workload/policy identity, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, the exact canonical `authorityEvidenceBundle/v1` by reference to ADR 0047, and every schema-bound typed presence/absence value) using `controlPlaneRequestId` only to locate a candidate record. An exact tuple match with a terminal result returns the stored result without new validation or mutation, and any mismatch returns `IDEMPOTENCY_CONFLICT`. An expired or revoked reference permits only the allowlisted read-only result lookup against this exact tuple: an exact terminal result may be returned, but if none exists the request remains non-replayable with no forward, owner mutation, or other continuation and requires a new explicit operator request plus fresh Account authorization; it never continues as a new non-replayable attempt; +- compares the canonical complete `postAuthorizationExecutionTuple` (the action-family request identity, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact authenticated workload and actor binding, applicable workload/policy identity, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, the exact canonical `authorityEvidenceBundle/v1` by reference to ADR 0047, and every schema-bound typed presence/absence value) using the action-family request identity only to locate a candidate record. An exact tuple match with a terminal result returns the stored result without new validation or mutation, and any mismatch returns `IDEMPOTENCY_CONFLICT`. An expired or revoked reference permits only the allowlisted read-only result lookup against this exact tuple: an exact terminal result may be returned, but if none exists the request remains non-replayable with no forward, owner mutation, or other continuation and requires a new explicit operator request plus fresh Account authorization; it never continues as a new non-replayable attempt; - authorizes the current actor or automation policy and scope rather than trusting ingress-derived domain conclusions or Logging and Admin assertions, requires Account redemption to confirm the exact current generation and any required privileged predicate, and only then validates current domain preconditions and, where applicable, the current authority generation or gameplay fence; - atomically persists or claims the owner request as `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` before dispatching any owner call or business execution, including when the preceding `ACCOUNT_AUTHORIZATION/AUTHORIZED` state was completed by a fenced recovery owner, with a durable owner claim lease and monotonic fenced execution token that prevents a superseded claimant from authorizing, forwarding, mutating, or committing; - durably commits the authoritative owner mutation and terminal result together when both reside in the same owner store, or records `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` when it can prove that no owner mutation committed; `ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` is reserved for the pre-authorization phase and cannot be emitted by owner execution; and -- returns the previously committed result only when a duplicate `controlPlaneRequestId` carries an exact match for the canonical complete `postAuthorizationExecutionTuple`, including `mutationDigest` integrity, `issuanceKind`, normalized `actionFamily`, schema identifier/version, typed scope, target, immutable typed `targetOwner`, expected version, mutation, audit reason, every schema-bound typed presence/absence value, `authorityTuple`, `membershipVersion`, `issuanceFence`, `reservationOwnerId`, `reservationClaimFence`, and immutable authority evidence/source versions. The same comparison includes authenticated workload/actor binding and applicable automation-policy identity. The initial attempt has its own immutable `ownerMutationId`; its durable record retains that attempt's identity, terminal evidence, claim/fence, and timestamps so later reconciliation cannot attribute an old response or effect to another attempt. A same-identifier request with any difference in digest, authorization-reference fingerprint, issuance kind, typed scope, normalized action family, schema identifier/version, target, immutable typed `targetOwner`, expected version, mutation, audit reason, workload identity, applicable automation-policy identity, `authorityTuple`, `membershipVersion`, `issuanceFence`, `reservationOwnerId`, `reservationClaimFence`, authority evidence/source version, or any bound presence/absence value fails with canonical `IDEMPOTENCY_CONFLICT` and never applies either payload again. A later owner attempt is a new explicit request with fresh Account authorization and a new opaque reference; it never reuses this consumed reference or `ownerMutationId`. A stale owner, expired lease, or fencing-token mismatch may produce `FENCE_REJECTED` only after the owner atomically persists durable no-accept/no-commit evidence proving that this attempt did not mutate the owner state; absent or inconsistent proof leaves `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` and is never reported as `IDEMPOTENCY_CONFLICT` or replayed. +- returns the previously committed result only when a duplicate action-family request identity carries an exact match for the canonical complete `postAuthorizationExecutionTuple`, including `mutationDigest` integrity, `issuanceKind`, normalized `actionFamily`, schema identifier/version, typed scope, target, immutable typed `targetOwner`, expected version, mutation, audit reason, every schema-bound typed presence/absence value, `authorityTuple`, `membershipVersion`, `issuanceFence`, `reservationOwnerId`, `reservationClaimFence`, and immutable authority evidence/source versions. The same comparison includes authenticated workload/actor binding and applicable automation-policy identity. The initial attempt has its own immutable `ownerMutationId`; its durable record retains that attempt's identity, terminal evidence, claim/fence, and timestamps so later reconciliation cannot attribute an old response or effect to another attempt. A same-identifier request with any difference in digest, authorization-reference fingerprint, issuance kind, typed scope, normalized action family, schema identifier/version, target, immutable typed `targetOwner`, expected version, mutation, audit reason, workload identity, applicable automation-policy identity, `authorityTuple`, `membershipVersion`, `issuanceFence`, `reservationOwnerId`, `reservationClaimFence`, authority evidence/source version, or any bound presence/absence value fails with canonical `IDEMPOTENCY_CONFLICT` and never applies either payload again. A later owner attempt is a new explicit request with fresh Account authorization and a new opaque reference; it never reuses this consumed reference or `ownerMutationId`. A stale owner, expired lease, or fencing-token mismatch may produce `FENCE_REJECTED` only after the owner atomically persists durable no-accept/no-commit evidence proving that this attempt did not mutate the owner state; absent or inconsistent proof leaves `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` and is never reported as `IDEMPOTENCY_CONFLICT` or replayed. Logging and Admin then records the correlated outcome. It reports success only after the owner confirms its durable commit. ### Canonical Evidence Reference -ADR 0048 uses the exact complete `authorityEvidenceBundle/v1` by reference to ADR 0047 and the Account API; it defines no local variant. Any compact tuple or result-lookup list below that names only authority scope, source evidence/version, projection status/freshness, or issuance-operation identity refers to that same complete bundle. The bundle never contains `reservationOwnerId`, `reservationClaimFence`, `targetOwner`, or other execution-tuple fields; those remain separately bound by `postAuthorizationExecutionTuple`. +ADR 0048 uses the exact complete `authorityEvidenceBundle/v1` by reference to ADR 0047 and the Account API; it defines no local variant. That bundle's `issuanceOperationIdentity` uses ADR 0047's single `actionFamilyRequestIdentity` representation, with exactly one action-family kind and request ID; moderation's `controlPlaneRequestId`, when carried, remains correlation-only. Any compact tuple or result-lookup list below that names only authority scope, source evidence/version, projection status/freshness, or issuance-operation identity refers to that same complete bundle. The bundle never contains `reservationOwnerId`, `reservationClaimFence`, `targetOwner`, or other execution-tuple fields; those remain separately bound by `postAuthorizationExecutionTuple`. ### Failure and Reconciliation Semantics +The pre-authorization duplicate and conflict path is located by the stable `controlPlaneRequestId`; the tagged action-family identity is an exact tuple member and is separately compared only where Account or the domain owner applies action-family idempotency. It must not be interpreted as an alternate ADR 0048 orchestration key. + Before authorization, the reservation and authorization-recovery paths compare only `preAuthorizationReservationTuple` plus the applicable claim metadata. An ambiguous Account call remains `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` during this phase. After the atomic `AUTHORIZED` enrichment, every owner identity, durable owner request, result lookup, and reconciliation path compares `postAuthorizationExecutionTuple`; a later rearm is a new request with a new pre-authorization/post-authorization tuple and fresh reference. The durable transition to `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` occurs before any owner handoff or owner dispatch. Result lookup is therefore a post-authorization owner operation; no pre-authorization path may use it or fabricate the authority fields it requires. The Account-returned authorization and authority-evidence fields are immutable additions to the pre-authorization request data; all members are compared exactly and none is reconstructed from caller assertions, fabricated before issuance, or replaced by a later authority read. -A failed final audit-outcome update does not roll back an already committed domain mutation. Each owner exposes an internal, read-only request-result lookup callable only by the allowlisted Logging and Admin workload. The lookup request carries the canonical complete `postAuthorizationExecutionTuple`: `controlPlaneRequestId`, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, the exact authenticated `workloadIdentity` and actor binding, the applicable automation-policy identity, `reservationOwnerId`, positive `reservationClaimFence`, exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, the exact canonical `authorityEvidenceBundle/v1` by reference to ADR 0047, and every schema-bound typed presence/absence value, including the explicit no-policy value for a human request and any schema-bound absent or null values represented by the digest. The owner may use `controlPlaneRequestId` only to locate a candidate durable idempotency/result record; it then validates `mutationDigest` integrity and every typed tuple member, including normalized action family, schema pair, scope, target, immutable typed `targetOwner`, expected version, mutation, audit reason, workload/actor and policy identity, reservation owner/fence, `authorityTuple`, `membershipVersion`, `issuanceFence`, authority evidence/source versions, and every bound presence/absence value, before returning the result. Any mismatch returns canonical `IDEMPOTENCY_CONFLICT` without exposing the stored result or mutating state. The lookup cannot execute or reauthorize the mutation, so it remains safe after the original human or automation authorization reference expires or is revoked. +A failed final audit-outcome update does not roll back an already committed domain mutation. Each owner exposes an internal, read-only request-result lookup callable only by the allowlisted Logging and Admin workload. The lookup request carries the canonical complete `postAuthorizationExecutionTuple`: the action-family request identity, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, the exact authenticated `workloadIdentity` and actor binding, the applicable automation-policy identity, `reservationOwnerId`, positive `reservationClaimFence`, exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, the exact canonical `authorityEvidenceBundle/v1` by reference to ADR 0047, and every schema-bound typed presence/absence value, including the explicit no-policy value for a human request and any schema-bound absent or null values represented by the digest. The owner may use the action-family request identity only to locate a candidate durable idempotency/result record; it then validates `mutationDigest` integrity and every typed tuple member, including normalized action family, schema pair, scope, target, immutable typed `targetOwner`, expected version, mutation, audit reason, workload/actor and policy identity, reservation owner/fence, `authorityTuple`, `membershipVersion`, `issuanceFence`, authority evidence/source versions, and every bound presence/absence value, before returning the result. Any mismatch returns canonical `IDEMPOTENCY_CONFLICT` without exposing the stored result or mutating state. The lookup cannot execute or reauthorize the mutation, so it remains safe after the original human or automation authorization reference expires or is revoked. + +The ADR 0048 orchestration record for this lookup is located by `controlPlaneRequestId`. An owner may use the tagged action-family identity only to locate its own domain idempotency/result candidate, then must exact-compare the complete tuple; the tag never creates a second orchestration record or reservation key. Every owner result lookup carries the expected phase and state in addition to the complete authority-bound tuple. An exact tuple with the wrong phase/state is not an existing result for that request: it returns `IDEMPOTENCY_CONFLICT` or the applicable stale-fence outcome and cannot authorize a phase transition. -Logging and Admin retains the original durable intent and reconciles through the owner result lookup until the owner result can be recorded. A terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` result must satisfy one of ADR 0048's two terminal-proof forms: pre-redemption no-redemption evidence, or post-redemption evidence of no owner acceptance, owner commit, or business mutation. It is read-only evidence for the original attempt, not rearm authority. An `IDEMPOTENCY_CONFLICT`, an unconverted `FENCE_REJECTED`, or any mismatch in the complete post-authorization authority-bound tuple is not rearmable. A pre-authorization `ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` record is terminal and requires a new explicit operator request. Any later owner attempt requires a new `controlPlaneRequestId`, fresh Account authorization, a new opaque reference, and a new owner record; it never calls `RedeemOperatorAuthorization` with the consumed reference or reuses the prior owner attempt. Any other terminal result is replay-only through the read-only lookup. An expired `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` claim remains in that phase until a fenced recovery owner recovers the original response and atomically enriches to `AUTHORIZED`, or until the independent no-authorization/no-forward proof permits `NOT_EXECUTED_BEFORE_AUTHORIZATION`; it never becomes `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` merely because the Account call was ambiguous. An expired `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` claim, missing owner record after owner dispatch, or any other indeterminate owner-execution phase remains read-only and non-replayable and retains its existing `ownerMutationId`; it never allocates a successor attempt. Durable absence cannot prove that an already dispatched mutation will not commit later, and authority revocation or expiry prevents rearm rather than creating a fresh reference to replay the old write. +Logging and Admin retains the original durable intent and reconciles through the owner result lookup until the owner result can be recorded. A terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` result must satisfy one of ADR 0048's two terminal-proof forms: pre-redemption no-redemption evidence, or post-redemption evidence of no owner acceptance, owner commit, or business mutation. It is read-only evidence for the original attempt, not rearm authority. An `IDEMPOTENCY_CONFLICT`, an unconverted `FENCE_REJECTED`, or any mismatch in the complete post-authorization authority-bound tuple is not rearmable. A pre-authorization `ACCOUNT_AUTHORIZATION/NOT_EXECUTED_BEFORE_AUTHORIZATION` record is terminal and requires a new explicit operator request. Any later owner attempt requires a new action-family request identity, fresh Account authorization, a new opaque reference, and a new owner record; it never calls `RedeemOperatorAuthorization` with the consumed reference or reuses the prior owner attempt. Any other terminal result is replay-only through the read-only lookup. An expired `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` claim remains in that phase until a fenced recovery owner recovers the original response and atomically enriches to `AUTHORIZED`, or until the independent no-authorization/no-forward proof permits `NOT_EXECUTED_BEFORE_AUTHORIZATION`; it never becomes `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` merely because the Account call was ambiguous. An expired `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` claim, missing owner record after owner dispatch, or any other indeterminate owner-execution phase remains read-only and non-replayable and retains its existing `ownerMutationId`; it never allocates a successor attempt. Durable absence cannot prove that an already dispatched mutation will not commit later, and authority revocation or expiry prevents rearm rather than creating a fresh reference to replay the old write. `FENCE_REJECTED` is the initial wire/status outcome for a stale owner or fence and is non-rearmable only after the rejecting owner atomically persists that outcome with immutable no-accept/no-commit proof for the exact owner attempt, observed owner/gameplay fence, and complete tuple. The owner must not emit `FENCE_REJECTED` before that durable proof exists. If the proof is absent, incomplete, or inconsistent, the durable request remains `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`; it cannot be replayed, converted to `NOT_EXECUTED`, or rearmed. If the owner loses its lease afterward, exactly one CAS-selected recovery owner with a newer owner fence may validate the persisted proof, confirm that the rejecting owner can no longer commit, and transition `OWNER_EXECUTION/FENCE_REJECTED` to terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION`. Logging and Admin, a caller, or a recovery reader without the fenced owner-recovery CAS may not synthesize or advance that transition. Until the rejecting owner or qualifying recovery owner records the terminal outcome, a valid `FENCE_REJECTED` remains non-rearmable. @@ -121,13 +129,13 @@ Owner-side admission, feature-flag, and tick control RPCs are `internal_workload `/moderation/actions` and `ApplyModerationAction` are a Logging & Admin-owned policy-input/audit path, not a forwarded domain mutation. Account owns issuance of the Account authorization reference, and Logging & Admin validates and redeems it at the receiving boundary before the path can persist policy input and audit evidence. This path does not require or perform domain-owner redemption or enforcement. The separate live `EvaluateModerationPolicy` read remains input at the current Game Session and Social & Groups enforcement boundaries; Account enforces its account-wide categories from Account-owned state, while versioned propagation and domain enforcement remain target-state work. -Until its action-family schema, shared `mutationDigest/v1` vectors, Account issuance, and receiving-boundary validation/redemption are complete, this path remains unavailable/gated and these are target contract rules, not enablement. Once enabled, its durable intent uses the exact path request tuple: `controlPlaneRequestId`, `mutationDigest`, action-family schema pair, typed scope/target/expected-version/mutation/audit-reason fields, and every schema-declared presence/absence value. Before Account issuance or receiving-boundary redemption, the exact `preAuthorizationReservationTuple/v1` and its claim fence are the idempotency identity; after Account returns, the unchanged authorization fingerprint, applicable authority evidence, and reservation fields are retained through receiving-boundary redemption and policy/audit persistence. An exact duplicate returns the stored lifecycle result without a second issuance, redemption, or policy write; any tuple, digest, schema, fingerprint, evidence, or claim mismatch returns `IDEMPOTENCY_CONFLICT` without mutation. The durable intent must exist before the first Account call; if it cannot be written, the path is not attempted. A successful receiving-boundary redemption is not by itself a committed policy outcome: policy-input and audit persistence must reach the durable terminal result. If persistence fails or the response is lost after redemption, the consumed reference is never redeemed again and no replacement reference is issued; the intent remains outcome-pending and a fenced recovery owner performs only an exact read-only lookup/reconciliation of the intent and policy/audit record until the stored result is known. No domain-owner execution phase, owner mutation, owner-result store, or owner-side `NOT_EXECUTED` proof is created for this path. +Until its action-family schema, shared `mutationDigest/v1` vectors, Account issuance, and receiving-boundary validation/redemption are complete, this path remains unavailable/gated and these are target contract rules, not enablement. Once enabled, its durable intent uses the exact path request tuple: `policyIntentRequestId`, `mutationDigest`, action-family schema pair, typed scope/target/expected-version/mutation/audit-reason fields, and every schema-declared presence/absence value; any carried `controlPlaneRequestId` is correlation-only. Before Account issuance or receiving-boundary redemption, the exact `preAuthorizationReservationTuple/v1` and its claim fence are the idempotency identity; after Account returns, the unchanged authorization fingerprint, applicable authority evidence, and reservation fields are retained through receiving-boundary redemption and policy/audit persistence. An exact duplicate returns the stored lifecycle result without a second issuance, redemption, or policy write; any tuple, digest, schema, fingerprint, evidence, or claim mismatch returns `IDEMPOTENCY_CONFLICT` without mutation. The durable intent must exist before the first Account call; if it cannot be written, the path is not attempted. A successful receiving-boundary redemption is not by itself a committed policy outcome: policy-input and audit persistence must reach the durable terminal result. If persistence fails or the response is lost after redemption, the consumed reference is never redeemed again and no replacement reference is issued; the intent remains outcome-pending and a fenced recovery owner performs only an exact read-only lookup/reconciliation of the intent and policy/audit record until the stored result is known. No domain-owner execution phase, owner mutation, owner-result store, or owner-side `NOT_EXECUTED` proof is created for this path. ### Redis-Backed Owner Mutations The Redis-backed owner record, write-ahead evidence, effect/outcome evidence, and Redis projection are created only after the durable `ACCOUNT_AUTHORIZATION/AUTHORIZED -> OWNER_EXECUTION/OWNER_EXECUTION_PENDING` transition. They use the canonical complete `postAuthorizationExecutionTuple` defined above; Redis markers, key presence, and command responses never replace its `issuanceKind`, immutable typed `targetOwner`, `authorityTuple`, `membershipVersion`, `issuanceFence`, `reservationOwnerId`, `reservationClaimFence`, or immutable authority evidence/source versions. The `ACCOUNT_AUTHORIZATION/RESERVED`, `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`, and `ACCOUNT_AUTHORIZATION/AUTHORIZED` states remain in the Logging and Admin reservation record until the durable owner-execution transition; no Redis owner record or projection is created for them, and no post-authorization field is fabricated before Account authorization. -Coordination Redis is a volatile projection, not the durable owner of an operator mutation. After the durable authorized-to-owner transition, any supported action that materializes state in Redis must first create or claim a durable owner request record containing the canonical complete `postAuthorizationExecutionTuple` (`controlPlaneRequestId`, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, exact `workloadIdentity`, applicable workload/policy identity, exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, the exact canonical `authorityEvidenceBundle/v1` by reference to ADR 0047, and every schema-bound typed presence/absence value), desired mutation, `phase=OWNER_EXECUTION`, `state=OWNER_EXECUTION_PENDING`, `ownerMutationId`, current owner/lease identity, fencing token, lease expiry, and terminal result, together with durable write-ahead and effect evidence sufficient to distinguish a committed effect, an unstarted attempt, and an indeterminate attempt. Atomic mutation-plus-result commit applies within the authoritative durable owner store; it does not imply a distributed transaction with Redis. The Logging and Admin reservation record remains the sole durable record for `ACCOUNT_AUTHORIZATION/RESERVED`, `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`, and `ACCOUNT_AUTHORIZATION/AUTHORIZED`; the owner record and effect evidence are the source of truth only for `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`, `COMMITTED`, `FAILED`, `FENCE_REJECTED`, and `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION`. Redis key presence or a Redis command response alone is never a terminal result. +Coordination Redis is a volatile projection, not the durable owner of an operator mutation. After the durable authorized-to-owner transition, any supported action that materializes state in Redis must first create or claim a durable owner request record containing the canonical complete `postAuthorizationExecutionTuple` (the action-family request identity, `mutationDigest`, `issuanceKind`, Account-returned `authorizationReferenceFingerprint`, exact typed `scope`, normalized `actionFamily`, `actionFamilySchemaId`, `actionFamilySchemaVersion`, typed `target`, immutable typed `targetOwner`, typed `expectedVersion`, typed `mutation`, typed `auditReason`, exact authenticated `workloadIdentity` and actor binding, applicable workload/policy identity, exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, the exact canonical `authorityEvidenceBundle/v1` by reference to ADR 0047, and every schema-bound typed presence/absence value), desired mutation, `phase=OWNER_EXECUTION`, `state=OWNER_EXECUTION_PENDING`, `ownerMutationId`, current owner/lease identity, fencing token, lease expiry, and terminal result, together with durable write-ahead and effect evidence sufficient to distinguish a committed effect, an unstarted attempt, and an indeterminate attempt. Atomic mutation-plus-result commit applies within the authoritative durable owner store; it does not imply a distributed transaction with Redis. The Logging and Admin reservation record remains the sole durable record for `ACCOUNT_AUTHORIZATION/RESERVED`, `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`, and `ACCOUNT_AUTHORIZATION/AUTHORIZED`; the owner record and effect evidence are the source of truth only for `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`, `COMMITTED`, `FAILED`, `FENCE_REJECTED`, and `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION`. Redis key presence or a Redis command response alone is never a terminal result. The owner-execution durable record is written ahead of Redis in this order: persist the exact `ownerMutationId`, originating owner fence, target-state digest, intended effect, and `dispatchState=NOT_DISPATCHED`; persist `dispatchState=DISPATCHED` before any call that could reach Redis; then, only after a successful script result or an exact read-only marker/state proof, persist effect evidence bound to that attempt, marker identity, originating fence, target version, and canonical tuple. A durable terminal result is written only from that evidence and with the current durable owner fence. A crash with `NOT_DISPATCHED` and durable proof that the old claimant can no longer dispatch reconciles to `UNSTARTED`; a crash after `DISPATCHED` and before a script result is `INDETERMINATE` unless exact durable evidence proves no dispatch could occur; a crash after an accepted script and before effect/terminal persistence reconciles to `COMMITTED` only when the marker and target state exactly match the attempt and tuple, after which the durable effect and result are recorded. If the Redis marker is lost, durable committed effect evidence still supports `COMMITTED`; a missing marker with only write-ahead or dispatch evidence is `INDETERMINATE`, never `UNSTARTED`, and is never replayed. These classifications are produced by read-only reconciliation of durable owner evidence and current Redis state; reconciliation does not call the business mutator or Lua script, and an indeterminate attempt remains non-replayable. @@ -172,7 +180,7 @@ Rejected because the front end is not the lease owner and cannot safely serializ The current implementation is partial. Each supported operator-action family must demonstrate: -- Wherever the proof refers to a full or complete authority-bound identity, it must name and compare the canonical complete `postAuthorizationExecutionTuple`, including `controlPlaneRequestId`, `mutationDigest` integrity, `issuanceKind`, exact authenticated workload and actor/policy binding, normalized `actionFamily`, schema identifier/version, typed scope/target, immutable typed `targetOwner`, typed expected-version/mutation/audit-reason fields, every schema-bound typed presence/absence value, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, and immutable authority evidence/source versions. No complete-authority proof may substitute a digest, current owner lookup, or partial identity for this tuple. +- Wherever the proof refers to a full or complete authority-bound identity, it must name and compare the canonical complete `postAuthorizationExecutionTuple`, including the action-family request identity, `mutationDigest` integrity, `issuanceKind`, exact authenticated workload and actor/policy binding, normalized `actionFamily`, schema identifier/version, typed scope/target, immutable typed `targetOwner`, typed expected-version/mutation/audit-reason fields, every schema-bound typed presence/absence value, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, immutable authority evidence/source versions, and the Account-returned `authorizationReferenceFingerprint`. No complete-authority proof may substitute a digest, current owner lookup, or partial identity for this tuple. - Current WorldLifecycle evidence is not full support for this ADR. `WorldLifecycleCommandServiceImpl.prepareWorldInstance` looks up by `(tenantId, gameInstanceId)` and compares the prepared fields, including `controlPlaneRequestId`; an exact prepared duplicate returns the existing snapshot, while a mismatch currently returns `INVALID_ARGUMENT`, not request-keyed `IDEMPOTENCY_CONFLICT`. Activation and failure are guarded by lifecycle epoch/state but have no complete request-tuple record. Termination uses `terminationRequestId` for state transitions and repeated terminal reads, but does not yet provide a durable terminal result/fingerprint for every retry or prove that a same-request retry cannot repeat cleanup. `TemporalWorldLifecycleOrchestrator` uses a deterministic tenant/game-instance workflow ID and queries an existing workflow after `WorkflowExecutionAlreadyStarted`, but does not compare a full request digest on prepare; its lifecycle read attaches Temporal describe metadata to a fallback domain snapshot rather than proving domain-state and workflow-status equivalence. The workflow signals also do not enforce a durable request identity/digest. These paths remain partial and must not be reported as satisfying the target idempotency contract. - For WorldLifecycle to satisfy this ADR, each lifecycle command must use a stable request identity and canonical digest for the complete typed request tuple, with durable same-tuple replay and `IDEMPOTENCY_CONFLICT` on mismatch; deterministic workflow identity alone is insufficient. A status response must separately identify the authoritative domain snapshot and Temporal execution metadata, and may claim convergence only after proof that both represent the same lifecycle state and epoch. @@ -181,7 +189,7 @@ The current implementation is partial. Each supported operator-action family mus - for `/moderation/actions` and `ApplyModerationAction`, Account authorization-reference issuance plus Logging & Admin receiving-boundary validation/redemption, without treating domain-owner redemption or enforcement as part of the policy-input/audit path; - atomic owner mutation and result persistence with duplicate delivery returning the original result only on a full tuple match, and every mismatch returning canonical `IDEMPOTENCY_CONFLICT` without mutation; - for Redis-backed owner state, a durable reservation-owner claim lease with CAS acquire/renew/expiry/completion and a monotonic fence, explicit phase/state in every CAS, durable claim/state/result and effect-evidence records, marker-based Lua mutation, atomic no-accept/no-commit proof with `FENCE_REJECTED`, lease-owner fencing for new writes and terminal commits, and non-replayable read-only reconciliation that validates the prior `ownerMutationId` and originating fence after a crash or lease transfer; -- an allowlisted read-only owner result lookup that locates by `controlPlaneRequestId` but validates the canonical complete `postAuthorizationExecutionTuple`, including `mutationDigest` integrity, `issuanceKind`, normalized `actionFamily`, typed scope/target, immutable typed `targetOwner`, typed expected-version/mutation/audit-reason fields, every schema-bound typed presence/absence value, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, immutable authority evidence/source versions, Account-returned authorization-reference fingerprint, schema identifier/version, exact workload/policy identity, and actor binding, returning `IDEMPOTENCY_CONFLICT` for any mismatch and recovering only the durable terminal outcome after authorization expiry or revocation without executing, forwarding, or reauthorizing the mutation; if no exact terminal result exists, the request remains non-replayable and requires a new explicit operator request plus fresh Account authorization; +- an allowlisted read-only owner result lookup that locates by the action-family request identity but validates the canonical complete `postAuthorizationExecutionTuple`, including `mutationDigest` integrity, `issuanceKind`, normalized `actionFamily`, typed scope/target, immutable typed `targetOwner`, typed expected-version/mutation/audit-reason fields, every schema-bound typed presence/absence value, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, immutable authority evidence/source versions, Account-returned authorization-reference fingerprint, schema identifier/version, exact workload/policy identity, and actor binding, returning `IDEMPOTENCY_CONFLICT` for any mismatch and recovering only the durable terminal outcome after authorization expiry or revocation without executing, forwarding, or reauthorizing the mutation; if no exact terminal result exists, an `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` attempt remains non-replayable and no fresh request identifier may be accepted until durable terminal commit/no-commit evidence, or an equivalent owner-fenced proof that the prior attempt cannot commit, is recorded; only then may a new explicit operator request plus fresh Account authorization be used; - recovery from crashes before forwarding, during owner execution, after owner commit, and before final outcome recording; - truthful operator outcomes for rejection, timeout, lost response, duplicate delivery, authorization expiry, and reconciliation; - no successful mutation when the initial intent store is unavailable; diff --git a/design/architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md b/design/architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md index 8d504a0b3e..ff182107c3 100644 --- a/design/architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md +++ b/design/architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md @@ -46,11 +46,11 @@ The existing split is sound, but two contracts are too weak. Reusing an `EffectI ### Effect Identity and Participant Guards -Game Session assigns one stable root `EffectId` to the logical effect and persists intended pre/post state and required participants. Each participant derives a deterministic guard identity from the root effect, typed operation, and target aggregate. Its durable guard binds that identity to an immutable request digest and stored outcome. +For a root mutation, Game Session assigns one stable root `EffectId` to the logical effect and persists intended pre/post state and required participants. Each participant resolves its owner-local guard using the persisted mutation `EffectId` as the stable collision key for that participant (the root `EffectId` for a root mutation or the persisted child `EffectId` for a generated child). An existing candidate is reusable only after separately exact-comparing the typed operation, exact target aggregate, owner-declared runtime-family partition—S1/S2 use `(tenantId, playableStateNamespaceId)`, explicit S3 uses `(tenantId, gameInstanceId)`, and an unknown or unclassified family fails closed—and immutable `requestDigest`; any mismatch fails closed. Where one mutation has multiple participants, the owner-local participant/target slot keeps those sibling guards distinct. A generated child retains its enclosing root only as lineage and reconciliation context. The durable guard stores the binding and outcome. The separate [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not accepted target state and may not be used as an implementation requirement. - Same identity plus the same request returns the prior durable result. - Same identity with a different operation, target, or request digest fails closed. -- Derived reactions use deterministic child effect identities rather than accidental reuse. +- Derived reactions use deterministic child effect identities rather than accidental reuse. Any future allocator or replay binding remains subject to the non-authoritative [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). - Participant acknowledgement means the guard and effect-visible domain rows committed together. - Player success waits for all declared required participants under ADR 0053. diff --git a/design/architecture/decisions/adr-0061-single-owner-spatial-mutations-across-split-authority.md b/design/architecture/decisions/adr-0061-single-owner-spatial-mutations-across-split-authority.md index 357ffee08e..08ea007ac6 100644 --- a/design/architecture/decisions/adr-0061-single-owner-spatial-mutations-across-split-authority.md +++ b/design/architecture/decisions/adr-0061-single-owner-spatial-mutations-across-split-authority.md @@ -48,7 +48,7 @@ The canonical Game Session root binding is authenticated and exact-compared befo - `MOVE` mutates World location/occupancy in one World transaction. Pure movement has no Entity mutation participant. - `DROP` and `PICKUP` mutate the item's holder in one Entity transaction. They use the existing World `TargetingFactSnapshot` actor-location/location-version token, admitted under the Game Session actor/executor fence and passed to Entity as owner-issued location evidence. Before committing, Entity atomically validates that token for the same room/epoch together with the expected holder and Entity aggregate version; stale or mismatched World location evidence fails admission and re-resolves under the same root `EffectId` and immutable request digest, without transferring item authority to World. -Every owner derives a participant guard identity from the root `EffectId`, typed operation, and target aggregate, and binds it to an immutable request digest and durable result. Same guard and same request replays the prior result; the same guard with a different operation, target, or digest fails closed. +Every owner resolves its participant guard using the persisted mutation `EffectId` as the stable collision key for that participant (the root `EffectId` for a root mutation or the persisted child `EffectId` for a generated child). An existing candidate is reusable only after separately exact-comparing the typed operation, exact target aggregate, owner-declared runtime-family partition—S1/S2 use `(tenantId, playableStateNamespaceId)`, explicit S3 uses `(tenantId, gameInstanceId)`, and an unknown or unclassified family fails closed—and immutable `requestDigest`; any mismatch fails closed. Where one mutation has multiple participants, the owner-local participant/target slot keeps those sibling guards distinct. A generated child retains its enclosing root only as lineage and reconciliation context. Same guard and same request replays the prior result. Generated-child allocation and root/child lineage beyond this accepted guard boundary remain subject to the non-authoritative [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Correctness mutations carry exact scope, epoch, and relevant expected state: @@ -56,7 +56,7 @@ Correctness mutations carry exact scope, epoch, and relevant expected state: - drop and pickup include World-authoritative actor-location evidence plus expected current holder and Entity aggregate version; and - ambient changes include the owning World aggregate and expected version. -Derived ambient or gameplay reactions use deterministic child effect identities and declare whether they are required or optional. Only declared required participants delay logical player success. Presentation reads use ADR 0059's causal floor and distinct component versions, never service-local snapshot equality; that presentation causal floor is not a mutation guard and is never substituted for the World targeting token. +Derived ambient or gameplay reactions use deterministic child effect identities and declare whether they are required or optional. Only declared required participants delay logical player success. Presentation reads use ADR 0059's causal floor and distinct component versions, never service-local snapshot equality; that presentation causal floor is not a mutation guard and is never substituted for the World targeting token. The non-authoritative [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) describes a possible future allocation boundary. ## Consequences @@ -90,7 +90,7 @@ Rejected because at-least-once delivery and stale room evidence could duplicate ## Implementation and Proof Obligations -Proof must cover digest-conflict rejection, duplicate replay, stale epoch/location/holder/version, move without an Entity mutation, drop/pickup without World item ownership, no double location or holder, deterministic required and optional child effects, crash and reconciliation, and causal-floor room presentation. The effect catalog is the required inventory for new spatial and ambient effect families. +Proof must cover digest-conflict rejection, duplicate replay, stale epoch/location/holder/version, move without an Entity mutation, drop/pickup without World item ownership, no double location or holder, deterministic required/optional child admission and outcome classification, crash and reconciliation, and causal-floor room presentation. Allocation/replay proof for the pending [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not claimed here. The effect catalog is the required inventory for new spatial and ambient effect families. ## Reversibility and Revisit Triggers diff --git a/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md b/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md index 98361054af..20a8d94593 100644 --- a/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md +++ b/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md @@ -49,7 +49,7 @@ Within one entity's eligible queue, work uses persisted deterministic ordering: `entity_enqueue_seq` is monotonic within the entity's current region epoch and assigned by the owning Game Session admission/scheduling path. Same-tick derived children use the persisted parent order plus deterministic child ordinals rather than completion timing. New sources map into this tuple and do not introduce private tie-breakers. -The historical final tuple label `commandId_or_effectKey` is one normalized, persisted, source-specific stable identity slot: `command` uses `commandId`; `timer` uses the timer member ID; `retry` uses the persisted retry member/effect identity required by its owning contract; `remote_followup` uses the durable follow-up row ID; and `generated_effect` uses its recorded deterministic child `EffectId`, derived under the immutable parent/root identity and child ordinal contract. The selected manifest retains this exact source-to-slot mapping for each item; this does not introduce a second tuple or schema field. +The historical final tuple label `commandId_or_effectKey` is one normalized, persisted, source-specific stable identity slot: `command` uses `commandId`; `timer` uses the timer member ID; `retry` uses the persisted retry member/effect identity required by its owning contract; `remote_followup` uses the durable follow-up row ID; and `generated_effect` uses its recorded deterministic child `EffectId` under the immutable parent/root identity and child ordinal contract. The selected manifest retains this exact source-to-slot mapping for each item; this does not introduce a second tuple or schema field. The pending [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not current target state. Across eligible entities, each lane uses persisted deterministic rotating/deficit scheduling. The scheduler accounts for declared work cost, advances only with the durable selected batch, and ensures a permanently eligible entity eventually receives capacity within a healthy epoch. Non-best-effort priority classes declare bounded aging or `maxDeferralTicks`; work explicitly classified as best effort follows its declared delay/drop policy. diff --git a/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md b/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md index 72ec754ff6..e6bc471fde 100644 --- a/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md +++ b/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md @@ -6,13 +6,14 @@ Accepted ## Implementation Status -The command/effect boundary and single logical terminal outcome are target state; complete durable identity guards, evidence-based reconciliation, and focused crash/replay proof remain incomplete. +The command/effect boundary, deterministic command-plan root identity, and single logical terminal outcome are target state; complete durable identity guards, evidence-based reconciliation, and focused crash/replay proof remain incomplete. ## Canonical Design - [Tick Execution Flows](../system-architecture-tick-execution-flows.md) - [Tick Failure and Operations](../system-architecture-tick-failures-and-operations.md) - [Transaction Strategies](../system-architecture-transactions.md) +- [Identifier Glossary](../system-architecture-identifier-glossary.md#cross-service-effect-identity) ## Decision Record @@ -35,18 +36,32 @@ Describing this as “exactly-once execution” would wrongly imply one physical ## Decision -An accepted command lost before durable staging terminates at the command lifecycle with: +An `ACCEPTED_VOLATILE` command still in `RECEIVED` or `ENQUEUED`, with no surviving durable `tickBatchId`, effect ledger, or source/effect claim, may terminate as lost before durable staging only when an atomic owner-defined no-batch CAS/version-fenced check wins. A pre-staging plan manifest or root-allocation row alone is a non-executable identity reservation, not a batch/effect binding and does not disqualify this outcome; it remains linked to the terminal command as evidence and cannot be reused for another command: - `executionOutcome = LOST_BEFORE_STAGING`; and - `gameplayResult = NOT_APPLIED`. -No effect ledger row is invented for a command that never produced a durably claimed or staged effect. +An `ACCEPTED_DURABLE` command follows its feature-specific durable intake and recovery contract instead; it is not classified as `LOST_BEFORE_STAGING` by this rule. No effect ledger row is invented for a command that never produced a durably claimed or staged effect. -Before any participant verification, the canonical Game Session context binds each durably claimed or staged effect's root `EffectId` to its typed operation, immutable request digest, required-participant context, and sealed manifest. Participants validate that sealed binding before their local guard/effect work; a conflicting operation, digest, or participant binding fails closed. Before terminal aggregation, Game Session must also verify that the returned participant projections exactly equal the sealed expected participant set and that every projection matches that same root, operation, digest, participant context, and manifest binding. A missing, extra, duplicate, partial, or conflicting projection fails closed and remains reconciliation-required rather than producing a terminal aggregate. Physical execution is at least once: retries may invoke the handler multiple times after crashes, lost acknowledgements, or replay. +Before any participant verification, the canonical Game Session context binds each durably claimed or staged effect's persisted mutation `EffectId`—the root `EffectId` for a root effect or the generated child's persisted `EffectId` for a child effect—to its typed operation, immutable request digest, required-participant context (including applicable `playableStateNamespaceId` identity evidence and separately persisted `playableStateScope` fence evidence), and sealed manifest. When applicable, the enclosing `rootEffectId` is retained only as lineage and reconciliation context. Participants exact-validate that sealed binding before their local guard/effect work; a conflicting operation, digest, namespace, scope, or participant binding fails closed. Before terminal aggregation, Game Session must also verify that the returned participant projections exactly equal the sealed expected participant set and that every projection matches that same persisted mutation `EffectId`, operation, digest, participant context, namespace, scope, and manifest binding. A missing, extra, duplicate, partial, or conflicting projection fails closed and remains reconciliation-required rather than producing a terminal aggregate. Physical execution is at least once: retries may invoke the handler multiple times after crashes, lost acknowledgements, or replay. The owning domain's durable idempotency guard permits at most one logical authoritative state mutation for that identity and digest. Reuse of the identity with a conflicting digest fails closed. -Every staged effect ledger row reaches exactly one terminal status: +The accepted decision does not select a generated-child allocator or exact scalar format. Those unresolved target-state questions are recorded, without authority, in the pending [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). + +### Deterministic command plans and root identity + +An admitted command has one deterministic effect plan: the ordered set of logical root effects admitted for that command. The order is supplied by the frozen typed command or `ResolvedEffectPlan` semantic order owned by the command/action contract; Game Session does not infer it from scheduler selection. Built-in commands declare an equivalent stable semantic order. An ambiguous or duplicate root order fails before admission, and Game Session persists the ordered plan manifest and its digest before tick staging. Each logical operation in the plan has exactly one root `EffectId`, with any affected participants represented by guards beneath that root. A conserved multi-participant operation normally shares one root across its participants, but still follows [ADR 0053](./adr-0053-command-atomicity-by-invariant-class.md)'s required/optional classification and its co-location or reservation/escrow rules; one root does not claim global atomicity. + +The plan assigns a stable zero-based `planOrdinal` in that supplied semantic order. A single-root plan uses `planOrdinal=0`; a multi-root plan uses `0..n-1`; a zero-effect plan allocates no ordinal and no root `EffectId`. Before allocation, the durable gameplay command row freezes/binds its request fingerprint, resolved runtime scope, applicable `playableStateNamespaceId`, and separately persisted `playableStateScope` fence evidence. Game Session owns an opaque root `EffectId` allocation row unique on `(tenantId, gameInstanceId, commandId, planOrdinal)`; that row also binds the ordered plan manifest digest and exact-validates the command row's frozen binding, including the namespace and scope evidence. Reuse requires the same command row identity, frozen command/runtime binding, `planOrdinal`, and manifest digest; any mismatch fails closed. `playableStateNamespaceId` and `playableStateScope` are bound evidence, not additional allocation-key dimensions. For Automation, the complete applicable Command-Handoff Identity, including any optional distinct target runtime fields, is the admission/deduplication identity and must exact-map to one durable target `commandId`; after that mapping, root allocation uses the target command row's same canonical key. Trigger Identity and `scriptEventId` remain handler/correlation identities, not root-allocation inputs. Ordinary retries, replay, and reconciliation read and reuse the binding; the opaque ID is not derived by participants. + +`planOrdinal` and this allocation binding apply only to command-root work. Passive, inbound/remote, timer, retry, and already-generated effects retain their owner/source-specific root identity contracts and do not synthesize a command plan unless they materialize as an admitted command; generated children remain beneath the enclosing root. Random `tickBatchId`, mutable command text, `effectKey`, `sourceOrdinal`/`enqueueSeq`, participant tuples, Trigger Identity or `scriptEventId`, and child ordinals cannot substitute for the durable command row identity or allocation binding; they retain their existing staging, ordering, descriptor, participant, handler, and lineage roles. + +Command receipts, root-allocation records, tick batches, and selected-work manifests are S3 instance-scoped operational evidence: they may be cleaned up only after linked source claims and effects are terminal, replay/restore and reconciliation horizons have elapsed, and the owner cleanup fence permits it. Participant guards remain owner-domain durable evidence, with their own namespace/state classification and retention contract; they are not disposable Redis coordination state. A reset or replacement alone never authorizes bulk deletion or abandonment. + +The plan root is distinct from the command ingress identity, source-claim identity, Automation Command-Handoff Identity, participant guard identity, and generated child identity. A post-abandon command re-drive may receive a fresh root only under the existing conclusive `ABANDONED` and source-terminalization rules and must create a new durable `commandId` linked to the abandoned command and effect lineage; reusing the old `commandId` returns its prior terminal result and cannot allocate another plan root. A non-command source follows its owner-specific linked re-drive identity. An ordinary retry or replay never allocates a fresh root. + +Every staged effect ledger row reaches at most one terminal status, and terminalization occurs only when the applicable evidence policy permits it: - `APPLIED` when authoritative domain evidence proves that the logical mutation committed; or - `ABANDONED` only when authoritative evidence proves the effect was unapplied and any already-declared applicable feature rule permits it to be no longer valid, with an explicit reason. Inconclusive execution remains `SCHEDULED`/reconciliation-required; timeout, retry exhaustion, missing coordination, age, or technical failure alone never proves `ABANDONED`. @@ -65,6 +80,8 @@ The system does not silently drop staged effects, leave them permanently ambiguo - Recovery may retry physical work without duplicating authoritative gameplay state. - Operators and callers can distinguish command results, effect terminal states, and replay reasons. - Owner services require durable identity-and-digest guards and authoritative evidence queries. +- Deterministic plans make command-root admission and replay stable without deriving the allocation binding from scheduler selection, staging coordinates, source ordering, or handler identity. +- Multi-participant conservation remains governed by command atomicity/co-location or reservation semantics; a shared root is not a distributed transaction. - The ledger and recovery controller must retain unresolved staged effects until they reach a justified terminal outcome. - Presentation output can duplicate even while authoritative state remains logically single-apply. @@ -88,7 +105,7 @@ Rejected as the normal contract because unresolved effects could remain ambiguou ## Implementation and Proof Obligations -Proof must cover accepted-command loss before staging without an invented effect row; sealed root/operation/digest/participant/manifest binding before participant verification and conflict rejection; crashes before and after domain commit; lost acknowledgements; duplicate physical invocation with one logical mutation; authoritative `REPLAY_NOOP` evidence terminalizing as `APPLIED`; evidence-qualified `ABANDONED` outcomes with timeout, retry-exhaustion, missing-coordination, age, and technical-failure rejection; command-result derivation across zero, one, and multiple required effects; duplicate presentation feedback without duplicate state; replay and reset convergence; and absence of silent drop or permanently ambiguous staged rows. +Proof must cover accepted-command loss before staging without an invented effect row, including a surviving pre-staging plan/root allocation but no batch/effect binding; semantic zero-, single-, and multi-root plan ordering supplied by the frozen typed command/action contract, including built-in stable order and ambiguous/duplicate-order rejection; freezing/binding of command request fingerprint, runtime scope, `playableStateNamespaceId`, and separately persisted/exact-validated `playableStateScope`; persistence of the ordered plan manifest/digest and opaque allocation-row binding; uniqueness on `(tenantId, gameInstanceId, commandId, planOrdinal)`; reuse only with the same command row identity, frozen command/runtime binding, `planOrdinal`, and manifest digest, with mismatch rejection; Automation handoff admission exact-mapping to one durable target command; preservation of separate source-ordering, participant, handler, and child identities; command-root-only scope; conserved multi-participant handling under ADR 0053; sealed root/operation/digest/participant/manifest binding before participant verification and conflict rejection; crashes before and after domain commit; lost acknowledgements; duplicate physical invocation with one logical mutation; authoritative `REPLAY_NOOP` evidence terminalizing as `APPLIED`; evidence-qualified `ABANDONED` outcomes with timeout, retry-exhaustion, missing-coordination, age, and technical-failure rejection; command-result derivation across zero, one, and multiple required effects; duplicate presentation feedback without duplicate state; replay and reset convergence; and absence of silent drop or permanently ambiguous staged rows. The current implementation and runtime proof are not claimed to satisfy this decision. diff --git a/design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md b/design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md index a222f72559..1a0e65826c 100644 --- a/design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md +++ b/design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md @@ -54,11 +54,11 @@ Recovery classes are: Redis timer keys, due indexes, leader checkpoints, and wake-up hints are rebuildable and disposable for every class. Durable timer identity, due state, recovery policy, resume-window identity, and terminal or skipped outcomes live outside Redis whenever the class requires recovery or audit. -For target-state `COALESCE_ONE` recovery, Automation owns one durable timer-recovery resume-window record per runtime scope, epoch, and `isDryRun` mode. Its `resumeWindowId` is the exact tuple ``. A durable compare-and-set creates or returns the one `OPEN` window for that scope, epoch, and mode; leader, worker, takeover, and attempt IDs never participate in the identity. At creation, the durable record binds the exact `(scriptPatchVersion, scriptPinEpoch)` tuple as immutable execution-fence evidence without adding it to `resumeWindowId`, freezes the effective numeric tenant-local cap and the selection-policy revision, and persists a frozen pre-window `recoveryStart` watermark plus a monotonic `lastObservedThrough` watermark for each applicable clock domain. Each observation supplies an `observedThrough` watermark, which is durably recorded as the new `lastObservedThrough` only with settlement under that `resumeWindowId`. `recoveryStart` is the exclusive lower bound for the first scan, the prior `lastObservedThrough` is exclusive for every later scan, and the current `observedThrough` is inclusive, so the ranges are `(recoveryStart, observedThrough]` initially and `(lastObservedThrough, observedThrough]` thereafter. A candidate exactly at the inclusive through point is eligible once; a candidate at an exclusive lower bound is not rediscovered. Same-window retries, observations, and takeovers re-read and compare those persisted watermarks and reuse the record, its mode-specific `resumeWindowId`, and its frozen cap and selection-policy revision unchanged; each `CATCH_UP` firing claim and candidate audit includes that ID in uniqueness and comparison. A cap or selection-policy change applies only to a later window allocated after this one reaches `COMPLETE`. The current window becomes `COMPLETE` only after the selected candidates' firing or shared-admission-denial outcomes and all cap-excluded candidate outcomes governed by its frozen values are durable. Only a later recovery episode after completion allocates the next `resumeGeneration`, producing a distinct mode-specific `resumeWindowId`. +For target-state `COALESCE_ONE` recovery, Automation owns one durable timer-recovery resume-window record per playable-state namespace/runtime scope, epoch, and `isDryRun` mode. Its `resumeWindowId` is the exact tuple ``. A durable compare-and-set creates or returns the one `OPEN` window for that namespace/runtime scope, epoch, and mode; the server-derived `playableStateScope` is retained and exact-validated as immutable policy/routing/authorization/fence evidence, not as a uniqueness input. An authoritative scope transition starts a new playable-state lifecycle and namespace; stale presented scope with unchanged authority may reuse the existing identity. Leader, worker, takeover, and attempt IDs never participate in the identity. At creation, the durable record binds the exact `(scriptPatchVersion, scriptPinEpoch)` tuple as immutable execution-fence evidence without adding it to `resumeWindowId`, freezes the effective numeric tenant-local cap and the selection-policy revision, and persists a frozen pre-window `recoveryStart` watermark plus a monotonic `lastObservedThrough` watermark for each applicable clock domain. Each observation supplies an `observedThrough` watermark, which is durably recorded as the new `lastObservedThrough` only with settlement under that `resumeWindowId`. `recoveryStart` is the exclusive lower bound for the first scan, the prior `lastObservedThrough` is exclusive for every later scan, and the current `observedThrough` is inclusive, so the ranges are `(recoveryStart, observedThrough]` initially and `(lastObservedThrough, observedThrough]` thereafter. A candidate exactly at the inclusive through point is eligible once; a candidate at an exclusive lower bound is not rediscovered. Same-window retries, observations, and takeovers re-read and compare those persisted watermarks and reuse the record, its mode-specific `resumeWindowId`, and its frozen cap and selection-policy revision unchanged; each `CATCH_UP` firing claim and candidate audit includes that ID in uniqueness and comparison. A cap or selection-policy change applies only to a later window allocated after this one reaches `COMPLETE`. The current window becomes `COMPLETE` only after the selected candidates' firing or shared-admission-denial outcomes and all cap-excluded candidate outcomes governed by its frozen values are durable. Only a later recovery episode after completion allocates the next `resumeGeneration`, producing a distinct mode-specific `resumeWindowId`. A scope-level durable atomic epoch transition must move each prior epoch's `OPEN` resume window, independently for each `isDryRun` mode, out of `OPEN` before any corresponding new-epoch `OPEN` window can be created. Claims from the prior window remain fenced to, and are reconciled under, their original `regionEpoch`, `isDryRun`, and resume-window identity; they cannot be admitted through the new window. The transition follows the existing evidence-based completion and terminalization rules and does not invent a new terminal status or recovery policy. -Every exact script-pin selection change is also a resume-window transition, including a same-patch repin that advances `scriptPinEpoch`, even when the runtime region and region epoch are unchanged. Before any new exact-pin timer admission, durable reconciliation must move every prior mode-specific `OPEN` window for the affected scope out of `OPEN`, fence its claims to the prior exact pin and `resumeWindowId`, and preserve those claims and candidate audits for settlement under their original identities. They cannot consume the next window's cap or be rewritten for the target pin. After the target exact `(scriptPatchVersion, scriptPinEpoch)` and its schedules reconcile, a still-required catch-up episode allocates the next monotonic `resumeGeneration` independently for each mode and therefore a distinct mode-specific `resumeWindowId`; retries of this transition are idempotent under the initiating `controlPlaneRequestId`. +Every exact script-pin selection change is also a resume-window transition, including a same-patch repin that advances `scriptPinEpoch`, even when the runtime region and region epoch are unchanged. Before any new exact-pin timer admission, durable reconciliation must move every prior mode-specific `OPEN` window for the affected namespace/runtime scope out of `OPEN`, fence its claims to the prior exact pin and `resumeWindowId`, and preserve those claims and candidate audits for settlement under their original identities. They cannot consume the next window's cap or be rewritten for the target pin. After the target exact `(scriptPatchVersion, scriptPinEpoch)` and its schedules reconcile, a still-required catch-up episode allocates the next monotonic `resumeGeneration` independently for each mode and therefore a distinct mode-specific `resumeWindowId`; retries of this transition are idempotent under the initiating `controlPlaneRequestId`. `COALESCE_ONE` never replays a burst of missed cadence boundaries. One configurable tenant-local cap bounds synthetic firings across complete stable schedule-instance identities within one mode-specific resume window, which is already scoped to one tenant and one `isDryRun` mode. Selection is deterministic and fair across those identities, including target-scope and plugin-binding dimensions. Candidates excluded by the cap are not deferred into an unbounded backlog; their skipped outcomes and reasons are audited. Candidates selected within the tenant-local cap still enter the shared scheduler/cluster admission layer, where [ADR 0166](./adr-0166-attributable-script-breakers-and-tenant-first-fairness.md) tenant-first fairness precedes priority; catch-up cannot bypass per-tenant or cluster ceilings. A selected catch-up candidate denied there by a tenant or cluster capacity ceiling is terminally skipped for that due candidate and mode-specific `resumeWindowId`: it consumes its deterministic selection slot, records the applicable bounded capacity-denial reason in the candidate audit, creates no firing claim or `scriptEventId`, and is not deferred, retried, backfilled, or reminted in that or a later mode-specific resume window. This candidate-level ceiling gate is distinct from later handler-scoped Table 3 decisions: a per-script quota or materialized sandbox/dry-run capacity denial follows that table under the identity established at its stage, including any firing claim, `scriptEventId`, or work item already created, and is not reminted as catch-up. This terminal skip does not suppress the schedule's next ordinary future occurrence. @@ -75,7 +75,7 @@ else: else resumeTick + intervalTicks - remainder ``` -During a version transition, due state may be carried forward only when `scheduleDefinitionId`, resolved `playableStateScope`, and `scheduleSemanticsHash` match. The replacement version-owned schedule row must be created or confirmed before the prior row is retired, as one atomic durable reconciliation or a resumable idempotent operation keyed by `controlPlaneRequestId`. +During a version transition, due state may be carried forward only when `scheduleDefinitionId`, the exact `(scriptPatchVersion, scriptPinEpoch)` tuple selected for the preserved schedule, exact `playableStateNamespaceId`, resolved `playableStateScope`, and `scheduleSemanticsHash` match. The replacement version-owned schedule row must be created or confirmed before the prior row is retired, as one atomic durable reconciliation or a resumable idempotent operation keyed by `controlPlaneRequestId`. This preserved-schedule calculation maintains cadence and permits an occurrence exactly on the resume boundary. Reload or rollback preservation is distinct from downtime catch-up: preservation chooses the next valid due point for the retained schedule, while downtime recovery separately applies the declared `SKIP_MISSED` or `COALESCE_ONE` policy under a durable resume-window identity. diff --git a/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md b/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md index f5f0bef74c..8495bbded5 100644 --- a/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md +++ b/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md @@ -43,7 +43,9 @@ The platform retains a hard generated-effect depth ceiling with `8` as the share Platform hard ceilings bound every setting. Operators may configure lower environment bounds, and an authored feature may lower its own limits further, but a feature can never exceed the resolved operator or platform bounds. -Every generated child carries an immutable parent identity, immutable root identity, depth equal to `parent.depth + 1`, and a deterministic child ordinal. The immutable root identity is the existing ADR 0069 canonical Game Session root `EffectId` binding to the typed operation, immutable request digest, required participant context, and sealed manifest; this decision introduces no second root authority. The sealed root manifest also persists the resolved platform, operator, and feature depth/count/cost/per-target limits, cost weights, and cost-model version. The ordinal is covered by the request digest. Retry, replay, and reconciliation reuse those persisted resolved values and never re-resolve them. Replay reuses the recorded child identity, lineage, ordinal, and budget accounting; it does not increment them again or mint a replacement identity. +Every generated child carries an immutable parent identity, immutable root identity, depth equal to `parent.depth + 1`, and an owner-defined deterministic child ordinal allocated and persisted by the owning contract for replay-stable reuse. For generated work under an admitted command, the immutable root identity is the opaque Game Session root `EffectId` allocated for the enclosing command plan and its `planOrdinal`; this decision introduces no second root authority. Generated work under a passive, inbound/remote, timer, retry, or other non-command-root contract retains that owner's root identity and does not acquire a `planOrdinal` unless it materializes as an admitted command. A generated child never allocates a new command plan root, and its child ordinal is lineage/accounting metadata rather than an input to the root allocation binding. The sealed root manifest also persists the resolved platform, operator, and feature depth/count/cost/per-target limits, cost weights, and cost-model version. Retry, replay, and reconciliation reuse those persisted resolved values and never re-resolve them. Replay reuses the recorded child identity, lineage, ordinal, and budget accounting; it does not increment them again or mint a replacement identity. + +The owner-scope/root/parent/ordinal mapping to each child `EffectId` is one atomic durable admission record. The owning contract must persist the child `EffectId` and complete mapping before enqueue/apply; retry, replay, and reconciliation read and reuse that mapping and its sealed accounting, while a missing or conflicting mapping fails closed rather than allocating another child identity. Count, cost, per-target, and depth admission are evaluated deterministically for the root chain. When admitting a new child would exceed a limit, only that child is suppressed. A suppressed child is not enqueued or applied, and no already committed parent or earlier child is rolled back. @@ -94,9 +96,9 @@ Rejected because the parent may already be durably committed across authoritativ ## Implementation and Proof Obligations -Implement one canonical generated-chain admission and accounting path with the platform hard depth ceiling, shared depth bootstrap default of `8`, deterministic total count and cost budgets, per-target caps, operator bounds, and feature-lowering rules. Persist immutable parent and root identities, `parent.depth + 1`, digest-covered deterministic ordinals, required or optional classification, and the complete suppression evidence. +Implement one canonical generated-chain admission and accounting path with the platform hard depth ceiling, shared depth bootstrap default of `8`, deterministic total count and cost budgets, per-target caps, operator bounds, and feature-lowering rules. When the enclosing work is command-root work, persist its `planOrdinal`/opaque root allocation binding; otherwise retain the owner/source-specific root identity. Persist immutable parent and root identities, `parent.depth + 1`, owner-defined deterministic child ordinals allocated and persisted for replay-stable reuse, required or optional classification, and the complete suppression evidence; child ordinals must not allocate or replace a command plan root. -Prove hard-ceiling and lower-bound resolution; depth, count, cost, and per-target suppression at each boundary; deterministic admission order; cost accounting; immutable lineage and ordinals; request-digest validation; crash and replay without re-incrementing accounting or reminting identity; suppression of only the new child; preservation of committed parents and earlier children; truthful `SUCCESS`, `PARTIAL`, and `FAILED` derivation; complete durable evidence; bounded metric labels and bands; raw-identity exclusion from Prometheus; audit-query retrieval; one-off optional audit behavior; repeated optional designer warnings; prompt required-suppression alerts; and operational paging for sustained aggregate suppression or tick degradation. +Prove hard-ceiling and lower-bound resolution; depth, count, cost, and per-target suppression at each boundary; deterministic admission order; cost accounting; immutable lineage and ordinals; request-digest validation; crash and replay without re-incrementing accounting or reminting identity; suppression of only the new child; preservation of committed parents and earlier children; truthful `SUCCESS`, `PARTIAL`, and `FAILED` derivation; complete durable evidence; bounded metric labels and bands; raw-identity exclusion from Prometheus; audit-query retrieval; one-off optional audit behavior; repeated optional designer warnings; prompt required-suppression alerts; and operational paging for sustained aggregate suppression or tick degradation. The pending [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not proved or accepted by this ADR. The current implementation, configuration resolution, authored classification, observability, alerting, and focused proof are not claimed by this decision. diff --git a/design/architecture/decisions/adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md b/design/architecture/decisions/adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md index 778f578d81..4325ed9396 100644 --- a/design/architecture/decisions/adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md +++ b/design/architecture/decisions/adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md @@ -41,6 +41,8 @@ Every global or multi-region effect first creates one durable parent identity. A Fan-out creates an idempotent durable child or injection row for every affected region before publishing any wake signal for that region. The parent and children expose pending, injected, terminal, and feature-specific outcome information sufficient to show partial injection. Game Session owns fan-out reconciliation. A feature may not casually assign another durable coordinator: any transfer must follow [ADR 0057](./adr-0057-game-session-owned-reconciliation-with-isolated-workers.md)'s complete authority-transfer model and a new accepted ADR defining the new owner's ledger/backlog, frozen participant set, retry/reconciliation, outcome, audit, retention, and worker controls. The owner retries missing injections, reconciles duplicate attempts to the same child identity, and derives the visible parent outcome. +The exact child-identity allocation, manifest schema, and replay binding are not selected by this accepted fan-out decision. They are described only as a non-authoritative pending proposal in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); no implementation may treat that proposal as current target state. + Redis markers, notifications, or equivalent wake signals are disposable latency hints. Losing a hint cannot erase a child, and duplicating one cannot create another logical regional effect. Each child enters the target region's ordinary durable inbound-effect path and remains subject to that region's lease, executor fence, epoch checks, lane budgets, and idempotency rules. Global effect admission has a bounded global outstanding-work cap and explicit backpressure. Within that capacity, per-region child admission is deterministic and fair so a hot region or large fan-out cannot indefinitely exclude another eligible region. Rejected, delayed, or terminalized children remain visible on the durable parent rather than disappearing behind wake delivery. diff --git a/design/architecture/decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md b/design/architecture/decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md index 8369afa4c3..8cb3658652 100644 --- a/design/architecture/decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md +++ b/design/architecture/decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md @@ -51,7 +51,7 @@ Workflow run IDs, process or JVM execution IDs, retry-attempt IDs, and message o ### Current Automation Adopter Mapping -The Temporal mapping for `script-patch-readiness` is `workflowFamily=script-patch-readiness`, `tenantId=`, `scopeKey=script-patch-version`, and `businessKey=`, yielding `workflowId=script-patch-readiness::script-patch-version:`. Each readiness `onLoad` step uses the stable `onLoad` step name and the `FORWARD` execution role. Its deterministic occurrence key is the canonical ordered serialization of the complete applicable handler-scoped tenant-readiness Trigger Identity: ``. The optional plugin fields are included exactly when applicable and remain absent otherwise; `scriptId` and, for a plugin handler, `bindingId` identify the resolved handler occurrence, so no attempt, delivery, worker, or runtime ordinal participates. +The Temporal mapping for `script-patch-readiness` is `workflowFamily=script-patch-readiness`, `tenantId=`, `scopeKey=script-patch-version`, and `businessKey=`, yielding `workflowId=script-patch-readiness::script-patch-version:`. Each readiness `onLoad` step uses the stable `onLoad` step name and the `FORWARD` execution role. Its deterministic occurrence key is the canonical ordered serialization of the complete applicable embedded-script-only tenant-readiness Trigger Identity: ``. `pluginId`, `pluginVersionId`, and `bindingId` are absent and not applicable because linked-plugin bindings do not participate in tenant-readiness `onLoad`; plugin initialization remains in the independently versioned, instance-scoped plugin lifecycle. No attempt, delivery, worker, or runtime ordinal participates. The immutable request digest covers those admitted identity fields plus immutable handler descriptor content/version. Runtime-only game, playable-state, region, epoch, and entity fields are absent. Adopter proof must show that the same complete guard and digest replays the recorded readiness step across Temporal run replacement without repeating its logical effect, while the same guard with any different digest fails closed without execution or false replay. diff --git a/design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md b/design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md index 9513a7427d..9977b2383d 100644 --- a/design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md +++ b/design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md @@ -47,11 +47,11 @@ Durable recurring schedules declare exactly one missed-firing policy: - `SKIP_MISSED` emits no synthetic firing for missed boundaries. - `COALESCE_ONE` may emit at most one synthetic firing for one logical schedule in a durable resume window. -One durable, mode-scoped resume-window identity covers the complete recovery attempt across repeated scans or progress observations: live and dry-run/test recovery use separate windows and separate caps, with `isDryRun` included in the window identity and every candidate-selection, firing-claim, candidate-audit, and proof comparison. Each window also binds the exact `(scriptPatchVersion, scriptPinEpoch)` as immutable execution-fence evidence without adding the pin tuple to `resumeWindowId`, and at creation freezes the effective numeric tenant-local cap plus the selection-policy revision that defines grouping, ordering, round-robin passes, and tie breaks. Repeated observations, retries, and takeovers reuse those frozen values unchanged and cannot remint another catch-up firing for the same schedule and window; a cap or policy change applies only to a later window after the current one reaches `COMPLETE`. The deterministic fair tenant-local cap applies within each mode-specific resume window, which is already scoped to one tenant, and selects coalesced candidates across complete stable schedule-instance identities; cap-excluded candidates are dropped with bounded audit and metrics under that window's frozen policy rather than deferred into an unbounded backlog. Selected candidates still enter the shared scheduler/cluster admission layer, where [ADR 0166](./adr-0166-attributable-script-breakers-and-tenant-first-fairness.md) tenant-first fairness precedes priority; catch-up cannot bypass per-tenant or cluster ceilings. A selected candidate denied by a tenant or cluster capacity ceiling is terminally skipped under the same due-candidate, `isDryRun`, and `resumeWindowId` identity with bounded audit, consumes its deterministic selection slot, creates no firing claim or `scriptEventId`, and is never deferred, retried, backfilled, or reminted as catch-up. Its next ordinary future cadence remains eligible. +One durable, mode-scoped resume-window identity covers the complete recovery attempt across repeated scans or progress observations: live and dry-run/test recovery use separate windows and separate caps, with `isDryRun` included in the window identity and every candidate-selection, firing-claim, candidate-audit, and proof comparison. The authoritative `playableStateNamespaceId` is part of the due and resume-window identity; server-derived `playableStateScope` remains immutable policy/routing/authorization/migration-fence evidence, is exact-validated alongside that identity, and is not a uniqueness discriminator. An authoritative scope transition starts a new playable-state lifecycle and namespace; stale presented scope with unchanged authority may reuse the existing identity. Each window also binds the exact `(scriptPatchVersion, scriptPinEpoch)` as immutable execution-fence evidence without adding the pin tuple to `resumeWindowId`, and at creation freezes the effective numeric tenant-local cap plus the selection-policy revision that defines grouping, ordering, round-robin passes, and tie breaks. Repeated observations, retries, and takeovers reuse those frozen values unchanged and cannot remint another catch-up firing for the same schedule and window; a cap or policy change applies only to a later window after the current one reaches `COMPLETE`. The deterministic fair tenant-local cap applies within each mode-specific resume window, which is already scoped to one tenant, and selects coalesced candidates across complete stable schedule-instance identities; cap-excluded candidates are dropped with bounded audit and metrics under that window's frozen policy rather than deferred into an unbounded backlog. Selected candidates still enter the shared scheduler/cluster admission layer, where [ADR 0166](./adr-0166-attributable-script-breakers-and-tenant-first-fairness.md) tenant-first fairness precedes priority; catch-up cannot bypass per-tenant or cluster ceilings. A selected candidate denied by a tenant or cluster capacity ceiling is terminally skipped under the same due-candidate, `isDryRun`, and `resumeWindowId` identity with bounded audit, consumes its deterministic selection slot, creates no firing claim or `scriptEventId`, and is never deferred, retried, backfilled, or reminted as catch-up. Its next ordinary future cadence remains eligible. Every exact script-pin selection change is a resume-window transition, including a same-patch repin that advances `scriptPinEpoch`, even when the runtime region and region epoch are unchanged. Before any new exact-pin timer admission, durable reconciliation must move every prior mode-specific `OPEN` window for the affected scope out of `OPEN`, fence its claims to the prior exact pin and `resumeWindowId`, and preserve those claims and candidate audits for settlement under their original identities. They cannot consume the next window's cap or be rewritten for the target pin. After the target exact `(scriptPatchVersion, scriptPinEpoch)` and its schedules reconcile, a still-required catch-up episode allocates the next monotonic `resumeGeneration` independently for each mode and therefore a distinct mode-specific `resumeWindowId`; retries of this transition are idempotent under the initiating `controlPlaneRequestId`. -Preserved schedules across reload, rollback, or an allowed owner-version transition use the canonical modulo resume formula. If the previous due point is at or after the resume point it is retained. If the resume point lands exactly on a later cadence boundary, the schedule fires at that boundary at most once under the durable schedule-instance plus resume-window identity; otherwise it advances to the first cadence boundary strictly after resume. Version and runtime-scope fencing remains part of the due identity. +Preserved schedules across reload, rollback, or an allowed owner-version transition use the canonical modulo resume formula. If the previous due point is at or after the resume point it is retained. If the resume point lands exactly on a later cadence boundary, the schedule fires at that boundary at most once under the durable schedule-instance plus tagged due-point identity, adding `resumeWindowId` only when `triggerMode=CATCH_UP`. Otherwise, it advances to the first cadence boundary strictly after resume. The exact `(scriptPatchVersion, scriptPinEpoch)` tuple and `playableStateNamespaceId` remain part of the due identity, while runtime scope remains separately captured and exact-validated as fence evidence. The lack of an eventual-execution guarantee applies to each best-effort recurring firing. It does not mean that the recurring schedule disappears: after recovery, future eligible boundaries continue under the preserved cadence unless the schedule is removed, disabled, fenced, or terminally invalid. diff --git a/design/architecture/decisions/adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md b/design/architecture/decisions/adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md index 7b7c826e8f..09a5ade09b 100644 --- a/design/architecture/decisions/adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md +++ b/design/architecture/decisions/adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md @@ -31,7 +31,7 @@ ADR 0011 correctly separates session front-end socket ownership from lease-owner A Game Session front-end owns the edge-facing socket, connection-local protocol state, bounded input/output queues, and presentation delivery. The current fenced lease owner for a target region is the only Game Session executor allowed to admit and mutate region-scoped tick work. -The front-end resolves an owner through a directory or lease projection and forwards a request carrying complete gameplay scope, `commandId`, target region, expected executor fence, session identity, front-end generation, and `sessionSequence`. The directory is a routing hint, not authority. The receiving executor validates current ownership and fence at admission and rejects stale or missing authority. +The front-end resolves an owner through a directory or lease projection and forwards a request carrying complete gameplay scope: `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, and separately validated server-derived `playableStateScope`; it also carries `commandId`, target region, expected executor fence, session identity, front-end generation, and `sessionSequence`. The namespace is the durable gameplay identity dimension; scope is separately validated routing/authorization/migration-fence evidence and is not a uniqueness key. The directory is a routing hint, not authority. The receiving executor validates current ownership and fence at admission and rejects stale or missing authority. `sessionSequence` preserves FIFO for commands from one live connection generation. It is not a dedupe key, effect identity, transaction fence, or cross-connection global order. `commandId`, effect identity, and owning domain request identities provide idempotency and ambiguous-result reconciliation. A stale-owner rejection before admission may refresh routing and retry the same logical identity; an ambiguous response never creates a new identity and is reconciled through the authoritative command-status surface. diff --git a/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md b/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md new file mode 100644 index 0000000000..03f2d51121 --- /dev/null +++ b/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md @@ -0,0 +1,120 @@ +# ADR 0183: Deterministic Command-Plan and Generated-Child EffectId Allocation + +## Status + +Proposed - Pending Human Review + +## Implementation Status + +This proposal is not current target state and is not an accepted implementation requirement. The current services, wire contracts, and focused proof remain implementation gaps as recorded by the linked canonical documents. No implementation may treat this proposal as approved before human review. + +The move from the conflicting draft number ADR 0182 to ADR 0183 is mechanical preservation only. It neither accepts this allocator decision nor authorizes proposal-dependent implementation; independently authoritative effect and replay obligations continue to apply on their own authority. + +## Decision Record + +- Human review status: Pending +- Human review date: Not yet reviewed +- Human review disposition: Pending +- Review source: `AI-AUTHORED-PENDING` +- Decision date: 2026-08-31 +- Decision key: `TICK-20` +- Primary capability: `GR-1.2` effect execution and reconciliation +- Affected capabilities: `GR-1.4`, `GR-4.1`, `AS-1.2`, `AS-1.4`, `SF-1.4`, `SF-2.3`, `PO-4.2` +- Decision owner: FireMUD human product and architecture owner +- Consultation: AI-authored proposal requiring explicit human review of identity format, persistence, ownership, compatibility, security, and operational proof + +## Context + +[ADR 0069](./adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) accepts at-least-once execution and one logical terminal outcome, but its accepted decision does not select the allocator contract for generated children or a precise scalar format. The current implementation also derives effect IDs from batch or effect-key material and exposes narrower service-local replay tables. Those paths are documented implementation gaps and cannot be made canonical by inference. + +Generated chains and global fan-out need an identity that survives retries, crashes, replay, runtime replacement, and reconciliation without turning semantic fields into an ID. Command roots additionally need a durable plan/ordinal binding so a changed plan cannot silently reuse an old root. Candidate suppression must remain auditable without inventing an ID for work that never entered execution. + +This proposal supplies one owner-bound allocation contract for those gaps. It is deliberately pending: its exact format and cross-service persistence boundary require human approval before any accepted ADR or implementation depends on them. + +## Decision + +### Scalar identity and allocation authority + +The canonical scalar `EffectId` is an opaque, lowercase, hyphenated UUIDv7 textual value of exactly 36 characters. UUIDv7 supplies collision-resistant allocation ordering properties without giving producers semantic parsing or meaning. Producers and participants must treat the value as an opaque scalar; they must not derive it from command text, batch IDs, effect keys, participant fields, ordinals, operation names, targets, or mutable payloads. + +Game Session owns command-root allocation. The owner of a generated child, non-command root, or remote/fan-out leg owns its corresponding allocation boundary. Each boundary allocates once, durably persists the value, and atomically binds it to the complete immutable owner scope, operation, exact target where applicable, request digest, enclosing root, parent, and stable ordinal. Insert-if-absent uniqueness covers the logical mapping and the scalar claim. A collision or any conflicting binding fails closed; it never remints or substitutes an ID. + +Retries, replay, failover, and reconciliation read and reuse the persisted mapping and exact scalar. Participants receive the persisted mutation identity and use it in their guard, ledger, response, and terminal outcome. The enclosing root remains lineage and reconciliation context for a child; it does not replace the child's identity or collapse siblings. A post-abandon re-drive receives a new explicitly linked identity under its own admission contract. + +### Command roots and versioned plan manifests + +Before staging a non-empty admitted command, Game Session freezes the typed command/action or `ResolvedEffectPlan` semantic order and persists a versioned root-plan manifest. The manifest records its schema version, registered canonical serialization identifier, canonical bytes/digest, ordered logical operations, and the frozen request/runtime/namespace binding. A root receives one `planOrdinal` in that order and one allocated opaque `EffectId`; zero-effect plans allocate neither. + +The durable allocation row is unique on `(tenantId, gameInstanceId, commandId, planOrdinal)` and binds the manifest schema version, serializer, digest, exact root scalar claim, and frozen command binding. Replay and reuse require every one of those values to match. Unknown, duplicate, ambiguous, noncanonical, or changed order/manifest evidence fails before staging or side effects. Automation handoff identity maps exactly to one durable target command before this command-root allocation is attempted; trigger and correlation identities are not allocation inputs. + +### Generated-child candidates and suppression + +Before enqueue or apply, the owning chain boundary seals one versioned child-candidate manifest using its registered canonical serialization. Each candidate records root/parent lineage, stable ordinal, typed operation, exact target, depth, required/optional classification, immutable request or plan digest, and resolved count/cost/per-target budget revisions. The candidate manifest schema version, serializer, canonical digest, and ordered candidate set are immutable replay evidence. + +Candidates receive no child `EffectId` at manifest creation. For an admitted candidate, one serializable transaction or explicitly equivalent locked multi-key atomic boundary validates the manifest, reserves the ordinal, checks and charges only the admitted candidate's count/cost/per-target budgets, allocates and persists the opaque scalar mapping together with the manifest schema version, registered serializer identifier, and canonical digest (or an immutable manifest reference resolving to those exact fields), and commits the mapping before enqueue/apply. Replay and retry must exact-compare that schema version, serializer, digest/reference, candidate ordinal, and all other immutable binding fields before reusing the mapping or enqueueing work. Concurrent sibling admission cannot double-charge, reserve two mappings for one ordinal, or leave partial budget, ordinal, mapping, or suppression state. Exact retries reuse the committed mapping. + +An over-limit candidate is suppressed without a child ID. The same atomic boundary records immutable ID-free suppression evidence containing root/parent identity, the sealed candidate-manifest schema/serializer/digest, candidate ordinal, operation and exact target, feature/script/version, required/optional classification, reason, configured and actual limits, and outcome. Suppressed candidates are never enqueued or applied; committed parents and earlier children remain authoritative. + +### Global fan-out and regional child binding + +At acceptance, the fan-out parent freezes the affected region set and topology generation. Each regional child or leg is one exact member of that sealed set and gets its own one-time allocated child `EffectId` before its wake signal. The durable child row binds root and parent lineage, child ordinal, exact operation, target region/aggregate, request digest, and the versioned child-manifest schema, registered serializer, canonical bytes/digest, and expected-participant projection. It also retains the root binding needed for reconciliation. + +The child scalar and all binding fields are persisted before wake delivery. Retry, duplicate wake, late result, and reconciliation look up the same row and scalar. A missing, extra, duplicate, reordered, schema/serializer/digest-conflicting, target-conflicting, ordinal-conflicting, or identity-conflicting child fails closed. Wake markers remain disposable latency hints and cannot create, expand, or replace a child. + +## Rationale + +An exact scalar format makes wire and storage compatibility testable while keeping identity opaque. Durable allocation separates identity from semantic derivation and allows a participant or coordinator to prove that a replay is the same logical mutation. Versioned canonical manifests make plan and fan-out interpretation stable across deployments, while ID-free suppression evidence prevents rejected work from appearing to have executed. A serializable allocation/budget boundary preserves chain accounting under concurrency and a frozen fan-out set prevents topology changes from creating new work during recovery. + +## Alternatives Considered + +### Derive IDs from command, batch, ordinal, or payload fields + +Rejected because mutable or replay-order-dependent fields can collide, change identity, or allow a participant to invent a value. Derivation also makes fan-out and generated-child reuse depend on semantics rather than durable allocation. + +### Permit UUID/ULID producer choice without an exact scalar contract + +Rejected for the canonical cross-service boundary because callers could disagree on casing, width, textual form, or parser behavior. The selected pending proposal uses lowercase hyphenated UUIDv7 text while retaining opaque semantics. + +### Allocate at manifest creation for every candidate + +Rejected because suppressed work would acquire an execution identity and could be mistaken for an admitted mutation. Allocation belongs to the atomic admission boundary after budget and ordinal checks. + +### Use a best-effort global fan-out allocator or wake message identity + +Rejected because notifications can be lost or duplicated and cannot own durable correctness. The parent-owned child row and sealed manifest binding are authoritative. + +## Consequences + +- Game Session and each generated-effect or fan-out owner need durable allocation rows with uniqueness, immutable binding fields, and conflict-safe replay behavior. +- Root and child manifests require registered schema versions and canonical serializers whose bytes and digests are stable across supported readers. +- Chain admission must use a serializable or explicitly equivalent atomic boundary and retain ID-free suppression evidence. +- Existing string protobuf and database fields remain wire/storage-compatible with a 36-character scalar, but current derivation, optional fields, and narrower replay guards remain gaps until separately implemented and proved. +- Participants, ledgers, coordinators, and operational reconciliation must carry both mutation identity and enclosing-root lineage where applicable. +- Adoption is a breaking target convergence for identity allocation; compatibility shims must not preserve semantic derivation or silently accept conflicting formats. + +## Reversibility and Revisit Triggers + +Before acceptance, human review may change the scalar format, allocator ownership, or manifest boundary without a migration obligation. After acceptance and persisted use, changing the scalar or canonical serialization requires a versioned migration and explicit old/new binding and replay policy; it must not reinterpret existing IDs. Revisit UUIDv7 only if a reviewed cross-service identity standard provides equal exact textual compatibility, opaque semantics, collision handling, and operational proof. + +## Security and Privacy + +Opaque UUIDv7 values must not encode tenant, account, character, target, operation, or authorization meaning. Exact scope, namespace, runtime-fence, target, and request-digest validation remains separate evidence. Collision, parser, schema, digest, or binding conflicts fail closed before domain mutation. Raw IDs remain durable audit/reconciliation fields but are excluded from bounded metric labels and player-facing messages. Suppression and replay evidence must not expose unauthorized target or tenant data across scope boundaries. + +## Operations and Recovery + +Game Session or the owning allocation boundary exposes durable allocation, collision, manifest-mismatch, budget-suppression, fan-out-injection, and reconciliation outcomes with bounded reason labels. Recovery retries the same persisted mapping and manifest; it never regenerates an ID or expands a frozen candidate/region set from current topology. An unresolved binding, partial participant set, or uncertain old-epoch effect remains reconciliation-required and non-terminal under the original mutation identity until the accepted evidence policy permits terminalization. + +## Implementation and Proof Obligations + +Implementation and focused proof must cover: + +- lowercase, hyphenated, exactly 36-character UUIDv7 scalar validation and opaque treatment at every supported wire/storage boundary; +- one-time allocation, insert-if-absent uniqueness, collision/conflict failure, crash recovery, concurrent allocation races, and exact replay/reconciliation reuse; +- zero-, one-, and multi-root plans; frozen semantic order; root manifest schema version, serializer, canonical bytes/digest, ordinal, command binding, and mismatch rejection; +- child-candidate schema version/serializer/digest, candidate ordering, depth and budget revisions, serializable sibling admission, no double charge, and no partial commit; +- ID-free suppression evidence proving no enqueue/apply and preserving committed parent/earlier-child outcomes; +- fan-out frozen region/topology set, exact child ordinal and target binding, child-manifest schema/serializer/digest, request digest, pre-wake durability, duplicate wake, late result, and topology-conflict handling; +- participant guard, ledger, coordinator, and terminal projection exactness across root/child identity and enclosing-root lineage; and +- current protobuf/database compatibility, rejected blank/invalid IDs, migration/replay behavior, bounded observability, tenant isolation, and old-epoch recovery. + +The focused proof must be added only after human acceptance of this proposal and must include the existing [tick failure and operations proof obligations](../system-architecture-tick-failures-and-operations.md), [transaction contract](../system-architecture-transactions.md), [tick execution flows](../system-architecture-tick-execution-flows.md), [tick incident runbook](../system-architecture-tick-incident-runbook.md), [Entity Management API contract](../microservices/entity-management-service/api-contracts.md), and [gameplay implementation tracker](../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md). diff --git a/design/architecture/infrastructure/deployment-environments.md b/design/architecture/infrastructure/deployment-environments.md index b5b780c32b..d2c725ed92 100644 --- a/design/architecture/infrastructure/deployment-environments.md +++ b/design/architecture/infrastructure/deployment-environments.md @@ -192,7 +192,7 @@ In production, FireMUD is deployed into Kubernetes (e.g., AWS EKS, Google GKE, o - Redis is deployed as **two logical roles** in both Kubernetes and Docker Compose (see [Redis Architecture](../system-architecture-redis.md)): - A **Coordination Redis** deployment runs as a clustered StatefulSet with automatic failover in production and smaller clusters in non-production. It uses AOF, persistent volumes, and `noeviction` in player-facing environments to preserve volatile coordination state across normal rollouts and pod restarts within the documented tail-loss envelope; Redis is not the authoritative recovery or audit log. AOF, persistent volumes, and `noeviction` alone are insufficient for player-facing replay safety: the deployment must also satisfy the [ADR 0029 replay-readiness contract](../decisions/adr-0029-single-use-gameplay-connect-token-carriage.md), including Redis 7.2+, ACL isolation, reserved capacity and an admission-readiness threshold, atomic marker consumption, configured `WAITAOF` local/replica acknowledgement thresholds, and a shared reset/uncertain-durability quarantine fence. A profile that cannot prove those controls is not eligible to admit new player handshakes. - A **Cache/Rate-Limit Redis** deployment runs as a separate StatefulSet or Deployment tuned for eviction-driven workloads (for example using `allkeys-lru`), with sizing independent of Coordination Redis. It may use lighter durability (RDB snapshots or even ephemeral volumes) because its keys are best-effort and recomputable. - - Local development runs **two Redis containers** under Docker Compose with the same role split: a Coordination Redis service and a Cache/Rate-Limit Redis service, with Coordination Redis durable via AOF and Cache/Rate-Limit Redis configured for eviction-driven workloads. When operators want to **reset** coordination state (for example, to test reset-tolerant behavior or remediate mis-keyed data), they use the explicit coordination-reset Job or script described in the Redis Operations runbook rather than relying on Helm to clear data automatically on every deploy. A reset that affects connect-token replay state must advance `replayAdmissionFence`, record shared `QUARANTINED` readiness, reject affected tokens for the complete ADR 0029 barrier, and reopen only after the disposable-marker plus configured `WAITAOF` proof succeeds; wiping the AOF volume alone never restores admission readiness. +- Local development runs **two Redis containers** under Docker Compose with the same role split: a Coordination Redis service and a Cache/Rate-Limit Redis service, with Coordination Redis durable via AOF and Cache/Rate-Limit Redis configured for eviction-driven workloads. The existing `redis-coord-wipe-aof` Helm hook and `restore-redis-aof.sh` helper are isolated local/test fixture tooling only; neither is a supported Coordination Redis reset path for shared or player-facing environments, and neither proves the durable maintenance lock, fencing, Account projection repair, replay quarantine, or post-reset verification required by the owner contract. The target coordination-maintenance reset sequence is unavailable today. Current operators must preserve evidence, keep the affected scope fenced, use the shipped pause/status and read-only inspection surfaces, and escalate through the [Current Operator Fallback](../system-architecture-redis-reset-and-recovery.md#current-operator-fallback). A future reset that affects connect-token replay state must advance `replayAdmissionFence`, record shared `QUARANTINED` readiness, reject affected tokens for the complete ADR 0029 barrier, and reopen only after the disposable-marker plus configured `WAITAOF` proof succeeds; wiping the AOF volume alone never restores admission readiness. - PostgreSQL is deployed within the cluster (or provided as a managed database service) to store persistent domain data. See [System Architecture Overview](../system-architecture-overview.md#data-and-state-management). Backup and restore procedures are outlined in [Backup & Disaster Recovery](../system-architecture-backup-recovery.md) and the [operations recovery index](../../operations/README.md#recovery). - **Hosted dev/demo Kubernetes environments** use [`dev-demo.yml`](../../../.github/workflows/dev-demo.yml) for the fixed environment and [`preview.yml`](../../../.github/workflows/preview.yml) for credential-free per-PR rendering. The trusted default-branch [`hosted-identity-request.yml`](../../../.github/workflows/hosted-identity-request.yml) validates the render artifact and deploys the per-PR runtime. These workflows use the full-stack chart under [`k8s/helm/firemud`](../../../k8s/helm/firemud) with environment-specific example values and deployment metadata. These environments are intentionally excluded from the staging → production promotion chain and must not emit attestation artifacts. - **Staging and production** deployments are applied from a secure operator environment using **Kustomize overlays** (for example `kubectl apply -k k8s/overlays/stage` and `kubectl apply -k k8s/overlays/prod`). Immutable image digest changes for these overlays are the promotion model, and the player-facing bootstrap contract is now intentionally expressed through environment-owned bindings plus preflight rather than through checked-in placeholder Secret content. See [Deployment Runbook](../system-architecture-deployment-runbook.md) and [CI/CD Pipeline](../system-architecture-cicd.md#promotion--rollback-model). diff --git a/design/architecture/microservices/automation-scripting-service/README.md b/design/architecture/microservices/automation-scripting-service/README.md index 9dd4f1f23e..bced4193e2 100644 --- a/design/architecture/microservices/automation-scripting-service/README.md +++ b/design/architecture/microservices/automation-scripting-service/README.md @@ -42,7 +42,7 @@ The current Automation pin projection and wire contract now retain the observed - Faction reputation influences NPC aggression states. NPCs may become `FLEEING` or `SURRENDERED` when low on health or morale, allowing players to resolve encounters non-lethally. - Web UI for creating and testing scripts using a component-based DSL. - Advanced AI modules support formations, squads, and complex behaviors. -- Bounded procedural encounter generation is present: the current population hook invokes seeded encounter generation, but its result is discarded; it does not spawn or persist NPCs/loot or emit tick-driven commands. Full World-owned generation and tick handoff remain target work; see [Automation and Scheduler Runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#active-gaps). Scripts do not persist world topology or directly mutate World Management instance rows. +- Procedural population is not a live NPC/loot handoff: the current population hook calls bounded, seeded `PveEncounterService.generateEvent(...)` for each generated room and discards the returned event. It does not spawn or persist NPCs/loot or emit tick-driven commands. Full World-owned generation and tick handoff remain target work; see [Automation and Scheduler Runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#active-gaps). Scripts do not persist world topology or directly mutate World Management instance rows. - `ScriptQuotaService` enforces fairness quotas and per-script resource limits. ## Document Map diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md index 9e6c9ba36e..eb695221fe 100644 --- a/design/architecture/microservices/automation-scripting-service/api-contracts.md +++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md @@ -85,8 +85,8 @@ On the current public Automation & Scripting API, `workItemId` and `workItemIds` Domain services such as Game Session and Game Logic deliver automation events through event-ingress RPCs (for example `TriggerScriptEvent`). The required identity fields, endpoint ownership, and audit behavior are defined in the [normative scripting contract tables](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields); the following list describes the service-local wire envelope: -- `tenantId`, `gameInstanceId`, `regionId`, and `entityId` for the target runtime context. -- resolved `playableStateScope` for gameplay-originated events so shared versus isolated realm state stays explicit through durable trigger identity, timer follow-up work, and operator read models. +- `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, and `entityId` for the target runtime context when applicable. +- resolved `playableStateScope` for gameplay-originated events as separately persisted, exact-validated policy/routing/authorization/migration-fence evidence. It stays explicit for handler/work fencing and operator read models but is excluded from Trigger Identity, timer-follow-up identity, uniqueness, and deduplication keys; see the [normative identity tables](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). - `regionEpoch` for gameplay/runtime triggers and scheduler triggers so Trigger Identity is fenced across scoped coordination resets. - `scriptEventId` in the normalized applicable Trigger Identity. Its wire requirement follows the [ingress ownership matrix](../../system-architecture-scripting-normative-contract-tables.md#table-1a-event-ingress-scripteventid-ownership-matrix), and it is not a complete idempotency key by itself. - `isDryRun` so live and dry-run/test traffic are always in separate idempotency namespaces. @@ -240,7 +240,7 @@ Target-state replay claim and scope rules for `ReplayDeadLetteredWorkItems`: - **Current admission implementation boundary:** direct V1 schema changes and focused unit proof cover normalized exact-scope/mode/request identity, length-delimited SHA-256 fingerprints, immutable `APPLIED`/`ALREADY_APPLIED` history, exact retry readback, changed-input conflict, read-only `NOT_FOUND`/`ACKNOWLEDGEMENT_UNAVAILABLE` diagnostics, and response fields. Missing durable history remains fail-closed and is never reconstructed from mutable state. 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. Unrelated admission, queue, and workflow gaps remain partial. - `GetAutomationPinConvergence(tenantId, gameInstanceId)` – read-only operator surface for the latest exact pin observation (`observedPinnedScriptPatchVersion`, `observedScriptPinEpoch` as a nullable pair, `lastObservedControlPlaneRequestId` nullable/absent only for a never-pinned semantic `UNPINNED` and atomically associated with that pair, `observedAt`) used as input by admission and scheduler logic, plus freshness flags (`projectionAsOfMs`, `projectionLagMs`, `isProjectionStale`). A stored observation retains its pair and request identity when marked stale. It does not return an admission decision or handler outcome and never replaces the Game Session owner read. - `GetScriptBreakerStatus`, `ListScriptBreakerEvents`, and `ResetScriptBreaker` use the exact tuple, monotonic breaker revision/sample generation, and evidence contract defined by the control-plane API. A new exact patch/script selection starts `CLOSED`; only the operator-authorized, digest-bound, expected-state/revision reset clears that tuple, advances its sample generation, and makes prior samples history-only, with no automatic half-open state. Current status and immutable reset history retain the bounded reset reason beside actor, request, and validation evidence. Exact retries return the stored reset result; the breaker revision fence serializes concurrent trip/reset attempts, and a trip additionally binds the observed sample generation. These breaker surfaces do not alter `GetScriptPatchStatus` readiness or `GetScriptStatus` pre-DSL work semantics. The current proto/implementation exposes none of them. -- `ListScriptScheduleInstances(tenantId, gameInstanceId, ...)` currently returns the resolved `playableStateScope` used when the schedule row was materialized. Target schedule rows, due candidates and claims, timer-audit rows, and any derived scheduler work/dead-letter/replay evidence additionally retain and expose stable `playableStateNamespaceId` as non-identity evidence, revalidate it with the exact namespace/scope and active-instance/region owner binding on materialization, claim, replay, and readback, and fail closed on missing or mismatched evidence. The current schema, proto, implementation, and dead-letter/replay path do not persist or expose that namespace field. +- `ListScriptScheduleInstances(tenantId, gameInstanceId, ...)` currently returns the resolved `playableStateScope` used when the schedule row was materialized. Target schedule rows, due candidates and claims, timer-audit rows, and any derived scheduler work/dead-letter/replay evidence additionally retain and expose stable `playableStateNamespaceId` as the applicable gameplay/runtime namespace identity component; `playableStateScope` remains separately persisted exact-validated policy/routing/authorization/migration-fence evidence and is excluded from schedule, candidate, firing-claim, event-scope, and handler uniqueness/deduplication. Revalidate both with the active-instance/region owner binding on materialization, claim, replay, and readback, and fail closed on missing or mismatched evidence. The current schema, proto, implementation, and dead-letter/replay path do not persist or expose that namespace field. - `GetPluginStatus(tenantId, gameInstanceId, pluginId)` – **target-state read:** returns plugin runtime state (`ENABLED`, `DISABLED`, `DRAINING`, `RELOADING`, `FAILED`), active and pending version IDs, the current committed `pluginActivationEpoch` and `lifecycleRevision`, the last control-plane request id, the last recorded actor principal for the runtime row, separate failure-rate breaker outputs (`breakerState`, bounded `breakerReason`, monotonic `breakerRevision`, and monotonic `breakerSampleGeneration`) for the exact active version/runtime scope, nullable current breaker-reset evidence including bounded immutable `lastResetReason` distinct from lifecycle `statusReason`, and current policy-check freshness (`lastPolicyCheckedAtMs`, `policyCheckStale`). The current proto/implementation returns the state/version and policy/publication fields but does not persist or expose the target activation epoch/lifecycle revision or breaker/reset outputs. - `ListPluginRuntimeEvents(tenantId, gameInstanceId?, pluginId?, pluginState?, breakerState?, activePluginVersionId?, changedAfterMs?, changedBeforeMs?, limit?)` – **target-state read:** returns append-only instance-scoped plugin lifecycle history for activation, drain, disable, policy-reconcile fail-closed transitions, and breaker trip/reset transitions. Breaker trip rows retain exact active-version, policy/window/threshold/count/sample evidence; reset rows retain actor, bounded immutable `resetReason`, request, validation, and sample-generation evidence; lifecycle rows omit those transition-only fields and use separate lifecycle `statusReason`. The current event proto/implementation has no epoch/revision or breaker/reset evidence and remains a narrower history projection. - `GetPluginPolicyConvergence(tenantId, gameInstanceId?, maxResults?)` – the current read inspects enabled plugin runtime states with an active version, optionally narrows them to one game instance, filters them against the current runtime region/region-epoch scope when that scope is available, and reports publication, signer, or component-policy violations plus freshness. The response has no `pluginActivationEpoch` or `lifecycleRevision` fields and cannot serve as ADR 0119 lifecycle-fence proof. diff --git a/design/architecture/microservices/automation-scripting-service/configuration.md b/design/architecture/microservices/automation-scripting-service/configuration.md index 30d99ad169..5f9c67a92c 100644 --- a/design/architecture/microservices/automation-scripting-service/configuration.md +++ b/design/architecture/microservices/automation-scripting-service/configuration.md @@ -27,7 +27,7 @@ For day-to-day operations, environment variables fall into three broad categorie **Target-state retention and recovery:** [ADR 0107](../../decisions/adr-0107-stage-aware-script-dead-letter-recovery.md) requires that a row advertised as recoverable and all of its stage, manifest, evaluated-output, and child-dispatch evidence form one coherent retention bundle. Age/capacity cleanup or explicit purge may remove the whole bundle when eligible, but must not delete supporting evidence independently while leaving the row advertised recoverable; configuration validation covers settings only, while runtime cleanup and explicit purge fail closed on incoherent retained evidence. The bounded `SCRIPT_DEAD_LETTER_MAX_AGE_SECONDS` and `SCRIPT_DEAD_LETTER_MAX_ROWS` controls select cleanup candidates rather than guaranteeing deletion of an ineligible bundle or authorizing partial evidence removal; there is no additional numeric floor. [ADR 0110](../../decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md) keeps timer continuity declarations in authored artifact data rather than a service-wide configuration switch: `SCRIPT_TIMER_CATCH_UP_MAX_FIRINGS_PER_RESUME` applies only to interval schedules, while one-shot recovery uses its durable intent/outcome semantics. -These knobs are the authoritative defaults referenced by the scripting architecture docs: +These knobs are the authoritative settings referenced by the scripting architecture docs. Each row distinguishes a live default from a required target-only setting: - publish-time validation and runtime enforcement share `SCRIPT_OUTPUT_MAX_COMMANDS_PER_RUN`, `SCRIPT_OUTPUT_MAX_COMMANDS_PER_ENTITY_PER_TRIGGER`, and `SCRIPT_OUTPUT_MAX_SERIALIZED_WORK_ITEM_BYTES` as the runtime-cap ceilings, while the artifact-pinned cost metadata/digests determine whether a component graph may publish or run; - the durable quota owner records one full-Trigger-Identity handler admission charge and a separate execution-start marker; `SCRIPT_QUOTA_LIMIT` / `SCRIPT_QUOTA_WINDOW_SECONDS` and the live tenant-tier settings are inputs to those decisions. Queued work holds no capacity; execution uses a separately fenced/reclaimable lease, and `PUBLISH_READINESS` `onLoad` work is isolated; @@ -36,7 +36,7 @@ These knobs are the authoritative defaults referenced by the scripting architect - pin and rollout convergence reads use `SCRIPT_PIN_PROJECTION_STALE_THRESHOLD_MS` to derive the public `isProjectionStale` wire field; internal Java projection summaries use `projectionStale` and map it to that public field rather than exposing a second public field or relying on hardcoded local thresholds; - enabled plugin runtime states are rechecked against current publication, signer-revocation, and component-policy metadata using `SCRIPT_PLUGIN_POLICY_RECONCILE_INTERVAL_SECONDS` and `SCRIPT_PLUGIN_POLICY_RECONCILE_BATCH_SIZE`; plugin-trigger ingress fails closed when the last successful policy check is older than `SCRIPT_PLUGIN_POLICY_STALE_THRESHOLD_SECONDS`; - outbox cleanup and diagnosis for `HANDED_OFF`, `CANCELED`, and `DEAD_LETTERED` rows must follow the documented retention knobs above rather than ad hoc cleanup windows; and -- **Target state only:** an owner-gated queue rebuild may define bounded cadence and scan limits for the derived `automation:queue:*` projection; no current queue-rebuild execution or configuration is bound until that owner/serialization gate exists; and +- **Target state only:** an owner-gated queue rebuild may define bounded cadence and scan limits through `SCRIPT_OUTBOX_QUEUE_REBUILD_INTERVAL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_REBUILD_BATCH_SIZE`, and atomically enforce positive pointer TTL/cap settings through `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY`; no current queue-rebuild execution or configuration is bound until that owner/serialization gate exists, and the live RPUSH-only path does not enforce those pointer bounds; and - the durable evaluator cadence and claim bounds must follow `SCRIPT_OUTBOX_EXECUTION_INTERVAL_SECONDS` and `SCRIPT_OUTBOX_EXECUTION_BATCH_SIZE` rather than ad hoc polling loops. ## Implementation Status @@ -85,6 +85,8 @@ Current live bindings in the service are narrower than the full target-state scr | `SCRIPT_OUTBOX_TERMINAL_CLEANUP_INTERVAL_SECONDS` | Cleanup sweep interval for terminal outbox rows (`HANDED_OFF`, `CANCELED`, `DEAD_LETTERED`) | `300` | Stable operator knob | | `SCRIPT_OUTBOX_QUEUE_REBUILD_INTERVAL_SECONDS` | Target-state-only cadence for an owner-gated bounded rebuild; no current scheduled rebuild is bound | `60` | Internal implementation detail | | `SCRIPT_OUTBOX_QUEUE_REBUILD_BATCH_SIZE` | Target-state-only maximum durable work items inspected per owner-gated rebuild sweep | `200` | Internal implementation detail | +| `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` | Target liveness TTL for each disposable `automation:queue:*` pointer list; the live RPUSH-only path currently ignores this setting | Required; no default | Target-only, not currently consumed; each environment must provide a validated positive value before adoption | +| `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY` | Target maximum pointers retained in one disposable `automation:queue:*` list; the live RPUSH-only path currently ignores this setting | Required; no default | Target-only, not currently consumed; each environment must provide a validated positive value before adoption | | `SCRIPT_OUTBOX_EXECUTION_INTERVAL_SECONDS` | Scheduled interval for the durable work-item execution loop that claims and evaluates pending work | `5` | Stable operator knob | | `SCRIPT_OUTBOX_EXECUTION_BATCH_SIZE` | Maximum claimed work items processed per execution sweep | `50` | Stable operator knob | | `SCRIPT_DEAD_LETTER_MAX_ROWS` | Maximum dead-lettered automation work items retained before cleanup | `100000` | Stable operator knob | 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 c0b9d36b5f..7a2e02d413 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -1,6 +1,6 @@ # Automation & Scripting Service Runtime and Data -This document defines the Automation & Scripting Service runtime model, persistence boundaries, reload semantics, Redis usage, and script work-item lifecycle. +This document defines the Automation & Scripting Service runtime model, persistence boundaries, reload semantics, Redis usage, and pre-DSL trigger/evaluated script work-item lifecycle. ## Implementation Status @@ -23,7 +23,19 @@ The same V2 migration replaces handler work-item and audit identities so authent The current `script_event_ingress_audit` event-scope claim uses branch-specific `INSERT ... ON CONFLICT` claims: instance-scoped rows include their exact runtime identity and positive pin tuple, while pre-instance tenant-readiness `onLoad` rows use the nullable branch without inventing absent optional identity fields. The V5 indexes provide the corresponding positive-epoch instance and pre-instance uniqueness branches. Retained pre-fencing instance rows may keep a null epoch as historical evidence, but no live repository claim can create that shape; duplicate retained identities fail migration preflight for operator reconciliation rather than being deleted. The claim row carries a row-version/lease token. Before quota acquisition, work-item or projection fan-out, and handler-audit persistence, the owner renews that token with an atomic row-version/state check; stale reclaim advances the same fence, so a reclaimed slow owner fails before those effects. The implementation has unit and deterministic mocked concurrency proof for claim/reclaim fencing, but does not yet provide a full database-backed slow-owner/reclaim proof or rollback compensation for external quota counters; those remain implementation and proof gaps. -The command-plan preview boundary in [ADR 0114](../../decisions/adr-0114-command-plan-preview-dry-run-isolation.md) is non-committing: a preview must not persist live `script_work_items`, populate the live automation queue, hand off commands, or perform external side effects. It may persist isolated audit/result evidence containing the exact input identity, fenced snapshot/fixture reference, and ordered plan. The current materialized dry-run path may use the internal pre-DSL work-item/queue shape and persists that dry-run work item, but its live implementation records `finalStage=DSL_EVAL`, `finalOutcome=dry_run_completed`, and `finalReason=dry_run_no_handoff`; the shared terminal-success helper marks its internal `script_work_items.status=HANDED_OFF` even though no Game Session handoff or gameplay-work acceptance occurs. It has not converged on target `DRY_RUN_RESULT` terminology; that internal marker is not target live-work persistence or downstream-handoff evidence, and complete plan-result/input proof is still absent. This is an implementation handoff, not a competing contract. +The current service validates and resolves handlers during admission, persists each admitted handler as a pre-DSL `PENDING_EVALUATION` trigger record, and later lets a scheduled executor claim the record and evaluate the sandboxed DSL; it carries only the narrower read-snapshot token field, does not yet seal the complete handler input manifest, and does not persist the separate evaluated-descriptor layer. Current admission, runtime projection, schedule rows, and handoff also do not propagate `scriptPinEpoch` end to end, so exact-epoch persistence and final fencing remain target-state gaps. The target Automation-owned `pluginActivationEpoch` and owner `lifecycleRevision` are likewise not yet persisted in plugin runtime/status/work records or propagated through handoff, retry, replay, and recovery, so same-version re-enable and same-epoch lifecycle fencing remain implementation and proof gaps. These are implementation and proof gaps; the target lifecycle and manifest contracts below remain normative. + +The live `faction`/`faction_standing` schema and `FactionServiceImpl` currently make Automation the player-reputation writer and derive isolated standing identity from `gameInstanceId`. The target owner is Social & Groups under a stable playable-state namespace; Automation remains a consumer for NPC behavior. Owner migration, retained-row disposition, namespace-stable identity, and focused owner-read proof remain unimplemented. + +The live `script_event_audit` and `script_work_items` schema uniqueness constraints omit plugin provenance, and neither current row shape nor repository identity lookup carries the required resolved `bindingId`. Distinct plugin handlers can therefore alias or collide even though the target full Trigger Identity requires `pluginId`, `pluginVersionId`, and `bindingId` where applicable. A new owner-local migration, aligned jOOQ/repository identity, and focused multi-handler retry/concurrency proof are required; this is current implementation drift, not a change to Trigger Identity authority. + +The command-plan preview boundary in [ADR 0114](../../decisions/adr-0114-command-plan-preview-dry-run-isolation.md) is non-committing: a preview must not persist live evaluated script work items, populate the live automation queue, hand off commands, or perform external side effects. It may persist isolated audit/result evidence containing the exact input identity, fenced snapshot/fixture reference, and ordered plan. The current materialized dry-run path may use the internal pre-DSL trigger-record/queue shape and persists that current pre-DSL trigger record, but its live implementation records `finalStage=DSL_EVAL`, `finalOutcome=dry_run_completed`, and `finalReason=dry_run_no_handoff`; the shared terminal-success helper marks its internal `script_work_items.status=HANDED_OFF` even though no Game Session handoff or gameplay-work acceptance occurs. It has not converged on target `DRY_RUN_RESULT` terminology; that internal marker is not target live-work persistence or downstream-handoff evidence, and complete plan-result/input proof is still absent. This is an implementation handoff, not a competing contract. + +Redis adoption has separate current gaps: the live `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` builders are named in the cache catalog but are not yet all represented in the central reset/ACL ownership inventory, and readiness plus dry-run capacity reservation invokes the shared two-key counter/lease script with untagged keys. The live `automation:queue:{tenantInstanceTag}:*` projection also appends to lists without a pointer TTL or maximum-length bound, so it is not yet proven TTL-only; its current `AutomationRedisKeys` builder accepts raw nonblank IDs and does not prove canonical opaque tuple encoding, delimiter/brace rejection, or collision safety. The latter issues are not same-slot-safe identity proof for Redis Cluster, while the capacity families are unsupported for atomic multi-key use until central ownership registration is complete and the keys use one canonical scope hash tag/Redis Cluster slot, or the reservation is replaced with a single-key design. These are current implementation/proof gaps, not new authority. In the target state, PostgreSQL owns durable automation work, definitions, and persisted charge/admission truth, but the current implementation has no durable charge/admission markers or charge record: `ScriptQuotaServiceImpl`, `ScriptTenantBudgetServiceImpl`, and the readiness/dry-run capacity services make best-effort Redis counter/lease decisions. Current quota, tenant-budget, readiness, capacity, and queue-pointer decisions are therefore Redis best-effort and reset-sensitive; their loss may relax or tighten admission fairness or delay discovery, but cannot change the durable work and definition rows that currently exist. Before claiming the target boundary, register each family with its owner/class/reset behavior, define and enforce the queue retention policy, and either use one canonical encoded tuple builder for every key or prove canonical UUID parsing at every boundary, then add focused retention, collision/brace, same-scope slot, cluster, reset, and durable charge/admission proof. + +The current dry-run and readiness capacity reservations also are not idempotent by work item: each retry generates a new lease token, increments the same counter, and overwrites the prior `(tenantId, workItemId)` lease. Releasing the earlier reservation then fails its token check and leaves one count occupied until expiry. The counters remain heuristic and reset-tolerant, but lease accounting must not leak on repeated reservation attempts; duplicate/retry and release-order proof is absent. + +The current queue consumer has an additional bounded-drain limitation that must remain explicit: `drainWorkItems` and `drainIndexedWorkItemPointers` perform a non-atomic range/read followed by deletion, and the indexed path uses database-wide `KEYS("automation:queue:*")`; it can delete a whole list, including concurrently appended or unreturned pointers, before stopping at `maxPointers`. Durable claim fallback and the scheduled rebuild can recover eligible PostgreSQL rows, so this is projection delay/duplicate risk rather than durable-work authority, but the current path is not a cluster-safe discovery or retention proof. Target enqueue/rebuild must atomically apply `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY`, preserve or durably account for unreturned tails and concurrent appends, use an owner-maintained/cursor-based cluster-safe queue index rather than database-wide `KEYS`, and trigger bounded durable re-drive with exact identity/readback before reset-gate release. The two settings remain environment/service configuration (currently `TBD`); no target support claim is valid until each environment supplies validated positive bounds and focused concurrent-drain, truncation/expiry, cluster, and re-drive proof. ## Architecture and Design Notes @@ -40,7 +52,7 @@ The command-plan preview boundary in [ADR 0114](../../decisions/adr-0114-command - **Target plugin lifecycle state:** Automation persists the current `(pluginVersionId, pluginActivationEpoch, pluginState, lifecycleRevision)` and at most one pending transition with the captured current tuple and fixed target values. The same runtime row separately persists `breakerState` (`CLOSED` or `DISABLED_DUE_TO_ERRORS`), bounded `breakerReason`, monotonic `breakerRevision`, and monotonic `breakerSampleGeneration` for the exact active version/runtime scope; a new active version starts at sample generation `0`, and each reset advances that generation exactly once. Breaker trip transactions compare-and-set the exact active version, observed closed-state revision, and sample generation while atomically appending immutable sample/transition evidence and advancing `breakerRevision` once. Reset transactions compare-and-set the expected disabled state/revision, clear the breaker, advance both `breakerRevision` and `breakerSampleGeneration` once, and atomically append immutable reset evidence; prior-generation samples remain history-only. Breaker transitions do not mutate lifecycle state or counters. Every state-changing lifecycle transition persists/reserves `targetLifecycleRevision = current lifecycleRevision + 1`; epoch-advancing transitions additionally persist/reserve `targetPluginActivationEpoch = current pluginActivationEpoch + 1`. Same-epoch entry to `DRAINING` retains the current `pluginActivationEpoch` while advancing/reserving the next lifecycle revision. The fixed target epoch/revision are bound into the canonical request digest, initiation and completion compare-and-set, idempotent Game Session fence-install command and durable acknowledgement, exact retry, and commit; they are never recomputed after initiation and become current exactly once on commit. - Patch reload now also persists a first durable `script_schedule_definitions` catalog for scheduler-owned handlers such as `onInterval` / `onTimerExpire`. Its current live uniqueness key is `(tenantId, scriptPatchVersion, pluginId, pluginVersionId, scheduleDefinitionId)` with cadence/unit metadata and normalized schedule hash; because core scripts use empty plugin fields, their `scheduleDefinitionId` values are currently patch-wide unique. Observed Game Session pins create durable `script_schedule_instances` rows for the matching `(tenantId, gameInstanceId)` scope, retaining the current exact owner tuple `(scriptPatchVersion, scriptPinEpoch, scriptPinControlPlaneRequestId)`, schedule identity, binding target, and mutable due-point state; schedule reconciliation and firing fail closed on absent or mismatched pin/owner evidence. The pin-owner request ID is retained as owner evidence/correlation and is distinct from any reconciliation operation request ID. `ObserveRuntimeTickProgress` updates the runtime region and due-point fields for tick-aligned schedules, including the next future due tick; wall-clock schedules currently expose `nextDueAt`, which maps to target durable `dueAt` plus projected `nextRunAt`, not to independent deadlines. Current live schedule rows retain `playableStateScope` but not the stable `playableStateNamespaceId`; target rows must retain both, and a missing namespace fails closed rather than being inferred. Target schedule rows also retain the exact pin tuple, and target scheduler identity is scoped by stable owner kind/id as defined by [Scripting Scheduler and Timer Lifecycle](../../system-architecture-scripting-scheduler-and-timers.md#stable-schedule-instance-row-identity), while live region ownership remains a transitional non-empty scope marker and core-script owner identity remains narrower than that target. Richer recovery guarantees and their proof remain implementation gaps. - Authoritative gameplay reads use the durable handler-scoped input manifest owned by the [DSL lifecycle contract](../../system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract). The manifest records bounded trigger facts, pinned artifacts, owner versions/values, causal floor, and seed version for each resolved handler. A `readSnapshotToken` may remain as one owner-specific manifest input or correlation value where the owner contract requires it; it is not universal authority, and retries/recovery must never fetch a fresher value. -- **Target state:** For gameplay-originated events, ingress and durable runtime state must persist the resolved `playableStateScope` and stable `playableStateNamespaceId` alongside `tenantId`, `gameInstanceId`, `regionId`, `regionEpoch`, and `entityId`, so shared-state and isolated-state realms remain distinct through work-item identity, timer/schedule materialization, replay checks, dead letters, and operator reads even when they share the same tenant. `playableStateNamespaceId` is durable playable-state identity; `gameInstanceId` remains the active runtime fence and S3 scope. At the Game Session-to-Automation handoff, Game Session must resolve `playableStateNamespaceId` and `playableStateScope` from the scoped runtime context and the receiving owner must validate the exact `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId, regionId, regionEpoch}` atomically with the enqueue/claim transition before enqueue or execution. The current `script_work_items` schema/model and live ingress/handoff wire carry only `playableStateScope`; they do not yet persist or guarantee `playableStateNamespaceId` or its owner proof, so missing or mismatched authority remains an implementation gap and must fail closed. This namespace/scope evidence is separate from the canonical Command-Handoff Identity and does not redefine that identity. `regionEpoch` is an explicit Trigger Identity dimension and replay fence, not metadata that may be refreshed from the current region later. A retry is the same trigger only when it carries the same epoch. Admission, ownership transfer, handoff, and execution must not rely on a detached compare-then-apply check: the owner that durably claims or applies the work must validate the supplied epoch atomically with that transition, or the handoff must carry an authoritative fence token that the downstream execution owner validates immediately before application. A stale or mismatched event is rejected or made a fenced no-op under its original identity, recorded with a bounded `runtime_scope_changed` reason where an admitted run is canceled, and is never evaluated or reminted under the newer epoch. A producer must emit a new identity against the current epoch when the event is still valid. +- **Target state:** For gameplay-originated events, ingress and durable runtime state persist the resolved `playableStateScope` and stable `playableStateNamespaceId` alongside `tenantId`, `gameInstanceId`, `regionId`, `regionEpoch`, and `entityId`, so shared-state and isolated-state realms remain distinct through trigger/descriptor identity, timer/schedule materialization, replay checks, dead letters, and operator reads even when they share the same tenant. `playableStateNamespaceId` is the durable playable-state uniqueness component; `playableStateScope` is separately retained and exact-validated policy/routing/authorization/migration-fence evidence. `gameInstanceId` remains the active runtime fence and S3 scope. At the Game Session-to-Automation handoff, Game Session resolves `playableStateNamespaceId` and `playableStateScope` from the scoped runtime context and the receiving owner validates the exact `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId, regionId, regionEpoch}` atomically with the enqueue/claim transition before enqueue or execution. The namespace participates in the canonical Trigger and Command-Handoff identities; scope evidence is separate from those uniqueness keys and does not redefine them. **Current implementation gap:** The live ingress/handoff wire does not yet guarantee the namespace/scope fields or their owner proof, so missing or mismatched authority must fail closed. `regionEpoch` is an explicit Trigger Identity dimension and replay fence, not metadata that may be refreshed from the current region later. A retry is the same trigger only when it carries the same epoch. Admission, ownership transfer, handoff, and execution must not rely on a detached compare-then-apply check: the owner that durably claims or applies the work must validate the supplied epoch atomically with that transition, or the handoff must carry an authoritative fence token that the downstream execution owner validates immediately before application. A stale or mismatched event is rejected or made a fenced no-op under its original identity, recorded with a bounded `runtime_scope_changed` reason where an admitted run is canceled, and is never evaluated or reminted under the newer epoch. A producer must emit a new identity against the current epoch when the event is still valid. - Each game’s scripts live in tables keyed by `tenantId`, ensuring automation for one game cannot access another’s data. Derived Redis coordination and index keys must preserve runtime instance isolation as well, not just tenant isolation. - Utilizes the [Shared Libraries](../../system-architecture-shared-libraries.md) for DTO definitions, logging interceptors, and Micrometer metrics. @@ -57,16 +69,16 @@ Tick-driven automation and event handling never use synchronous sagas or Tempora - `script` holds compiled component definitions and version metadata. - `npc_memory` is a live but latent NPC-behavior state family. The baseline schema and repository key it only by `tenantId`, `npcId`, and `key`; they do not carry a stable playable-state namespace or a typed runtime-actor identity. Owner classification and any required mapping/application evidence are not established, so no S1/S2/S3 selection is made. The path is non-admissible for replacement until its owner classification, identity mapping, and focused proof exist; this is not a claim that it is S3 or disposable. -- **Target-state:** Admitted script work items are persisted durably in a PostgreSQL-backed outbox in `PENDING_EVALUATION`, keyed only by the full canonical Trigger Identity plus sequencing fields as needed, including `playableStateScope` and `regionEpoch`; the exact observed `(scriptPatchVersion, scriptPinEpoch)` tuple, captured plugin `pluginActivationEpoch` and owner `lifecycleRevision` where applicable, resolved binding `priorityTag`/`quotaClass`, immutable `lane`, and bounded `cost_class` are execution evidence used for the canonical charge lifecycle. The owner-committed `controlPlaneRequestId` is persisted separately as owner-grounded projection/correlation evidence and retained through reload, convergence, handoff, and recovery; it is not part of Trigger Identity, sequencing, uniqueness, or deduplication. Pre-DSL records retain the sealed immutable handler input manifest, including `priorityTag`, `quotaClass`, `lane`, `cost_class`, `componentCostRegistryDigest`, and `artifactRuntimeCapDigest` where applicable. Gameplay/runtime persistence, handoff, retry/replay, and recovery preserve these values unchanged; missing, changed, or contradictory lane/cost or plugin lifecycle-fence evidence fails closed rather than being inferred or refreshed. +- **Target-state:** Admitted pre-DSL trigger records are persisted durably in a PostgreSQL-backed outbox in `PENDING_EVALUATION`, keyed only by the full canonical Trigger Identity plus sequencing fields as needed, including `playableStateNamespaceId` and `regionEpoch`; the exact observed `(scriptPatchVersion, scriptPinEpoch)` tuple, captured plugin `pluginActivationEpoch` and owner `lifecycleRevision` where applicable, resolved binding `priorityTag`/`quotaClass`, immutable `lane`, and bounded `cost_class` are execution evidence used for the canonical charge lifecycle. The owner-committed `controlPlaneRequestId` is persisted separately as owner-grounded projection/correlation evidence and retained through reload, convergence, handoff, and recovery; it is not part of Trigger Identity, sequencing, uniqueness, or deduplication. `playableStateScope` is persisted and exact-validated alongside the namespace as policy/routing/authorization/migration-fence evidence, but is excluded from Trigger Identity, schedule, and Command-Handoff uniqueness. Where the current repository/schema includes scope in uniqueness, that is current implementation drift and not target identity authority. Pre-DSL records retain the sealed immutable handler input manifest, including `priorityTag`, `quotaClass`, `lane`, `cost_class`, `componentCostRegistryDigest`, and `artifactRuntimeCapDigest` where applicable. Gameplay/runtime persistence, handoff, retry/replay, and recovery preserve these values unchanged; missing, changed, or contradictory lane/cost or plugin lifecycle-fence evidence fails closed rather than being inferred or refreshed. - For scheduler-derived plugin work, the captured `pluginActivationEpoch` is also a tagged input to the durable schedule-candidate/firing-claim identity and therefore transitively to the derived event-scope `scriptEventId`; it remains excluded from handler Trigger Identity and Command-Handoff Identity, while `lifecycleRevision` remains fence-only. Ordinary producer ingress must not fabricate either scheduler-owned field. -- `automation:queue:{tenantInstanceTag}:` keys in Redis buffer indexes or pointers for admitted handler work after its durable `PENDING_EVALUATION` work item is persisted. Each entry includes enough identity to locate the durable work item and must not be treated as an authoritative log of commands. +- `automation:queue:{tenantInstanceTag}:` keys in Redis buffer indexes or pointers for admitted handler work after its durable `PENDING_EVALUATION` pre-DSL trigger record is persisted. Each entry includes enough identity to locate the durable trigger record and must not be treated as an authoritative log of commands. - Queue activity must be surfaced through the canonical observability contract metric families rather than through an unsupported parallel metric surface. - **Current migration drift:** The unauthenticated `PATCH /factions/{id}/reputation` route has been removed from the service-local HTTP port and OpenAPI. The remaining `FactionServiceImpl` is not an exposed route, but it still contains an Automation-owned `faction_standing` writer keyed from `gameInstanceId`; its faction lookup is now tenant-qualified. Removal of the public route does not prove Social ownership, character binding, a null-safe unique standing identity for `{tenantId, playableStateNamespaceId, characterId, factionId}`, or concurrent first-write safety. Before any new caller reaches this service method, the owner migration must converge it on an authenticated, caller-bound Social contract rather than resume Automation standing writes. **Target state:** Social owns durable player faction standing under `{tenantId, playableStateNamespaceId, characterId, factionId}`; see the [Social & Groups runtime/data owner contract](../social-groups-service/runtime-and-data.md#data-model). Automation is read-only for standing and consumes Social's owner read contract to drive NPC morale and aggression behavior. ## Script Lifecycle - Scripts reside in the service database and are versioned along with other game data as described in the design-service versioning process. -- **Target-state lifecycle:** Events from Game Session and other domain services trigger script admission via gRPC. Event/handler admission seals the handler input manifest and durably creates each admitted handler's `PENDING_EVALUATION` work item, then queues its rebuildable pointer; DSL evaluation is later, only after the executor claims the work and the lease/executor-acceptance transaction advances it to `EXECUTING`. +- **Target-state lifecycle:** Events from Game Session and other domain services trigger script admission via gRPC. Event/handler admission seals the handler input manifest and durably creates each admitted handler's `PENDING_EVALUATION` pre-DSL trigger record, then queues its rebuildable pointer; DSL evaluation is later, only after the executor claims the record and the lease/executor-acceptance transaction advances it to `EXECUTING`. - The sandboxed engine limits CPU time and memory for each script to prevent runaway behavior. - After evaluation, bounded command descriptors are staged into the already admitted durable handler work item and handed off for tick enqueue; the `automation:queue:{tenantInstanceTag}:` entry remains a rebuildable pointer rather than a post-evaluation source of truth. - A scheduled durable executor claims persisted `PENDING_EVALUATION` work items, evaluates the current command-emission format, and hands off commands to Game Session for tick enqueue. `automation:queue:*` remains a rebuildable pointer projection rather than the driver of authoritative execution state. In the current legacy materialized dry-run path, the work-item storage status is nevertheless set to `HANDED_OFF` as a terminal compatibility marker even though no Game Session handoff occurs; the authoritative audit remains `finalStage=DSL_EVAL`, `finalOutcome=dry_run_completed`, and `finalReason=dry_run_no_handoff`. This is current implementation drift, not target `TICK_HANDOFF`/`handoff_accepted` semantics; target ADR 0114 previews use an isolated preview result and do not create a live work item. @@ -91,6 +103,8 @@ This behavior ensures that a script patch either becomes the new active version **Target-state recovery evidence:** Automation owns a monotonic `failureGeneration` per `(tenantId, outboxWorkItemId)` and initializes/advances it exactly once in the same atomic transition that enters `DEAD_LETTERED`; exact transition retries/no-ops do not advance it. Dead-letter rows retain the immutable failure stage and current `failureGeneration`, original Trigger Identity, exact patch/epoch, immutable `lane` and bounded `cost_class`, owner-committed `controlPlaneRequestId`, plugin provenance and captured `pluginActivationEpoch`/`lifecycleRevision` where applicable, frozen manifest, immutable evaluated output, and a complete descriptor/child-dispatch ledger keyed by the full Command-Handoff Identity. Per-item request results, recovery claims/attempts, successful-recovery evidence, and `already_recovered` readback bind `(tenantId, outboxWorkItemId, failureGeneration)`; one active claim exists per current generation and stale owners/generations fail CAS. A new request resolves the current failure generation atomically, so older-generation evidence remains immutable and cannot satisfy or block a newer current generation. Per-child recovery state records each child status, its persisted `handoffRequirement`, attempt/claim information, and durable downstream acknowledgement or outcome. The evaluated output and complete ledger are replay input; an evaluated-output or command digest is integrity evidence only and cannot substitute for the retained output or descriptor identity. `outboxWorkItemId`, the parent Trigger Identity, and `scriptEventId` remain correlation-only identifiers and are not child identity. The frozen manifest retains `priorityTag`, `quotaClass`, `lane`, `cost_class`, `componentCostRegistryDigest`, and `artifactRuntimeCapDigest` where applicable; evaluation-stage and post-evaluation recovery reuse that evidence verbatim without recomputing mutable registry, cap, scheduler-policy, or required/optional classification values. Evaluation-stage recovery may retry the original graph; post-evaluation recovery only resumes unfinished children. Missing or contradictory evidence, including missing or changed lane/cost, plugin lifecycle-fence, or handoff-requirement values at handoff, replay, or recovery, remains dead-lettered and fails closed. Schedule reconciliation defaults to cancel-and-recreate, with continuity only when the authored stable identity and compatibility declaration explicitly match. +Ordinary owner-local dead-letter recovery/retry remains non-conflicting routine replay when it only replays the owner’s existing durable PostgreSQL work-item truth. Target `automation:queue:*` queue-pointer rebuild is non-conflicting routine reprojection only through the owner-reconciled `PENDING_EVALUATION` status/owner/CAS gate; current reset/rebuild/resume remains unavailable and must fail closed because the implementation cannot distinguish safe from stale claims. Automation records the owner classification and the evidence for that exemption, including the exact durable identity, source snapshot/cursor, request or output digest, and affected scope; this does not grant maintenance authority. Any maintenance or reset mutation, including one reached from dead-letter recovery or pointer rebuild, must instead carry the unchanged ADR-0085 external maintenance handoff with its exact `operationId`, external maintenance fence/lock binding, classifier, immutable evidence digest, and complete affected scope, or fail closed. + ## Redis Roles and Prefixes - **Coordination Redis participation** @@ -105,7 +119,9 @@ Ownership and durability expectations for Automation & Scripting prefixes: | Prefix | Redis role | Durability / reset tolerance | | --- | --- | --- | -| `automation:queue:{tenantInstanceTag}:*` | Cache/Rate-Limit | Reset-tolerant only in the target state; best-effort cache or queue of automation work-item indexes. **Target state:** loss is recoverable from durable work through the accepted owner/status/CAS gate, initially limited to the safe `PENDING_EVALUATION` path. **Current state:** reset/rebuild and resume are unavailable and must fail closed because the implementation cannot distinguish safe from stale claims; a non-atomic status preflight cannot authorize recovery. | +| `automation:timer:{tenantRegionTag}` | Coordination (target-only, once implemented) | Once implemented, this will be a reset-tolerant derived timer index. Entries retain and exact-validate the complete durable schedule identity in their payload, including `gameInstanceId` and `playableStateNamespaceId` (plus plugin identity when applicable), despite the region-scoped key; loss is repaired from PostgreSQL schedule/claim state and authoritative tick progress. There is no current projection or supported current reset/rebuild guarantee. | +| `script-scheduler:{tenantRegionTag}:lastTickId` | Coordination (target-only, once implemented) | Once implemented, this will be a reset-tolerant scheduler progress hint. The value carries `regionEpoch` and `latestTickId` only; an epoch mismatch is rejected and rebuilt from the authoritative tick heartbeat/progress, and it never owns `streamOffset` or durable schedule identity. There is no current projection or supported current reset/rebuild guarantee. | +| `automation:queue:{tenantInstanceTag}:*` | Cache/Rate-Limit | Reset-tolerant only in the target state; best-effort cache or queue of pre-DSL trigger-record indexes. **Target state:** loss is recoverable from durable work through the accepted owner/status/CAS gate, initially limited to the safe `PENDING_EVALUATION` path. The target applies the configured pointer-liveness TTL and maximum list length atomically on enqueue/rebuild; current RPUSH-only lists have no TTL or bound and remain implementation/proof drift. **Current state:** reset/rebuild and resume are unavailable and must fail closed because the implementation cannot distinguish safe from stale claims; a non-atomic status preflight cannot authorize the target PENDING-only path. Truncation or expiry never settles or drops durable work. | | `automation:quota::` | Cache/Rate-Limit | Reset-tolerant, best-effort quota counters. Dropping these keys temporarily resets budgets but does not affect script correctness or long-term state. | | `automation:tenant-budget::tier:` | Cache/Rate-Limit | Reset-tolerant, best-effort tenant budget counters for live automation execution reservations. Dropping these keys temporarily relaxes tenant fairness but does not affect durable work truth. | | `automation:test:quota::script::tenant`, `automation:test:quota::script::principal:` | Cache/Rate-Limit | Reset-tolerant one-minute dry-run/test admission counters, respectively per tenant/script and per principal/script. They are isolated from live quota and budget families; expiry or reset may temporarily allow another test window but cannot change durable work truth. The Automation service owns both families and only its Cache/Rate-Limit ACL may access them; there is no rebuild because the counters are disposable windows. | @@ -122,17 +138,20 @@ Quota and queue-related caches are best-effort TTL-only caches unless this servi ## Durable Script Work-Item Outbox -To avoid “DSL evaluated successfully but effects were silently dropped”, the service must durably persist and queue each admitted handler's `PENDING_EVALUATION` work item before DSL evaluation or execution acceptance: +To avoid “DSL evaluated successfully but effects were silently dropped”, the service must durably persist and queue each admitted handler's `PENDING_EVALUATION` pre-DSL trigger record before DSL evaluation or execution acceptance: -- **Target state:** Admitted triggers seal the handler input manifest and produce `PENDING_EVALUATION` script work items written to a PostgreSQL-backed outbox table keyed by Trigger Identity plus sequencing fields as needed. -- Target materialized `script_schedule_instances`, resume windows, due candidates, firing claims/audits, timer-generated work items, handoff events, and dead-letter rows preserve the same stable `playableStateNamespaceId` and gameplay `playableStateScope` evidence so scheduler-driven follow-up work stays in the same shared-versus-isolated state namespace as the original admitted event. Namespace evidence remains separate from canonical schedule, Trigger, and Command-Handoff identities; missing or mismatched evidence fails closed rather than being inferred or refreshed. Current schedule rows still lack `playableStateNamespaceId`, as recorded in the implementation-status boundary above. +- **Target state:** Admitted triggers seal the handler input manifest and produce `PENDING_EVALUATION` pre-DSL trigger records written to a PostgreSQL-backed outbox table keyed by the canonical Trigger Identity plus sequencing fields as needed. `playableStateNamespaceId` is the playable-state uniqueness dimension; `playableStateScope` is separately persisted and exact-validated policy/routing/authorization/migration-fence evidence and is excluded from Trigger Identity, schedule, and Command-Handoff uniqueness. Where the current repository/schema includes scope in uniqueness, that is current implementation drift and not target identity authority. +- Target materialized `script_schedule_instances`, resume windows, due candidates, firing claims/audits, timer-generated pre-DSL trigger records, evaluated script work items, handoff events, and dead-letter rows preserve the same stable `playableStateNamespaceId` and gameplay `playableStateScope` evidence so scheduler-driven follow-up work stays in the same shared-versus-isolated state namespace as the original admitted event. The namespace participates in canonical schedule, Trigger, and Command-Handoff identities; `playableStateScope` evidence remains separate from those identities. Missing or mismatched evidence fails closed rather than being inferred or refreshed. Current schedule rows still lack `playableStateNamespaceId`, as recorded in the implementation-status boundary above. - `automation:queue:*` keys are derived coordination indexes that accelerate draining and batching, not the authoritative record of pending work. -- On restart, failover, or Cache/Rate-Limit Redis resets, the target service rebuilds `automation:queue:*` indexes from durable pending items. The current `rebuildPendingWorkItemIndex` also selects `EVALUATING` rows without a stale, owner, or compare-and-set gate, so queue reset/rebuild and resume are unavailable and must fail closed; a non-atomic status preflight cannot authorize the target PENDING-only path. This implementation/proof gap is recorded in the [scripting runtime rebuild contract](../../system-architecture-scripting-runtime-execution.md#rebuild-and-deduplication-rules). +- On restart, failover, or Cache/Rate-Limit Redis resets, the target service rebuilds `automation:queue:*` indexes from durable pending items. The current `rebuildPendingWorkItemIndex` also selects `EVALUATING` rows without a stale, owner, or compare-and-set gate, so queue reset/rebuild and resume are unavailable and must fail closed; a non-atomic status preflight cannot authorize the target PENDING-only path. The current scheduled implementation also uses `PageRequest.of(0, maxItems)` for each rebuild batch, so later eligible rows with missing pointers can be starved when earlier rows already have pointers; this bounded page-0 scan is not a completeness or readback proof. The durable claim fallback remains able to process pending PostgreSQL rows independently. Target reset/rebuild state requires a cursor- or owner-maintained index with an atomic status/owner/CAS gate that proves complete eligible-row coverage before the external maintenance gate is released. This implementation/proof gap is recorded in the [scripting runtime rebuild contract](../../system-architecture-scripting-runtime-execution.md#rebuild-and-deduplication-rules). This enables stage-aware outcomes in `script_event_audit`: the system can distinguish “DSL evaluation succeeded” from “handoff or enqueue succeeded”, and can re-drive delivery where appropriate without re-executing the DSL body for the same trigger. ## Redis Cluster Slotting Rules +- Every Automation-owned multi-key operation must use keys carrying one canonical scope hash tag and therefore resolve to one Redis Cluster slot. Key families without a canonical shared tag are unsupported for atomic multi-key operations. Queue discovery must also avoid database-wide `KEYS`; it must use an owner-maintained index or bounded cursor/read path whose completeness and per-scope coverage are proven across cluster nodes. +- The target `tenantInstanceTag` is an opaque, collision-safe encoding of the complete `(tenantId, gameInstanceId)` tuple. The live builder concatenates raw nonblank strings, so it must not be described as canonical until it either uses the shared encoded/length-prefixed tuple helper or proves canonical lowercase UUID parsing and rejection of separators/braces at every boundary. Focused tests must cover delimiter/brace inputs, collision vectors, and same-scope slot equality. +- The current `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` capacity families are unsupported until their central ownership/reset/ACL registration is complete and their keys use one canonical scope hash tag/Redis Cluster slot, or the cross-key reservation is replaced with a single-key design. - Automation Redis usage must never perform multi-key operations that span both `automation:*` and `tick:*` keys in a single invocation. - Allowed examples: - A Redis operation that touches only `automation:queue:{tenantInstanceTag}:*` keys for one runtime scope. diff --git a/design/architecture/microservices/automation-scripting-service/sandbox-runtime-design.md b/design/architecture/microservices/automation-scripting-service/sandbox-runtime-design.md index 8e92c5c90c..1592da72ed 100644 --- a/design/architecture/microservices/automation-scripting-service/sandbox-runtime-design.md +++ b/design/architecture/microservices/automation-scripting-service/sandbox-runtime-design.md @@ -82,7 +82,7 @@ For the [ADR 0114](../../decisions/adr-0114-command-plan-preview-dry-run-isolati 2. **Sandbox setup and executor acceptance** - The scheduler allocates a **sandbox context** from the sealed handler manifest. The following locally useful categories are not an exhaustive schema; the [canonical read-consistency contract](../../system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract) defines every required field and evidence: - - For instance-bound gameplay/runtime runs, the complete applicable owner/runtime scope (`tenantId`, `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `entityId` when applicable) + - For instance-bound gameplay/runtime runs, the complete applicable owner/runtime scope (`tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `entityId` when applicable) - Tenant/script identity (`scriptId`, `eventType`, `eventSchemaVersion`, `scriptEventId`, and `isDryRun`) - The exact pinned `(scriptPatchVersion, scriptPinEpoch)` tuple for instance-bound gameplay/runtime runs - The applicable component-revocation security-policy fence under [ADR 0116](../../decisions/adr-0116-routine-component-migration-and-explicit-emergency-revocation.md) for any work referencing a revocable component, including embedded/core-script and plugin-backed work @@ -103,7 +103,7 @@ For the [ADR 0114](../../decisions/adr-0114-command-plan-preview-dry-run-isolati 4. **Command staging** - For eligible instance-bound gameplay/runtime runs, successful emitted commands are bounded descriptors staged into the already admitted per-handler durable work item and persisted atomically, then follow the separate durable Game Session handoff path. The already admitted `automation:queue:*` projection remains the pre-evaluation discovery pointer and is not a handoff queue. - Tenant-readiness `onLoad` is outside this descriptor-staging and handoff path. After readiness validation/evaluation it terminates with only platform-owned readiness, audit, and fencing evidence: it emits no gameplay descriptors or dispatch identity, creates no gameplay work, and never calls `EnqueueAutomationCommandIfAbsent`. This is the local sandbox consequence of the canonical [`onLoad` runtime contract](../../system-architecture-scripting-runtime-execution.md#onload-semantics-and-failure-handling). - - For those eligible instance-bound gameplay/runtime runs, target-state handoff through `EnqueueAutomationCommandIfAbsent` gives each emitted command child the complete Command-Handoff Identity: source `(tenantId, gameInstanceId, playableStateScope, regionId, regionEpoch)`, optional distinct target `(targetGameInstanceId, targetPlayableStateScope, targetRegionId, targetRegionEpoch)`, the `automationDispatchId` allocated and persisted by the first atomic durable evaluated-descriptor/outbox commit only when commands are emitted, and a deterministic `commandOrdinal` starting at `0` in canonical emitted-command order. Pre-commit evaluation retries preserve the Trigger/work-item/frozen-input identity and allocate no command-child identity; retries after a winning commit reuse its dispatch ID and ordinals. A valid zero-command evaluation creates no dispatch identity. Game Session deduplicates the complete child identity. The parent Trigger Identity and `outboxWorkItemId` are correlation-only and are excluded from command-child uniqueness and deduplication; they are not substitutes for the complete child identity. The live handoff remains narrower and is not complete child-identity proof; see the [current runtime handoff status](../../system-architecture-scripting-runtime-execution.md#current-implementation-status) and [normative Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state). + - For those eligible instance-bound gameplay/runtime runs, target-state handoff through `EnqueueAutomationCommandIfAbsent` uses the [normative Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state): source `playableStateNamespaceId`/region identity, optional distinct target namespace/region identity, the `automationDispatchId` allocated and persisted by the first atomic durable evaluated-descriptor/outbox commit only when commands are emitted, and a deterministic `commandOrdinal` starting at `0` in canonical emitted-command order. Source and target `playableStateScope` values are separately validated routing/fence evidence, not identity fields. Pre-commit evaluation retries preserve the Trigger/work-item/frozen-input identity and allocate no command-child identity; retries after a winning commit reuse its dispatch ID and ordinals. A valid zero-command evaluation creates no dispatch identity. Game Session deduplicates the complete child identity. The parent Trigger Identity and `outboxWorkItemId` are correlation-only and are excluded from command-child uniqueness and deduplication; they are not substitutes for the complete child identity. The live handoff remains narrower and is not complete child-identity proof; see the [current runtime handoff status](../../system-architecture-scripting-runtime-execution.md#current-implementation-status). - Before constructing each generated command or data-dependent collection for an eligible instance-bound gameplay/runtime run, the engine applies the artifact-pinned conservative prospective serialized-byte bound together with command-count, per-entity, and data-dependent caps. Before atomic persistence, it checks the exact bounded serialized size of the staged descriptors against the pinned ceiling. Any cap exceed is a non-success outcome; all staged output for that handler is discarded and no partial work item or handoff is committed. The evaluator accepts only the artifact-pinned `componentCostRegistryDigest` and `artifactRuntimeCapDigest` plus their embedded payloads as validated by the runtime owner; it does not estimate from a newer local registry. - Eligible instance-bound gameplay/runtime work reaches this stage only after the earlier execution-scheduler selection over queued work. Target-state handoff uses the event-count ceiling (`AUTOMATION_TICK_MAX_EVENTS`) and only documented `automation:*` Redis prefixes for projection and quotas. The Automation & Scripting Service never writes `tick:*` keys directly; it hands off commands to Game Session over internal gRPC so Game Session can enqueue tick commands under its own tick and locking model. Current live capacity enforcement is the aggregate per-tenant, priority-tier reservation described below. diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 65246b825b..a64502c116 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -49,7 +49,7 @@ curl http://localhost:8080/ping - `ListRoomEntities(ListRoomEntitiesRequest) returns (ListRoomEntitiesResponse)` (target-state namespace-carrying response) – returns players, NPCs, and visible items present in a room, scoped by `RoomInstanceRef` and the resolved `playableStateNamespaceId`; PLAYER projections/lookups carry that namespace alongside the current `gameInstanceId` runtime fence. The current adapter remains floor-free and its response lacks `playableStateNamespaceId`, so this namespace boundary is not implemented or proved. - `GetDraftDesignDigest` – returns publish-gating digest for Draft entity templates using typed scope request `GetDraftDesignDigestRequest { tenantId, scope: oneof { versionId, scriptPatchVersion } }`. Entity Management supports `versionId` scope only and must return `UNSUPPORTED_SCOPE` for `scriptPatchVersion`. Minimum response fields are `{tenantId, scope, appliedCommitId, contentDigest, digestSchemaVersion}`. `appliedCommitId` means the highest Game Design commit whose full revision set has been durably applied to the target Draft entity scope. `contentDigest` must cover only version-scoped entity template/binding rows and must exclude live runtime entities and audit/history metadata. -Target-state gameplay mutation RPCs that change item, equipment, or container state accept the canonical `effectId` and its complete structured identity supplied by Game Session durable effect execution. Entity Management validates the `{tenantId, playableStateNamespaceId, gameInstanceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId}` projection before applying the mutation; `{tenantId, effectId}` alone is not a sufficient substitute for the scoped identity. `ApplyActorCondition` requires a dedicated `effectId` as the operation-level replay identity, while `sourceId` remains separate authored/source provenance. Duplicate delivery returns the stored applied/no-op response instead of applying the mutation again. Read-only query RPCs do not require an `effectId`. Equipment occupancy and compatibility additionally require the complete published game-authored vocabulary/body-layout schema and digest; missing, partial, or mismatched schema/mapping evidence fails closed. Current live mutation surfaces may still expose an optional or narrower effect field; that is an implementation gap, not permission to define a competing idempotency contract. +Target-state gameplay mutation RPCs that change item, equipment, or container state accept the canonical `effectId` and its complete structured identity supplied by Game Session durable effect execution. Entity Management validates the `{tenantId, playableStateNamespaceId, gameInstanceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId}` projection before applying the mutation; `{tenantId, effectId}` alone is not a sufficient substitute for the scoped identity. The participant guard also exact-compares the typed operation and immutable `requestDigest`; an enclosing `rootEffectId`, when carried for a generated child, is lineage/reconciliation context only and is not an additional uniqueness dimension. `ApplyActorCondition` requires a dedicated `effectId` as the operation-level replay identity, while `sourceId` remains separate authored/source provenance. Duplicate delivery returns the stored applied/no-op response instead of applying the mutation again. Read-only query RPCs do not require an `effectId`. Equipment occupancy and compatibility additionally require the complete published game-authored vocabulary/body-layout schema and digest; missing, partial, or mismatched schema/mapping evidence fails closed. Current live mutation surfaces may still expose an optional or narrower effect field; that is an implementation gap, not permission to define a competing idempotency contract. Exact allocator and scalar-format details remain non-authoritative in the pending [ADR 0183 proposal](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). The actor-entry contract deliberately does not make `race`, `class`, attributes, abilities, ship configuration, or other RPG-shaped columns platform requirements. Such values are authored components validated against the exact published descriptor/template. A playtest copy has a new fork-local `characterId`; when `sourceCharacterId` is retained, it must carry the immutable `{sourceTenantId, sourcePlayableStateNamespaceId}` binding and remains provenance-only, never authorizing cross-namespace reads or writes or any other identity, ownership, mutation, controller, reconnect, or merge operation. @@ -171,7 +171,7 @@ Only entities approved by the `EntityVisibilityPolicy` are returned; hidden NPCs Under [ADR 0112](../../decisions/adr-0112-typed-bounded-gameplay-effect-extension.md), Entity Management is the canonical owner of actor/effect mutation, resource costs, and cooldown state. It accepts only a validated typed plan or registered effect operation resolved by the owning server-side gameplay path from the exact release-pinned typed effect declaration/reference and digest, preserves the operation/effect replay identity and request digest, and never parses script text, executes caller-supplied DML, or reconstructs targeting policy from a partial request. -`ApplyActorCondition` is the first mutation contract for the same actor-state table. The current implementation validates the concrete mTLS caller and method allowlist, `PlayerExecutionContext`, and playable-state scope before creating an `actor_active_conditions` row with `conditionKey`, `stackCount`, `sourceType`, `sourceId`, optional `expiresAt`, and optional caller-supplied `effectPayloadJson`; accepting that payload directly, and allowing `QueryActorState` to evaluate it into gameplay-visible state, is the transitional gap identified above. Until the target typed request exists, callers using the current wire contract must keep a supplied `sourceId` unique tenant-wide per intended operation/effect because it is also the durable replay marker key. Within that operation, the actor-condition table lookup is narrower—`{tenantId, playableStateKey, characterId, sourceType, sourceId}`—and returns the first matching source row without comparing changed `effectPayloadJson` values. The target contract carries a dedicated `effectId` as the operation-level replay identity under `{tenantId, effectId}`, while `sourceId` remains authored/source provenance and may legitimately recur across separate applications. Target-state replay behavior (not currently enforced by this transitional request) is: a completed duplicate with the same canonical request payload returns the original serialized `ApplyActorConditionResponse` without another condition mutation; an in-progress duplicate returns conflict, payload or operation reuse returns invalid argument, and an unreadable stored response fails internally. Until dedicated `effectId`, canonical request-digest, and stored-response enforcement are live, clients must not rely on those outcomes or on changed-payload conflict detection. This is intended for gameplay-owned actions such as the first transient `blocking` state as well as later spells, consumables, and scripted effects. Reads ignore expired rows, so an expired effect is not restored; the scheduled default-30-second sweep then globally and without a batch bound deletes elapsed `actor_active_conditions` rows. The sweep does not delete separate `entity_mutation_effects` receipts, which `ApplyActorCondition` checks before mutation, but a receipt-retention guarantee across the replay/restore horizon remains unproved. Current behavior makes no concrete duplicate-application or S2-loss claim; target proof still requires explicit S1/S2 classification, dependent-reference/hold checks, and typed target, request-digest, and concurrency enforcement. Callers must still treat the mutation response as the authoritative applied state for that request. +`ApplyActorCondition` is the first mutation contract for the same actor-state table. The current implementation validates the concrete mTLS caller and method allowlist, `PlayerExecutionContext`, and playable-state scope before creating an `actor_active_conditions` row with `conditionKey`, `stackCount`, `sourceType`, `sourceId`, optional `expiresAt`, and optional caller-supplied `effectPayloadJson`; accepting that payload directly, and allowing `QueryActorState` to evaluate it into gameplay-visible state, is the transitional gap identified above. Until the target typed request exists, callers using the current wire contract must keep a supplied `sourceId` unique tenant-wide per intended operation/effect because it is also the durable replay marker key. Within that operation, the actor-condition table lookup is narrower—`{tenantId, playableStateKey, characterId, sourceType, sourceId}`—and returns the first matching source row without comparing changed `effectPayloadJson` values. The target contract carries a dedicated `effectId` as the operation-level replay identity under `{tenantId, effectId}`, while `sourceId` remains authored/source provenance and may legitimately recur across separate applications. Target-state replay behavior (not currently enforced by this transitional request) accepts a completed duplicate only when the persisted participant guard exact-matches the owner-resolved partition, mutation `effectId`, typed operation, exact actor target, and immutable canonical `requestDigest`; an enclosing `rootEffectId` is lineage/reconciliation context rather than a uniqueness dimension. Such a match returns the original serialized `ApplyActorConditionResponse` without another condition mutation; an in-progress duplicate returns conflict, payload or operation reuse returns invalid argument, and an unreadable stored response fails internally. Until dedicated `effectId`, canonical request-digest, and stored-response enforcement are live, clients must not rely on those outcomes or on changed-payload conflict detection. This is intended for gameplay-owned actions such as the first transient `blocking` state as well as later spells, consumables, and scripted effects. Reads ignore expired rows, so an expired effect is not restored; the scheduled default-30-second sweep then globally and without a batch bound deletes elapsed `actor_active_conditions` rows. The sweep does not delete separate `entity_mutation_effects` receipts, which `ApplyActorCondition` checks before mutation, but a receipt-retention guarantee across the replay/restore horizon remains unproved. Current behavior makes no concrete duplicate-application or S2-loss claim; target proof still requires explicit S1/S2 classification, dependent-reference/hold checks, and typed target, request-digest, and concurrency enforcement. Callers must still treat the mutation response as the authoritative applied state for that request. Condition and item-template effect payloads are an internal persisted contract in this first slice. They may contain a top-level `modifiers` array whose entries include `operation`, `target_key`, `value`, optional `scope_kind`, optional `scope_key`, and optional `priority`; supported operations currently match the shared evaluator primitives: `ADD`, `MULTIPLY`, `CLAMP_MIN`, `CLAMP_MAX`, `GRANT_FLAG`, and `GRANT_CONDITION`. diff --git a/design/architecture/microservices/entity-management-service/operations.md b/design/architecture/microservices/entity-management-service/operations.md index 01ba084089..720f62a073 100644 --- a/design/architecture/microservices/entity-management-service/operations.md +++ b/design/architecture/microservices/entity-management-service/operations.md @@ -4,7 +4,7 @@ This document collects Entity Management’s readiness model, tick-lock/tick-ide ## Implementation Status -The complete participant-guard contract described here—root `EffectId`, typed operation and target, immutable `requestDigest`, and complete replay verification—is target-state. The current `EntityMutationEffectReplayService` and schema provide narrower effect/operation replay and do not yet enforce or prove the target mutation-boundary contract. Its duplicate-marker catch also runs inside the surrounding transaction, so a PostgreSQL unique-race loser can inherit an aborted/rollback-only transaction rather than reliably replaying or returning conflict; a conflict-safe insert or isolated marker transaction plus real PostgreSQL concurrent proof is required. [Transaction Strategies](../../system-architecture-transactions.md) is the canonical owner of participant-guard and replay-verification semantics. +The complete participant-guard contract described here—root `EffectId`, typed operation and target, immutable `requestDigest`, and complete replay verification—is target-state. The current `EntityMutationEffectReplayService` and schema provide narrower effect/operation replay and do not yet enforce or prove the target mutation-boundary contract. Its duplicate-marker catch also runs inside the surrounding transaction, so a PostgreSQL unique-race loser can inherit an aborted/rollback-only transaction rather than reliably replaying or returning conflict; a conflict-safe insert or isolated marker transaction plus real PostgreSQL concurrent proof is required. [Transaction Strategies](../../system-architecture-transactions.md) is the canonical owner of participant-guard and replay-verification semantics. The pending [ADR 0183 proposal](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative. The current replacement-validation path is also narrower than the target contract: `ValidateEntityUpgradeMappings` does not yet bind the stable `playableStateNamespaceId`, owner-resolved `playableStateScope`, and active-instance authorization to the exact source/target versions, and the live result may echo a supplied `remapSetId` without locally validating or applying its mapping. This is an implementation/proof gap; the echo is not compatibility or cleanup evidence. @@ -24,23 +24,23 @@ Replacement operations use the stable `playableStateNamespaceId` and owner-resol ## Tick Locking -Target-state Entity Management tick processing acquires Redis locks before mutating entity state using the `tick:{tenantRegionTag}:lock:` key described in the [Redis Architecture](../../system-architecture-redis.md) document, so lock keys share a hash tag with tick queues and pending state. The live implementation remains drift: `TickLockServiceImpl` writes the legacy `tick:lock::` key and derives a private 500–5,000 ms TTL from `game.tick-duration-ms`, without `gameInstanceId`, `regionId`, or the canonical mutation fence. This is not a second lock authority and cannot authorize canonical mutation; see [Runtime and Data](./runtime-and-data.md#redis-role-and-prefixes) for the current/target boundary. The target settings contract in [Tick Concepts & Invariants](../../system-architecture-tick-concepts-and-invariants.md#tick-budget-ttls-and-region-health-conceptual) and [ADR 0073](../../decisions/adr-0073-evidence-calibrated-tick-budgets-and-lock-ttls.md) is owned by the shared resolver: +Target-state tick processing uses the canonical `tick:{tenantRegionTag}:lock:` key described in the [Redis Architecture](../../system-architecture-redis.md) document so lock keys share a hash tag with tick queues and pending state. The live `TickLockServiceImpl` remains implementation drift: it writes the unscoped `tick:lock::` key, derives a private TTL, and does not carry `gameInstanceId`, `regionId`, a shared resolver value, or the canonical mutation fence. This family is registered as current legacy Coordination state in the [Redis reset policy matrix](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary); it cannot authorize canonical mutation and must remain fenced from target reset/admission until the writer is removed or routed through the Game Session/shared helper. Entity Management must not define or retain a second lock authority. The settings contract in [Tick Concepts & Invariants](../../system-architecture-tick-concepts-and-invariants.md#tick-budget-ttls-and-region-health-conceptual) and [ADR 0073](../../decisions/adr-0073-evidence-calibrated-tick-budgets-and-lock-ttls.md) is owned by the shared resolver: - The Game Session Service exposes `game.tick-interval-ms` as the primary pacing knob. - The shared resolver supplies opaque effective values from measured execution, dependency latency, runtime pauses, and recovery evidence. Numeric bounds for those shared values remain pending the owner/settings decision; Entity Management must consume the resolved value and must not introduce `500`/`5_000` bounds or another private formula. -At target, Entity Management treats `lock_ttl_ms` as an opaque value supplied by shared helpers; it does not define its own lock TTL configuration. This keeps locks alive long enough for normal ticks to complete while still bounding the recovery window for stalled ticks. +Target Entity operations treat `lock_ttl_ms` as an opaque value supplied by shared helpers; they do not define a private lock TTL configuration. The current implementation's `game.tick-duration-ms` formula and 500–5,000 ms bounds are not evidence-calibrated and are not proof of the target contract. This keeps target locks alive long enough for normal ticks to complete while still bounding the recovery window for stalled ticks. At target runtime, the Game Session Service compares observed tick execution time to the mode-specific TTL: `tick_lock_ttl_ms{scope_class}` (derived from `lock_ttl_ms`) for `tick_mode="normal"` and `solo_lock_ttl_ms{scope_class}` (derived from `solo_tick_budget_ms`) for `tick_mode="solo"`, as described in the [Tick System design](../../system-architecture-ticks.md#timeout-and-fairness-policy). A bounded `scope_class` p99 ratio that approaches or exceeds a configured fraction of its selected TTL is a detection/escalation signal; it does not identify or classify an individual region. Exact region health and any degraded actionability are resolved from authoritative runtime-health/control-plane records, after which operators may increase the tick interval or simplify per-tick work. Entity Management does not adjust TTLs itself; it relies on the shared helpers and scheduler behavior to keep lock usage within safe bounds. -Entity Management follows the per-command execution phases in the [Tick System design](../../system-architecture-ticks.md#per-command-execution-phases), but each Redis Lua invocation acquires at most one `tick:{tenantRegionTag}:lock:` lock under [ADR 0074](../../decisions/adr-0074-one-entity-lock-per-redis-script.md). Multi-entity invariants use one owning PostgreSQL transaction where a single owner can enforce them, or durable effect/workflow legs with explicit reconciliation across owners; they never use piecemeal multi-lock Redis scripts. If an eligible entity lock is unavailable, Game Session reschedules the work through the canonical failure-class retry path. +Target Entity Management follows the per-command execution phases in the [Tick System design](../../system-architecture-ticks.md#per-command-execution-phases), but each Redis Lua invocation acquires at most one canonical `tick:{tenantRegionTag}:lock:` lock under [ADR 0074](../../decisions/adr-0074-one-entity-lock-per-redis-script.md). Multi-entity invariants use one owning PostgreSQL transaction where a single owner can enforce them, or durable effect/workflow legs with explicit reconciliation across owners; they never use piecemeal multi-lock Redis scripts. If an eligible entity lock is unavailable, Game Session reschedules the work through the canonical failure-class retry path. The live `TickLockServiceImpl` does not yet prove these target phases, scope, or fencing rules. ## Tick Idempotency Target-state Entity Management tick idempotency uses the per-aggregate last-tick state pattern described in the [Tick System and Runtime Design](../../system-architecture-ticks.md#domain-idempotency-rules-timeline-context--owner-guards) document. The live schema does not yet implement this watermark; its current domain-local replay table is `entity_mutation_effects` as recorded in [Runtime and Data](./runtime-and-data.md#implementation-status). - The target-only `entity_tick_state` shadow table is an `S3` instance/region timeline projection. It uses `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, targetAggregateType, entityId)` as its complete lookup key and tracks `(last_region_epoch, last_tick_id)` for that concrete runtime timeline; `playableStateScope` is separately persisted and exact-validated evidence, not a key dimension. For this table, `entityId` is the `targetAggregateId`; entity handlers supply the canonical entity aggregate type. Entity must exact-validate both the owner-resolved namespace and immutable scope evidence before reading or writing this future row; neither is inferred from the entity or instance id. -- `gameInstanceId`, `regionEpoch`, and `tickId` in this projection are runtime and fencing context; they do not define the durable uniqueness of a namespace-backed effect. Replacement replay retains the stable playable-state namespace/scope, the same root `EffectId`, and the same S1/S2 operation and target identity; the disposable watermark is only the concrete runtime timeline guard. +- `gameInstanceId`, `regionEpoch`, and `tickId` in this projection are runtime and fencing context; they do not define the durable uniqueness of an effect. Replacement replay retains the stable playable-state namespace/scope, the same persisted mutation `EffectId` (root or generated child), its enclosing root `EffectId` lineage, and the same S1/S2 operation and target identity; the disposable watermark is only the concrete runtime timeline guard. - Tick-driven handlers that mutate an entity: - resolve and read the target `entity_tick_state` row using the complete `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, targetAggregateType, entityId)` key, exact-validate the separately stored current namespace/scope evidence, and validate active-instance mutation authorization; an aggregate-only, namespace-free, scope-free, or instance-free watermark lookup is invalid; - compare `(last_region_epoch, last_tick_id)` from that exact row with `(currentRegionEpoch, currentTickId)` and treat `>=` as a replay/out-of-order no-op (or validation-only check); and @@ -48,18 +48,18 @@ Target-state Entity Management tick idempotency uses the per-aggregate last-tick The `entity_tick_state` watermark is a single-aggregate claim only. It must not coordinate a multi-aggregate or multi-effect operation by claiming several watermark rows; those operations use the structured operation-level `tick_effect_guard` participant set below. For one aggregate, Entity resolves and claims its watermark row and applies the mutation in the same local transaction. Multiple legitimate effects for one aggregate in one tick must use distinct structured participant guards rather than treating the watermark as an at-most-one-effect gate. -Complex multi-entity operations (for example trades that touch two inventories) use the operation-level effect guard pattern owned by [Transaction Strategies](../../system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory) and referenced by the tick document. They derive the complete target guard set from one stable root `EffectId` and its typed operation/target projections, while retaining the operation’s stable `effectKey` in the explicit ledger/guard projection; they insert or verify every participant guard in the same transaction before applying changes, and treat a conflict as completion only after the complete expected guard set and authoritative target state are present. Those root effect and target guards, not the disposable `entity_tick_state` watermark, own durable S1/S2 replay safety across runtime replacement. A partial conflict must reconcile the original root effect and its participant guard identities or fail closed; it must not be treated as proof that the whole operation already applied. +Complex multi-entity operations (for example trades that touch two inventories) use the operation-level effect guard pattern owned by [Transaction Strategies](../../system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory) and referenced by the tick document. A root operation derives its complete target guard set from one stable root `EffectId`; a generated or derived operation uses its persisted child `EffectId` and retains the enclosing root `EffectId` lineage. In either case, the guard uses the mutation identity and typed operation/target projections while retaining the operation’s stable `effectKey` in the explicit ledger/guard projection; Entity inserts or verifies every participant guard in the same transaction before applying changes, and treats a conflict as completion only after the complete expected guard set and authoritative target state are present. Those mutation effect and target guards, not the disposable `entity_tick_state` watermark, own durable S1/S2 replay safety across runtime replacement. A partial conflict must reconcile the original mutation identity, its enclosing root `EffectId`, and participant guard identities or fail closed; it must not be treated as proof that the whole operation already applied. Examples: - **Damage application** – when a tick instructs Entity Management to apply damage to `entityId`, the handler: - - uses the stable root `EffectId`, derives the typed damage operation/target guard identity, and inserts/verifies the corresponding `tick_effect_guard` row in the same transaction as the HP mutation; the stable `effectKey` remains in the explicit guard/ledger projection; - - treats a guard conflict as a replay only after verifying the complete effect and target state, and otherwise reconciles or fails closed with the original EffectId. Damage does not assume an at-most-one-damage-per-aggregate-per-tick invariant, so the per-aggregate `entity_tick_state` watermark is not sufficient for this path. + - uses the mutation's persisted `EffectId` (the root identity for a root damage mutation or a persisted child identity for a generated/derived damage mutation), derives the typed damage operation/target guard identity, and inserts/verifies the corresponding `tick_effect_guard` row in the same transaction as the HP mutation; the stable `effectKey` remains in the explicit guard/ledger projection; + - treats a guard conflict as a replay only after verifying the complete effect and target state, and otherwise reconciles or fails closed with the original mutation identity and its enclosing root `EffectId` lineage. Damage does not assume an at-most-one-damage-per-aggregate-per-tick invariant, so the per-aggregate `entity_tick_state` watermark is not sufficient for this path. - **Trade between two entities** – when a tick performs a trade between `fromEntityId` and `toEntityId`: - - **Target state:** the complete Command-Handoff Identity identifies an admitted automation command and is an input to allocating or looking up that command's stable root `EffectId`; it does not replace the effect identity or participant guards. `(automationDispatchId, commandOrdinal)` is only that command identity's dispatch-group suffix and must be interpreted with the complete source/target scope; a non-automation command instead uses its admitted `commandId`. `scriptEventId`, participant/item fields, and mutable payload text are never fallback identities. Every retry and owner commit preserves the resulting root `EffectId`, typed operation/target projections, and immutable request digest. The live Game Session handoff does not yet carry the full automation command identity end to end, so the current path uses the admitted `commandId` and available persisted work-item/dispatch fields; it must reject a missing command identity rather than synthesize one from the participants. This target gap is tracked under `AS-1.5` in the [automation and scheduler runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status); - - before encoding, the handler validates every identity-bearing and typed field against its declared type and domain; it does not encode malformed input, fallback identities, or alternate textual spellings. Quantity is parsed as its declared numeric type and rendered as canonical base-10 decimal, so semantically equal values such as `1` and `01` produce identical bytes; - - the handler serializes the admitted identity, the stable per-effect trade discriminator, and the validated canonical fields in a fixed versioned order using canonical UTF-8 length-prefixed fields, for example `trade:v1|:|:|:|:|:|:`; the exact resulting bytes are the retry identity and must be reused unchanged, while sibling effects from one command and separate admitted trades remain distinct; + - **Target state:** the complete Command-Handoff Identity identifies an admitted automation command and is an input to allocating or looking up that command's stable root `EffectId`; it does not replace the effect identity or participant guards. `(automationDispatchId, commandOrdinal)` is only that command identity's dispatch-group suffix and must be interpreted with the complete source/target scope; a non-automation command instead uses its admitted `commandId`. `scriptEventId`, participant/item fields, and mutable payload text are never fallback identities. Every retry and owner commit preserves the resulting root identity, typed operation/target projections, and immutable request digest. The live Game Session handoff does not yet carry the full automation command identity end to end, so the current path uses the admitted `commandId` and available persisted work-item/dispatch fields; it must reject a missing command identity rather than synthesize one from the participants. This target gap is tracked under `AS-1.5` in the [automation and scheduler runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status); + - **Illustrative proposal only (not an accepted canonical encoding):** before encoding, the handler would validate every identity-bearing and typed field against its declared type and domain; it would not encode malformed input, fallback identities, or alternate textual spellings. Quantity would be parsed as its declared numeric type and rendered as canonical base-10 decimal, so semantically equal values such as `1` and `01` produce identical bytes. The exact scalar/encoding contract remains pending human review in ADR 0182; + - **Illustrative proposal only (not an accepted canonical encoding):** the handler would serialize the admitted identity, the stable per-effect trade discriminator, and the validated canonical fields in a fixed versioned order using canonical UTF-8 length-prefixed fields, for example `trade:v1|:|:|:|:|:|:`. If later accepted, the exact resulting bytes would be the retry identity and would be reused unchanged, while sibling effects from one command and separate admitted trades would remain distinct; the pending ADR 0183 proposal is not an implementation or target-state requirement; - no canonical one-trade-per-`(fromEntityId,toEntityId,itemId)`-per-tick invariant exists, so the participant/item tuple alone cannot be the effect key; - - it inserts one complete `(tenantId, gameInstanceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType=INVENTORY, targetAggregateId)` `tick_effect_guard` storage projection, linked to the root `EffectId` and participant guard identity, for each affected inventory aggregate before moving items between inventories; and - - on any primary-key conflict, it verifies that guard projections for both affected inventories and the corresponding inventory state are complete and consistent; only then is the trade an already-applied no-op. A partial guard set reconciles the original root effect and both participant guard identities rather than being accepted as completion. + - it inserts one complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, effectId, rootEffectId, typedOperation, targetAggregateType=INVENTORY, targetAggregateId)` `tick_effect_guard` storage projection, linked to the mutation's persisted root-or-child `EffectId` and its enclosing root lineage, for each affected inventory aggregate before moving items between inventories. The S1/S2 participant-guard uniqueness tuple is `(tenantId, playableStateNamespaceId, effectId, typedOperation, targetAggregateType, targetAggregateId)`; `playableStateNamespaceId` is its canonical partition/key component, while `playableStateScope` is separately persisted immutable and exact-validated policy/routing/authorization/migration-fence evidence. `gameInstanceId`, `regionId`, `regionEpoch`, `tickId`, `effectKey`, and `rootEffectId` are active-runtime, descriptor, timeline, or lineage evidence, not uniqueness dimensions; and + - on any primary-key conflict, it verifies that guard projections for both affected inventories and the corresponding inventory state are complete and consistent; only then is the trade an already-applied no-op. A partial guard set reconciles the original mutation identity, its enclosing root `EffectId`, and both participant guard identities rather than being accepted as completion. 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 a1c5ba24ba..3126641e6f 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -29,13 +29,13 @@ This document defines Entity Management’s runtime model, persistence ownership - The target persistence design applies tenant- and namespace-bound optimistic version CAS to avoid conflicting updates on the same entity; the current character update path is not proof of that invariant (see Implementation Status). - Entity Management instances are intended to be replaceable workers over authoritative persistent state and documented caches. Item, inventory, containment, and character data that must survive instance loss belongs in the service-owned database rows and cache invalidation model, not as the sole authoritative copy in one process. - Database writes are deferred and batched for ordinary entity updates, not triggered on every gameplay action. The Game Session Service coordinates real-time updates using Redis; the database is normally updated when ticks complete. -- Spatial containment mutations that participate in cross-service effects are the exception: before Entity Management acknowledges a spatial `EffectId` back to Game Session, it must durably flush the effect’s idempotency guard plus the affected containment/container rows for that effect within the same local transaction. A participant acknowledgement must never be emitted for Redis-only staged state. -- Target-state cross-service participant guards use a structured root `EffectId`, typed operation, target aggregate, and immutable request digest; matching retries return the durable result, while an operation, target, or digest mismatch fails closed. This target guard is not the current domain-local replay table described above. +- Spatial containment mutations that participate in cross-service effects are the exception: before Entity Management acknowledges a spatial mutation's persisted `EffectId` (the root `EffectId` for a root effect or the persisted child `EffectId` for a generated child effect) back to Game Session, it must durably flush the effect’s idempotency guard plus the affected containment/container rows for that effect within the same local transaction. A participant acknowledgement must never be emitted for Redis-only staged state. +- Target-state cross-service participant guards use the persisted mutation `EffectId` (the root `EffectId` for a root mutation or the persisted child `EffectId` for a generated child mutation), typed operation, target aggregate, and immutable request digest; any enclosing `rootEffectId` is lineage and reconciliation context only. Matching retries return the durable result, while an operation, target, or digest mismatch fails closed. This target guard is not the current domain-local replay table described above. The pending [ADR 0183 proposal](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative. - The target design reduces write frequency and contention, making optimistic version CAS a natural fit because most entities are updated by only one process at a time and conflicts are rare; it remains target-only until the predicates, affected-row checks, and concurrent proof exist. - Item transfers and other gameplay actions span services but execute within ticks using Redis scripts for rollback. Sagas are reserved for non-gameplay workflows. See [Transaction Strategies](../../system-architecture-transactions.md). - For long-running, non-gameplay workflows such as publishing a game version, this service participates as a domain step in durable publish workflows coordinated by the Game Design Service as described in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). - **Target state:** Entity-owned tables carry a `tenantId` column wherever the row is a tenant-isolation boundary, and service methods enforce that tenant predicate; Redis keys mirror this prefix. **Current exceptions:** the live `inventory` and `character_equipment` tables have no `tenant_id` and obtain isolation by joining their `character_id` to `characters.tenant_id`; `crafting_ingredients` has no `tenant_id` and is reached through its tenant-owned `crafting_recipes` parent. The current `CraftingRecipeRepository.findWithIngredientsById` lookup is ID-only, so it does not itself prove a tenant predicate even though tenant-scoped list methods select recipe IDs first. These exceptions and the holder/containment cleanup gaps above mean the target all-table/filtering claim is not current proof. Details are in [Multi-Tenancy](../../system-architecture-multi-tenancy.md). -- Durable playable state that survives runtime replacement is keyed by `(tenantId, playableStateNamespaceId)` plus the applicable domain object identity and is authorized against the separately validated immutable `playableStateScope` and currently active `gameInstanceId`; `gameInstanceId` alone is reserved for explicitly disposable S3 runtime families. At target, S1/S2 durable storage identity is `{tenantId, playableStateNamespaceId, domainObjectId}` and omits both routing scope and `gameInstanceId`. This storage identity is distinct from cross-service effect participant replay/deduplication identity, which uses a structured root `EffectId`, typed operation, exact target aggregate, and immutable request digest. Within that participant record, `playableStateScope`, `gameInstanceId`, and `effectKey` are projection/validation metadata, not participant uniqueness; other service-local idempotency keys remain operation-specific. Only explicitly S3 rows use `gameInstanceId` as part of durable identity. The namespace is resolved by the realm/lifecycle contract and is never inferred from an entity id, Redis key, or caller-supplied remap identifier. See [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). +- Durable playable state that survives runtime replacement is keyed by `(tenantId, playableStateNamespaceId)` plus the applicable domain object identity and is authorized against the separately validated immutable `playableStateScope` and currently active `gameInstanceId`; `gameInstanceId` alone is reserved for explicitly disposable S3 runtime families. At target, S1/S2 durable storage identity is `{tenantId, playableStateNamespaceId, domainObjectId}` and omits both routing scope and `gameInstanceId`. This storage identity is distinct from cross-service effect participant replay/deduplication identity, which uses the persisted mutation `EffectId` (root or generated child), typed operation, exact target aggregate, and immutable request digest; generated children retain their root `EffectId` for lineage and reconciliation. Within that participant record, `playableStateScope`, `gameInstanceId`, and `effectKey` are projection/validation metadata, not participant uniqueness; other service-local idempotency keys remain operation-specific. Only explicitly S3 rows use `gameInstanceId` as part of durable identity. The namespace is resolved by the realm/lifecycle contract and is never inferred from an entity id, Redis key, or caller-supplied remap identifier. See [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). - `playableStateScope` is accepted only as the realm/lifecycle owner's authoritative resolved snapshot or attestation. Callers cannot select or derive it, and Entity validates the exact immutable `{playableStateNamespaceId, playableStateScope}` pair before create or update; a scope change for an existing namespace is rejected rather than reinterpreting or splitting durable state. The `{tenantId, playableStateNamespaceId, characterId}` key is the stable actor storage identity, while `{tenantId, accountId, playableStateNamespaceId}` is the auto-provision actor-uniqueness identity; the separate operation replay guard uses `{tenantId, playableStateNamespaceId, accountId, autoProvisionRequestId}` and binds the exact `mutationDigest`. Neither identity reinterprets scope. `gameInstanceId` remains only the active-instance authorization fence. See [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). - Gameplay-facing gRPC endpoints do not parse JWT tokens. The Game Session Service injects identity context using `SessionContext` and may request a new JWT from the Account Service if a player's roles change. It does not validate tokens for gameplay. Traffic between services still uses mutual TLS certificates as outlined in the [Security Architecture](../../system-architecture-security.md). - Design-time writes are a separate surface: @@ -360,7 +360,7 @@ Equipment is intentionally not modeled as "just another bag position": - The complete-schema and fail-closed behavior in the following contract is target state, not current implementation; current missing-schema and unknown-layout bootstrap fallback gaps are recorded in the [Entity Management README](./README.md) and [Item & Equipment Balancing Tools](../game-design-service/item-equipment-balancing.md#target-equipment-schema-requirements). - Game Design owns the complete published equipment vocabulary/body-layout schema and its digest. Entity Management consumes that exact schema for occupancy and compatibility checks; all missing, partial, or mismatched vocabulary or mapping evidence is rejected and validation fails closed. It does not provide a platform-global slot fallback. Replacement cutover remaps bindings only through the owner-validated mapping contract; profiles materialize authored equipment content rather than supplying runtime defaults. See [ADR 0127](../../decisions/adr-0127-game-authored-equipment-layouts-with-fail-closed-publication.md). -The target inventory/equipment operation context for a durable holder or binding is `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId, holderRef, itemInstanceId, itemDefinitionId, equipmentBindingId?, slotKey?}`, with one typed `holderRef` for each source, destination, or equipment owner required by the operation. A holder reference is a closed tagged union: character inventory or equipment carries `CHARACTER {characterId}`; NPC, pet, or summon ownership carries `ACTOR {actorId}`; an ordinary bag, chest, corpse, bank, vendor stock, or nested holder carries `CONTAINER {containerInstanceId}`; and room-ground storage carries `ROOM_GROUND {roomInstanceId, containerInstanceId}`. `characterId` is therefore required only for character-owned inventory or equipment and must not be fabricated for another holder kind. For namespace-backed S1/S2 inventory, character, and equipment state, durable storage identity is `{tenantId, playableStateNamespaceId, ...domainObjectId}` and omits both `playableStateScope` and `gameInstanceId`; those two values are validated separately as immutable routing/authorization evidence and the active-instance fence. Cross-service effect participant replay/deduplication identity is separate and uses a structured root `EffectId`, typed operation, exact target aggregate, and immutable request digest; `playableStateScope`, `gameInstanceId`, and `effectKey` are projection/validation metadata, not participant uniqueness. Other service-local idempotency keys remain operation-specific. Explicitly instance-scoped S3 holders instead include `gameInstanceId` in durable identity. Future proto and OpenAPI surfaces must carry the same typed holder-reference union consistently, but current surfaces do not yet carry this complete operation context on every inventory/equipment read or mutation, so this is a target contract only: this ADR parcel does not add wire fields, regenerate protos, or change runtime lookup behavior. +The target inventory/equipment operation context for a durable holder or binding is `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId, holderRef, itemInstanceId, itemDefinitionId, equipmentBindingId?, slotKey?}`, with one typed `holderRef` for each source, destination, or equipment owner required by the operation. A holder reference is a closed tagged union: character inventory or equipment carries `CHARACTER {characterId}`; NPC, pet, or summon ownership carries `ACTOR {actorId}`; an ordinary bag, chest, corpse, bank, vendor stock, or nested holder carries `CONTAINER {containerInstanceId}`; and room-ground storage carries `ROOM_GROUND {roomInstanceId, containerInstanceId}`. `characterId` is therefore required only for character-owned inventory or equipment and must not be fabricated for another holder kind. For namespace-backed S1/S2 inventory, character, and equipment state, durable storage identity is `{tenantId, playableStateNamespaceId, ...domainObjectId}` and omits both `playableStateScope` and `gameInstanceId`; those two values are validated separately as immutable routing/authorization evidence and the active-instance fence. Cross-service effect participant replay/deduplication identity is separate and uses the mutation's persisted `EffectId` (root or generated child), typed operation, exact target aggregate, and immutable request digest; generated children retain their root `EffectId` for lineage and reconciliation. `playableStateScope`, `gameInstanceId`, and `effectKey` are projection/validation metadata, not participant uniqueness. Other service-local idempotency keys remain operation-specific. Explicitly instance-scoped S3 holders instead include `gameInstanceId` in durable identity. Future proto and OpenAPI surfaces must carry the same typed holder-reference union consistently, but current surfaces do not yet carry this complete operation context on every inventory/equipment read or mutation, so this is a target contract only: this ADR parcel does not add wire fields, regenerate protos, or change runtime lookup behavior. This keeps the platform compatible with games that need unusual body plans or attachment models such as horns instead of hands, asymmetric limbs, species-specific slot topologies, or non-humanoid wearable layouts. diff --git a/design/architecture/microservices/game-design-service/modding-framework.md b/design/architecture/microservices/game-design-service/modding-framework.md index 2f254424d4..acc4c98c03 100644 --- a/design/architecture/microservices/game-design-service/modding-framework.md +++ b/design/architecture/microservices/game-design-service/modding-framework.md @@ -178,7 +178,7 @@ The exact Trigger Identity, evaluated-descriptor recovery, Command-Handoff Ident - Each plugin trigger has one logical evaluation per full applicable Trigger Identity. Before `EVALUATED_COMMITTED`, infrastructure recovery may re-enter the DSL only under that same identity and must converge on the same durable work item and command-child identities; after that boundary, recovery replays durable descriptors without re-entering the graph. `scriptEventId` is one field of Trigger Identity, not the complete key. Each resolved live handler invocation has one `script_event_audit` row, and the current legacy materialized dry-run/test handler path likewise records one handler row for its terminal result. Target ADR 0114 command-plan previews use the isolated preview result/audit surface or return the result directly and do not create a handler audit row; command attempts and outcomes are child handoff records keyed by the complete Command-Handoff Identity. - Recurring and advisory plugin timers such as `onInterval` (or an advisory `onTimerExpire`) are **best-effort** under their declared recovery policy. Individual firings may be skipped or delayed when per-script quotas, per-tenant budgets, or cluster ceilings are reached, and skipped firings are not backfilled beyond bounded `COALESCE_ONE` behavior. A correctness-bearing one-shot timer instead persists durable intent outside Redis; physical execution may be at least once and replay-safe, while the same logical identity converges to one logical terminal outcome. -- Recurring/advisory plugin logic must therefore tolerate missed or delayed events (for example, by recomputing from current world state rather than assuming every interval executed). Every emitted command remains deduplicated and replay-selectable at child handoff under the complete Command-Handoff Identity: complete source runtime scope, optional `targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, and `targetRegionEpoch` only when the command targets a distinct runtime scope, persisted `automationDispatchId`, and deterministic `commandOrdinal`; same-instance handoffs omit every optional target field. The complete parent Trigger Identity, including plugin `bindingId` when applicable, is retained for correlation only. Downstream authoritative effect idempotency instead uses the stable root `EffectId`, typed operation, and exact target aggregate, with the immutable request digest stored and compared; a conflicting operation, target, or digest fails closed. `automationDispatchId` is reused across retries but is not globally unique, and `scriptEventId` alone is insufficient for fan-out commands; follow the [canonical scripting contract tables](../../system-architecture-scripting-normative-contract-tables.md). +- Recurring/advisory plugin logic must therefore tolerate missed or delayed events (for example, by recomputing from current world state rather than assuming every interval executed). Every emitted command remains deduplicated and replay-selectable at child handoff under the [canonical Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state), whose source and applicable distinct target namespace/region identity is separate from the server-derived scope evidence; same-instance handoffs omit every optional target field. The complete parent Trigger Identity, including plugin `bindingId` when applicable, is retained for correlation only. Downstream authoritative effect idempotency instead uses the persisted mutation `EffectId` (the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child mutation), under the owner-declared participant-guard partition (S1/S2: tenant plus `playableStateNamespaceId`; explicitly classified S3: tenant plus `gameInstanceId`), with separately validated `playableStateScope` and active-instance fence evidence, together with the typed operation, exact target aggregate, and immutable request digest stored and compared; a conflicting operation, target, or digest fails closed. `automationDispatchId` is reused across retries but is not globally unique, and `scriptEventId` alone is insufficient for fan-out commands. - Before plugin work is evaluated and again before handoff, Automation revalidates the captured exact Game Session `(scriptPatchVersion, scriptPinEpoch)` tuple against current authoritative state for the same `(tenantId, gameInstanceId)` runtime scope, together with the exact `(pluginId, pluginVersionId, bindingId)` and scoped Automation-owned `(pluginActivationEpoch, lifecycleRevision)` fence; see [Scripting Contracts §8](../../system-architecture-scripting-contracts.md#8-plugin-version-fencing-and-control-plane-scope). Already-terminal work is unaffected; no new admission proceeds without fresh signer-policy and Game Session authority, and immediately before any final side effect the applicable execution owner revalidates the exact plugin provenance, current activation/lifecycle, component policy, capability grant, signer/publication evidence, `(pluginActivationEpoch, lifecycleRevision)`, and Game Session tuple. Routine component-policy reclassification uses the captured admission decision for already-admitted work and does not invalidate it; final-fence rejection or containment of admitted work requires the independent component-revocation fence and explicit audited emergency workflow. Missing, stale, contradictory, or unavailable authority remains a separate fail-closed condition under the stage-specific dispositions below. Specifically unavailable signer policy/evidence retains `signer_policy_unavailable` on its stage-specific response/audit surface, while an unavailable authoritative runtime/fence read keeps unresolved work fenced and retryable as `authority_unavailable`. A present-but-different activation epoch fails closed with `plugin_activation_epoch_mismatch`; a proven plugin tuple/binding or lifecycle-evidence mismatch uses `plugin_binding_mismatch`; signer or revocation mismatches remain durably terminal/ineligible with their specific canonical dispositions. See [Scripting Runtime Execution](../../system-architecture-scripting-runtime-execution.md#version-fencing-and-rollback-safety), the [scripting outcome contracts](../../system-architecture-scripting-normative-contract-tables.md#table-2-script_event_audit-stages-and-outcomes), and the [Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state) owner contracts. These guarantees ensure that plugins do not rely on stronger delivery semantics than the underlying scripting engine provides and that their behavior remains predictable under load. @@ -354,7 +354,7 @@ Design-time publication and runtime activation are separate: - **Disable after drain** – reserves a same-epoch `targetLifecycleRevision = current lifecycleRevision + 1` for `DRAINING` without making it current, installs that exact target through Game Session, and waits for durable acknowledgement before committing the Automation owner state/history/revision. Once `DRAINING` is committed, only already-admitted work whose winning admission/fence CAS durably committed the immediately preceding `ENABLED` revision before the durable Automation-owned `DRAINING` admission barrier was created may complete within the bounded drain policy; capture or observation alone is insufficient. At bounded completion or forced timeout, it independently reserves `targetPluginActivationEpoch = current pluginActivationEpoch + 1` and `targetLifecycleRevision = current lifecycleRevision + 1` from the committed owner row for `DISABLED`, installs and durably acknowledges that exact target through Game Session, then commits the Automation owner state/history/epoch/revision. New triggers are rejected once draining begins and cleanup remains asynchronous. See [ADR 0119](../../decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md) for the single canonical drain exception rather than repeating its full fence contract here. - Updating a plugin involves setting a new `pendingVersionId`, loading and validating the new plugin graphs and bindings, reconciling plugin-owned timers and other derived scheduler state, and then atomically switching `activeVersionId` if validation succeeds. If validation or activation-state reconciliation fails, the new version is marked `FAILED`, `activeVersionId` remains unchanged, and triggers for the failed version are rejected at admission with an appropriate `finalOutcome` (for example, `version_unavailable` or `plugin_version_failed`). -Plugin triggers share the same Trigger Identity and `scriptEventId` lifecycle as regular scripts. Pre-handler admission outcomes are recorded in `script_event_ingress_audit` and create no handler row. Each resolved live handler invocation has one `script_event_audit` row with the required Trigger Identity fields (including `tenantId`, `gameInstanceId`, and for gameplay/runtime triggers `regionEpoch`) plus `pluginId` / `pluginVersionId` and stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`) so operators can correlate plugin behavior with publish and enable/disable operations and still distinguish “DSL evaluated” from “accepted into tick queues”. The current legacy materialized dry-run/test handler path also records one handler audit row for its terminal result. Target ADR 0114 command-plan previews instead use the isolated preview result/audit surface or direct authorized result path and never create a handler row. Per-command acceptance, retry, and downstream outcomes belong in handoff child records keyed by the complete Command-Handoff Identity (source/target runtime scope plus `automationDispatchId` and `commandOrdinal`), not by dispatch ID alone and not in extra handler audit rows. The parent Trigger Identity and `outboxWorkItemId` remain correlation-only. +Plugin triggers share the same Trigger Identity and `scriptEventId` lifecycle as regular scripts. Pre-handler admission outcomes are recorded in `script_event_ingress_audit` and create no handler row. Each resolved live handler invocation has one `script_event_audit` row with the required Trigger Identity fields (including `tenantId`, `gameInstanceId`, and for gameplay/runtime triggers `playableStateNamespaceId` and `regionEpoch`) plus separately persisted exact-validated `playableStateScope` policy/routing/authorization/migration-fence evidence, `pluginId` / `pluginVersionId`, and stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`) so operators can correlate plugin behavior with publish and enable/disable operations and still distinguish “DSL evaluated” from “accepted into tick queues”. The current legacy materialized dry-run/test handler path also records one handler audit row for its terminal result. Target ADR 0114 command-plan previews instead use the isolated preview result/audit surface or direct authorized result path and never create a handler row. Per-command acceptance, retry, and downstream outcomes belong in handoff child records keyed by the complete Command-Handoff Identity (source/target runtime scope plus `automationDispatchId` and `commandOrdinal`), not by dispatch ID alone and not in extra handler audit rows. The parent Trigger Identity and `outboxWorkItemId` remain correlation-only. At handler admission, before evaluation or handoff, a plugin handler must prove and capture `breakerState=CLOSED` for the exact active `pluginVersionId` and runtime scope. That captured admission decision remains valid through evaluation and handoff; a later breaker trip blocks only newly resolved handlers and does not retroactively cancel accepted work. A disabled breaker is recorded as the bounded handler admission outcome above; it cannot be inferred from or folded into the lifecycle `pluginState`. @@ -389,7 +389,7 @@ Handler identity and ordering: - Trigger Identity, dedupe, audit, quota attribution, timer ownership, and drain/disable cleanup must retain `bindingId` alongside `pluginId` and `pluginVersionId` whenever the unit of work is binding-scoped. - Runtime ordering delegates to the shared [canonical stable handler-order identity and field-wise comparator](../../system-architecture-scripting-dsl-reference-and-lifecycle.md#canonical-stable-handler-order-identity): the total key is `(orderIndex, normalized finite handler-kind rank, canonical stable handler-order identity)`, with `SCRIPT` before `PLUGIN` by default unless an operator-controlled policy places `PLUGIN` ahead; designers cannot control that rank. For plugin handlers, that shared identity includes `(pluginId, pluginVersionId, bindingId)`; `bindingId` is the immutable manifest binding identity. Duplicate identical normalized total keys are rejected before `handlerSequence` assignment. - For non-exclusive fan-out, Automation assigns a durable `handlerSequence` from that order and preserves it through handler work, command handoff, and final application. Plugin execution priority and worker timing do not override semantic handler order. -- At most one binding in the complete resolved handler set for the full applicable [Trigger Identity scope](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) may have `requiresExclusiveEvent=true`. For instance-bound events, that scope includes `tenantId`, `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, concrete target identity, `eventType`, and `eventSchemaVersion` as applicable. Tenant-readiness `onLoad` uses the explicit pre-instance exception: it is tenant-scoped and omits instance, playable-state, region, and entity fields. An authorized exclusive binding is selected before fan-out and becomes the sole handler; no core-script or plugin sibling runs before or after it, and failure does not cause sibling fallback. +- At most one binding in the complete resolved handler set for the full applicable [Trigger Identity scope](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) may have `requiresExclusiveEvent=true`. For instance-bound events, that scope includes `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`, concrete target identity, `eventType`, and `eventSchemaVersion` as applicable. `playableStateScope` remains separately persisted and exact-validated as policy/routing/authorization/migration-fence evidence, not an identity or exclusivity-uniqueness dimension. Tenant-readiness `onLoad` uses the explicit pre-instance exception: it is tenant-scoped and omits instance, playable-state, region, and entity fields. An authorized exclusive binding is selected before fan-out and becomes the sole handler; no core-script or plugin sibling runs before or after it, and failure does not cause sibling fallback. - Game Design rejects publish-time-known multiple-exclusive or unauthorized plugin claims against the exact `baseVersionId`. Automation & Scripting re-checks the complete resolved base-script plus active-plugin set during instance activation because active selections and bindings from different declared scopes may converge on the same concrete target. - Plugin exclusivity requires an explicit operator grant and audit evidence bound to the exact `pluginVersionId`, `bindingId`, target policy scope, and granting actor. Manifest intent alone grants no exclusivity. Automation must revalidate the current exclusivity grant both when activating a plugin and when resolving handlers; it persists the grant version and canonical grant digest with the activation/resolution evidence. Missing, stale, revoked, narrowed, or contradictory grant evidence fails closed at that boundary. @@ -449,9 +449,9 @@ Plugin rollback/disable/revocation flows must also invoke Automation's `CancelPe Rollback/disable/revocation flows must also reconcile durable plugin-owned timers: -- The timer-reconciliation operation identity includes `` plus the same `controlPlaneRequestId` used by the surrounding control-plane operation. Each schedule is a separate durable child reconciliation identified by that full tuple; one parent control-plane request must not collapse distinct schedules into one child result. Each owner row retains its own `pluginVersionId`; the operation-level displaced and optional replacement owner versions must not be inferred from whichever row happens to be read first. +- The timer-reconciliation operation identity includes `` plus the same `controlPlaneRequestId` used by the surrounding control-plane operation. `playableStateScope` is retained separately as exact-validated policy/routing/authorization/migration-fence evidence and is excluded from this identity, schedule uniqueness, and deduplication. Each schedule is a separate durable child reconciliation identified by that full tuple; one parent control-plane request must not collapse distinct schedules into one child result. Each owner row retains its own `pluginVersionId`; the operation-level displaced and optional replacement owner versions must not be inferred from whichever row happens to be read first. - For rollback or repin to a replacement `pluginVersionId`, any timer or interval owned by the displaced version must follow the scheduler continuity contract: on the default, reset, or incompatible path, reconciliation fences and tombstones the displaced owner before creating or confirming the replacement owner entry, as one atomic durable result or a resumable idempotent operation; a valid explicit typed-compatible continuity transition instead rewrites the existing stable row in place with the target ownership and pin metadata and creates no replacement row. The operation must persist and reuse the same `controlPlaneRequestId` across the applicable ownership update and displaced-row retirement, while each schedule child retains its own `scheduleDefinitionId` and full reconciliation identity; it must not generate a new request identity per timer or phase. No normal scheduling or trigger admission resumes for the plugin until ownership and durable timer reconciliation complete; queued-work cancellation remains bounded asynchronous cleanup and is not a resumption gate because exact pin/runtime fences remain authoritative. -- For disablement or revocation without a replacement version, the control plane must atomically fence admission and tombstone the displaced timer owner without creating a replacement entry, as one durable result or a resumable idempotent operation. It must persist and reuse the same `controlPlaneRequestId` across fencing and tombstoning, while each schedule child remains keyed by ``; no normal scheduling or trigger admission resumes for the disabled or revoked plugin until durable timer tombstoning/reconciliation completes. Queued-work cancellation must be launched and tracked as bounded asynchronous cleanup under the same surrounding operation and remains non-gating because the exact plugin/runtime fence remains authoritative. +- For disablement or revocation without a replacement version, the control plane must atomically fence admission and tombstone the displaced timer owner without creating a replacement entry, as one durable result or a resumable idempotent operation. It must persist and reuse the same `controlPlaneRequestId` across fencing and tombstoning, while each schedule child remains keyed by ``; its separately persisted exact-validated `playableStateScope` evidence is not part of the child key. No normal scheduling or trigger admission resumes for the disabled or revoked plugin until durable timer tombstoning/reconciliation completes. Queued-work cancellation must be launched and tracked as bounded asynchronous cleanup under the same surrounding operation and remains non-gating because the exact plugin/runtime fence remains authoritative. - Canceling queued work items alone is insufficient; otherwise an old plugin version could continue minting new timer-driven triggers after disablement or rollback. - If a newer plugin version preserves the same schedule, carry-forward is allowed only when both the old and new definitions explicitly declare continuity for the same stable logical key and typed compatibility holds for interval kind/cadence, trigger conditions, handler identity, target and binding, playable scope, dry-run namespace, and runtime ownership/fences. If either the source or target continuity declaration is absent or false, reconciliation uses the reset/tombstone path. On that reset/incompatible path, reconciliation must fence and tombstone the old owner before creating or confirming the new `pluginVersionId` entry; on a valid continuity path, it rewrites the existing stable row in place with the target ownership and pin metadata and creates no replacement row. Both paths must explicitly rewrite ownership without reusing old trigger claims. `scheduleSemanticsHash` remains diagnostic evidence only: equality does not grant continuity and inequality does not deny an otherwise valid declaration. diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index 3ad84d632c..57b771363d 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -6,6 +6,26 @@ - Logging, metrics, and tracing follow the standard [Logging & Monitoring](../../system-architecture-logging-monitoring.md) pipeline. - Publishing a game version is coordinated through the Temporal-backed `publish` workflow family. The synchronous `PublishVersion` API now requires a stable `publish_request_id`, while the durable workflow performs version metadata creation, participant digest gating, release attestation, and publish reconciliation under one caller-visible workflow identity. See [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md) for the overall flow. +### Publish request identity and digest binding + +The target publish contract binds the stable `publish_request_id` to one canonical request digest. Game Design normalizes the complete preallocation caller intent, including `tenantId`, publish type, `notes`, and any other actual request inputs, before computing and durably recording that digest with the workflow/attempt identity. The owner-allocated `versionId` is not an input to that original digest because it does not exist at request admission; after allocation, it is immutable attempt/result evidence bound durably to the same workflow identity and exact replay/readback. A retry with the same `publish_request_id` and the same preallocation-intent digest may attach to or replay the existing workflow and recorded outcome. Reuse of that identity with a different digest is an identity conflict: it must fail closed without executing the new request or returning the prior outcome as though the requests matched. This is the Game Design adopter mapping of [ADR 0078](../../decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md). + +**Current implementation gap:** `PublishWorkflowRequest` and the `publish_attempt` persistence currently carry no immutable normalized preallocation-intent digest or exact comparison. Temporal `AlreadyStarted` handling and existing-attempt reconciliation therefore reuse `publishWorkflowId` without comparing normalized caller intent; although the attempt stores the allocated `versionId`, it does not bind that result evidence to a request digest. The current implementation must not be treated as proof of the target different-digest conflict behavior; code and focused proof remain a future implementation gap tracked with the shared runtime contract. + +### Publication terminality and attempt ownership + +The publication artifact/release-bundle state, allocated version state, participant/release evidence, and publish-attempt terminal state must commit atomically in one Game Design owner-local transaction. If the workflow boundary cannot provide that transaction, the adopter must use an explicit durable state machine with readback reconciliation; it must never expose `SUCCEEDED` until the artifact and version commit is durably readable and bound to the same immutable request and attempt evidence. A terminal attempt is therefore not an acknowledgement that a separate transaction was started: it is the commit/readback proof of the publication state. + +**Current implementation gap:** `VersionPublishCommandServiceImpl` writes publication state and then calls `PublishAttemptServiceImpl.markSucceeded`, whose `REQUIRES_NEW` transaction can commit the attempt terminal state independently of the outer artifact/version transaction. The same `REQUIRES_NEW` boundary is used by `createAttempt` and `recordParticipantDigests`: an outer version rollback can therefore leave an attempt and participant rows committed with no committed version (the script-patch path has the same ordering). `publish_attempt.version_id` has no referential constraint to prevent that orphan. `PublishAttemptRepository` updates attempts by id without status/revision compare-and-set (CAS), and the failure path can mark failure and clean up while a concurrent publisher has already won. The current path consequently does not prove that `SUCCEEDED` is coupled to the artifact/version commit, that a failed preallocation can be recovered, or that losing cleanup cannot delete a winning publication. + +The target attempt record must immutably bind the normalized preallocation request digest, workflow/request identity, allocated version, artifact/release identity, and owner evidence. Every attempt transition must CAS both the expected status and monotonic attempt revision; only the still-current attempt owner may publish a terminal result. Failure cleanup may delete or mark provisional state only when it conditionally owns the same still-current nonterminal attempt and the target has not been won or published. Same-identity/same-digest retries must read back and replay the existing state; a different digest, stale revision/status, or contradictory artifact/version readback fails closed. Focused proof must cover crashes before and after each commit/readback boundary, concurrent exact retries, different-digest reuse, and a losing failure cleanup racing a winning publisher. + +### External artifact recovery + +The target publication boundary treats object-store export as a durable candidate operation: persist `STAGED` export intent before any write, retain a deterministic candidate manifest or incremental durable key evidence, make writes and deletes idempotent, and use a durable cleanup retry/outbox with exact object/readback verification. An ambiguous external result remains nonterminal and reconciliation-required until the candidate and release state are proven; it must not be reported as terminal `FAILED` merely because a storage call timed out. `version_asset_artifact` and the immutable release attestation remain the Game Design authorities; object-store listings alone cannot authorize publication or purge. + +**Current implementation gap:** `AssetExportServiceImpl` writes directly to S3-compatible storage before the artifact row receives the exported manifest. If an asset or manifest write fails, `VersionPublishCommandServiceImpl` has no manifest to record or clean up; if later cleanup fails, it is only logged. The Temporal activity catches these failures and returns terminal `FAILED`, so ambiguous partial exports have no durable recovery authority. The current direct-prefix implementation is therefore not proof of the target `STAGED`/candidate/reconciliation contract described in [Asset Storage](./asset-storage.md). + ## Local Development Notes `TestDataSeeder` populates a demo game, template, revision and version only when explicit smoke/runtime seeding is enabled through deployment config (`FIREMUD_SMOKE_SEED_DEMO_RUNTIME_ENABLED=true` in the local Compose smoke stack). Run `services/game-design-service/smoke-test.sh` to verify both REST and gRPC endpoints. The lightweight maintained application smoke now lives under `src/test/java/integration`; the old disabled GHCR-based cross-service placeholder was removed because it did not prove a meaningful current contract. diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index 7313ec6e58..d0e7033a0e 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -20,8 +20,8 @@ Current cross-seam security status is also blocked: Account's runtime membership - Publishing a version creates an immutable snapshot identified by `version_id`. Script-only fixes use a `scriptPatchVersion` tied to a `baseVersionId` so minor automation updates can go live without republishing all assets. -- **Target state:** To provide Git-style history, revisions will be grouped under explicit branches and commits stored in a durable Game Design history model. No branch/commit tables or current APIs exist in the first slice; current history is limited to service-owned revision/version rows and publish metadata. -- **Target state:** A future service contract may expose branch creation and commit-history reads; no such branch/commit APIs are currently exposed by the Game Design proto/service. Canonical multi-branch merge semantics require an explicit validated conflict contract. +- **Target state:** To provide Git-style history, revisions will be grouped under explicit durable branches and commits stored in the Game Design history model. This branch/commit model is not implemented by the current schema or service; current history is limited to service-owned revision/version rows and publish metadata. +- **Target state:** A future service contract may expose branch creation and commit-history reads, but no such branch/commit APIs are currently exposed by the Game Design proto/service. The current proto exposes version-scoped revision, publication, and version-read APIs instead. Canonical multi-branch merge semantics require an explicit validated conflict contract. - Any future external Git webhook or repository integration must submit changes through Game Design-owned revision APIs and must not become a second content authority. ### History and Provenance Across Services @@ -41,7 +41,7 @@ content even though domain services own the runtime templates: - Domain services do not maintain their own commit histories; they expose only the current and historical versioned templates keyed by `(tenantId, versionId)`. -To audit current history for a room, NPC, or item, contributors make a best-effort audit by querying the Game Design Service’s revision/version rows and correlating those revisions with the owning domain’s versioned templates and, where available, its applied-revision ledger (currently World Management’s ledger; Entity Management’s ledger remains future work). This cross-service view is not a canonical branch/commit audit because synchronized branch/commit read APIs do not exist yet. **Target state:** once the durable branch/commit model and synchronized read APIs exist, those surfaces will provide the canonical branch/commit audit view. +To audit current history for a room, NPC, or item, contributors make a best-effort audit by querying the Game Design Service’s revision/version rows and correlating those revisions with the owning domain’s versioned templates and, where available, its applied-revision ledger (currently World Management’s ledger; Entity Management’s ledger remains future work). This cross-service view is not a canonical branch/commit audit because synchronized branch/commit read APIs do not exist yet. In the target state, contributors will audit through Game Design branches and commits and correlate the resulting revisions with domain-service versioned templates once those durable branch/commit and synchronized read APIs exist; the current service exposes only version-scoped revisions and version reads. **Target state:** those surfaces will provide the canonical branch/commit audit view. ### Design-Time Synchronization diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index c6897aaaaa..9a5005c4a7 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -16,6 +16,7 @@ This document mixes live and target-state control-plane surfaces. Current live b - The live `/actuator/settings/effective` endpoint is guarded only by the shared HTTP `PRIVILEGED` requirement. `SessionClaims.hasPrivilegedRole()` treats a role scoped to any tenant as sufficient, while `EffectiveSettingsController` accepts caller-supplied `tenantId`, `gameInstanceId`, `bootstrapGameInstanceId`, or a `sessionId` and does not bind those selectors to the scoped role or compare persisted-session ownership. A tenant-scoped operator for tenant A can therefore request effective settings for tenant B (or a tenant-B session). Existing proof covers malformed selectors and a global privileged token, not this cross-tenant denial boundary. - **Target effective-settings boundary:** a tenant-scoped `tenantAdmin`/operator role may read only the exact requested tenant, and a persisted `sessionId` must resolve to that same tenant; a missing tenant selector is allowed only when it is unambiguously derived from the session. A global `platformAdmin` operator may select another tenant only through the explicit global branch with current operator authorization, target-tenant generation, and required `privileged_control` assurance. Tenant/session mismatch, absent or unavailable authority, and a scoped role selecting another tenant fail closed before settings resolution. Focused negative proof must cover tenant A versus tenant B for both synthetic and persisted-session reads, plus the global branch without privileged control. - the live script-transition proto/runtime now persists and exposes the exact owner `{scriptPatchVersion, scriptPinEpoch, controlPlaneRequestId}` tuple on `GetPinnedScriptPatchVersion` and the corresponding observed tuple on `GetGameSessionPinConvergence`; pin/rollback requests carry the tagged `expectedCurrentPin` precondition. The owner persists a request digest/result ledger and commits the pin tuple under a row lock with deterministic replay/conflict and expected-tuple failure results. It does not expose target `GetScriptPinTransitionWorkflowStatus`; commit-time revalidation of external Game Design publication and Automation readiness evidence (or an immutable preparation attestation) is not live, so that cross-service authority proof remains an implementation gap alongside atomic history proof and complete rollout semantics. Local instance-scoped Automation admission, duplicate replay, durable tick staging/replay, and final Game Session execution now enforce the complete tuple; complete source/target remote tuple binding and remote final-effect fencing remain tracked in the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md) and the [canonical runtime-execution owner](../../system-architecture-scripting-runtime-execution.md#normative-target-contract). A missing epoch never matches a pinned target tuple. Semantic `UNPINNED` matching is defined separately below; +- the target spatial/ambient `effect_reconciliation_backlog`, typed `EffectReconciliationAuthority`, and `ListEffectReconciliationBacklog` / `RetryEffectReconciliation` / `AcknowledgeEffectDeadLetter` surfaces are not implemented. Current Game Session has `tick_batch` and `tick_effect` persistence plus narrower domain and remote-follow-up reconciliation, but no backlog schema, immutable effect-guard/action-ledger schema, or API; those current seams must not be presented as this target cross-service reconciliation surface. The normative owner, guard, CAS, action-idempotency, and authority-branch requirements remain in [Transaction Strategies](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects); Read the pause/status/recovery APIs below as the target-state contract unless the [Game Session runtime and tick coordination tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md) explicitly records them as live. @@ -87,7 +88,7 @@ The internal front-end to lease-owner path is a **target-state** fenced gameplay - A dispatcher reconciles the durable work item after commit and retries delivery until source cleanup-work dispatch and the World lifecycle request are acknowledged by their authoritative readbacks. Lost responses, dispatcher restarts, and duplicate deliveries are recovered by the stable work-item identity, source instance binding, and acknowledgement state; delayed reconciliation does not delay deadline-based command rejection, and the cutover result is not reported as fully completed merely because an in-memory termination request was sent. Final `TERMINATED` readback is World’s authoritative all-owner cleanup result. - `EnqueueAutomationCommandIfAbsent` – internal Automation & Scripting handoff API that records or replays a durable automation dispatch row keyed by the complete [Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state) before staging the generated command into the normal Game Session tick queue. For non-exclusive fan-out, the target handoff also retains, as non-identity evidence, the already-assigned `handlerSequence` and the event resolution record (or equivalent durable manifest) identifying the complete ordered handler set, plus the handler-local command order; Game Session carries and reuses those facts through admission, retry/recovery, and final application, and fails closed on missing or contradictory sequence/completeness evidence rather than falling back to arrival order. An authorized exclusive event has only its selected handler and no sibling admission. The live `EnqueueAutomationCommandIfAbsentRequest` carries `script_patch_version`, `script_pin_epoch`, and `script_pin_control_plane_request_id`. For local instance-scoped Automation, Game Session compares this complete tuple with the locked current `GameInstance` while durably admitting fresh work or checking a duplicate, commits that admission before Redis materialization or an immediate tick, locks and rechecks the tuple while sealing fresh or replayed tick work, persists the tuple on `gameplay_command` and the selected-work manifest, and compares it again before final execution; a same-patch/different-epoch or owner-request mismatch fails closed. These local consequences are owned normatively by [Scripting Runtime Execution](../../system-architecture-scripting-runtime-execution.md#normative-target-contract). Remote Automation follow-ups retain their separate legacy source/target path and are not widened by this local boundary. Only an already-staged or downstream-confirmed dispatch returns `DUPLICATE_NOOP` with the existing `commandId`; a matching pre-Redis `ACCEPTED` row is not a duplicate. Target behavior retries materialization from that durable row or converges it to a terminal non-applied outcome under the command-status rules. The current implementation returns `UNAVAILABLE` for an existing `ACCEPTED` row, and later recovery may mark stale accepted-but-unstaged work `LOST_BEFORE_STAGING`; it does not introduce a separate staging state. New same-scope dispatches validate and persist one current durable owner/epoch fence, while a dispatch with a distinct target reads and locks the source and target owner rows in one stable canonical owner-identity order, validates each against its source or target role, and persists both owner/epoch fences before Redis mutation. Missing source/target ownership returns `OWNERSHIP_UNAVAILABLE`, a stale source/target `regionEpoch` returns `STALE_TIMELINE`, and paused ownership returns `RUNTIME_PAUSED` without staging into Redis. `dueTickId` is still carried for scheduler/timer-derived automation, but immediate event-driven automation may omit it and rely on immediate enqueue semantics. - At the Game Session-to-Automation handoff, Game Session first resolves `playableStateNamespaceId` and `playableStateScope` from the authoritative admission-pointer/world-lifecycle snapshot; neither Automation nor the caller supplies namespace authority. The owner-side admission/CAS validates the exact `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId, regionId, regionEpoch}` tuple atomically before staging. The current handoff wire carries only a narrower tenant/instance/region fence in some paths and lacks complete namespace/scope plus active-instance proof, so this is an explicit current wire/implementation gap rather than a claim that the target handoff is live. -- `GetGameplayCommandStatus` – returns the durable command status by the canonical current lookup key `{tenantId, gameInstanceId, commandId}`, including accepted/staged/completed timestamps, attempt count, failure code/message, source type, automation dispatch/work-item ids, script/plugin provenance, target entity, `regionId`, `regionEpoch`, `dueTickId`, and the full remote origin/target game-instance, `playableStateNamespaceId`, and region scope when the command has entered the cross-region follow-up path. That same status read now also exposes the durable remote follow-up contract itself when present: follow-up status, payload kind, requested command, solo-tick requirement, origin-source tuple, target entity/effect/failure summary, and trigger-script-event identity. `regionId`, `regionEpoch`, and `automationDispatchId` are correlation or filter fields for that read, not replacements for its lookup key. Automation handoff deduplication, replay, and fence diagnostics instead use the complete [Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state), including `playableStateNamespaceId`, `playableStateScope`, optional distinct target-scope fields, and `commandOrdinal`; they do not change the status resolver's required `{tenantId, gameInstanceId, commandId}` lookup tuple, which is never reduced to a single `commandId`. +- `GetGameplayCommandStatus` – returns the durable command status by the canonical current lookup key `{tenantId, gameInstanceId, commandId}`, including accepted/staged/completed timestamps, attempt count, failure code/message, source type, automation dispatch/work-item ids, script/plugin provenance, target entity, `regionId`, `regionEpoch`, `dueTickId`, and the full remote origin/target game-instance, `playableStateNamespaceId`, and region scope when the command has entered the cross-region follow-up path. That same status read now also exposes the durable remote follow-up contract itself when present: follow-up status, payload kind, requested command, solo-tick requirement, origin-source tuple, target entity/effect/failure summary, and trigger-script-event identity. `regionId`, `regionEpoch`, and `automationDispatchId` are correlation or filter fields for that read, not replacements for its lookup key. Automation handoff deduplication, replay, and fence diagnostics instead use the complete [Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state), including `playableStateNamespaceId`, optional distinct target-scope fields, and `commandOrdinal`; source `playableStateScope` and target `targetPlayableStateScope` values are separately persisted and exact-validated policy/routing/authorization/migration-fence evidence, not Command-Handoff Identity or uniqueness inputs. They do not change the status resolver's required `{tenantId, gameInstanceId, commandId}` lookup tuple, which is never reduced to a single `commandId`. - `ListRemoteCommandCoordinators` – returns bounded remote coordinator rows for a tenant, filterable by persisted origin/target game-instance, `playableStateNamespaceId`, and region scope, state, linked `followupId`, script/plugin/dispatch/command provenance, the admitted routing bundle, linked follow-up target-leg traits (`targetEntityId`, `effectKey`, `payloadKind`, `originSourceKind`, `automationWorkItemId`), and first-class trigger-event identity (`eventType`, `scriptEventId`) instead of requiring point lookup by one coordinator id. The target admitted routing bundle is (`realmId`, `playableStateScope`, `worldSlug`, `realmSlug`, `pointerVersion`); `playableStateScope` remains separately validated evidence and is not a substitute for namespace identity. The current selector-based model does not yet carry durable `realmId` or namespace fields. - `ListRemoteFollowups` – returns bounded remote target-leg rows for a tenant, filterable by persisted origin/target `playableStateNamespaceId` and scope, follow-up status/id, script/plugin/dispatch/command provenance, the admitted routing bundle, current live payload/source classifiers (`payloadKind`, `originSourceKind`), direct target-leg identity/terminal fields (`automationWorkItemId`, `targetEntityId`, `effectKey`, `failureCode`, `requiresSoloTick`), and first-class trigger-event identity (`eventType`, `scriptEventId`) instead of requiring operators to scrape one entire target-region stream. - `ListRemoteFollowupResults` – returns bounded origin-addressed remote result rows for a tenant, filterable by coordinator/follow-up identity, origin/target game-instance, `playableStateNamespaceId`, and region scope, outcome, script/plugin/dispatch/command provenance, the admitted routing bundle, and durable result identity/failure fields (`resultErrorCode`, `resultCommandId`, `automationWorkItemId`). Result admission compares the complete persisted origin and target namespace/timeline tuples, while separately validating `playableStateScope`; it does not accept a result based on region/epoch or scope alone. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index a43b417133..e1fc8a00ca 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -19,11 +19,22 @@ The sections below define the target-state runtime contract. Current implementat - The live `startSession` path keeps the Game Session row and runtime projection `STARTING` until World confirms its fenced `PREPARING -> ACTIVE` transition, then records `RUNNING`; failures before an activation attempt use the existing pre-activation cleanup. Once activation may have been issued or committed, an activation error or ambiguous result, or a later local runtime-state save/finalization failure, retains both the runtime projection and local owner row as `STARTING`, and never calls stale-epoch `failPrepared` or deletes either record. A failure proven before any World termination request is issued may restore the prior `RUNNING` row and runtime state while the World remains `ACTIVE`; once a termination request may have been issued, an error or ambiguous result leaves the local row `STOPPING` and runtime projection absent. Confirmed World termination retries local `STOPPED` finalization and never restores `RUNNING`. Durable stable lifecycle-operation identity and lifecycle readback/reconciliation remain unimplemented, so these local fail-closed quarantines are not a replacement for the target durable lifecycle cleanup workflow. - Current `onCommand` ingress uses the live `{tenantId, gameInstanceId}` boundary as a region surrogate until true region partitioning is shipped; it carries the current `regionEpoch` and a producer-supplied `readSnapshotToken` derived from the command and ownership fence. That token is retained only as an owner-specific manifest input or correlation value, not universal evaluation authority. The target handler-scoped input manifest is owned by the [DSL lifecycle contract](../../system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract); current producer/storage behavior is narrower and does not yet seal the complete manifest. - Durable command/effect execution currently covers movement and `PUT`, `TAKE`, `WEAR`, and `REMOVE` fully at the existing boundary. Current `GET` is the command spelling for the target `PICKUP`/`PickupVisibleRoomItem` family, and `GET` plus `DROP` also enqueue and execute on that durable command path, but their ADR 0054 spatial correctness remains incomplete until World `TargetingFactSnapshot` attestation/location-version propagation, the shared actor-lock/executor-fence critical section and durable barrier/handoff path, and stale-race proof are implemented. Current movement/item replay rows do not yet prove the ADR 0054 participant guard bound to root `EffectId`, typed operation, target, and request digest, or fail-closed changed reuse. +- The target spatial/ambient reconciliation contract is not a current Game Session surface: the typed `EffectReconciliationAuthority`, durable `effect_reconciliation_backlog`/authority schema, immutable effect guards, durable action ledger/results, and list/retry/acknowledgement APIs remain unimplemented. Current persistence is limited to `tick_batch`/`tick_effect` and narrower domain/remote-follow-up reconciliation; see [Game Session API status](./api-contracts.md#implementation-status) and the normative [transaction reconciliation owner](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects). +- The target remote-follow-up contract makes terminal timeout/late outcomes immutable under the original identity: exact retries return the stored terminal outcome, and a late-applied result requires a separately documented feature-specific compensation flow. Current implementation/proof gap: an exact `scheduleFollowup` retry can reset an existing terminal timeout/late coordinator/follow-up pair to `PENDING_REMOTE`/`SCHEDULED`, mirror that pending state to the origin command, and clear mirrored terminal completion/failure fields. The live `late_result_requires_reconciliation` path also writes `LATE_RESULT_RECONCILED`/`PARTIAL` and mirrors `APPLIED`/`PARTIAL` to the origin without a separately identified compensation/saga flow; post-abandon re-drive and compensation ownership remain unproved. +- Current tick staging has Redis-first windows that are not the target durable-first boundary: ingress pushes the queue payload before marking the durable command `STAGED`, and tick processing moves queue entries to Redis `pending` before creating the durable `tick_batch`/`tick_effect` rows. A crash or Redis loss in either window can strand a `STAGED` command with no batch/effect, while startup recovery only handles `ACCEPTED` rows with no staging timestamp and purge can classify a no-effect row as `LOST_BEFORE_STAGING`. Only explicitly classified volatile ingress may receive that evidence-qualified outcome; durable accepted work needs a durable source claim/materialization recovery path and its feature-specific replay/re-drive contract. The target boundary creates the durable batch/effect/source claim before `pending` staging and treats Redis-only residue as reconstructible coordination state; the current ordering and no-batch recovery are implementation drift. +- The target stale-fence contract preserves a drained effect under its original mutation `EffectId` and enclosing root lineage while evidence-fenced reconciliation determines whether it is `APPLIED` or safely unapplied. `ABANDONED` requires authoritative participant/domain evidence; ordinary retry/replay retains the original command/effect identity, and only a conclusive post-abandon re-drive allocates a new command ID and root. The current implementation instead marks stale drained batches/effects `ABANDONED` on the fence/technical signal alone and requeues the same command, after which a later batch derives a new effect identity. This is unsafe implementation drift: a crash after participant mutation but before ledger terminalization can permit duplicate logical application or false abandonment. - `BLOCK` is also on the current durable effect replay/no-op seam; other state-changing command families still need to migrate onto it. - Current Game Session code still defaults `FIREMUD_AUTH_SESSION_EXPIRATION_MS` to one hour and does not enforce the target five-minute continuity cap. - Current Game Session code has not converged on the canonical bounded `session:game:*` index families or proved their repair protocol: it still uses transitional `sessionctx:*` and tenant/identity lookup records and does not implement/prove the generation-safe global `accountIndexMember` set, the partitioned global issuer index, or their cross-slot repair/acknowledgement flows. This is implementation/proof drift, not a transfer of ownership or a different member shape. -- Current Game Session Redis-backed per-session rate limiting under the legacy `ratelimit:` key remains implementation drift from ADR 0034's target in-process ordinary gameplay limiter; its Cache/Rate-Limit role isolation, eviction behavior, and loss semantics are not yet proved. Migration must stop legacy writers and drain the maximum key TTL before unversioned target helpers consume `ratelimit:*`, or use a distinct versioned namespace. +- Current Game Session Redis-backed per-session rate limiting under the legacy `ratelimit:` key remains implementation drift from ADR 0034's target in-process ordinary gameplay limiter. `SessionRateLimiterImpl` uses the generic Game Session Redis client and a one-second counter/TTL; its Cache/Rate-Limit endpoint, ACL/admission, eviction behavior, and loss semantics are not yet proved. The exact family is registered in the [Cache/Rate-Limit key catalog](../../system-architecture-redis-cache-reference.md#cache-rate-limit-key-catalog) and [reset policy matrix](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). Migration must stop legacy writers and drain the maximum key TTL with readback before unversioned target helpers consume `ratelimit:*`, or use a distinct versioned namespace. +- Current hosted wiring still exposes one generic `firemud.redis` connection to Game Session while the shared Helm profile sets `FIREMUD_REDIS_HOST=redis-cache`; the role-specific `FIREMUD_REDIS_COORD_*` and `FIREMUD_REDIS_CACHE_*` variables are not consumed by the common Redis auto-configuration. Consequently, the live Game Session tick/session coordination path is not proven to reach Coordination Redis in that profile and may share the Cache/Rate-Limit endpoint. This is implementation drift against ADR 0171, not a target-state role assignment; named role clients, endpoint-collision failure, and role-specific health/eviction proof remain required. +- Current tick/session coordination also bypasses the target key/script boundary: `TickQueueControlService`/`TickServiceImpl` build untagged `gamesession:tick:*` keys and pass queue, pending, and lock keys together to Lua, while `RedisSessionContextService` performs watched multi-key writes across untagged `sessionctx:*` families. Those calls are not proven same-slot and can fail with `CROSSSLOT` on a supported Redis Cluster profile; the live families are not represented by the canonical builder/registry contract. This records current implementation/proof drift only; migration must use the canonical tagged builders, registered scripts, reset inventory, and fenced readback before claiming cluster support. +- The current `IpConnectionLimiter` stores the source address directly in `ipconn:
` keys and `sessionip:` values, and registration passes both keys to one Lua invocation without a shared hash slot, so it fails with `CROSSSLOT` on Redis Cluster. This is not the ADR 0087 opaque-HMAC subject contract and has no evidenced tenant/policy scope or current Cache/Rate-Limit loss profile. The limiter remains a current heuristic seam; convergence requires one mutation on one opaque subject bucket, session lifecycle correlation outside exact cross-key atomicity, an owner-declared subject scope, opaque full-digest mapping, and focused privacy, isolation, eviction, reset, clustered, and unavailable-store proof; no final reverse-index design is implied. +- The current `LOGIN` path receives Account's `game-session-account-delegation` JWT and places it in the persisted `SessionContext.jwt` value, which is serialized into Redis by `RedisSessionContextService`. This contradicts the process-local/no-raw-delegation-JWT boundary in ADR 0031. The target binding must persist only bounded non-secret evidence such as the token hash or opaque rebind handle; stripping the token, fenced cleanup of existing values, and focused no-secret serialization proof remain implementation work. - Bounded durable semantic reconnect-context persistence is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, while namespace-key migration to `{tenantId, playableStateNamespaceId, characterId}`, the distinct durable `resumeContextGeneration` episode fence and termination protocol, complete-envelope hard-bound accounting and omission-marker convergence, and post-logout replay suppression remain implementation/proof gaps. +- Current live/recent presence projection wiring is implementation drift: `gameplaypresence:session:`, its game-instance/account set indexes, and `accountrecentpresence::` are written with untagged, separate Redis value/index operations. Game Session remains the target owner, but the physical shapes, storage-role classification, exact scope, partial-write handling, reset/rebuild/readback behavior, and private-by-failure contract are unproved; the [Redis owner and reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) records these current families without accepting them as target authority. +- Current LOOK handling writes the legacy `lookcache::` projection even though reads remain authoritative/uncached. Its ten-minute, session-or-instance-only scope lacks the target viewer, policy, and causal read-fence identity; it is disposable implementation drift and must not be treated as the target `view:room-look:*` cache. See the [Redis cache catalog](../../system-architecture-redis-cache-reference.md#cache-rate-limit-key-catalog). +- The current Flyway history also contains the Java/nontransactional `V8__remote_followup_target_instance_effect_identity` migration (`CREATE INDEX CONCURRENTLY`, `canExecuteInTransaction() = false`). This is outside the SQL migration input used by shared jOOQ generation and is not yet inventoried or proved as a narrow exception to the SQL-only persistence lineage. ## Runtime Details @@ -92,7 +103,7 @@ Game Session treats Redis Coordination and Cache/Rate-Limit roles as separate co ### Redis role and prefix details -- Coordination prefixes are reset-tolerant in line with [Redis Reset & Recovery](../../system-architecture-redis-reset-and-recovery.md), except for reset-sensitive gameplay session bindings under `session:game:*`. That document owns reset lifecycle and session policy; Game Session retains only local consequences: the canonical session record is the policy-selected binding, while derived gameplay indexes reconcile independently under either policy. Account token and generation authority remains outside session policy. Game Session’s coordination design must therefore remain safe under the documented Redis tail-loss envelope rather than assuming perfect recovery of every transient coordination key. +- Coordination prefixes follow the reset policies in the complete [Redis Reset & Recovery matrix](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). Region-scoped tick queues, pending state, locks, leases, timers, retries, and session-binding projections are reset-tolerant (with preserved-session rebind fencing where specified), while gameplay session records, all derived gameplay indexes, `sessionctx:*`, presence projections, disconnect deduplication, and pre-auth transport context are reset-sensitive or unavailable-by-failure under that matrix. Account token and generation authority remains outside session policy. Game Session’s coordination design must therefore preserve the matrix’s fences and remain safe under the documented Redis tail-loss envelope rather than assuming perfect recovery of every transient coordination key. - The canonical opaque `{tenantRegionTag}` is derived by the shared key builders from the full `` tuple. It is the region scope for lease, queue, timer, retry, pending, and lock keys below; key examples must retain `{tenantRegionTag}` rather than substituting a differently named or partial tag. - Coordination ownership includes registered Lua-script access to prefixes such as: - `tick:{tenantRegionTag}:queue:` @@ -108,12 +119,13 @@ Game Session treats Redis Coordination and Cache/Rate-Limit roles as separate co - Changes to Game Session Redis usage must also be reviewed against the [Redis Design Checklist](../../system-architecture-redis-design-checklist.md) in addition to the core Redis architecture docs. - Game Session may rely on Cache/Rate-Limit Redis for read-side caches that help serve hot-path session views, most notably pre-rendered room LOOK aggregates under `view:room-look:::::::` as defined in [Redis Cache & Rate Limiting](../../system-architecture-redis-cache.md#key-naming-and-overwrite-expectations). - `view:room-look:*` entries are Class B, TTL-only caches. They may become stale briefly, but gameplay correctness still comes from authoritative reads and tick execution rather than cache contents. The key must remain bound to the exact room, viewer/session, policy context, and applicable read-fence context; use the [canonical Class-B contract](../../system-architecture-redis-cache.md#canonical-viewroom-look-class-b-contract) for the fence-hash derivation and the uncached fallback when the complete fence is unavailable. Underlying world or entity changes do not require synchronous invalidation of these keys; recomputation happens on cache miss or TTL expiry, and correctness-critical flows must not treat the cache as authoritative. +- The current LOOK writer uses legacy `lookcache::` keys with a ten-minute TTL. This projection is disposable and non-authoritative, but its incomplete scope cannot support target causal room-read semantics; current composition remains authoritative/uncached until the registered `view:room-look:*` contract is implemented and proved. The legacy writer must be removed/drained or explicitly isolated before target cache helpers consume the family. - Cache prefixes must never be silently repurposed onto Coordination Redis, and new cache usage should be introduced only through the central cache-key catalog rather than ad-hoc per-service naming. - Game Session must not read or write Social & Groups history caches such as `chat:say:*`, `chat:tell:*`, `chat:guild:*`, or `chat:account:*`. Chat history ownership stays behind Social & Groups APIs. -Crash recovery replays ticks stored in Redis using AOF persistence and the idempotent replay rules described in [Tick System and Runtime Design](../../system-architecture-ticks.md#crash-recovery-and-replay). Replication remains asynchronous, and Redis is treated as a volatile coordination layer rather than a durable source of truth. +Crash recovery is driven by durable PostgreSQL commands, tick batches, effects, and participant guards, using the idempotent replay rules described in [Tick System and Runtime Design](../../system-architecture-ticks.md#crash-recovery-and-replay). Redis `pending` entries and AOF state remain volatile coordination hints subject to measured exposure; they may assist recovery only after durable reconciliation and never supply recovery authority or the sole source of replayable work. Replication remains asynchronous. -When Redis becomes slow or unavailable, Game Session applies the graceful degradation and halt behavior defined in [Redis Architecture – Graceful Degradation & Redis Outage Policy](../../system-architecture-redis.md#graceful-degradation--redis-outage-policy) instead of buffering authoritative commands only in memory. If coordination state must be cleared or repaired, operators follow the scoped reset flows in [Redis Operations & Migrations](../../system-architecture-redis-operations.md) rather than issuing ad-hoc key deletions. +When Redis becomes slow or unavailable, Game Session applies the graceful degradation and halt behavior defined in [Redis Availability, Consistency, and Safety Guarantees](../../system-architecture-redis.md#redis-availability-consistency-and-safety-guarantees) instead of buffering authoritative commands only in memory. Current operators do not clear or repair Coordination Redis through ad-hoc key deletion or the target-state scoped reset flows, which remain unavailable; they preserve evidence, keep the affected scope fenced, use shipped pause/status and read-only inspection surfaces, and follow the [current operator fallback](../../system-architecture-redis-reset-and-recovery.md#current-operator-fallback) and escalation path. ## Session Keys and Indexes @@ -140,7 +152,7 @@ Target-state Game Session maintains the bounded active-binding index families ow - `session:game:index:realm-grant:{tenantGameplayTag}:` -> active `sessionId` set for lifecycle-bound private/playtest grant-gated realms, where `grantScopeId` is the exact canonical `grant/v1` scope ID for the complete Account-owned tuple; public-production and unscoped bindings have no entry - `session:game:index:issuer:{issuerIndexLayoutTag}::` -> partitioned global issuer active-binding hash, using the immutable layout and `bindingRef` fields defined by the [Redis issuer-index contract](../../system-architecture-redis.md#issuer-active-binding-index) across all tenants -These indexes are derived gameplay projections, not preserved-session state or Account authority. Game Session is the target-state local writer and reconciler for them under the reset consequences in [Redis Reset & Recovery](../../system-architecture-redis-reset-and-recovery.md); affected tenant-owned indexes may be dropped and rebuilt under either explicit session policy, while the global account index and partitioned global issuer index require their separate account-wide or issuer-wide owner-defined coverage before replacement. A region/tenant parent may repair only its local binding consequences and consume a complete issuer-wide child or standalone issuer-wide recovery result; it may not claim issuer coverage from a local snapshot. Binding transitions use the owner-defined generation/fence and repair protocol; this service must not use wildcard scans or treat index presence as authorization. Missing or ambiguous index/coordination state fails closed for admission and reconnect, while local cleanup remains idempotent. +These indexes are derived gameplay projections, not preserved-session state or Account authority. Game Session is the target-state local writer and reconciler for them under the reset consequences in [Redis Reset & Recovery](../../system-architecture-redis-reset-and-recovery.md); at tenant scope, affected tenant-owned index families may be dropped and rebuilt under either explicit session policy, while a region scope updates or reconciles only exact affected index entries from durable inventory and preserves unrelated keys, members, regions, and tenants. The global account index and partitioned global issuer index require their separate account-wide or issuer-wide owner-defined coverage before replacement. A region/tenant parent may repair only its local binding consequences and consume a complete issuer-wide child or standalone issuer-wide recovery result; it may not claim issuer coverage from a local snapshot. Binding transitions use the owner-defined generation/fence and repair protocol; this service must not use wildcard scans or treat index presence as authorization. Missing or ambiguous index/coordination state fails closed for admission and reconnect, while local cleanup remains idempotent. Gameplay session bindings persist the local identity and receiver-validation fields required by the owner contract: @@ -158,23 +170,23 @@ The target transition's durable identity spans the target session record and cha Game Session acts as the authoritative tick executor for each `` region scope it owns: -- It participates in region leadership using the Redis lease key `tick-executor-lease:{tenantRegionTag}` described in [Redis Architecture](../../system-architecture-redis.md#region-leadership-and-tick-executor-lease). +- It participates in region leadership using the Redis lease key `tick-executor-lease:{tenantRegionTag}` described in [Tick System: Region Authority and Tick Executor](../../system-architecture-ticks.md#region-authority-and-tick-executor). - While it holds the lease for a region, it is the only instance allowed to consume commands from that region’s queues and timers, drive `tick:{tenantRegionTag}:pending`, and issue tick-scoped gRPC calls on behalf of that region’s commands. -- On crash or deliberate handoff, another instance acquires the lease and resumes tick processing from Redis using the epoch-scoped `(regionEpoch, tickId)` timeline and EffectId/effect-guard rules from the tick-system design. +- On crash or deliberate handoff, another instance acquires the lease and resumes tick processing from durable PostgreSQL commands, tick batches, effects, and participant guards, using surviving Redis queues, timers, retries, `pending`, or AOF state only as reconciled coordination hints after that durable baseline is established. Redis state never supplies recovery authority or the sole source of replayable work; the successor preserves the epoch-scoped `(regionEpoch, tickId)` timeline and EffectId/effect-guard rules from the tick-system design. - Tick execution correctness must not depend on process-local executor memory surviving restart. Lease acquisition, staged tick state, retry metadata, and resumable session bindings are all externalized specifically so another Game Session instance can continue work from shared state. - **Target state:** The executor monitors mode-aware `tick_execution_time_ms_p99{scope_class,tick_mode}` and selects `tick_lock_ttl_ms{scope_class}` for `tick_mode="normal"` or `solo_lock_ttl_ms{scope_class}` for `tick_mode="solo"`. A repeated over-TTL class-level signal is for detection and escalation only; it does not identify or classify an individual region. The executor resolves the exact region and current health from authoritative runtime-health/control-plane records before reducing tick fan-out, marking a region degraded, halting new ticks, or rejecting new commands for that region until operators intervene. - Changing `tick_interval_ms` is not part of this in-place degradation path. Any live cadence change that alters timer ordering must run as an epoch-bumped maintenance operation with pause, timer re-derivation, and resume on the new `regionEpoch`, as defined in the tick and scaling docs. - The staging Lua script only moves a bounded number of commands each tick, governed by `GAME_TICK_MAX_COMMANDS`, so one player cannot starve others. Commands marked `requiresSoloTick: true` are dequeued into isolated ticks so expensive operations such as runtime procedural generation do not share time with normal actions. - Each tick-staging or entity-lock-acquiring Lua invocation uses a registered script governed by [ADR 0074](../../decisions/adr-0074-one-entity-lock-per-redis-script.md), acquires at most one entity lock, and fails closed if the operation would require more. Multi-entity correctness is enforced by one owning PostgreSQL transaction when the invariant is co-located, or by durable effect/workflow legs with [ADR 0076](../../decisions/adr-0076-failure-class-specific-durable-tick-retries.md) retry and reconciliation when authority is split. Redis locks are coordination only: Game Session does not assemble entity lock sets or use Redis rollback as a transaction boundary. Each retryable outcome maps to ADR 0076's declared failure class, whose policy owns its deterministic cadence, attempt and age bounds, and exhaustion disposition; only authoritative pre-dispatch lock contention uses capped exponential tick backoff. An unstaged command may surface an explicit retry-budget failure, while a staged or ambiguously dispatched effect remains unresolved for owner reconciliation, dead-letter, quarantine, or verified terminal evidence rather than being logged as permanently unapplied merely because automation exhausted. -These degraded and halt transitions follow the same thresholds and policies captured under [Redis Architecture – Operational SLOs & Alert Thresholds](../../system-architecture-redis.md#operational-slos--alert-thresholds) so operators and implementations share a single set of red lines for coordination health. +These degraded and halt transitions follow the same thresholds and policies captured under [Redis Operations & Migrations – Redis SLOs & Budgets](../../system-architecture-redis-operations.md#redis-slos--budgets) so operators and implementations share a single set of red lines for coordination health. -For `DROP` and `PICKUP`, Game Session acquires the actor lock keyed by the complete gameplay scope, including `regionId`, and `actorEntityId`, captures the current `(regionId, regionEpoch, executorFence)` from its durable region-status snapshot after authority validation, and durably records an in-flight barrier keyed by the existing scoped root identity `(tenantId, gameInstanceId, EffectId)` and bound to the actor, `regionId`, `RoomInstanceRef`, epoch, fence, and canonical immutable `requestDigest` before World validation. `regionId` propagates unchanged through World validation and any Game Logic re-resolution and is checked with the same root `EffectId` and unchanged `requestDigest` at Entity commit. It owns lock/retry orchestration, renews the actor-lock lease through Entity commit acknowledgement, and invokes Game Logic to re-resolve stale evidence under the same root `EffectId`, preserving that `requestDigest`; Entity verifies the attestation, guard, and `requestDigest` at local commit. A changed request is rejected rather than reusing the root. Lock-renewal failure, owner crash, or fence change fences the old orchestrator and leaves the barrier reconciliation-required. Handoff/recovery may reconcile the exact root but MOVE admission must pass the same actor lock/barrier gate and cannot authorize a conflicting move merely because Redis lock state expired; a later valid `MOVE` is allowed only after terminal barrier evidence. The detailed local-transaction and proof contract is in [Transaction Strategies](../../system-architecture-transactions.md#drop-pickup-targeting-and-actor-fence-critical-section). +For `DROP` and `PICKUP`, Game Session acquires the actor lock keyed by the complete gameplay scope, including `regionId`, and `actorEntityId`, captures the current `(regionId, regionEpoch, executorFence)` from its durable region-status snapshot after authority validation, and durably records an in-flight barrier keyed by the canonical scoped root identity `(tenantId, gameInstanceId, EffectId)` before World validation. The barrier binds the exact `playableStateNamespaceId`, `playableStateScope`, actor, `regionId`, `RoomInstanceRef`, epoch, fence, and canonical immutable `requestDigest` as evidence that must match and fail closed, not as alternate uniqueness inputs. `regionId` propagates unchanged through World validation and any Game Logic re-resolution and is checked with the same root `EffectId` and unchanged `requestDigest` at Entity commit. It owns lock/retry orchestration, renews the actor-lock lease through Entity commit acknowledgement, and invokes Game Logic to re-resolve stale evidence under the same root `EffectId`, preserving that `requestDigest`; Entity verifies the attestation, guard, and `requestDigest` at local commit. A changed request is rejected rather than reusing the root. Lock-renewal failure, owner crash, or fence change fences the old orchestrator and leaves the barrier reconciliation-required. Handoff/recovery may reconcile the exact root but MOVE admission must pass the same actor lock/barrier gate and cannot authorize a conflicting move merely because Redis lock state expired; a later valid `MOVE` is allowed only after terminal barrier evidence. The detailed local-transaction and proof contract is in [Transaction Strategies](../../system-architecture-transactions.md#drop-pickup-targeting-and-actor-fence-critical-section). -Tick coordination is region-scoped, not session-scoped. Tick queues, locks, timers, retry metadata, and `tick:{tenantRegionTag}:pending` use the `tick:{tenantRegionTag}:...` prefix described in [Redis Architecture](../../system-architecture-redis.md#tick-integration-resilience-locking-staging). Region keys follow region lifecycle and crash-recovery rules: +Tick coordination is region-scoped, not session-scoped. Tick queues, locks, timers, retry metadata, and `tick:{tenantRegionTag}:pending` use the `tick:{tenantRegionTag}:...` prefix described in [Tick System: Tick Staging and Commit Flow](../../system-architecture-ticks.md#tick-staging-and-commit-flow). Region keys follow region lifecycle and crash-recovery rules: - `tick:{tenantRegionTag}:pending` is created without a TTL so it survives process crashes and failover. -- It is cleared only when the tick is successfully committed or an operator-driven recovery flow explicitly marks the tick as skipped/failed and removes the key. +- It is cleared only when the tick is successfully committed or a named owner recovery flow (target-state) durably reconciles the authoritative PostgreSQL command/batch/effect state and explicitly marks the tick as skipped/failed under the exact ADR 0085 handoff (`operationId`, fence/lock binding, classifier decision, evidence digest, and complete affected scope), or under an explicitly recorded owner-classified non-conflicting routine replay/cleanup exemption. Missing or incomplete handoff/classification fails closed. Current operators do not have this reset/repair flow; they preserve evidence, keep the affected scope fenced, and use the current fallback and escalation path described above. Session shutdown therefore cleans up session keys but does not implicitly delete region-level tick coordination keys. @@ -182,7 +194,7 @@ Session shutdown therefore cleans up session keys but does not implicitly delete Game Session restores player sessions after disconnects and enforces single-session control as outlined in the [Reconnection Strategy](../../system-architecture-reconnection.md). For Telnet clients, it also consumes best-effort, at-least-once `NotifyDisconnect` events emitted by the TCP Proxy Service over an internal gRPC link and treats them as idempotent hints keyed by `` rather than a guaranteed source of truth. -Game Session persists the latest processed `disconnectSequence` per `` and ignores older or duplicate events so retry behavior at the proxy can remain simple while consumption stays idempotent. Any `{tenantId, gameInstanceId}` values coming from proxy-owned bootstrap metadata or future hidden MCP-carried smart-client hints remain advisory context that may be used for logging and audit, but they are not trusted as authorization claims or binding directives. Game Session still validates any game-instance ownership claims against Redis and its authenticated session state before rebinding the transport. **Current implementation gap:** the live Redis sequence-dedupe path fails open on Redis errors and is reset-loss-vulnerable; no current connection/generation binding guard runs before `NotifyDisconnect` presence or region-exit effects or `GameInstance` suspension. The live path therefore does not yet satisfy the target advisory safety contract; the eventual binding design remains unspecified. +Game Session persists the latest processed `disconnectSequence` per `` and ignores older or duplicate events so retry behavior at the proxy can remain simple while consumption stays idempotent. Any `{tenantId, gameInstanceId}` values coming from proxy-owned bootstrap metadata or future hidden MCP-carried smart-client hints remain advisory context that may be used for logging and audit, but they are not trusted as authorization claims or binding directives. Game Session still validates any game-instance ownership claims against Redis and its authenticated session state before rebinding the transport. **Current implementation gap:** the live `gamesession:notifydisconnect:dedup:` path fails open on Redis errors and is reset-loss-vulnerable; no current connection/generation binding guard runs before `NotifyDisconnect` presence or region-exit effects or `GameInstance` suspension. The live path therefore does not yet satisfy the target advisory safety contract. Until exact connection/generation binding and durable sequencing are proven, Redis loss/error must not authorize stale effects; see the [Redis reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). Recent/offline account-presence state should preserve the last admitted routing bundle too. In target state, when live presence drops to recent presence after transport loss, takeover, or logout, the bounded recent-presence record keeps the last admitted `tenantId`, `gameInstanceId`, `realmId`, `worldSlug`, `realmSlug`, and `pointerVersion` so account-presence and friend-presence reads can continue to describe the last resolved durable realm target directly instead of collapsing immediately to a routing-less timestamp. The current selector-based record does not yet prove durable `{tenantId, realmId}` propagation. @@ -203,6 +215,7 @@ Each running game instance has durable pin state alongside its `runtimeVersion`, - For target remote-follow-up delivery, Game Session revalidates source authority and race-safely captures the target instance's current exact tuple in the durable target delivery/claim. For an authoritative target semantic `UNPINNED`, the existing Game Session result transaction owns exactly one terminal `remote_followup_result` row under `resultId=remote-result:`, with `outcome=ABANDONED`, `resultErrorCode=REMOTE_TARGET_UNPINNED`, canonical empty `resultPayloadJson={}`, and no result command or Automation event/work/command; it updates the existing follow-up/coordinator identities atomically. Exact retries return that row without work, while a changed scope, tuple/identity, outcome, or normalized result-authority fingerprint conflicts without overwrite. This uses existing persisted fields and identities, with no new digest column or outcome family. `authority_unavailable` persists no terminal result and remains non-admitted/retryable under the same follow-up identity after authority recovers. When source and target are the same game instance, including a cross-region follow-up, one authoritative tuple serves both roles. - For each recognized player command, durable staging validates the required gameplay session and current runtime ownership row and reads the exact Game Session-owned current pin state, including `{scriptPatchVersion, scriptPinEpoch, scriptPinControlPlaneRequestId}`, in that same staging transaction. Only an authoritative instance row with all three owner fields absent (`UNPINNED`) means that no script is configured: in that case the transaction creates no `onCommand` outbox/event record and no later tuple is synthesized. When an exact pin exists, it creates one retryable/idempotent `onCommand` outbox/event record keyed by the durable command/event identity; same-identity retries reuse that record, and the post-commit tick kick is only a wake-up/retry hint, not the durability proof. A missing, unreadable, partial, or ambiguous pin-authority result is not `UNPINNED`; staging must retain/retry the command or reject it with bounded `pin_state_unavailable`, never silently suppressing the `onCommand` record. - Scripting availability is not a gameplay admission dependency beyond the normal session and runtime-ownership checks: a scripting outage leaves the staged `onCommand` record retryable while ordinary gameplay and tick processing continue. +- **Current implementation/proof gap:** The live path persists the accepted command and then invokes Automation through an asynchronous best-effort publisher; publisher submission/RPC failures are logged without a durable producer retry or reconstruction record. This is nonconformant with [ADR 0083](../../decisions/adr-0083-no-general-event-broker-until-measured-adoption-gates.md)'s atomic producer-outbox and recoverable consumer-delivery requirements, so an admitted command can currently lose its `onCommand` trigger. The target outbox and per-consumer delivery boundary is not shipped or proven here. - Script-generated commands enter only through the canonical handoff contract. For plugin-originated binding-scoped work, final validation uses the exact tuple `(pluginId, pluginVersionId, bindingId, pluginActivationEpoch, lifecycleRevision)`. The activation epoch and lifecycle revision are execution-fence evidence, not child identity; Game Session enforces them at its owned boundaries and fails closed when any field or its authoritative lifecycle/policy evidence is missing, unavailable, stale, changed, or mismatched. Automation remains the plugin lifecycle and policy authority, and plugin-only changes do not advance `scriptPinEpoch` but do advance the independent lifecycle fence as defined by ADR 0119. - At final execution, any command/work referencing a revocable component, including embedded/core-script and plugin-backed work, carries the applicable component-revocation security-policy fence. Game Session validates current applicable evidence immediately before gameplay effects; missing, stale, unavailable, or mismatched evidence fails closed and records the established bounded component/authority disposition. Plugin-backed work additionally carries the independent `pluginActivationEpoch` and `lifecycleRevision` fences; neither lifecycle fence substitutes for the other or for component policy. @@ -221,7 +234,7 @@ Game Session now has a real current-boundary durable gameplay execution seam ins - accepted gameplay commands persist a durable command ledger row with both a human-safe sanitized text projection and the canonical raw command payload used for later execution; - the tick runtime stages Redis queue work into durable `tick_batch` / `tick_effect` rows before drain commit, including the current-boundary selected-work manifest, expected effect count, and manifest digest on the batch row; - after drain commit, Game Session resumes from any durable `DRAINED` effects for that queue boundary and executes the supported command families from the ledger itself rather than assuming Redis drain already implies terminal gameplay work; -- drained effects re-check the durable runtime owner row before application. If the batch fence is stale, unapplied drained effects are marked `ABANDONED`, their durable commands are requeued for a fresh fenced batch, and the old executor does not invoke the effect handler. +- drained effects re-check the durable runtime owner row before application. In the target contract, a stale fence preserves the effect under its original mutation `EffectId` and enclosing root lineage for evidence-fenced reconciliation; only authoritative evidence that the effect was unapplied may permit `ABANDONED`, and an ordinary retry/replay must retain the original command/effect identity. A post-abandon re-drive is the only path that may allocate a new command ID/root with explicit lineage. The current implementation instead marks stale drained effects/batches `ABANDONED` from the fence/technical signal alone, requeues the same command, and lets a later batch derive a new effect identity; this is unsafe implementation drift that can duplicate a mutation or falsely terminalize an uncertain effect. The live ledger does not yet prove the target retention boundary. Game Session owns cleanup for its command receipts, batches, effects, manifests, and its `tick_effect` ledger/projection. Each domain service owns its participant guards and local cleanup; Game Session retains cross-service blocker references and safe-watermark consequences until those owners provide the evidence that permits ledger cleanup. The family-specific application of [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) is: @@ -252,9 +265,11 @@ Fairness-critical automation enters gameplay through the same durable command/ad The current live `EnqueueAutomationCommandIfAbsent` implementation compares the complete set of immutable fields carried by its request against an existing `gameplay_command` row before returning a duplicate outcome. This includes the command payload and derived name/sanitized text, target, solo-tick and due fields, current routing bundle and region fence, all currently carried source/provenance fields, and the local Automation tuple `(scriptPatchVersion, scriptPinEpoch, scriptPinControlPlaneRequestId)`. The same comparison runs after an atomic insert loses an `ON CONFLICT` race; an exact match may return the existing bounded outcome, while any mismatch—including same-patch epoch drift or owner-request mismatch—returns `REJECTED` with `IDEMPOTENCY_CONFLICT` and does not enqueue. The persisted local tuple is compared again at final execution. Non-script player commands retain their existing admission path and do not acquire these Automation-only fields. Remote Automation follow-ups retain their separate legacy source/target path; this local boundary does not widen remote tuple behavior. See [Scripting Runtime Execution](../../system-architecture-scripting-runtime-execution.md#normative-target-contract) for the owner contract. -- Target-state handoff uses one complete Command-Handoff Identity for each emitted command: source `(tenantId, gameInstanceId, playableStateScope, regionId, regionEpoch)`, optional distinct target `(targetGameInstanceId, targetPlayableStateScope, targetRegionId, targetRegionEpoch)`, the `automationDispatchId` allocated and persisted at the first durable evaluated-descriptor/outbox commit when commands are emitted (not reserved before DSL evaluation), and deterministic `commandOrdinal` in canonical emitted-command order starting at `0`. Optional target fields are present only when the command is routed to a distinct runtime scope, including its own `targetPlayableStateScope` when applicable; same-instance handoffs keep every optional target field absent. Replay selection and child uniqueness use only the complete source runtime scope, any applicable distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`; the parent Trigger Identity, `outboxWorkItemId`, and `scriptEventId` are correlation-only and are excluded from child uniqueness, deduplication, and replay selection. +- Target-state handoff uses one complete Command-Handoff Identity for each emitted command: source `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch)`, optional distinct target `(targetGameInstanceId, targetPlayableStateNamespaceId, targetRegionId, targetRegionEpoch)`, the `automationDispatchId` allocated and persisted at the first durable evaluated-descriptor/outbox commit when commands are emitted (not reserved before DSL evaluation), and deterministic `commandOrdinal` in canonical emitted-command order starting at `0`. The server-derived source and, when applicable, target `playableStateScope` values are separately persisted and exact-validated as policy/routing/authorization/fence evidence, not identity fields. Optional target fields are present only when the command is routed to a distinct runtime scope; same-instance handoffs keep every optional target field absent. Replay selection and child uniqueness use only the complete source runtime scope, any applicable distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`; the parent Trigger Identity, `outboxWorkItemId`, and `scriptEventId` are correlation-only and are excluded from child uniqueness, deduplication, and replay selection. - For a non-exclusive multi-handler event, each emitted child also retains, as non-identity evidence, the already-assigned `handlerSequence` and the event resolution record (or equivalent durable manifest) that identifies the complete ordered handler set, together with that handler's local command order. Game Session preserves and reuses those facts through durable admission, Redis materialization/recovery, retries, and final application; missing or contradictory sequence/completeness evidence fails closed rather than permitting higher-sequence application or arrival-order fallback. An authorized exclusive event carries Automation's sealed complete-resolution proof and sole-handler selection and creates no sibling admission or application; Game Session validates that sealed proof but does not independently resolve bindings or select the handler. - In target state, Game Session records or reads a durable `gameplay_command` admission row through `EnqueueAutomationCommandIfAbsent` using that complete child identity before mutating Redis. Existing child dispatches are classified by durable state: only rows with proven Redis staging or downstream application return duplicate/no-op from the durable key; matching pre-Redis `ACCEPTED` rows enter materialization recovery and may converge to terminal non-applied only after durable proof that neither staging nor application occurred. Without a durable materialization marker or authoritative downstream evidence, the row remains indeterminate and retryable under the same identity. Same-scope dispatches validate and persist one current durable owner/epoch fence; dispatches with a distinct target read and lock the source and target owner rows in one stable canonical owner-identity order, validate each row against its source or target role, and persist both owner/epoch fences before Redis mutation. Missing or paused source/target ownership, or a mismatched source/target `regionEpoch`, returns a non-mutating rejection. The admission row retains the validated source and, when distinct, target owner/epoch fences so retry, Redis materialization, and final execution recheck the stored fences and fail closed on displacement. The row stores optional `dueTickId`, target entity, parent/work-item correlation fields, command payload, and current execution outcome. Target-state action execution persists a structured `GameplayActionOutcome` rather than relying on one free-form result string; Game Session renders its separate semantic presentation events without interpreting target-leg state itself. +- Current live handoff wording retains an optional `dueTickId` for scheduler/timer work; this is not the target wire or storage contract and must not encode a wall-clock due point as a tick value. +- In target state, scheduled admission rows carry exactly one tagged due point, `dueTickId:` or `dueAt:`, with the alternate physical due column `NULL`; immediate event-driven rows use a separate branch, omit scheduler-only fields and `duePoint`, and keep both physical due columns `NULL`. The branch and due point are retained as immutable comparison/readback evidence through materialization, retry, replay, and final execution. - Conflicting payloads for the same key are validation failures and must not enqueue. - Only after durable admission succeeds does Game Session invoke the region-lease Redis script that materializes the command into `tick:{tenantRegionTag}:queue:`. - If Redis enqueue times out or returns an unknown outcome after durable admission, a missing acknowledgement is not terminal evidence: Game Session reconciles materialization under the same durable child identity using a durable materialization marker or equivalent authoritative staging/downstream-application evidence before choosing an outcome. Only a proven pre-materialization failure with proof that no staging or application occurred may converge to terminal non-applied; otherwise the retry/idempotency path remains active. Redis queue contents are never the sole proof that the automation action existed. @@ -264,7 +279,7 @@ Current implementation/proof gap: the live recovery path still terminalizes stal ## Saga Participation -Game Session includes the `common-saga` module and its migrations as a normal service dependency; the optional element is the `SagaRunner` bean and the dependency check that uses it. The current start hook uses that check only to ping Entity Management and Game Logic when those clients and the `SagaRunner` are available; when the optional bean is unavailable, the check is skipped. The saga runner is not the authority for game startup or shutdown, does not coordinate World Management's lifecycle, and is not the cross-service lifecycle-compensation mechanism. Target start-failure cleanup follows Game Session's explicit local cleanup and fenced World lifecycle calls; current implementation status is that the failed-preparation call stops at the World `FAILED_PRE_ACTIVATION` state and does not yet initiate the durable termination and owner-cleanup flow. World Management's durable lifecycle row and epoch remain authoritative, with Temporal coordinating the restart-safe lifecycle workflow; Game Session consumes that evidence and performs its owner-local session-state consequences. See [Transaction Strategies](../../system-architecture-transactions.md) and [Database-Authoritative, Temporal-Coordinated World Lifecycle](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). +Game Session includes the `common-saga` module and its migrations as a normal service dependency; the optional element is the `SagaRunner` bean and the dependency check that uses it. The current start hook uses that check only to ping Entity Management and Game Logic when those clients and the `SagaRunner` are available; when the optional bean is unavailable, the check is skipped. Short synchronous Saga use in Game Session is limited to caller-owned dependency/startup checks; session stop uses the direct World termination seam. The saga runner is not the authority for game startup or shutdown, does not coordinate World Management's lifecycle, and is not the cross-service lifecycle-compensation mechanism. Target start-failure cleanup follows Game Session's explicit local cleanup and fenced World lifecycle calls; current implementation status is that the failed-preparation call stops at the World `FAILED_PRE_ACTIVATION` state and does not yet initiate the durable termination and owner-cleanup flow. World Management's durable lifecycle row and epoch remain authoritative, with Temporal coordinating the restart-safe lifecycle workflow; Game Session consumes that evidence and performs its owner-local session-state consequences. See [Transaction Strategies](../../system-architecture-transactions.md) and [Database-Authoritative, Temporal-Coordinated World Lifecycle](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). ## Runtime Data Notes diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index f91d573a40..46c08e9f43 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -47,7 +47,7 @@ The local API surface retains only Logging & Admin consequences of the owner con ## REST -- `GET /ping` – basic health check returning `"pong"`. +- Current `GET /ping` – privileged Bearer JWT-protected basic health check returning an `ApiResponse` with `data: "pong"`. The target classification remains Public/infra health under platform health policy; the HTTP route has not converged to that target. - `GET /game-session-pins/{tenantId}/{gameInstanceId}` (`getPinnedScriptPatchVersion`) – live tenant-scoped bounded read returning `PinnedScriptPatchVersionDto` through the internal Game Session `GetPinnedScriptPatchVersion` RPC; it is not a Logging & Admin gRPC operation, and the current DTO omits `scriptPinEpoch`. - `GET /game-session-pins/{tenantId}/{gameInstanceId}/convergence` (`getGameSessionPinConvergence`) – live tenant-scoped bounded read returning `GameSessionPinConvergenceDto` through the internal Game Session `GetGameSessionPinConvergence` RPC; it is not a Logging & Admin gRPC operation, and the current DTO omits `observedScriptPinEpoch`. @@ -113,12 +113,12 @@ The internal admission-pointer service/owner paths represent exactly one of two - Game Session remains the sole routing-state writer and audits the transition under the same identity and CAS result. Internal callers must not maintain a competing pointer or infer `tenantId` from `worldSlug` or `realmSlug`; Logging & Admin's public REST surface reads the resulting state and audit evidence only. ```bash -curl http://localhost:8080/ping +curl -H 'Authorization: Bearer ' http://localhost:8080/ping ``` ## gRPC -- `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in [`logging_admin_service.proto`](../../../../protos/logging-admin/v1/logging_admin_service.proto). +- `Ping(PingRequest) returns (PingResponse)` – connectivity check defined in [`logging_admin_service.proto`](../../../../protos/logging-admin/v1/logging_admin_service.proto); the current gRPC interceptor requires a Bearer JWT, while the target classification remains platform health policy. - `QueryLogs(QueryLogsRequest) returns (QueryLogsResponse)` – queries the service-owned PostgreSQL `log_events` table for the exact tenant and case-insensitive message containment and returns matching stored messages; it does not query the deployed structured-log pipeline. - `ApplyModerationAction(ApplyModerationActionRequest) returns (ApplyModerationActionResponse)` – unavailable/gated implementation contract for moderation policy input/audit until the action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account authorization-reference issuance, and receiving-boundary validation/redemption exist; it now hard fails closed with an application-level `UNAVAILABLE` error before dispatch or persistence, while separate fixed-category policy/audit evidence and owner enforcement are absent, and it is not current supported external operator mutation. Target behavior uses one Account reference bound to the exact request identity/digest and redeemed exactly once by Logging & Admin for local policy-input/audit persistence; that reference is never forwarded or reused. Any future owner-enforcement command uses a separate Account reference redeemed once by its receiving owner. `EvaluateModerationPolicy` remains the live read contract used at owner enforcement boundaries and carries no mutation authorization reference. - `CreateModerationAppeal` / `GetModerationAppeal` – target-only bounded case submission and status reads. Logging & Admin owns case/evidence/jurisdiction/review state; Account supplies authenticated browser handoff and notifications, while any modified or overturned result returns a separate owner-command outcome rather than mutating enforcement locally. `DECIDED` is the terminal case fact; owner execution uses ADR 0048's phase-qualified states, and `RETRYABLE` is guidance to poll/retry reconciliation for the same command identity/digest only. No current implementation or proof is claimed. @@ -149,7 +149,7 @@ curl http://localhost:8080/ping - Tick-remediation is not a Logging & Admin-owned state-mutation gRPC surface. Its HTTP ingress is hard fail closed and no Logging & Admin pause/resume forwarding method remains callable internally; the target owner contract remains unavailable until the minimum schema/authorization gate above and the complete [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md) durable, idempotent, fenced owner-execution contract are implemented and proved. Once enabled, Logging & Admin audits and forwards to Game Session, which owns tick state, fencing, idempotency, and the durable result. Future recovery operations require separate named typed owner contracts; no generic `remediate` RPC is reserved. ```bash -grpcurl -plaintext localhost:6565 logging_admin.v1.LoggingAdminService/Ping +grpcurl -plaintext -H 'Authorization: Bearer ' localhost:6565 logging_admin.v1.LoggingAdminService/Ping # Non-production local harness only; production callers require the target internal workload/method authorization, which remains unproved by the current transport configuration. grpcurl -plaintext -d '{"tenant_id":"1","reporter_account_id":"1","target_account_id":"2","type":"BUG","description":"example"}' \ @@ -162,7 +162,7 @@ Operator authentication and receiving-boundary rules are canonical in the [Autho | Surface | Examples | Required auth path | Notes | | --- | --- | --- | --- | -| Public/infra health | `GET /ping`, `Ping` | Internal network + platform health policy | Not a user-authenticated business operation. | +| Public/infra health (target; current HTTP/gRPC drift) | `GET /ping`, `Ping` | Target: internal network + platform health policy. Current HTTP `/ping`: privileged Bearer JWT; current gRPC `Ping`: Bearer JWT via interceptor. | The current HTTP route is not public: the shared interceptor returns `401` for missing/invalid credentials and `403` when the caller lacks a global privileged role. The current gRPC interceptor rejects missing/invalid credentials with `UNAUTHENTICATED`. | | Administrative report persistence (HTTP) | Unavailable; the unsafe former `POST /reports` controller and `/api/admin/reports/**` exposure were removed, and any restored administrative route uses `POST /admin/reports` | [Operator route authentication](../../system-architecture-authz-route-matrix.md#operator-delegation) | The administrative route remains unavailable until tenant scope, reporter relationship, optional target relationship, report policy, and authorization-reference checks are implemented. This is not player ingress. `POST /reports` is reserved for a separate player-bootstrap contract and must bind `player-bootstrap` authority independently. | | Read/investigation APIs (HTTP) | `/logs/query`, `/sagas*`, `GET /admission-pointers`, `GET /admission-pointers/{tenantId}/{worldSlug}/{realmSlug}/audit`, `GET /admission-pointers/version-upgrades/{tenantId}/{preparationId}`, `GET /game-session-pins/{tenantId}/{gameInstanceId}`, `GET /game-session-pins/{tenantId}/{gameInstanceId}/convergence` | The exact route-declared read auth path, normally `control-ui` plus current role and route classification | These surfaces do not mutate domain or policy state and do not receive an operator mutation reference. The two game-session-pin reads are current tenant-scoped controller routes: the REST path variables are positive decimal numeric text parsed to `long`; the controller validates positive decimal numeric `tenantId`/`gameInstanceId` values and authorized tenant scope before the internal Game Session RPC. The internal proto fields are strings carrying the same decimal numeric text, and `GameSessionPinConvergenceDto` currently emits the identifiers as JSON integer values; exact client round-trip above JavaScript's safe-integer limit is an explicit implementation gap, not a supported contract. Canonical UUID strings remain the target migration state per the [Identifier Glossary](../../system-architecture-identifier-glossary.md). They are not currently Gateway-forwarded. The other listed routes are the live admission-pointer read/audit/proof-read boundary; admission-pointer and preparation writes have no public HTTP route. | | Gated human mutation (HTTP) | Service-local `/moderation/actions` | [Operator route authentication](../../system-architecture-authz-route-matrix.md#operator-delegation) plus the action-family schema, shared `mutationDigest/v1` vectors, Account-issued authorization reference, and Logging & Admin validation/redemption | Unavailable at external Gateway ingress until the minimum schema/authorization gate and local durable intent/audit execution contract are implemented. The current service-local controller hard fails closed after its tenant-access check with HTTP `503 Service Unavailable`, without dispatch or persistence, and has no separate fixed-category audit evidence or owner enforcement. Once conformant, Logging & Admin redeems the intent reference and records durable policy intent/case/audit evidence locally; it does not forward that reference. A future owner-enforcement command is a separate contract with a separately issued reference redeemed by the receiving owner. | diff --git a/design/architecture/microservices/logging-admin-service/runtime-and-data.md b/design/architecture/microservices/logging-admin-service/runtime-and-data.md index a8953c8b6f..f58464631b 100644 --- a/design/architecture/microservices/logging-admin-service/runtime-and-data.md +++ b/design/architecture/microservices/logging-admin-service/runtime-and-data.md @@ -55,7 +55,7 @@ In addition to log and moderation tooling, the service acts as a control-plane c Game Session remains the only service allowed to mutate gameplay coordination state or execute tick pause/resume behavior. Logging & Admin owns operator UX, automation policy, and audit only; it does not become the runtime state owner for remediation. -There is no generic remediation command language. Ordinary actions use named owner contracts. Composed recovery exposes only a small high-level vocabulary such as pause, status, recover or reset, and resume through one durable workflow owner. Exceptional direct Redis maintenance remains separate version-matched break-glass tooling with dedicated narrow credentials, forced verification, and recovery evidence; Logging & Admin may invoke that owner or tool but never receives those credentials itself. +There is no generic remediation command language. Ordinary actions use named owner contracts. Composed recovery exposes only a small high-level vocabulary such as pause, status, recover or reset, and resume through one durable workflow owner. The evidence-qualified `replay_first`/`reset_first` selection and external durable maintenance operation/fence remain owned by [Redis Reset & Recovery](../../system-architecture-redis-reset-and-recovery.md); the named maintenance operation is target-state-only and unavailable for current invocation until its owner contract and complete evidence and release gates are implemented and proved. Logging & Admin may display that owner's projection and, once available under the owner's gates, request the named operation, but neither its projection nor its coordinator role is runtime authority or the maintenance fence. Exceptional direct Redis maintenance remains separate version-matched, incident-only break-glass tooling with dedicated narrow credentials, forced verification, and recovery evidence; without the target tooling, the current path is evidence preservation, fencing, and escalation, and Logging & Admin never receives or holds those credentials. Operator and support diagnostics do not impersonate a player, attach to a live player session, or observe gameplay through a hidden actor. They use purpose-built, minimized support-safe reads, logs, dashboards, reports, moderation records, and explicit control-plane operations. Break-glass controls remain separately authorized and audited and must not create a player actor, gameplay session, or tenant-scoped gameplay capability. @@ -130,6 +130,6 @@ When enabled, policy intent, case, appeal, owner-result, and audit records are r ## Saga Dashboard -The service exposes `/sagas` and `/sagas/{id}/steps` endpoints for operators to inspect short synchronous orchestration coordinated via the shared Saga library. These routes read Logging & Admin-local rows only, do not aggregate adopter-local state, return `404 NOT_FOUND` for an unknown Saga instance, and preserve `200` with an empty list for a known instance with no steps. If the conditional Saga/database beans are unavailable, they fail closed with `503 SAGA_DASHBOARD_UNAVAILABLE`. Durable long-running workflow inspection belongs on the corresponding Temporal adopter read surfaces, not on the shared saga dashboard. The dashboard reads from the `saga_instance` and `saga_step` tables and publishes a `sagas.active` Prometheus gauge. +The service exposes `/sagas` and `/sagas/{id}/steps` as local-schema-only read surfaces for short synchronous orchestration coordinated via the shared Saga library. They read only this service's `${serviceSchema}.saga_instance` and `${serviceSchema}.saga_step` tables, expose no foreign-service state, acquire no execution authority, return `404 NOT_FOUND` for an unknown Saga instance, and preserve `200` with an empty list for a known instance with no steps. If the conditional Saga/database beans are unavailable, they fail closed with `503 SAGA_DASHBOARD_UNAVAILABLE`. A future cross-service dashboard must fan out through read-only per-service Saga status APIs rather than read foreign databases or execute Saga actions. Durable long-running workflow inspection belongs on the corresponding Temporal adopter read surfaces, not on the shared saga dashboard. The local dashboard publishes a `sagas.active` Prometheus gauge. See [Transaction Strategies](../../system-architecture-transactions.md) for an overview of Saga usage across FireMUD. 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 f4a18ea950..7862f3159b 100644 --- a/design/architecture/microservices/world-management-service/world-creation-workflow.md +++ b/design/architecture/microservices/world-management-service/world-creation-workflow.md @@ -1,6 +1,6 @@ # World Creation Workflow -World creation is a long-running process that prepares the initial world state for a new **game instance** using already-published world data for a given `tenantId`. The workflow now runs on the shared **Temporal** substrate so prepare/activate/fail/terminate orchestration survives service restarts, keeps deterministic workflow identity, and exposes operator-visible execution status without pulling gameplay runtime onto the workflow engine. [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) owns lifecycle authority and all-owner cleanup convergence; this document records the World workflow consequence. [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) owns stable playable identity and replacement classification. World Management's activation lifecycle surface is invoked when the platform provisions a new game instance for an existing tenant, typically from the Game Session Service. The identifiers involved are: +Target state: World creation is a long-running process that prepares the initial world state for a new **game instance** using already-published world data for a given `tenantId`. The target workflow runs on the shared **Temporal** substrate so prepare/activate/fail/terminate orchestration survives service restarts, keeps deterministic workflow identity, and exposes operator-visible execution status without pulling gameplay runtime onto the workflow engine. The current implementation/proof is partial: extracted prepare/activate/status and a synchronous termination seam exist, but complete restart-safe lifecycle, durable step guards, frozen all-owner cleanup, and termination proof remain incomplete. [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) owns lifecycle authority and all-owner cleanup convergence; this document records the World workflow consequence. [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) owns stable playable identity and replacement classification. World Management's activation lifecycle surface is invoked when the platform provisions a new game instance for an existing tenant, typically from the Game Session Service. The identifiers involved are: - `tenantId` – identifies the game (tenant) as described in [Multi-Tenancy](../../system-architecture-multi-tenancy.md). @@ -11,7 +11,7 @@ World creation is a long-running process that prepares the initial world state f the Game Session Service. - `playableStateNamespaceId` – identifies durable playable state independently of the replaceable runtime instance. World retains the resolved namespace across replacement and uses the instance id only for topology and other explicitly instance-scoped state. -The cross-platform workflow placement and adopter-proof requirements are owned by [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification) and [Temporal Control-Plane Workflows](../../system-architecture-temporal-workflows.md). This document records the World Management consequences: the target `world-lifecycle` workflow coordinates the local lifecycle commands and read surface, while World Management's durable lifecycle row and epoch remain authoritative, with durable launch/workflow identity plus shared digest-bound step identity (stable step name, deterministic occurrence, execution role, and immutable request digest; see [ADR 0078](../../decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md)). Gameplay ticks and live in-world mutations remain outside this workflow. Current lifecycle proof covers the extracted command path and Temporal-backed status surface, while full durable step-guard and restart/failure proof remains an implementation gap noted below. +The cross-platform workflow placement and adopter-proof requirements are owned by [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification) and [Temporal Control-Plane Workflows](../../system-architecture-temporal-workflows.md). This document records the World Management consequences: the target `world-lifecycle` workflow coordinates the local lifecycle commands and read surface, while World Management's durable lifecycle row and epoch remain authoritative. Its canonical Temporal workflow ID is stable per world instance, and retries use that workflow identity plus durable launch/workflow identity and the shared digest-bound step identity (stable step name, deterministic occurrence, execution role, and immutable request digest; see [ADR 0078](../../decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md)). Gameplay ticks and live in-world mutations remain outside this workflow. Current lifecycle proof covers the extracted command path and Temporal-backed status surface, while full durable step-guard and restart/failure proof remains an implementation gap noted below. The current `TemporalWorldLifecycleOrchestrator` also treats `WorkflowExecutionAlreadyStarted` as reuse and returns the existing snapshot without exact-comparing its complete immutable prepared-launch identity with the incoming request. Until that race path validates at least the exact `controlPlaneRequestId` and `launchDescriptorId` plus every other immutable `PreparedWorldInstanceRequest` field, a conflicting request can observe the existing workflow as a successful retry; this is an implementation and race-proof gap, not target authorization to reuse a mismatched workflow. ## Implementation Status @@ -32,7 +32,7 @@ World creation consumes a previously resolved immutable launch descriptor for th For replacement-instance launches, World Management now persists the frozen `remapSetId` on `world_instance` so later cutover/termination consumers can prove they are still operating on the same approved cross-version remap identity that launch resolution selected. -Game Design owns the immutable mapping from `` to `launchDescriptorId`. After validating that descriptor, the Game Session instance-creation orchestrator owns the durable mapping from the same launch attempt and `launchDescriptorId` to one `gameInstanceId`; an exact retry reuses both mappings, while a conflicting descriptor, template, or instance fails closed. World workflow execution consumes those identities under the distinct business scope ``, while each lifecycle step uses the shared digest-bound workflow/step guards and its deterministic occurrence and role. `controlPlaneRequestId` is the sole launch/workflow request identity; neither a separate world-creation request ID, a Temporal run/attempt identity, nor a generated instance may replace it. +Game Design owns the immutable mapping from `` to `launchDescriptorId`. After validating that descriptor, the Game Session instance-creation orchestrator owns the durable mapping from the same launch attempt and `launchDescriptorId` to one `gameInstanceId`; an exact retry reuses both mappings, while a conflicting descriptor, template, or instance fails closed. The canonical Temporal workflow ID is `world-lifecycle::game-instance:`, stable across workflow run replacement. `controlPlaneRequestId` and `launchDescriptorId` remain immutable launch/request and digest/step evidence bound to that workflow; they are not workflow-ID components. Each lifecycle step uses the shared digest-bound workflow/step guards and its deterministic occurrence and role. The target workflow uses the published world topology for the chosen `tenantId` and `version_id`, inserts a starter region instance, and can generate terrain chunks and materialize instance-scoped population schedules for expansive worlds. Any initial event scheduling remains subject to the owning typed effect contract; while the Weather aggregate selector is unresolved, initial Weather scheduling is explicitly deferred and non-mutating. Activation-time topology must be derived only from the attested published template graph plus runtime generation runs whose canonical inputs are covered by the same published `generationConfigRevision`. Throughout the workflow, the Temporal workflow and its activities: @@ -130,7 +130,7 @@ Illustrative operator-facing workflow status fragment: ```json { "workflowFamily": "world-lifecycle", - "workflowId": "world-lifecycle:7b3b074e-d597-4e9b-b96f-4f5946d26120:world-instance:9a2bb6d1-74c7-4f81-a9e8-418e65f6ad78:request:wc-77", + "workflowId": "world-lifecycle:7b3b074e-d597-4e9b-b96f-4f5946d26120:game-instance:9a2bb6d1-74c7-4f81-a9e8-418e65f6ad78", "workflowStatus": "RUNNING", "tenantId": "7b3b074e-d597-4e9b-b96f-4f5946d26120", "gameInstanceId": "9a2bb6d1-74c7-4f81-a9e8-418e65f6ad78", @@ -150,7 +150,7 @@ Illustrative operator-facing workflow status fragment: World creation steps write durable instance rows and must be safely retryable under the general workflow/request and step-guard contract owned by [Transaction Strategies](../../system-architecture-transactions.md) and explained by [ADR 0078](../../decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md). This adopter document supplies workflow-local inputs without redefining the guard policy: -- Stable business scope is the resolved launch attempt for `` and its immutable `launchDescriptorId`. +- Stable business scope is the resolved world instance for ``. The immutable `controlPlaneRequestId` and `launchDescriptorId` remain bound launch/request and digest/step evidence for that workflow identity. - The stable step name identifies the lifecycle operation, while a deterministic occurrence key distinguishes each logical occurrence of that operation; for generation stages, the target-state `generationRequestId` is part of that occurrence input so retries across workflow runs converge on the same logical generation result. Its allocation and propagation remain unimplemented as noted above. - The execution role distinguishes forward preparation/activation work from applicable pre-activation compensation; it is not inferred from a Temporal run, process, retry attempt, or message/delivery identifier. - The immutable request-digest input covers the exact resolved launch descriptor and step request values used by the operation, including `expectedGenerationConfigRevision` and, where applicable, `generationRequestId`. Digest construction, persistence, comparison, and guard storage remain governed by the shared contract and are not specified here. @@ -172,6 +172,12 @@ The current `TemporalWorldLifecycleOrchestrator` workflow ID is derived only fro Temporal owns orchestration and workflow progress using the canonical `world-lifecycle` workflow identity; World Management's durable lifecycle row and epoch remain authoritative for lifecycle state. Operators can inspect progress through the normal lifecycle read surface and any Temporal-backed operator tooling that projects the same `workflowId`. +### Lifecycle signal identity and serialization + +The target workflow must represent each activate, fail, or terminate request as a durable queued signal/update envelope carrying a stable operation identity, normalized request digest, expected lifecycle epoch/status, and owner CAS evidence. Exact retries read back one logical result; changed identity, digest, status, or epoch fails closed, and conflicting lifecycle operations follow explicit precedence/conflict rules rather than last-writer-wins behavior. A signal may not be combined with or overwrite another logical operation whose outcome is still unresolved. + +**Current implementation gap:** `TemporalWorldLifecycleWorkflowImpl` stores only one pending epoch/reason per signal type and has no operation identity or digest. Repeated same-type signals overwrite one another, while an activate and terminate received together are both processed sequentially; termination then reuses the pre-activation epoch after activation has advanced it and can retry until the workflow fails. The current `TemporalWorldLifecycleOrchestrator`/workflow path therefore does not provide one durable lifecycle result for concurrent or lost signal requests. This is in addition to the existing `AlreadyStarted` identity-comparison gap above and remains unproved until the queued envelope, owner lifecycle CAS, conflict handling, and readback result are implemented. + See [World Management Service](README.md) for additional service context. See [Transaction Strategies](../../system-architecture-transactions.md) for the canonical boundary between ticks, short synchronous saga orchestration, and durable Temporal workflows. diff --git a/design/architecture/system-architecture-identifier-glossary.md b/design/architecture/system-architecture-identifier-glossary.md index 981cfe08b3..ec0c199166 100644 --- a/design/architecture/system-architecture-identifier-glossary.md +++ b/design/architecture/system-architecture-identifier-glossary.md @@ -84,9 +84,11 @@ World Management may use a numeric room row key as `roomInstanceId` only when it Tick-driven, cross-service mutations are at-least-once and must be idempotent. -- `EffectId` – the stable root identity for one logical effect. Game Session assigns it once from the admitted operation and its authoritative tick context; ordinary retry, recovery, and replay preserve it. It is not derived from mutable payload or regenerated for a replay. A fresh root is reserved for a **post-abandon re-drive**: the original effect must be conclusively terminal `ABANDONED` with its source claim terminalized, then recovery allocates a later coordinate, fresh root, new retry/source identity, and durable lineage. An implementation may store it opaquely only when the canonical identity projection remains retained or deterministically recoverable. -- **Participant guard identity** – a deterministic uniqueness identity derived from exactly the root `EffectId`, typed operation, and target aggregate. Its durable guard binds that identity to the immutable request digest; the durable outcome and other evidence/reconciliation fields are mutable guard-row state protected by CAS, not part of uniqueness identity. Same guard identity with the same request returns the prior result; a changed operation, target, or digest fails closed. Derived reactions receive deterministic child `EffectId` values. -- The root effect identity, required participant set, and participant outcomes are Game Session reconciliation data. The durable guard/effect behavior is owned by [Transaction Strategies](./system-architecture-transactions.md) and must not be replaced with an ad-hoc service-local key. +- `EffectId` – the opaque stable identity for one logical effect. For command-root work, Game Session allocates the root `EffectId` under the durable command-plan binding owned by [Transaction Strategies](./system-architecture-transactions.md#command-atomicity-and-outcome-aggregation); retries, replays, and reconciliation of that admitted command-root work reuse the same root. A generated child has its own persisted deterministic child `EffectId` while retaining the enclosing root and parent lineage; it does not allocate another command-plan root. Passive, inbound/remote, timer, and retry work that is not materialized as an admitted command retains its owner/source-specific root rather than being assigned a command-plan root. Participants never derive or replace an admitted identity. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative and does not change this accepted glossary contract. +- `deterministic effect plan` – the frozen semantic order of logical command-root effects admitted for one command. Its owner-supplied order, persisted manifest, allocation binding, replay checks, Automation handoff mapping, and command-only scope are defined once by [Transaction Strategies](./system-architecture-transactions.md#command-atomicity-and-outcome-aggregation). +- `planOrdinal` – the stable zero-based position of a root in its command's deterministic effect plan, assigned in the supplied semantic order. It is command-root binding metadata, not a scheduler/source-ordering, staging, participant, trigger, or generated-child ordinal. +- **Participant guard identity** – a deterministic uniqueness identity under the owning runtime-family contract. For owner-classified S1/S2 families, the durable guard partition is `(tenantId, playableStateNamespaceId)` plus the owning identity/effect (`EffectId`, typed operation, and target aggregate); `gameInstanceId` is not a uniqueness dimension and is carried and exact-validated separately as active-runtime authorization/fence evidence. Only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)` as its durable partition; an unknown or unclassified family is rejected before any participant-guard allocation or admission and is never treated as S3 by default. A root effect uses its root `EffectId`; a generated child mutation uses its persisted child `EffectId`, while the enclosing root remains lineage and reconciliation context rather than collapsing sibling guards. The child ordinal participates in deterministic child-ID derivation under the owning contract but is not a second guard-key field. For S1/S2, `playableStateNamespaceId` is the uniqueness partition; `playableStateScope` and `gameInstanceId` are separately persisted, exact-validated routing/authorization/fence evidence and are not additional uniqueness dimensions. Same family-partitioned guard identity with the same request and evidence returns the prior result; a changed tenant, namespace, owning effect, operation, target, scope, digest, or separately validated active-instance fence fails closed. Work explicitly outside playable-state scope must use an accepted owner-specific idempotency/partition contract; it cannot omit namespace/scope and proceed under this gameplay participant-guard contract. The durable outcome and other evidence/reconciliation fields are mutable guard-row state protected by CAS, not part of uniqueness identity. A conserved multi-participant operation normally shares one effect identity but still follows [ADR 0053](./decisions/adr-0053-command-atomicity-by-invariant-class.md)'s atomicity/co-location/reservation semantics. +- The root effect identity, required participant set, and participant outcomes are Game Session reconciliation data. The durable plan allocation and guard/effect behavior are owned by [Transaction Strategies](./system-architecture-transactions.md) and must not be replaced with an ad-hoc service-local key. ## Cross-Service Causal-Read Fence Identity diff --git a/design/architecture/system-architecture-overview.md b/design/architecture/system-architecture-overview.md index a29c60ef9b..24d7824cf3 100644 --- a/design/architecture/system-architecture-overview.md +++ b/design/architecture/system-architecture-overview.md @@ -54,7 +54,7 @@ The documents linked from this overview describe the target-state design, but th - **Redis topology policy:** In all non-ephemeral environments, Coordination Redis and Cache/Rate-Limit Redis are separate deployments. Local development is treated as non-ephemeral and should run two Redis deployments to exercise role separation. Only an explicitly labelled one-shot test/CI stack may collapse roles into a single Redis instance, and it must be guarded as an ephemeral topology; hosted `pr-preview` is not exempt. - **Coordination Redis ownership boundary:** Coordination Redis prefixes and fences are owner-governed (Game Session for gameplay coordination prefixes such as `session:game:*`, `tick:*`, `timer:*`, `retry:*`, and `tick-executor-lease:*`; Account Service for the registered auth-session and exact-input issuance-result families; Automation & Scripting for its documented scheduling families; Spring Cloud Gateway only for the narrow edge replay/denial contract), and no wildcard grant over future families is implied. The Account connect-token family is distinct from Gateway replay markers and follows its Account-owned fail-closed reset/recovery consequence. Gateway's exception does not grant it general Coordination Redis ownership. Non-owner participation is allowed only through documented shared-helper contracts. See [ADR 0009](./decisions/adr-0009-coordination-redis-ownership-boundary.md), [Redis Coordination Invariants](./system-architecture-redis.md#coordination-vs-cache-prefixes), the [reset policy matrix](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary), and the Gateway replay/denial contract in [Gateway Architecture](./system-architecture-gateway.md). - **TCP Proxy identity canonicalization:** Gateway selects exactly one environment-bound TCP Proxy trust profile. Steady-state player-facing deployments require the exact environment-specific URI SAN identity; named DNS migration and fingerprint break-glass profiles are explicit and expiring, while CIDR trust is development/test-only. See [ADR 0169](./decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md). -- **Canonical room-read composition:** [Transaction Strategies](./system-architecture-transactions.md) owns split spatial authority and operation-bound effect behavior. The [Identifier Glossary](./system-architecture-identifier-glossary.md#cross-service-effect-identity) owns root `EffectId`/participant identity, and its [causal-read fence contract](./system-architecture-identifier-glossary.md#cross-service-causal-read-fence-identity) owns the requested floor and composite identity. Game Logic composes World occupancy with Entity presentation under those owner contracts; see [Canonical Room Runtime Contract](#canonical-room-runtime-contract). +- **Canonical room-read composition:** [Transaction Strategies](./system-architecture-transactions.md) owns split spatial authority and operation-bound effect behavior. The [Identifier Glossary](./system-architecture-identifier-glossary.md#cross-service-effect-identity) owns root `EffectId`/participant identity and enclosing-root lineage, and its [causal-read fence contract](./system-architecture-identifier-glossary.md#cross-service-causal-read-fence-identity) owns the requested floor and composite identity. Game Logic composes World occupancy with Entity presentation under those owner contracts; see [Canonical Room Runtime Contract](#canonical-room-runtime-contract). Exact generated-child allocation remains non-authoritative in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). - **Canonical room-read interoperability:** The current live proto seam carries World `worldSnapshotId` / `world_snapshot_id` and Entity `entitySnapshotId` / `entity_snapshot_id` as deterministic scope markers only; both request paths are floor-free. Game Session allocates the complete target `CausalReadFence`, including `regionId`, from durable region commit authority before invoking `ResolveLook`, and Game Logic propagates that floor unchanged to World and Entity. Each participant returns the same region/scope/epoch proof, a scoped `servedThroughTickId`, and an opaque component version. Same-region/scope/epoch responses with `servedThroughTickId >=` the requested `committedTickId` are accepted; a participant behind the floor or mixed region/scope/epoch is rejected or retried, and opaque component versions are not directly compared. The composed identity exposes only the requested floor plus World and Entity component versions; `servedThroughTickId` is response validation proof, not an additional identity member. The target request/response and composite-proof protocol is not present in the current adapter/proto path. - **Durable cross-region effects and static live topology:** Cross-region gameplay uses durable asynchronous legs and current-epoch/executor-fence validation rather than shared region locks. Origin commit means the remote leg is durably scheduled, not that the whole command succeeded; old-epoch work is terminalized only when authority-fenced evidence proves it applied or was unapplied under [ADR 0067](./decisions/adr-0067-abandon-old-epoch-work-and-reschedule-with-new-lineage.md). Inconclusive old-epoch work remains fenced, non-terminal, and reconciliation-required, blocking new lineage and reopen. A normally open instance has static region topology; split/merge is an operator-controlled maintenance cutover with admission barriers, bounded drain, evidence-qualified terminalization, durable mapping installation, Redis rebuild, and controlled reopen. See [ADR 0055](./decisions/adr-0055-durable-cross-region-effects-with-static-live-topology.md). - **Logical-effect reconciliation authority:** Game Session owns one durable reconciliation record per logical effect, freezes its expected participant set at admission, derives the cross-owner player outcome, and runs retries in isolated resource-bounded workers. World, Entity, and other domain services retain write authority and report their durable participant outcomes; they do not create competing retry ledgers. See [ADR 0057](./decisions/adr-0057-game-session-owned-reconciliation-with-isolated-workers.md). @@ -665,9 +665,9 @@ To avoid drift between gameplay orchestration, entity state, and world occupancy 2. Game Logic computes deterministic movement/travel outcomes (valid destination, cost, and mechanics). 3. World Management performs the authoritative location/occupancy commit for the target room/region instance. 4. Entity Management applies entity-side state updates (stats/effects/inventory consequences) but does not maintain a competing authoritative occupancy index. -5. Each actual mutation owner derives its operation/aggregate-specific guard from the root `EffectId`, binds it to the immutable request digest, and returns a durable result; evidence-only services are not artificial mutation participants. Retries/replays use the same identity and converge through owner guards and Game Session reconciliation; no service may treat local admission or partial writes as authoritative command completion. +5. Each actual mutation owner uses its persisted effect identity, binds its operation/aggregate-specific guard to the immutable request digest, and returns a durable result; evidence-only services are not artificial mutation participants. Retries/replays use the same identity and converge through owner guards and Game Session reconciliation; no service may treat local admission or partial writes as authoritative command completion. -`DROP` and `PICKUP` are Entity-local containment commits against the admitted `RoomInstanceRef`; World location/version evidence is carried in an attestation bound to the root `EffectId`, `actorEntityId`, `RoomInstanceRef`, operational `regionId`, `regionEpoch`, `executorFence`, and `requestDigest`, and Entity verifies that binding with its participant guard at local commit. Game Session's durable barrier and actor-lock/fence gate prevents a conflicting `MOVE` across lock expiry or handoff until terminal evidence; stale re-resolution is requested by Game Session through Game Logic under the same root `EffectId`, preserving the `requestDigest`. A later valid `MOVE` is allowed after Entity commit and barrier terminalization. The current proto/request and focused proof do not yet carry or demonstrate this attestation/barrier path. +`DROP` and `PICKUP` are command-root Entity-local containment commits against the admitted `RoomInstanceRef`; World location/version evidence is carried in an attestation bound to the command-root `EffectId`, `actorEntityId`, `RoomInstanceRef`, operational `regionId`, `regionEpoch`, `executorFence`, and `requestDigest`, and Entity verifies that binding with its participant guard at local commit. Game Session's durable barrier and actor-lock/fence gate prevents a conflicting `MOVE` across lock expiry or handoff until terminal evidence; stale re-resolution is requested by Game Session through Game Logic under the same command-root `EffectId`, preserving the `requestDigest`. A later valid `MOVE` is allowed after Entity commit and barrier terminalization. The current proto/request and focused proof do not yet carry or demonstrate this attestation/barrier path. If a feature needs a different movement write order, it must be documented as a design change in tick + transactions docs before implementation. diff --git a/design/architecture/system-architecture-redis-cache-reference.md b/design/architecture/system-architecture-redis-cache-reference.md index 66068add5b..f291d318c6 100644 --- a/design/architecture/system-architecture-redis-cache-reference.md +++ b/design/architecture/system-architecture-redis-cache-reference.md @@ -4,7 +4,9 @@ This companion document holds the reference-heavy material for Redis cache and r ## Implementation Status -The `room:*` Class A cache contract below is target-state only. It is not a current correctness path until World Management has an opaque room component version and a proven invalidation path. Namespace-backed `inventory:*` and explicitly instance-scoped `inventory:room-ground:*` cache adoption is likewise target-state; current readers remain authoritative until Entity Management's owner-version/event validation is proven. Current readers must not substitute `worldSnapshotId` or `roomDynamicVersion` for that component version; they must use authoritative reads when the target validation contract is unavailable. A cache-embedded version, TTL, or invalidation event alone is not currentness proof. The current Game Session `ratelimit:` key is likewise a legacy implementation and must be drained by its maximum TTL or isolated behind a versioned prefix before target rate-limit helpers consume the shared family. The future reader, invalidation, and version-advance rules below remain normative. +The `room:*` Class A cache contract below is target-state only. It is not a current correctness path until World Management has an opaque room component version and a proven invalidation path. Namespace-backed `inventory:*` and explicitly instance-scoped `inventory:room-ground:*` cache adoption is likewise target-state; current readers remain authoritative until Entity Management's owner-version/event validation is proven. Current readers must not substitute `worldSnapshotId` or `roomDynamicVersion` for that component version; they must use authoritative reads when the target validation contract is unavailable. A cache-embedded version, TTL, or invalidation event alone is not currentness proof. The current Game Session `ratelimit:` key is likewise a legacy implementation: `SessionRateLimiterImpl` writes it through the generic Game Session Redis client with a one-second window/TTL, while its Cache/Rate-Limit endpoint and ACL binding remain unproved. It must be registered as current legacy state, its writer stopped, and its maximum one-second TTL allowed to elapse with an empty-key readback before unversioned target rate-limit helpers consume the shared family; an adopter that cannot prove that drain must use a distinct versioned prefix. The current Game Session `lookcache::` writer is also legacy implementation drift: it is disposable and non-authoritative, but its incomplete scope and ten-minute TTL cannot satisfy target causal room-read semantics. Current composition remains authoritative/uncached until the target `view:room-look:*` contract is proven. The future reader, invalidation, and version-advance rules below remain normative. + +The current Automation implementation also emits `automation:test:quota:*` and `automation:readiness:capacity:*` families. They are named in the catalog below as Cache/Rate-Limit, Class B, reset-tolerant projections, but the listed untagged shapes describe current/legacy implementation rather than a canonical cluster-safe target. Readiness and dry-run capacity counter/lease reservations currently pass two untagged keys to one Lua invocation, so a Redis Cluster deployment can reject them with `CROSSSLOT`. No canonical target family is registered until the owner chooses and proves either one shared hash-tag shape per atomic key set or a single-key reservation; this catalog does not invent that unresolved target. The current Game Session `IpConnectionLimiter` has the same current limitation: registration passes `ipconn:
` and `sessionip:` to one Lua invocation without a shared hash slot, so Redis Cluster returns `CROSSSLOT`; this is in addition to the raw-address/privacy drift. The target must follow ADR 0087's one-mutation/one-opaque-subject-bucket boundary, with session lifecycle correlation kept outside any exact cross-key atomicity requirement; no final reverse-index shape is assumed here. Destructive resets additionally require the external, generation-bound [Cache deployment maintenance gate](./system-architecture-redis-operations.md#external-cache-deployment-maintenance-gate), not a fence key stored in the cache being reset. ## Cache Adoption Checklist @@ -73,12 +75,17 @@ Cache/Rate-Limit Redis hosts prefixes that are not part of the coordination log | `world-dynamic::room-dynamic::` | Cache | Versioned (Class A) | Reset-tolerant | World Management room-scoped dynamic-state cache. | | `room:::` | Cache | Versioned (Class A) | Reset-tolerant | World Management correctness-critical room snapshot cache; payload stores and validates owner `regionId`/`regionEpoch` with the opaque component version, atomically with refresh/TTL, and invalidates on epoch change. | | `view:room-look:::::::` | Cache | TTL-only (Class B) | Reset-tolerant | Target-only Game Session-owned disposable presentation/redraw helper; see the [canonical Class-B contract](./system-architecture-redis-cache.md#canonical-viewroom-look-class-b-contract). Current `ResolveLook` behavior is uncached and no focused proof establishes this prefix. The cache remains non-authoritative and disposable: unavailable or untrusted cache/fence evidence falls back to authoritative uncached `ResolveLook`, and it is never semantic reconnect context, frame/output replay, a transcript archive, or a delivery ledger. | +| `lookcache::` | Cache (current legacy only; target role unapproved) | Legacy disposable projection (not target Class B) | Reset-tolerant for disposable loss | Current Game Session writer only. The ten-minute payload is non-authoritative, but the legacy session/game-instance scope lacks viewer, policy, and causal read-fence identity; a clustered cache reset may delete and verify this family only while the external, generation-bound Cache deployment maintenance gate is held through deletion and verification. Remove/drain this writer or migrate to the exact `view:room-look:*` contract before target helpers consume it; otherwise continue authoritative uncached composition. This prefix is not target Class B authority. | +| `ipconn:
` and `sessionip:` | Cache / Rate-Limit (current legacy implementation drift) | Legacy heuristic (not target Class B authority) | Reset-tolerant heuristic loss | Game Session owns the current paired raw-address counter and session reverse-map. Entries use the current connection TTL (`GAME_SESSION_CONN_TTL_SEC`, default 3600 seconds); a reset may temporarily relax or tighten abuse limits and can leave the pair incomplete, but must not be treated as durable authority. Current registration passes both untagged keys to one Lua invocation, so it fails with `CROSSSLOT` on Redis Cluster; this is in addition to the raw-address/privacy defect covered by ADR 0087. The target must use one mutation on one opaque subject bucket and keep session lifecycle correlation outside exact cross-key atomicity; no final reverse-index shape is assumed here. | | `screenbuffer:::` | Cache | TTL-only (Class B) | Reset-tolerant | Current Game Session disposable hot-cache prefix for durable semantic reconnect context; PostgreSQL `resume_transcript_entry` rows remain authoritative. This prefix is distinct from `view:room-look:*` and never serves as semantic authority. Current keying is `gameInstanceId`-based; target reconnect scope is `{tenantId, playableStateNamespaceId, characterId}` under ADR 0134, so namespace-key migration and complete reconnect-envelope/generation proof remain implementation gaps. The row records prefix semantics, not current endpoint/role wiring. | | `chat:say::`, `chat:whisper:::`, `chat:tell::`, `chat:guild::`, `chat:city::`, `chat:account::` | Cache | TTL-only (Class B) | Reset-tolerant | Social & Groups short-lived chat projections; current `SAY` is sender-account scoped. Any future gameplay-SAY projection must publish its exact recipient/view scope and original-view contract rather than infer it from a bare character ID. See the [canonical `chat:whisper` Class-B contract](#canonical-social--groups-chatwhisper-class-b-contract). | | `chat:whisper::` | Cache | TTL-only (Class B) | Reset-tolerant | Legacy `ChatService` account-keyed whisper implementation-drift prefix (`chat:whisper:%d:%d`); it does not provide the target playable-state/character scope and remains a reset-tolerant disposable projection during migration. | | `automation:queue:{tenantInstanceTag}:*` | Cache / Rate-Limit | TTL-only (target Class B; current reset/rebuild unavailable) | **Current queue reset/recovery is unavailable and must fail closed**; the implementation's rebuild query includes `EVALUATING` rows without stale-owner/CAS reconciliation, so this projection must not be flushed, rebuilt, or resumed as a supported current operation. Once the owner-reconciled target path is implemented and proven, it may be reset and rebuilt from durable work. | Automation & Scripting derived work-item pointers; PostgreSQL remains authoritative. See the [Automation & Scripting runtime/data owner contract](./microservices/automation-scripting-service/runtime-and-data.md#redis-roles-and-prefixes) and [API implementation status](./microservices/automation-scripting-service/api-contracts.md#implementation-status). The current queue implementation has no per-list TTL/trim or declared key-count/payload-size envelope; those are adoption/proof gaps, not implied bounds. | | `automation:quota::*`, `automation:tenant-budget::tier:`, `automation:test:quota::script::tenant`, `automation:test:quota::script::principal:`, `automation:test:capacity:{}:*`, `automation:test:capacity:{automation-test-capacity}:cluster*`, `automation:readiness:capacity:{}:*`, `automation:readiness:capacity:{automation-readiness-capacity}:cluster*` | Cache / Rate-Limit | TTL-only (Class B) | Reset-tolerant | Automation & Scripting per-script quota and tenant-budget counters, one-minute dry-run/test tenant/principal quota counters, exact tenantless cluster capacity counters paired with tenant/work-scoped leases, and bounded tenant/cluster `PUBLISH_READINESS` capacity reservations. Capacity counter/lease pairs share the documented hash tag (`{}` for tenant-scoped pairs and fixed family tags for cluster pairs) so their Lua operations remain in one Redis Cluster slot. The owner settings and capacity bounds are defined in the [Automation service configuration](./microservices/automation-scripting-service/configuration.md#service-specific-variables); the implementation uses one-minute counter windows and ten-minute capacity-lease TTLs. The counters/leases are disposable Cache/Rate-Limit projections, not Coordination Redis state, and are not rebuilt from Redis after reset. The catalog currently has no per-prefix key-count or serialized-payload envelope for these families; do not infer one from the concurrency limits until the owner declares and proves it. Durable trigger/work-item/readiness state and execution correctness remain in PostgreSQL and the owning service. | | `ratelimit:::` | Cache / Rate-Limit | TTL-only (Class B) | Reset-tolerant | Spring Cloud Gateway and other edge/credential rate-limit buckets. Each individual subject has one opaque stable hash; no modulo collision pool or request-derived shard is used. Reset-induced heuristic shifts are acceptable, while hard authority remains outside evictable Redis. | +| `ratelimit:` | Cache / Rate-Limit (current legacy; generic-client role unproved) | Legacy heuristic (not target Class B authority) | Reset-tolerant heuristic loss | Game Session's live `SessionRateLimiterImpl` command limiter. The current generic client may land on the wrong Redis role; the one-second counter/TTL is disposable and loss may relax or tighten heuristic limits. Cache-only writer registration and ACL proof do not make the legacy arity compatible with target helpers. Before any unversioned target `ratelimit:*` helper is enabled, stop the legacy writer, allow the maximum one-second TTL to elapse, and prove empty-key readback; an adopter that cannot prove that drain must use a distinct versioned prefix. | + +The current `automation:queue:{tenantInstanceTag}:*` implementation is not yet TTL-only: its enqueue and rebuild paths append to Redis lists without `EXPIRE`, `LTRIM`, or another bound. Target adoption requires configuration-backed `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY` (exact values remain environment/service settings), applied atomically with every enqueue and rebuild. Truncation or expiry is acceptable only as pointer loss: Automation must re-drive from eligible durable PostgreSQL work-item rows, and reset/rebuild release requires every eligible durable identity to be rematerialized or durably settled. That release also requires the external, generation-bound Cache deployment maintenance gate to remain held through deletion, post-reset verification, and the authorized rebuild/readback; because the current gate and safe rebuild path are unavailable, queue reset/rebuild must fail closed. Until that policy and focused retention, memory-pressure, and rebuild proof exist, this is implementation/proof drift rather than a proven TTL-only cache. Separately, the live `tenantInstanceTag` builder concatenates raw nonblank IDs and has no proven delimiter/brace rejection or collision-safe encoding; it remains implementation drift until the shared encoded tuple or canonical UUID-boundary contract is enforced. ### Canonical Social & Groups `chat:whisper` Class-B Contract @@ -125,7 +132,7 @@ CI and code review checks are expected to: - `world-dynamic:*` / `room:*` - hit/miss counters plus key-count gauges where available. - `view:room-look:*` - hit/miss, recompute, write-skip reason, oversize, active-key/variant-budget, and Redis-failure metrics as specified by the [canonical Class-B contract](./system-architecture-redis-cache.md#canonical-viewroom-look-class-b-contract). - `chat:*` - hit/miss counters plus chat-type gauges where helpful. -- `automation:queue:*` / `automation:quota:*` / `automation:tenant-budget:*` / `automation:test:quota:*` / `automation:test:capacity:*` / `automation:readiness:capacity:*` - queue, quota, and bounded-capacity counters or leases; service metrics should make best-effort loss, expiry, and any durable re-admission/reconciliation visible. +- `automation:queue:*` / `automation:quota:*` / `automation:tenant-budget:*` / `automation:test:quota:*` / `automation:test:capacity:*` / `automation:readiness:capacity:*` - queue, quota, and bounded-capacity counters or leases; service metrics should make best-effort loss, expiry, and any durable re-admission/reconciliation visible across tenant and cluster variants. - Prefix tags should stay consistent across services so dashboards can reason about cache behavior by aggregate family rather than by one-off metric names. ### Future Work / TODO diff --git a/design/architecture/system-architecture-redis-cache.md b/design/architecture/system-architecture-redis-cache.md index 371e0ffe77..6eae23eb36 100644 --- a/design/architecture/system-architecture-redis-cache.md +++ b/design/architecture/system-architecture-redis-cache.md @@ -2,7 +2,7 @@ Redis is already used for transient coordination (ticks, sessions, locks). This document describes how **Cache/Rate-Limit Redis** backs selected read-side caches and rate limiting as a performance optimization. It focuses on cache ownership, invalidation rules, consistency expectations, and canonical cache policy. The detailed prefix catalog, worked examples, reference tables, adoption checklist, and testing guidance live in [Redis Cache & Rate Limiting Reference](./system-architecture-redis-cache-reference.md). -The canonical cache policy in this file and the reference catalog in the companion document must stay aligned with the global reset policy matrix in `system-architecture-redis-reset-and-recovery.md`. +The canonical cache policy in this file and the reference catalog in the companion document must stay aligned with the global reset policy matrix in `system-architecture-redis-reset-and-recovery.md`. Any destructive Cache/Rate-Limit reset also requires the external, generation-bound [Cache deployment maintenance gate](./system-architecture-redis-operations.md#external-cache-deployment-maintenance-gate); it is outside Cache/Rate-Limit Redis and must cover every registered writer through deletion, verification, and rebuild. > ℹ️ **Implementation status** > @@ -35,7 +35,7 @@ All other controls (for example, per-tenant heuristics, noisy-tenant detection s - All non-ephemeral environments, including local development and small self-hosted setups, run **at least two Redis roles**: - A **Coordination Redis** deployment dedicated to ticks, locks, timers, sessions, and other gameplay-critical coordination state. - A **Cache/Rate-Limit Redis** deployment dedicated to read-side caches and gateway rate limits. - - Coordination Redis must not host large, eviction-driven caches under any profile. Even in development and hobby/self-hosted profiles, caches and rate limits are pointed at the separate Cache/Rate-Limit deployment so eviction and OOM behavior cannot silently affect coordination keys. The only supported exception is an explicitly marked ephemeral CI/test stack whose tests are reset-tolerant, do not exercise coordination tail-loss or replay guarantees, and surface the shared endpoint; such a stack is outside coordination SLO validation. See `system-architecture-redis-usage-and-profiles.md` for environment profiles and mappings. + - Coordination Redis must not host large, eviction-driven caches under any profile. Even in development and hobby/self-hosted profiles, caches and rate limits are pointed at the separate Cache/Rate-Limit deployment so eviction and OOM behavior cannot silently affect coordination keys. The only supported exception is one explicitly marked, one-shot ephemeral test/CI stack (never hosted `pr-preview` or another player-facing environment) whose tests are reset-tolerant, which surfaces the shared endpoint, and which passes the complete [canonical post-reset verification checklist](./system-architecture-redis-ops-access.md#canonical-post-reset-verification-checklist). That stack may run reset-tolerant tests but is outside and provides no role-isolation, replay, tail-loss, or coordination-SLO evidence. See `system-architecture-redis-usage-and-profiles.md` for environment profiles and mappings. - No soft coordination logs on Cache/Rate-Limit Redis: - Tick ordering, tick idempotency, and any correctness or fairness invariants for gameplay **must not** depend on cache or rate-limit keys. Cache/Rate-Limit Redis may only influence latency and load, never “what happened” or “in which order” from the tick engine’s perspective. - Automation and scripting structures on Cache/Rate-Limit Redis (for example `automation:queue:*`, `automation:quota:*`, `automation:tenant-budget:*`, `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*`) are explicitly documented as best-effort buffers, counters, and bounded owner-token leases; they cannot act as authoritative logs or effect ledgers. Durable automation schedules, work, and readiness state live in PostgreSQL; cache entries merely accelerate lookups, quota checks, and disposable capacity admission. @@ -204,10 +204,7 @@ Memory and eviction behavior for cache and rate-limit workloads must not comprom - Apply a safety factor of at least **2–3×** (`coord_bytes * SAFETY_FACTOR`) to account for spikes, fragmentation, and unforeseen growth. - Keep coordination prefixes (`tick:*`, `session:*`, `timer:*`, `retry:*`) under a target fraction of `maxmemory` (for example, <30–40%) and treat sustained growth beyond that as a sizing or design issue. - The canonical threshold source is `system-architecture-redis-operations.md` (Redis SLOs & Budgets); this doc intentionally mirrors that value. - - Does **not** store large cache payloads or unbounded aggregates; those belong in the Cache/Rate-Limit cluster or in PostgreSQL/object storage. Any exception must: - - Use a distinct, clearly documented prefix (for example, `coordCache:`). - - Respect strict per-key size limits and a small aggregate memory budget. - - Have an explicit incident plan if it contributes to memory pressure. + - Does **not** store large cache payloads or unbounded aggregates; those belong in the Cache/Rate-Limit cluster or in PostgreSQL/object storage. There is no general Coordination Redis cache exception: only the explicitly labelled, one-shot ephemeral test/CI topology (never hosted `pr-preview`) may collapse the physical roles. It must be reset-tolerant, surface the shared endpoint, preserve logical prefix, ACL, reset, and memory-policy classification, and pass the complete [canonical post-reset verification checklist](./system-architecture-redis-ops-access.md#canonical-post-reset-verification-checklist). It yields no role-isolation, replay, tail-loss, or coordination-SLO evidence. No unregistered cache family may be placed on Coordination Redis. - Treats any `OOM`/`OUT OF MEMORY` write error for coordination commands as a **critical failure condition**: the Game Session Service and other coordination clients: - Detect write failures from Redis clients (including Lua script results) instead of ignoring them. - Log structured errors and increment metrics (for example `redis.coordination_oom_errors`). @@ -220,7 +217,7 @@ For **all non-ephemeral deployments**, including local development: - Coordination and cache/rate-limit roles run on **separate Redis deployments** (for example, two containers/pods on the same host or separate processes), even when serving a single developer or tenant. - Deployment mechanisms vary by environment: local Docker Compose provides both `redis-coord` and `redis-cache`; the umbrella Helm chart's `k8s/helm/firemud/values.yaml` defaults `previewStack.enabled=false` and therefore does not render its in-chart Redis services by default; the hosted overlay enables both in-chart Redis services; and production Terraform provisions separate Redis releases. These are local deployment consequences of the two-role requirement, not a second role policy. -- Explicitly marked ephemeral CI/test stacks may collapse roles into a single Redis instance only when tests are reset-tolerant, do not exercise coordination tail-loss or replay guarantees, the environment is labelled `ephemeral / single-Redis`, and configuration/metrics surface the shared endpoint. These stacks are outside coordination tail-loss, replay, and SLO validation and must not be used for QA, staging, production, or any player-facing game instance. +- Only an explicitly marked, one-shot ephemeral CI/test stack other than hosted `pr-preview` may collapse roles into a single Redis instance. It must be labelled `ephemeral / single-Redis`, use reset-tolerant tests, not exercise coordination tail-loss or replay guarantees, surface the shared endpoint in configuration/metrics, and pass the complete [canonical post-reset verification checklist](./system-architecture-redis-ops-access.md#canonical-post-reset-verification-checklist). It provides no role-isolation, replay, tail-loss, or SLO evidence and must not be used for QA, staging, production, or any player-facing game instance. Operational dashboards track `used_memory`, `maxmemory`, and eviction counters for each deployment. In addition: diff --git a/design/architecture/system-architecture-redis-cheatsheet.md b/design/architecture/system-architecture-redis-cheatsheet.md index 75d472ef53..a8e437a72d 100644 --- a/design/architecture/system-architecture-redis-cheatsheet.md +++ b/design/architecture/system-architecture-redis-cheatsheet.md @@ -50,11 +50,13 @@ This table highlights representative prefixes and their intended Redis role. It | `session:auth:generation:issuer:`, `session:auth:generation:account:`, `session:auth:generation:tenant:`, `session:auth:generation:membership::` | **Approved global/account exception: Account durable authority with required Coordination Redis projection** | Account Service | Account advances one positive monotonic `generation` per scope transactionally in its durable store and is the sole writer of the Redis projection. Idempotent set-if-greater is permitted for a missing or lower projection only. A projection greater than durable authority is poison: Account must quarantine or replace that exact scope through an audited workflow, recreate it from durable authority, and emit immutable per-scope evidence/verification; consumers fail closed until the evidence is accepted. Region- and tenant-scoped resets preserve unaffected projections but verify affected scopes; a cluster reset may discard projections only after the Account repair/reset cutover and must rebuild and verify every affected scope before reopening. | | `session:connect-token:tenant::account::scope::request:` | **Coordination Redis — approved untagged Account legacy exception** | Account Service | Current Account-owned exact-input result-map projection. It is reset-sensitive, retained through the legacy TTL/retry horizon, and never read or promoted by target code. | | `session:connect-token:v1:tenant::account::scope::request:` | **Coordination Redis — approved untagged Account target exception** | Account Service | Target Account-owned exact-input issuance-result projection. It requires `schemaVersion: "connect-token-issuance-result-v1"`, durable SQL first-writer-wins before mint, and Redis set-if-absent/read-winner. Target readers and writers are isolated from the legacy family; exact repair comes only from the durable operation/envelope. | -| `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` | **Coordination Redis** | Spring Cloud Gateway | Target security-critical, non-evicting single-use connect-token replay and browser-denial state. The consume script uses the three tagged keys and one same-connection `WAITAOF` acknowledgement before readiness can admit tokens. Region- and tenant-scoped resets preserve the shared replay domain. The current writer emits only the untagged replay marker, with no deny/readiness/fence writer; that is migration-only drift and not target proof. A replay-continuity loss trigger, including a cluster reset that invalidates this shared state, requires new gameplay handshakes to remain closed for the 30-second maximum connect-token lifetime plus two configured clock-skew intervals, followed by the required disposable-marker and durability-acknowledgement proof before readiness may admit tokens. This quarantine does not apply to unrelated tenant/region reset handling or Cache/Rate-Limit Redis. | +| `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` | **Coordination Redis** | Spring Cloud Gateway | Target security-critical, non-evicting single-use connect-token replay and browser-denial state. The literal `{gateway-connect-token-replay-v1}` tag co-slots replay, browser-deny, and readiness/fence keys for the atomic consume script; the readiness value carries `replayAdmissionFence`. A winning consume (`1`) and a browser-deny write require the configured same-connection, threshold-satisfying `WAITAOF` durability acknowledgement; a definitive consume (`0`/`-1`) is non-mutating and has no marker acknowledgement. An unavailable, timed-out, malformed, below-threshold, lost, or otherwise ambiguous consume/deny result or durability acknowledgement is unconfirmed: fail the handshake or revocation operation closed, keep the affected admission quarantined, and enter the replay-continuity quarantine/reconciliation path for that `jti`/operation; never accept, mint, or report terminal revocation from uncertainty. This fence covers only the `/ws/game/**` gameplay-connect handshake; direct TCP/Telnet `LOGIN` does not consume this replay domain and follows its separate Account/Game Session authentication path. Region- and tenant-scoped resets preserve the shared replay domain. A replay-continuity loss trigger, including a cluster reset that invalidates this shared state, requires new gameplay handshakes to remain closed for the 30-second maximum connect-token lifetime plus two configured clock-skew intervals, followed by the required disposable-marker and durability-acknowledgement proof before readiness may admit tokens. The current generic Cache-bound writer emits only the untagged replay marker, with no deny/readiness/fence writer; that old replay key is migration-only drift and is quarantined/inventoried during cutover. This quarantine does not apply to unrelated tenant/region reset handling or Cache/Rate-Limit Redis. | + | `remote:{tenantInstanceTag}:` | **Coordination Redis** | Game Session Service / Automation & Scripting | Best-effort, TTL-bounded hint marker for remote participation scoped to the complete `` identity (typically “this entity has remote follow-ups due”). Default `remote_hint_ttl_ms = 60_000`. Region-scoped resets leave instance-scoped hints intact; tenant/cluster resets resolve every game instance from the durable scope inventory and enumerate `remote:{tenantInstanceTag}:*` per instance before removal. No tenant-only remote key family exists. | | `automation:timer:{tenantRegionTag}`, `script-scheduler:{tenantRegionTag}:lastTickId` | **Coordination Redis (target-only, once implemented)** | Automation & Scripting Service | Reserved target-only timer/checkpoint projections; they are not current runtime keys and have no current reset operation. Once implemented, they are reset-tolerant derived hints rebuilt from durable PostgreSQL schedules, trigger-instance rows, and heartbeat progress; they are never the source of truth for automation work. | | `tick-events:{tenantRegionTag}` and `tick-events-offset:{tenantRegionTag}:` | **Coordination Redis** | Game Session Service / Automation & Scripting | Best-effort tick event stream and per-consumer offsets used only as observer/wakeup hints. `tenantRegionTag` is the opaque encoding of the complete `` scope and must include `gameInstanceId`; no tenant-plus-region alias is valid. The key's `tenantRegionTag` and `` are authoritative for the event-offset scope; each offset payload stores `{tenantId, gameInstanceId, regionId, consumerId, region_epoch, latestTickId, streamOffset}` and is not a standalone scope identifier. It is discarded before reuse when `region_epoch` differs from the control-plane epoch. Stream retention is capped (default `tick_events_maxlen = 2048` per region). Correctness derives from committed heartbeats/RegionStatus plus durable schedules; missing/duplicated events must not change which schedules eventually fire. | -| `automation:queue:{tenantInstanceTag}:*` | **Cache/Rate-Limit Redis** (single-key ops) | Automation & Scripting Service | Non-authoritative, best-effort queue pointers. The target rebuild permits `PENDING_EVALUATION` and only an owner-reconciled/reclaimed safe non-stale `EVALUATING` row; stale or unresolved rows remain excluded. The current `rebuildPendingWorkItemIndex` unconditionally selects both statuses and has no stale, owner, or compare-and-set gate, so queue-prefix reset/rebuild and resume are unavailable and must fail closed; a non-atomic status preflight cannot authorize a safe PENDING-only path. Do not migrate or recover work from Redis payloads, or mix this single-key family with coordination prefixes in one Lua call. The adjacent timer/checkpoint projections remain target-only and unavailable. See [Redis Operations](./system-architecture-redis-operations.md#cacherate-limit-redis-reset), [Redis incident handling](./system-architecture-redis-incident-runbook.md#automation-queue-schema-mistakes), and [Scripting Runtime Execution](./system-architecture-scripting-runtime-execution.md#redis-queue-index-and-durable-work-boundary). | +| `conflict:entity::` and `conflict:session::` | **Coordination Redis** | `common-data-runtime` helper used by Entity Management and Game Session | Reset-tolerant, non-authoritative hotspot diagnostics. Current generic-client placement and separate `INCR`/`EXPIRE` warning-only path are implementation drift; target role, finite cardinality, 300-second inactivity TTL, ACL, and atomic-helper convergence are defined in [Redis Architecture](./system-architecture-redis.md#coordination-vs-cache-prefixes). | +| `automation:queue:{tenantInstanceTag}:*` | **Cache/Rate-Limit Redis** (single-key ops) | Automation & Scripting Service | Non-authoritative, best-effort queue pointers. The target rebuild permits `PENDING_EVALUATION` and only an owner-reconciled/reclaimed safe non-stale `EVALUATING` row; stale or unresolved rows remain excluded. The current `rebuildPendingWorkItemIndex` unconditionally selects both statuses and has no stale, owner, or compare-and-set gate, so queue-prefix reset/rebuild and resume are unavailable and must fail closed; a non-atomic status preflight cannot authorize a safe PENDING-only path. Do not migrate or recover work from Redis payloads, or mix this single-key family with coordination prefixes in one Lua call. The adjacent timer/checkpoint projections remain target-only and unavailable. See [Redis Operations](./system-architecture-redis-operations.md#cache-rate-limit-redis-reset), [Redis incident handling](./system-architecture-redis-incident-runbook.md#automation-queue-schema-mistakes), and [Scripting Runtime Execution](./system-architecture-scripting-runtime-execution.md#redis-queue-index-and-durable-work-boundary). | | `automation:quota::` | **Cache/Rate-Limit Redis** | Automation & Scripting Service | Best-effort per-script quota counters. Safe to drop; budgets are re-established from configuration and durable state. | | `automation:tenant-budget::tier:` | **Cache/Rate-Limit Redis** | Automation & Scripting Service | Best-effort per-tenant live execution budget counters. Safe to drop; counters are re-established from configuration and durable work state. | | `automation:test:capacity:{}:tenant` and `automation:test:capacity:{}:lease:`; `automation:test:capacity:{automation-test-capacity}:cluster` and `automation:test:capacity:{automation-test-capacity}:cluster:lease::` | **Cache/Rate-Limit Redis** | Automation & Scripting Service | Best-effort dry-run/test capacity: the first pair is the tenant-scoped counter/lease and the second pair is the fixed-tag cluster counter plus tenant/work-scoped lease. Same-slot tenant keys use the canonical `{}` tag; cluster keys use the fixed `{automation-test-capacity}` tag. Safe to drop; lease/counter expiry or Redis state loss may temporarily over- or under-admit test work, so this is a best-effort fairness control rather than a hard correctness cap; separate live capacity remains protected. See the [canonical quota lifecycle](./system-architecture-scripting-quotas-and-operations.md#budget-accounting-rules). | @@ -69,7 +71,6 @@ This table highlights representative prefixes and their intended Redis role. It When introducing **new prefixes**, update the owning service design doc and ensure the prefix is consistent with the role and reset expectations above. -The “shared replay-readiness generation” wording in the table is an explanatory alias for the canonical `replayAdmissionFence`; it is not a second key or field. For tick prefixes, `tenantRegionTag` is a naming alias, not a reduced scope: it must encode `tenantId`, `gameInstanceId`, and `regionId` in a stable, collision-free form. The event stream and offset rows are especially sensitive because omitting `gameInstanceId` would merge wakeups and baselines for otherwise independent game instances. --- diff --git a/design/architecture/system-architecture-redis-design-checklist.md b/design/architecture/system-architecture-redis-design-checklist.md index 1dddce5a93..7be48b9ccf 100644 --- a/design/architecture/system-architecture-redis-design-checklist.md +++ b/design/architecture/system-architecture-redis-design-checklist.md @@ -125,9 +125,10 @@ Use this when adding or changing cache or rate‑limit prefixes (for example `in ### Eviction and TTL - [ ] Set explicit TTLs that match the data’s volatility and usage patterns. +- [ ] For `automation:queue:*` pointer lists, declare `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY`, apply both atomically on enqueue/rebuild, and document that expiry/truncation triggers durable owner re-drive rather than work settlement. - [ ] Confirm eviction is acceptable: - [ ] Cold caches should degrade into acceptable behavior (extra DB reads, recomputation). - - [ ] Rate‑limit keys may be dropped without violating security or fairness guarantees. + - [ ] Rate-limit keys may be dropped without violating hard authorization, security, financial, or other declared invariants; declared heuristic enforcement may temporarily weaken or tighten, and the limiter's documented unavailable-store behavior must apply. - [ ] For versioned caches: - [ ] The authoritative store exposes a version or `lastModified` field. - [ ] Cache invalidation logic clearly ties updates to version changes. @@ -135,6 +136,7 @@ Use this when adding or changing cache or rate‑limit prefixes (for example `in ### Key Shape and Multi-Tenant Behavior - [ ] Keys include `tenantId` and any other isolation dimensions required (for example, per‑player or per‑guild). +- [ ] Any opaque hash-tag builder uses a canonical collision-safe tuple encoding (or a proven canonical UUID parser with separator/brace rejection); add delimiter/brace collision vectors and same-scope slot golden tests before claiming the builder is canonical. Use the shared [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md) to select the proof and record delimiter/brace collision-vector and same-scope slot golden-test execution results in PR/CI or implementation-tracking evidence; it supplements, rather than replaces, these owner-local requirements. - [ ] For rate‑limit prefixes: - [ ] Bucketing strategy is documented (per‑client vs hashed buckets). - [ ] Memory and key count growth per tenant/time window stays within budget. @@ -224,6 +226,11 @@ Use this when changing Redis profiles, topologies, or reset behavior. - [ ] Design changes explicitly state: - [ ] Which reset scopes are safe (region, tenant, cluster). - [ ] Whether reset or accept‑loss is the expected response to problems. +- [ ] For any destructive Cache/Rate-Limit reset, require the ADR-0085-derived external durable operation/fence outside Cache Redis: + - [ ] Bind an immutable `operationId`, exact deployment/generation, and frozen complete writer/prefix inventory to the external fence. + - [ ] Require restart-surviving writer admission/acknowledgement checks, stale-operation rejection, serialized takeover/expiry/release evidence, and fail-closed ambiguity handling. + - [ ] Keep ordinary writers denied through deletion and verification. The Automation rebuild/re-drive exception applies only to registered Automation prefixes (currently `automation:queue:*`) and only through the target-only named ACL principal `automation_queue_rebuild_maint` bound to the same `operationId`/fence/generation and exact registered prefix/scope. Non-Automation maintenance principals and their permitted prefix/scope contracts are target-only and undefined until each owner is separately named and its exact contract is accepted; do not infer or authorize a principal for Gateway, Game Session, Entity, World, or Social from ownership alone. No generic writer or operator principal is implied; use the owner and prefix contract in the [Cache/Rate-Limit reset runbook](./system-architecture-redis-operations.md#external-cache-deployment-maintenance-gate) and [cache reference](./system-architecture-redis-cache-reference.md). + - [ ] Attest Cache-only endpoint/role/ACL identity and complete prefix inventory before deletion; any coordination prefix, generic legacy writer, unknown prefix, or ambiguous evidence aborts/escalates without deletion. - [ ] Runbooks in `system-architecture-redis-operations.md` are updated or confirmed to cover new/reset behaviors. - [ ] For workloads that are **reset-sensitive** rather than reset-tolerant: - [ ] The impact of a reset is documented (player-facing effects, operational steps). diff --git a/design/architecture/system-architecture-redis-incident-runbook.md b/design/architecture/system-architecture-redis-incident-runbook.md index 9b9321ddf5..f5e1f82f72 100644 --- a/design/architecture/system-architecture-redis-incident-runbook.md +++ b/design/architecture/system-architecture-redis-incident-runbook.md @@ -39,7 +39,8 @@ Region-scoped coordination key examples use `{tenantRegionTag}`, the canonical o - Pause non-critical background scripts that depend heavily on Coordination Redis. 3. **Recover** - Follow cluster or node failover procedures documented in `design/architecture/system-architecture-redis-operations.md`. - - If a reset is required, use the coordination reset model and key enumeration strategy from `design/architecture/system-architecture-redis-reset-and-recovery.md` to clear affected prefixes safely. + - **Target state only, once the canonical gated coordination-maintenance operation is implemented and proven:** If a reset is required, use the coordination reset model and key enumeration strategy from `design/architecture/system-architecture-redis-reset-and-recovery.md` to clear affected prefixes safely. + - **Current deployments:** Do not execute a scoped reset or mutate raw coordination prefixes. Preserve the AOF, operation records, and incident evidence; keep the affected scope fenced or stopped; use only the shipped `PauseTicksForScope` / `GetRuntimeOwnershipStatus` boundary and `coord_ops_ro` read-only inspection; then escalate through the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). 4. **Inspect durable command outcomes** - After replay/reset work, use the canonical `GetGameplayCommandStatus` surface described in `design/architecture/system-architecture-tick-failures-and-operations.md` to confirm commands converged to their final durable outcomes. - Do not treat raw Redis queue/key inspection as the primary operator answer for player-visible command status after remediation. @@ -61,9 +62,9 @@ When Coordination Redis recovers after an outage or severe degradation: - **Tick executors** - Do not attempt to resume in-flight locks or leases based on in-memory state. - Re-establish the authoritative recovery baseline from PostgreSQL tick-batch records, the tick effect ledger, follow-up tables, and `RegionStatus`; surviving Redis keys are inspected only as coordination residue and hints. - - If `pending` survives for a region, the next executor validates each immutable pending envelope against the durable `tick_batch_id` and complete expected root-`EffectId`/participant set (or equivalent exact ledger-row identities), then replays the tick as described in the tick system design; a count, digest, or descriptor-only correlation is insufficient. - - If `pending` is missing (for example due to AOF tail loss), treat this as “coordination state may have been partially lost” rather than silently skipping work: - - Advance to the next `tickId` only after running the tick effect ledger replay controller / reconcile tooling for the affected scope so any lingering `SCHEDULED` effects converge to `APPLIED` or `ABANDONED` with an explicit tail-loss reason where the evidence policy permits. For `reset_first`, once the old timeline is durably fenced, the epoch bump is a separate fencing step and does not wait for conclusive ledger outcomes. Inconclusive old-epoch effects remain quarantined, non-terminal, owner-fenced reconciliation work under their original root `EffectId`; current-epoch executors must never replay that `EffectId`, and the work blocks reset-scope convergence, next-tick progress, and reopening, not the epoch bump itself. + - **Target state only — complete pending-envelope validation is not live:** If `pending` survives for a region, the future recovery controller validates each immutable pending envelope against the durable `tick_batch_id` and complete expected persisted-mutation/participant projection: the mutation `EffectId` (root `EffectId` for a root mutation or the persisted child `EffectId` for a generated child), any enclosing `rootEffectId` retained separately as lineage and reconciliation context, typed operation, complete scope/timeline and target projection, immutable request payload/digest, and sealed participant/manifest context. Every expected participant identity and guard must match exactly; missing, extra, stale, conflicting, or otherwise mismatched envelope evidence fails closed without replay or durable mutation. A count, digest, or descriptor-only correlation is insufficient. The current live Redis payload is only the compact `N||` / `S||` form, with no complete immutable participant envelope. Current code therefore applies only its narrower fail-closed checks: it excludes entries when current runtime ownership is absent, unusable, paused, or stale, when the durable command is missing or not `STAGED`/`RETRY_QUEUED`, or when tenant, game-instance, region, or epoch scope does not match; replay additionally requires the pending command set/scope and sealed-manifest/effect-count checks. These checks do not establish the target complete-envelope contract or authorize target recovery; when the current recovery path cannot prove the required boundary, keep the scope fenced or stopped and use the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). + - If `pending` is missing (for example due to AOF tail loss), treat this as “coordination state may have been partially lost” rather than silently skipping work: + - **Target state only — unavailable today:** Advance to the next `tickId` only after the tick effect ledger replay controller / reconcile tooling has converged lingering `SCHEDULED` effects to `APPLIED` or evidence-qualified `ABANDONED` outcomes. For `reset_first`, once the old timeline is durably fenced, the epoch bump is a separate fencing step and does not wait for conclusive ledger outcomes. Inconclusive old-epoch effects remain quarantined, non-terminal, owner-fenced reconciliation work under their original persisted mutation `EffectId`, with any enclosing `rootEffectId` retained separately as lineage and reconciliation context; current-epoch executors must never replay that mutation identity, and the work blocks reset-scope convergence, next-tick progress, and reopening, not the epoch bump itself. **Current deployments:** Do not run unavailable replay/reconcile tooling or advance the affected tick; preserve the AOF and incident evidence, keep the scope fenced or stopped, use only shipped pause/status and read-only inspection, and escalate through the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). - Converge only command records with `ackLevel` = `ACCEPTED_VOLATILE` in `RECEIVED`/`ENQUEUED` and no surviving batch/binding to `executionOutcome = LOST_BEFORE_STAGING`; `ACCEPTED_DURABLE` records follow their feature-specific durable replay or post-abandon re-drive contract, while inconclusive batch-bound work remains non-terminal/reconciliation-required. See the [canonical command outcome convergence](./system-architecture-tick-execution-flows.md#command-outcome-convergence-required). - Use the resulting evidence-qualified ledger outcomes plus service-level idempotency guards to validate that no effect is silently terminalized or left without an owned reconciliation path; inconclusive old-epoch work remains visible as non-terminal. - **Leases** @@ -80,8 +81,9 @@ When Coordination Redis recovers after an outage or severe degradation: - Throttle non-essential cache usage or, only through an explicitly documented cache-owner/deployment control, temporarily reduce TTLs for non-lease, disposable Class B cache prefixes. That control must identify the authorized operator or workload, exact deployment/scope, bounded duration, audit record, and rollback/readback proof; owner-token leases, including test/readiness capacity owner leases, are excluded unless their owner contract explicitly defines a semantic minimum lifetime plus renewal or reacquisition behavior. Operators must not issue Redis TTL commands directly. - Confirm that coordination keys are not co-located with caches. 3. **Recover** - - Scale the cache deployment or provision additional nodes. - - Mutating Cache/Rate-Limit reset tooling is currently unavailable. Preserve the keyspace and incident evidence; do not use `redis-cli` or any other ad-hoc tool or Redis command to issue writes, delete prefixes, change TTLs, `FLUSHDB`, or `FLUSHALL`. An explicitly documented cache-owner/deployment TTL control remains permitted only under the authorization, bounded-duration, audit, rollback, and readback proof above. Only supported bounded read-only inspection through the applicable read-only ops user, using known keys or an approved bounded inspection surface, is otherwise allowed. Follow the [current fail-closed Cache/Rate-Limit reset fallback](./system-architecture-redis-operations.md#runbook-environment-scoped-cache-reset), and escalate to the cache owner or authorized infrastructure operator if an existing deployment control cannot contain impact. Do not reset coordination prefixes from the cache deployment. + + - **Target state only, once the external generation-bound Cache maintenance gate and its writer admission/acknowledgement, complete inventory/readback, and accepted owner-specific rebuild or repopulation paths are implemented and proven:** First require trusted deployment/endpoint/role/ACL attestation and bounded exact prefix inventory/readback proving the selected deployment is Cache-only and distinct from Coordination Redis; abort without deletion on any Coordination prefix, generic legacy writer, unknown prefix, or ambiguous role evidence. Then flush or reset only registered Cache/Rate-Limit prefixes while holding the same external gate through deletion and verification. Automation rebuild/readback applies specifically to the `automation:queue:{tenantInstanceTag}:*` pointer family, from durable work truth as described below; every other affected Cache/Rate-Limit prefix requires its own accepted owner-specific rebuild or repopulation/readback contract before release. Do not reset coordination prefixes from the cache deployment. + - **Current deployments:** Do not flush or reset cache prefixes, perform a Coordination Redis reset, or issue raw Coordination-prefix writes. Non-colocation confirmation is diagnostic only and does not replace role/endpoint/ACL isolation proof. Keep affected writers/clients quarantined or stopped and use the role-specific `cache_ops_ro` read-only inspection path where configured (never for writes). If bounded inspection or abort evidence identifies Coordination prefixes or a generic legacy writer, use only the shipped instance-scoped `PauseTicksForScope` / `GetRuntimeOwnershipStatus` boundary as needed to fence and inspect the affected scope; this does not authorize any Coordination reset or raw mutation. Preserve reset/incident evidence and escalate through the [Cache/Rate-Limit Redis Reset](./system-architecture-redis-operations.md#cache-rate-limit-redis-reset) authority and its current fail-closed fallback. ## Session Schema and TTL Cleanup @@ -113,7 +115,7 @@ When session-related metrics indicate schema or TTL problems, use this scoped cl - The scoped reset/full-wipe flow in `system-architecture-redis-operations.md` is target state only until its durable controller, Account projection-repair workflow, immutable evidence gates, and bounded maintenance tooling are implemented and proven. It must use the [canonical coordination reset sequence](./system-architecture-redis-operations.md#canonical-coordination-reset-sequence), including the [canonical post-reset verification checklist](./system-architecture-redis-ops-access.md#canonical-post-reset-verification-checklist); node-level scope still requires the documented cluster-blast-radius or physical-dedication proof before handoff. The incident-specific fallback remains fail-closed when those target-state controls are unavailable. - Current fail-closed fallback: if the AOF cannot be trusted, keep protected admission, gameplay mutation, and affected coordination writers stopped; preserve the AOF and incident evidence; use the shipped pause/status surface and read-only inspection where available; and escalate through the incident process. Abort any destructive wipe, recovery continuation, or reopen attempt when the required durable controller, Account projection repair, or immutable evidence path is unavailable. There is no supported current full-wipe substitute. - Do not perform manual AOF truncation or file editing. - - Use idempotent replay and tick system rules to rebuild necessary state. + - **Target state only — unavailable today:** Use idempotent application-level replay/reconciliation and tick system rules to rebuild necessary state after the target recovery controller and its evidence gates are implemented and proven. **Current deployments:** Do not initiate application-level tick/ledger replay, state rebuild, or advance ticks; preserve the AOF and incident evidence, keep the affected scope fenced or stopped, use only shipped pause/status and read-only inspection, and escalate through the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). This prohibition does not cover Redis's built-in startup replay: when an existing AOF is trusted, a normal Redis restart/failover may replay it as-is, as described above. That storage-level replay is not application recovery or a state rebuild and does not authorize admission, gameplay mutation, tick progress, or reopen without the same evidence and fencing gates. - During Account projection repair, Account's snapshot field `issuerAuthGeneration` maps exactly to canonical persisted `lastAppliedIssuerGeneration` and that mapping is used consistently during bootstrap, persistence, exact readback, contiguous replay, and recovery; it is not a second persisted alias or a local fallback. Set-if-greater is permitted only for a missing or lower Redis generation. A Redis generation greater than Account durable authority is poisoned and must be quarantined or replaced by an Account-owned audited workflow, recreated from durable authority, and verified with immutable evidence for each affected scope before protected traffic reopens. The current repository does not ship and prove this projection-repair workflow end to end. ## Redis Incident Scenarios @@ -135,7 +137,7 @@ Before entering this measured-SLO detect/decide path, verify that the affected d - Goal: preserve as much in-epoch work as possible by driving lingering `SCHEDULED` rows to `APPLIED` or `ABANDONED` without bumping `regionEpoch`, only where durable evidence permits; inconclusive old-epoch rows remain reconciliation-required. - `reset_first` - The controller derives this classification when the region is already `STALLED`, when mixed-epoch or orphaned coordination state is suspected, when duplicate/inconsistent durable batches are detected, or when `replay_first` fails to make bounded progress within the replay convergence budget. - - Goal: fence the old timeline with an epoch bump and use the canonical reset handshake to reconcile old-epoch work explicitly, terminalizing only where the evidence policy permits and retaining inconclusive work as non-terminal reconciliation under its original root `EffectId`. + - Goal: fence the old timeline with an epoch bump and use the canonical reset handshake to reconcile old-epoch work explicitly, terminalizing only where the evidence policy permits and retaining inconclusive work as non-terminal reconciliation under its original persisted mutation `EffectId`, with any enclosing `rootEffectId` retained separately as lineage and reconciliation context. 3. **Act** - The account-wide branch uses one canonical lifecycle for linked and standalone flows. Before inventory capture, each flow acquires and holds the live `accountAdmissionFence` through exact full-key readback and durable `coverageGeneration`, and carries `accountCoverageState=ACTIVE` with that concrete fence. The atomic coverage-proven transition releases the live fence and retains its exact value as `historicalAccountAdmissionFence`, changes the result to `accountCoverageState=HISTORICAL`, and makes the parent-independent child or standalone result reusable only after that proof. A flow that acquired the fence never uses `accountCoverageState=NO_ACTIVE_ACCOUNT_WIDE_FLOW` or `NOT_APPLICABLE` for either fence. A linked parent edge and its consumption CAS exact-compare the active state/live fence while coverage is active, then exact-compare the historical state/released fence after success; a standalone operation applies the same checks without a parent-consumption path. Missing, mismatched, or lifecycle-inappropriate live/historical values fail closed while preserving the existing parent-independent global child result and historical fence contract. 1. If the controller-validated classification is `replay_first`: @@ -167,7 +169,8 @@ Before entering this measured-SLO detect/decide path, verify that the affected d - If mis-keyed data is purely coordination state (no unique business data), prefer a reset over in-place fixes. - If the mistake involves non-coordination prefixes that cannot be safely discarded, plan a one-off migration tool. 3. **Act** - 1. For coordination prefixes: follow the region/tenant/cluster reset flow from [Coordination Reset Model](./system-architecture-redis-reset-and-recovery.md#coordination-reset-model) and rely on PostgreSQL/idempotent ticks to rebuild state. + 1. **Target state only, once the canonical gated coordination-maintenance operation is implemented and proven:** For coordination prefixes, follow the region/tenant/cluster reset flow from [Coordination Reset Model](./system-architecture-redis-reset-and-recovery.md#coordination-reset-model) and rely on PostgreSQL/idempotent ticks to rebuild state. + - **Current deployments:** Do not execute this reset or mutate raw coordination keys. Preserve evidence, keep the affected scope fenced or stopped, use only the shipped `PauseTicksForScope` / `GetRuntimeOwnershipStatus` boundary and `coord_ops_ro` read-only inspection, and escalate through the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). 2. For non-coordination prefixes: write a small migration Job that: - Iterates the affected prefix (for example `automation:queue:{tenantInstanceTag}:*`). - Uses the prefix owner's documented writer fence while it writes corrected keys through shared builders. If no scope-wide writer fence exists, each corrected write must use an owner-specific atomic guarded transform whose single linearization boundary exact-compares the current source key's value digest, applicable version, and absolute expiry with the immutable per-key source evidence and conditionally writes the destination without overwriting a newer destination version. A changed or unavailable source aborts that key and leaves it for owner reconciliation rather than copying stale state. If the source and destination cannot be covered by that owner-specific primitive, including when they cannot share a Redis Cluster slot, the Job must abort and reconcile the key instead of migrating it. diff --git a/design/architecture/system-architecture-redis-lua-patterns.md b/design/architecture/system-architecture-redis-lua-patterns.md index 080826b4a9..902bd50d01 100644 --- a/design/architecture/system-architecture-redis-lua-patterns.md +++ b/design/architecture/system-architecture-redis-lua-patterns.md @@ -36,12 +36,19 @@ Every coordination script belongs to a **script category** that constrains which | Gameplay session CAS / bindings | `session:game:{tenantGameplayTag}::` plus tenant-tagged `session:game:index:*:{tenantGameplayTag}:*` | Gameplay session CAS/update scripts may be shard-local multi-key scripts where all gameplay-session keys share `{tenantGameplayTag}`. They own gameplay binding and reconnect state only; they do not operate on Account auth-token registry keys, tick keys, or the global account index in the same invocation. | | Cross-tenant gameplay-session account index | `session:game:index:account:` | This global account index cannot share every tenant gameplay slot and is never included in a shard-local gameplay CAS/Lua invocation. Game Session updates it through a separate idempotent write after the owning gameplay-session mutation and reconciles it from authoritative session bindings. Account-wide revocation uses the index as a discovery projection but verifies and mutates each tenant-local binding through its owning shard-local contract; missing or stale index entries are repaired rather than treated as authorization truth. | | Account auth-token registry | `session:auth:token:` | Account-owned issued-token registry operations are single-key operations for the exact token hash. The exact-token registry record is mandatory validity and per-token-revocation authority: a cryptographically valid JWT without a matching permitted record is denied, and Lua must not invent validity from absence or from a generation alone. Durable issuer/account/tenant/membership authority generations advance in Account Service; Redis entries project/read through those durable generations for validation, while Lua may enforce the stored record state but never becomes the authority for generation advancement. This is not part of gameplay session CAS. | +| Gateway replay admission | `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:` | The `gateway-connect-token-replay-consume/v1` descriptor is the only three-key descriptor in this category: it runs only on Coordination Redis and receives readiness/fence, replay, and deny keys in that order. The literal `{gateway-connect-token-replay-v1}` hash tag is required on all three keys so Redis Cluster executes the atomic operation in one slot; the readiness value carries `replayAdmissionFence`. The separate `gateway-connect-token-browser-revoke/v1` descriptor is a one-key deny-marker mutation using only `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:` with the same literal tag; it is not part of this three-key key order. The current generic Cache-bound writer's only untagged output is the replay marker; it has no deny-marker, readiness, or replay-fence writer. That old replay key is migration-only drift and is not a valid descriptor shape. | | Session-to-region bridge | `tick:{tenantRegionTag}:session-binding:` plus `tick-executor-lease:{tenantRegionTag}` | Region-lease scripts only. They update region-authoritative gameplay bindings using caller-supplied `sessionId` / `binding_generation` and never read `session:game:*` directly inside Lua. | | Maintenance / cleanup | Region-local maintenance keys under `tick:{tenantRegionTag}:*` or `timer:{tenantRegionTag}` | Shard-local scans and deletes constrained to one `{tenantRegionTag}` at a time; no cross-slot operations. | | Automation helpers (coordination role only, target-only once implemented) | `script-scheduler:{tenantRegionTag}:lastTickId` and similar | This is a reserved target pattern only: no current Automation-owned coordination helper or key is implemented. Any future helper must not touch Cache/Rate-Limit prefixes. | The Lua Script Registry encodes these category→prefix→shard rules so that callers do not hard-code prefixes or slots. New categories or key families must be added to this table and to the registry schema before scripts using them are accepted. +Automation queue-pointer enqueue and rebuild are a separate Cache/Rate-Limit descriptor boundary, not additions to the Coordination categories above. An atomic operation over `automation:queue:{tenantInstanceTag}:*` must declare `redis_role=cache`, use only queue keys for one exact `{tenantInstanceTag}` scope, and be authorized by `cache_app` for normal projection or by the target-only `automation_queue_rebuild_maint` ACL principal during an externally fenced reset/rebuild. The descriptor must carry the operation/fence, deployment generation, and exact prefix/scope admission fields described in the [Cache/Rate-Limit reset runbook](./system-architecture-redis-operations.md#external-cache-deployment-maintenance-gate); it must reject Coordination keys and `coord_app`, and its outcome must remain a best-effort pointer projection rather than durable-work authority. If the atomic enqueue/rebuild implementation uses single-key Redis commands instead of Lua, the same `redis_role`, key, slot, and ACL boundary still applies. These descriptors must be represented separately from the Coordination script categories in the ADR 0176 registry. + +The Gateway replay-consume descriptor is `gateway-connect-token-replay-consume/v1`: `redis_role=coordination`, `KEYS[1]=gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `KEYS[2]=gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, and `KEYS[3]=gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`. The descriptor must require the literal `{gateway-connect-token-replay-v1}` tag on every key, reject the untagged current-drift replay marker, and declare the stable outcomes `1` (marker created), `0` (already replayed), and `-1` (browser denied), with no mutation for `0` or `-1`. Focused contract tests must prove the three keys resolve to one Redis Cluster slot, reject any missing or different tag, preserve readiness/fence and deny-marker race ordering, and keep the same `KEYS` order under RESP2 and RESP3. Migration tests separately inventory/read back the current untagged replay prefix under quarantine and prove that it cannot be accepted by the target descriptor. + +Browser revocation has a separate descriptor, `gateway-connect-token-browser-revoke/v1`, because its deny-marker mutation and durability acknowledgement are not the three-key replay-consume script contract. It uses `redis_role=coordination`, `KEYS[1]=gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and the token's absolute expiry (including the configured clock-skew allowance) as the bounded marker TTL. The idempotent write returns `1` when it creates the marker and `0` when the marker already exists; both outcomes identify the committed deny state, while malformed or conflicting state is non-mutating and fails closed. Gateway must immediately issue `WAITAOF requiredLocalAofCount requiredReplicaAofCount firemud.gateway.replayConsumeAckTimeoutMs` on the same pinned connection, with the same exact two-integer threshold validation as replay consumption; only that acknowledgement yields `DURABLE_BROWSER_REVOKE_ACK`. This descriptor must require the literal `{gateway-connect-token-replay-v1}` tag and must not be folded into, or represented as, the replay-consume descriptor's three-key invocation. The current implementation provides neither this deny-marker write nor its `WAITAOF` proof: it is replay-only, untagged, and Cache-bound migration drift. + Entity-lock hard rule: each Redis tick Lua invocation may acquire at most one `tick:{tenantRegionTag}:lock:`. Piecemeal acquisition across invocations, a multi-lock whitelist, and a configurable multi-lock count are prohibited. A script fails closed when its declared or supplied key set would require more than one entity lock. Multi-entity invariants belong to an owning transaction or durable effect/workflow path, not Redis lock lifetime. See [ADR 0074](./decisions/adr-0074-one-entity-lock-per-redis-script.md). ## Idempotent Script Patterns and Examples @@ -263,7 +270,7 @@ The Automation & Scripting Service does not construct or invoke `tick:*` keys. G - Automation scripts **never** perform multi-key operations that span both `automation:*` and `tick:*` prefixes in one `EVAL`/`EVALSHA` call. - Automation work is projected under `automation:queue:*` and handed off to Game Session via gRPC; only Game Session scripts mutate `tick:*` prefixes. - Current live timer rows may expose an optional `dueTickId` alongside the existing due-state fields and derived projections; live Redis scripts must not assume that the tagged `duePoint` migration shape is already present. In target state, schedule-derived work uses the complete due-candidate and firing-claim projection defined by the [Scripting Scheduler and Timer Lifecycle](./system-architecture-scripting-scheduler-and-timers.md#script-timers-vs-tick-timers): it includes mandatory `stableOwnerKind` and `stableOwnerId`, `entityId` only for an entity-scoped target, `resumeWindowId` only for `triggerMode=CATCH_UP`, the exact script pin, `isDryRun`, and applicable plugin provenance. For plugin-owned candidates, `pluginActivationEpoch` is a tagged candidate/firing-claim and derived-`scriptEventId` identity field, while `lifecycleRevision` is required non-identity fence evidence. The winning claim derives `scriptEventId` from that complete candidate identity; it is not a pre-claim input, and retries reuse the derived value. Scheduled rows require exactly one tagged `duePoint`, either `dueTickId:` or `dueAt:`; both forms, neither form, empty values, and zero placeholders are invalid. Immediate event rows use the distinct event-driven identity branch, omit scheduler-only fields and `duePoint`, and have both physical `dueTickId` and `dueAt` columns explicitly `NULL`. A versioned migration must translate live due fields before enforcing the target tagged form. The per-command `automationDispatchId` plus `commandOrdinal` is the suffix of the complete source/optional-target-scoped Command-Handoff Identity and must not be replaced by `scriptEventId` or `commandKind` alone. - - Before invoking the Redis enqueue script, Game Session must insert or confirm a durable admission row whose uniqueness key is the complete [Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state): source runtime scope, optional distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`. When a distinct target applies, its `targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, and `targetRegionEpoch` are part of that optional target runtime identity. The parent Trigger Identity, due point, command payload, and any current-routing fields outside the immutable source/optional-target scopes are retained as immutable comparison and readback evidence; they do not extend command identity. Scheduled rows retain exactly one tagged due point (`dueTickId:` or `dueAt:`); immediate event rows use the separate immediate branch and keep scheduler-only fields and both physical due columns `NULL`. Redis enqueue scripts may project that complete Command-Handoff Identity into an idempotent member key for hot-path dedupe; the dispatch-plus-ordinal suffix alone is insufficient because `automationDispatchId` is not globally unique. The durable admission row and durable trigger-instance uniqueness projection remain the authorities used after resets, gRPC retries, and failover. + - Before invoking the Redis enqueue script, Game Session must insert or confirm a durable admission row whose uniqueness key is the complete [Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state): source runtime scope, optional distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`. When a distinct target applies, its `targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, and `targetRegionEpoch` are part of that optional target runtime identity; `targetPlayableStateScope` remains separately persisted and exact-validated target policy/routing/authorization/fence evidence, not a uniqueness input. The parent Trigger Identity, due point, command payload, and any current-routing fields outside the immutable source/optional-target scopes are retained as immutable comparison and readback evidence; they do not extend command identity. Scheduled rows retain exactly one tagged due point (`dueTickId:` or `dueAt:`); immediate event rows use the separate immediate branch and keep scheduler-only fields and both physical due columns `NULL`. Redis enqueue scripts may project that complete Command-Handoff Identity into an idempotent member key for hot-path dedupe; the dispatch-plus-ordinal suffix alone is insufficient because `automationDispatchId` is not globally unique. The durable admission row and durable trigger-instance uniqueness projection remain the authorities used after resets, gRPC retries, and failover. Once ADR 0176's target descriptor validation is implemented, CI must reject automation Lua/descriptors that construct or reference any `tick:*` key; Game Session alone uses its owner-local tick builders. @@ -333,18 +340,18 @@ Bulk key-walking is reserved for **offline maintenance tooling**, not tick execu - After the owner-defined recovery release, the first fenced staging CAS must accept only `requestedTickId = 0` and atomically advance exactly `-1 → 0` and `APPLIED → STAGED`; no other requested tick may treat `-1` as an ordinary terminal prior tick. Subsequent ticks follow the ordinary immediate-next-tick terminal transition. - These hot-path scripts are intentionally **not** the mechanism for reconstructing a lost older tick after coordination loss or reset. - First implementation replays older work directly from durable tick-batch manifests and ledger rows without re-materializing that old tick into `pending`. - - Older-tick recovery records `APPLIED` or `ABANDONED` only in the durable ledger/reconciliation state under the older tick's original epoch and root effect identity; it must not overwrite or regress `tick:{tenantRegionTag}:meta`. Redis `pending` contents alone are never sufficient evidence that the current epoch scheduler timeline may move on, and tick metadata updates are limited to that current timeline. + - Older-tick recovery records `APPLIED` or `ABANDONED` only in the durable ledger/reconciliation state under the older tick's original epoch and persisted mutation `effect_id`; `root_effect_id` remains separately retained as lineage and reconciliation context. It must not overwrite or regress `tick:{tenantRegionTag}:meta`. Redis `pending` contents alone are never sufficient evidence that the current epoch scheduler timeline may move on, and tick metadata updates are limited to that current timeline. - If FireMUD later introduces a dedicated recovery-restage script, it must be registered as a separate maintenance script category with its own explicit invariants, compatibility mode, and runbook entry; it must not silently reuse the normal tick staging contract. - Such a recovery-restage path is not considered specified or implementable until the corresponding maintenance runbook in the Redis operations docs names the entrypoint, scope restrictions, and post-run verification steps. -- **Pattern 3 – Immutable pending-envelope identity and replay (no collision-prone staging)** -- Each staged member in `pending` carries an immutable envelope whose logical identity is the exact `tick_batch_id` plus the complete root `EffectId` participant projection: `root_effect_id`, the canonical typed operation, the exact `target_aggregate_type`/`target_aggregate_id`, and the exact scope, epoch, and tick needed to resolve one durable ledger row. Envelope construction must reject a missing, malformed, or ambiguous typed operation or exact target; `effect_key` remains descriptor metadata only and is never the pending member identity or replay authority. Physical encoding may use a hash, set/ZSET member, or another registered representation, but it must preserve this complete logical envelope unchanged. -- Before adding or replaying a staged member, the script compares the complete envelope and bound request payload, including the typed operation and immutable request digest, not `effect_key` alone. An exact full-envelope/request-payload match returns the prior stored staging/replay outcome without creating another member or changing its payload or TTL. A same `effect_key` with a different `tick_batch_id`, root `EffectId`, typed operation, participant/target projection, scope, epoch, tick, or request payload is a conflict/fail-closed result and must not overwrite or merge the existing member. +- **Pattern 3 – Immutable pending-envelope identity and replay (target state; no collision-prone staging)** +- Each target staged member in `pending` carries an immutable envelope whose logical identity is the exact `tick_batch_id` plus the collision-safe participant/target projection: `(tenant_id, game_instance_id, playableStateNamespaceId, regionId, regionEpoch, tickId, mutation EffectId (effect_id), typed_operation, target_aggregate_type, target_aggregate_id)`. `playableStateScope` remains immutable envelope and exact-comparison/readback evidence, but is not a pending-member uniqueness dimension. The envelope also carries the exact immutable request payload/digest needed to resolve one durable ledger row. The enclosing `root_effect_id` is retained as immutable lineage/conflict evidence but is excluded from member uniqueness, so it cannot collapse sibling mutations. Envelope construction must reject a missing, malformed, or ambiguous typed operation or exact target; `effect_key` remains descriptor metadata only and is never the pending member identity or replay authority. Physical encoding may use a hash, set/ZSET member, or another registered representation, but it must preserve this complete logical envelope unchanged. Current Game Session `gamesession:tick:pending:*` entries instead use the narrower command envelope documented by [Tick Execution Flows](./system-architecture-tick-execution-flows.md#implementation-notes); complete Pattern 3 producer, consumer, replay, and focused proof remain an implementation gap. +- Before adding or replaying a staged member, the script compares the complete envelope and bound request payload, including the mutation `effect_id`, typed operation, participant/target projection, and immutable request digest; `root_effect_id` remains lineage/conflict evidence and `effect_key` remains descriptor metadata. An exact full-envelope/request-payload match returns the prior stored staging/replay outcome without creating another member or changing its payload or TTL. Distinct envelopes may share an `effect_key` when their complete identities differ; an exact identity with conflicting immutable envelope or request-payload evidence, including a differing bound `root_effect_id`, is a conflict/fail-closed result and must not overwrite or merge the existing member. Replay uses the mutation `effect_id`/participant identity, never `effect_key` or the enclosing root alone. - Missing, malformed, ambiguous, partial, or conflicting envelopes are non-mutating failures. Exact-envelope duplicate handling is local staging idempotency only; domain services still use their participant guards and Game Session still performs durable batch/ledger exact-set validation. - **Pattern 4 – Queue insertion with uniqueness** - When scripts enqueue work (for example timers or retryable actions), they use data structures that naturally deduplicate: - - ZSET-based queues use `ZADD` with a unique member identifier (effect key or command ID); scripts check `ZSCORE` first and only call `ZADD` when the member is not already present. + - ZSET-based queues use `ZADD` with a unique member identifier (effect key or command ID) only when the owning queue contract declares that value to be the complete member identity; this excludes `tick:pending`, which follows Pattern 3's full immutable envelope. Scripts check `ZSCORE` first and only call `ZADD` when the member is not already present. - For simple sets of flags or participants, scripts use `SADD` and ignore the return value except for observability; repeated `SADD` calls with the same member are safe no-ops. - This ensures that retries or replays do not create duplicate queue entries even when callers re-invoke the script. @@ -402,7 +409,7 @@ Unit tests for this script would: Script changes must be rolled out in a way that respects both AOF replay semantics and the reset model described in `system-architecture-redis-reset-and-recovery.md`: - **Compatibility levels** - - `compatible` – purely additive changes (for example, new return fields, extra read-only validations) that do not change key shape or semantics. These may be rolled out without coordination resets as long as callers tolerate older results. + - `compatible` – purely additive changes (for example, new return fields or additional observability) that preserve the accepted-input set, outcomes, fencing, idempotency, and mutation semantics. Any validation that can reject a previously valid caller or payload requires the versioned/reset path. These may be rolled out without coordination resets as long as callers tolerate older results. - `requires_region_reset` / `requires_tenant_reset` / `requires_cluster_reset` – changes that alter key shapes or semantics in ways that cannot be safely mixed with old behavior. These must run alongside the corresponding coordination reset flows and are expected to be rare. - If a rollout requires an epoch boundary to avoid mixed old/new semantics, classify it as the corresponding `requires_*_reset` scope and execute the full reset handshake (pause ticks → bump `region_epoch` → reconcile ledger → resume). Do not treat `region_epoch` bumps as a routine rollout mechanism outside this compatibility contract. - **Registry as the source of truth** @@ -424,7 +431,7 @@ The registry, validators, ownership enforcement, generic test harness, and CI ch - `reset_sensitivity` describing which reset scopes (region, tenant, cluster) must be considered when changing script behavior or key shape. - `loss_outcome_class` naming the ADR 0058 work class and its required loss/recovery disposition. - `tail_loss_behavior` describing what is expected to happen if the script’s writes are lost or replayed within the measured unreplicated-write exposure (for example “pure lease; safe to lose”, “can enqueue duplicates; relies on domain idempotency”, “must not silently drop without a corresponding ledger row”). - - Shard-locality metadata for multi-key scripts, including whether all `KEYS` must share the same `{tenantRegionTag}`, `{tenantInstanceTag}`, or `{tenantGameplayTag}` hash tag and slot. + - Shard-locality metadata for multi-key scripts, including whether all `KEYS` must share the same `{tenantRegionTag}`, `{tenantInstanceTag}`, `{tenantGameplayTag}`, or fixed `{gateway-connect-token-replay-v1}` hash tag and slot. The registry descriptors are sufficient to **drive a generic test harness** over owner-local or genuinely shared sources: any coordination script must be invokable in isolation using the registry metadata (script identifier, expected `KEYS`/`ARGV`, and allowed prefixes). Callers must not hard-code key names or slots that diverge from their owner descriptor. @@ -438,7 +445,7 @@ CI enforces the following invariants for registered scripts: - They reference prefixes that belong to Cache/Rate-Limit Redis, or - They omit required `reset_sensitivity`, `loss_outcome_class`, or `tail_loss_behavior` metadata. - For scripts that declare shard-local multi-key behavior, CI verifies that: - - All declared `KEYS` share the same hash tag (for example `{tenantRegionTag}`), and + - All declared `KEYS` share the same hash tag (for example `{tenantRegionTag}` or the fixed `{gateway-connect-token-replay-v1}`), and - No script attempts cross-slot operations under the `coordination` role. ## Call-Side Time and Randomness Contract diff --git a/design/architecture/system-architecture-redis-operations.md b/design/architecture/system-architecture-redis-operations.md index 6a7b0f9a85..a77e19e738 100644 --- a/design/architecture/system-architecture-redis-operations.md +++ b/design/architecture/system-architecture-redis-operations.md @@ -34,6 +34,8 @@ This target-state blanket explicitly excludes the linked **Current Operator Fall ## Canonical Coordination Reset Sequence +> **Target state only — unavailable today.** The `coordination-maintenance` operation and phases below are not current operator instructions. Current operators must use the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback): preserve evidence, keep the affected scope fenced, use only shipped pause/status and read-only inspection, and escalate. + This section is the normative source for the multi-step Coordination Redis reset/recovery workflow. Other runbooks should point here and then describe only scope choice, session policy, evidence, and scenario-specific abort or storage steps. Canonical public operation: @@ -135,7 +137,7 @@ This section centralizes the normative targets for Redis behavior that other doc - **Script runtime** - tick- and session-related Lua scripts are expected to complete within roughly 10–20 ms per invocation under normal load - **Coordination memory share** - - coordination prefixes should normally occupy no more than about 30–40% of `maxmemory` on Coordination Redis with `noeviction` + - coordination prefixes should normally occupy no more than about 30–40% of `maxmemory` on Coordination Redis with mandatory `maxmemory-policy=noeviction` for every non-ephemeral profile; the only permitted deviation is an explicitly labeled ephemeral one-shot test stack, and any non-ephemeral deviation or observed eviction is fail-closed incident evidence ### Cache/Rate-Limit Redis Core Targets @@ -174,6 +176,12 @@ Manual AOF surgery is not supported. Either the AOF is trusted and replayed as-i Goal: provide a simple, explicit runbook for resetting Cache/Rate-Limit Redis without entangling it with Coordination Redis resets. +> **Target state only — unavailable today.** The external Cache deployment maintenance gate, `FLUSHDB`/`FLUSHALL` or clustered deletion, client release, and authorized Automation rebuild/readback sequence below are not current operator instructions. The repository does not yet provide the required external gate, writer admission/acknowledgement proof, or authorized rebuild path. Current operators must preserve cache, reset, and incident evidence, avoid destructive reset or client-release actions, keep affected writers/clients quarantined or stopped, and use the safe fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) and escalation path. + +### External Cache Deployment Maintenance Gate + +The reset gate reuses the ADR-0085 external durable operation/fence pattern without making Cache/Rate-Limit Redis an authority. It is one durable operation outside the target deployment with an immutable `operationId`, exact environment/deployment identity and generation, a frozen complete registered writer and prefix inventory, and a durable external fencing token/generation. Before deletion, every ordinary writer must either pause and drain with an acknowledgement bound to that exact operation/fence or be denied Cache/Rate-Limit Redis connection/network admission. Writer admission and acknowledgements must revalidate the operation/fence and deployment generation after every restart or replacement; stale writers, stale operations, inventory changes, and missing, partial, or ambiguous evidence are rejected. Competing operations are serialized, and takeover, expiry, abort, and release each require durable evidence bound to the same operation/fence. A local Redis key is not the gate: the external gate must survive Redis and writer restarts and remain held through deletion, verification, and rebuild. Only the target-only named ACL principal `automation_queue_rebuild_maint`, bound to the same operation/fence, deployment generation, and exact registered `automation:queue:*` prefix/scope, may write while the gate is held; ordinary writers remain denied, and its completion/readback is required before release. This is not a generic cache or operator writer: any future non-Automation Cache/Rate-Limit rebuild, if needed, requires its own separately named owner principal and prefix contract. The current tooling does not yet provide this complete gate, writer acknowledgement/admission proof, or authorized rebuild path, so current operators must use the fallback above. + Cache/Rate-Limit Redis is fully reset-tolerant for the prefixes listed in [`system-architecture-redis-cache.md`](./system-architecture-redis-cache.md) and the reset policy matrix in [`system-architecture-redis-reset-and-recovery.md`](./system-architecture-redis-reset-and-recovery.md). A reset: - applies deletion only to the exact registered key patterns in the immutable Cache/Rate-Limit prefix inventory, under the bounded apply/readback contract; catalog family labels such as inventory, character-cache, world-dynamic, room, view:room-look, chat, and ratelimit are not executable deletion selectors, and broad `automation:*` matching remains prohibited @@ -182,8 +190,6 @@ Cache/Rate-Limit Redis is fully reset-tolerant for the prefixes listed in [`syst The current `automation:queue:{tenantInstanceTag}:*` family is a non-authoritative Cache/Rate-Limit projection. The target rebuild/index operation may index only safe durable `PENDING_EVALUATION` work, or an `EVALUATING` row only after the owner proves its lease is stale or explicitly releases it through one fenced CAS covering the status, lease owner, freshness, and fence transition. Non-stale, unresolved, or ambiguous rows remain excluded. Current `rebuildPendingWorkItemIndex` unconditionally selects both statuses and has no stale, owner, or compare-and-set gate, so queue-prefix reset/rebuild and resume are unavailable and must fail closed; a non-atomic status preflight cannot authorize a safe PENDING-only path. Redis queue payloads are never recovery authority. The reserved `automation:timer:{tenantRegionTag}` and `script-scheduler:{tenantRegionTag}:lastTickId` timer/checkpoint projections remain target-only and unavailable. -Do not use the generic Cache/Rate-Limit reset procedure below for the current Automation queue family. A queue-prefix flush, safe PENDING-only rebuild, and resume sequence is target-only until the owner-reconciled status/CAS recovery contract is implemented and proven; current queue incidents remain paused and fail closed under the [Automation queue incident runbook](./system-architecture-redis-incident-runbook.md#automation-queue-schema-mistakes). - ### Runbook: Environment-Scoped Cache Reset Mutating Cache/Rate-Limit reset is currently unavailable: the repository does not ship the owner-supported tooling that can bind a reset to the Cache/Rate-Limit deployment, an exact registered prefix inventory, and immutable apply/readback evidence. Do not turn the catalog labels or fallback below into ad-hoc `redis-cli`, `SCAN`, prefix-delete, `FLUSHDB`, or `FLUSHALL` instructions. The required target contract is owned by [Coordination Redis Ops Access & Tooling](./system-architecture-redis-ops-access.md#canonical-control-plane-and-cli-contract), which requires separate owner tooling and exact inventory/apply/readback postconditions for any future cache mutation. @@ -206,6 +212,8 @@ FireMUD classifies coordination-backed workloads by reset tolerance: - **reset-sensitive** - gameplay session prefixes such as `session:game:*`; current live Account auth uses the legacy `session:auth:account:*` and `session:auth:tenant:*` projections, while target-only Account auth families are `session:auth:token:*` and `session:auth:generation:*`; the Account-owned unversioned legacy `session:connect-token:*` result map and target `session:connect-token:v1:*` issuance-result projection are also reset-sensitive - future automation queues explicitly assigned to Coordination Redis by their owner contract (the current `automation:queue:{tenantInstanceTag}:*` family is a Cache/Rate-Limit projection and follows the unavailable queue-reset path above), or non-critical analytics that can be recomputed or re-enqueued + - The connect-token issuance-result family is distinct from Gateway replay/deny markers. Narrow region/tenant resets preserve it; cluster reset may discard it only after Account-owned durable/fenced recovery or request-identity expiry, otherwise missing state requires exact-result recovery or fail-closed refusal. + - future automation queues explicitly assigned to Coordination Redis by their owner contract, or non-critical analytics that can be recomputed or re-enqueued; new automation or analytics prefixes are not implicitly assigned this class and each exact family must be registered with its owner and reset contract before use. - **reset-forbidden** - future workloads that would treat Redis as a durable component of a long-lived contract @@ -221,12 +229,12 @@ Facts: - Coordination Redis uses asynchronous replication. - A promoted replica may be missing recent coordination writes. -- The new primary’s keyspace is authoritative after promotion. +- The new primary becomes the active source for surviving Redis coordination projections after promotion, but remains only a coordination projection and never durable authority. PostgreSQL and the owning domain stores remain authoritative for durable outcomes, timeline baselines, and recovery decisions. Behavior: - modest promotion lag contributes to the measured unreplicated-write exposure -- replay safety is preserved by lease/lock/epoch validation and PostgreSQL-backed effect ledgers +- tick/effect replay safety is preserved by lease/lock/epoch validation and PostgreSQL-backed effect ledgers; protected admission is separate and requires owner-specific replay-marker, auth-token, session, generation, and relevant fence continuity/readback proof Runbook: @@ -235,15 +243,15 @@ Runbook: - acceptable: `redis_replication_lag_ms <= 0.5 * redis_unreplicated_write_window_slo_ms` - warning: `0.5 * redis_unreplicated_write_window_slo_ms < redis_replication_lag_ms < redis_unreplicated_write_window_slo_ms` - red: `redis_replication_lag_ms >= redis_unreplicated_write_window_slo_ms` -3. If lag is in the acceptable band, promotion is acceptable from a replay perspective. +3. If lag is in the acceptable band, it bounds tick/effect replay exposure only; it does not by itself authorize protected admission or prove replay-marker/auth-token/session/generation continuity. Any uncertain continuity remains quarantined/fenced until the owning proof/readback succeeds. 4. If lag is in the warning band, investigate immediately and delay promotion unless the failover risk of waiting is worse than accepting a wider measured exposure. -5. If lag crosses the red line, either wait for recovery or treat promotion as a deliberate drop-recent-coordination-state event handled by one bounded `coordination-maintenance recover --mode reset --scope ` operation under the normal maintenance-lock and epoch-fencing workflow, with exactly one of `--preserve-sessions` or `--invalidate-sessions` selected. +5. If lag crosses the red line, the following is **target-state procedure only and unavailable in the current implementation**: either wait for recovery or treat promotion as a deliberate drop-recent-coordination-state event handled by one bounded `coordination-maintenance recover --mode reset --scope ` operation under the normal maintenance-lock and epoch-fencing workflow, with exactly one of `--preserve-sessions` or `--invalidate-sessions` selected. For a current red-lag incident, do not invoke that unavailable reset; use the fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback), preserve AOF and incident evidence, keep the affected scope fenced, and escalate through the linked incident runbook. ## Key Shape Mistakes and Coordination Resets > This runbook inherits the [current execution boundary](#current-execution-boundary); its imperative steps are target-state only. -Coordination keys are treated as reset-tolerant, volatile, and backed by PostgreSQL plus replay. +Coordination keys are volatile, and each prefix follows the class in the canonical [reset policy matrix](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). Only reset-tolerant families may be dropped without reset-sensitive owner gates. A reset-sensitive family may be deleted only after its owner’s pause and applicable cutover or invalidation and fencing gates succeed; the applicable reconciliation/readback must then complete before release, with preserved-session rebind required only when `--preserve-sessions` is selected. Before performing any coordination reset, operators should walk a short pre-reset validation checklist: @@ -258,6 +266,8 @@ Every coordination reset that affects tick execution must include the Game Sessi ### Runbook: Mis-Sharded Coordination Keys +> **Target state only — unavailable today.** Do not execute this reset/resume sequence in current operations. Use the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) and escalate with the affected scope fenced. + 1. detect the issue through CI, logs, or metrics 2. choose the smallest safe scope 3. execute the [Canonical Coordination Reset Sequence](#canonical-coordination-reset-sequence) for that scope @@ -265,10 +275,12 @@ Every coordination reset that affects tick execution must include the Game Sessi ### Key Enumeration Strategy for Scoped Resets -Cluster-safe scoped resets rely on prefix-scoped `SCAN` per master under strict operational preconditions: +Cluster-safe scoped resets use prefix-scoped `SCAN` per master only as an internal, target-state phase of the canonical durable `coordination-maintenance` operation described above. This phase is unavailable in the current implementation and is not a standalone reset or cleanup recipe. Before enumeration starts, that same operation must carry the unchanged ADR-0085 external maintenance handoff: the exact `operationId`, external maintenance fence/lock binding, classifier, immutable evidence digest, and complete affected scope, with the canonical pre-wipe gates already proven where the phase is destructive. The operation remains fenced through the canonical post-reset verification; scan completion or key absence is never evidence to bypass those gates. A fine-grained scoped reset lock may coordinate batches inside the already-held operation, but it never replaces the deployment-wide maintenance operation or lock. + +Within that operation, cluster-safe enumeration follows these internal steps: -1. pause the target region or scope -2. acquire a scoped reset lock +1. use the operation-owned pause and external maintenance fence for the target scope +2. bind any scoped reset lock to that operation and its complete recorded scope 3. enumerate only known prefix families 4. scan each master with modest `COUNT` and strict time budgets 5. delete via `UNLINK` where possible @@ -280,6 +292,8 @@ A lightweight unknown-prefix scanner periodically scans with conservative budget ## Session Schema Cleanup and Large Keyspaces +> **Target state only — unavailable today.** The `coordination-maintenance recover --mode session-schema-cleanup` flow and its mutating continuation/release controls are not current operator instructions. Current operators must use the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback): preserve evidence, keep the affected scope fenced, use shipped pause/status and read-only inspection, and escalate. + Session schema cleanup is a hygiene and recovery tool, not a normal steady-state path. When cleanup is required after a schema change or persistent unsupported-schema drift: - operate on tenant-scoped gameplay/bootstrap prefixes such as `session:game:{tenantGameplayTag}:*` and the current `sessionctx::*` family @@ -349,6 +363,7 @@ Canonical maintenance-active signal: ## Dual-Leader Detection and Coordination Reset > This runbook inherits the [current execution boundary](#current-execution-boundary); its imperative steps are target-state only. +> **Target state only — unavailable today.** The recovery commands in this runbook are not current operator instructions. Use the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback), keep affected admission and mutation fenced, and escalate. Goal: detect Redis split-brain or conflicting primaries and recover through a coordinated reset before duplicate logical effects can escape the tick subsystem. @@ -375,6 +390,8 @@ Goal: change how `tenantId` / `gameInstanceId` / `regionId` normalization and ha ### Runbook: Normalization Migration via Reset +> **Target state only — unavailable today.** This reset-based normalization migration and its `coordination-maintenance` CLI/release controls are not current operator instructions. Current operators must use the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback): preserve evidence, keep the affected scope fenced, use shipped pause/status and read-only inspection, and escalate. + The migration reset gate must pass the complete [canonical post-reset verification checklist](./system-architecture-redis-ops-access.md#canonical-post-reset-verification-checklist), including the two independent exact digests, mode-specific startup attestation, all positive and destructive negative probes, and isolated-target cleanup/readback evidence. A combined or caller-asserted digest value or copied probe subset cannot satisfy this gate. 1. define an immutable migration contract containing the old and new normalization/hash-tag versions, affected scope, maintenance CLI and control-plane build digests, every participating service image digest, and the Lua Script Registry version/digest diff --git a/design/architecture/system-architecture-redis-ops-access.md b/design/architecture/system-architecture-redis-ops-access.md index 102bb59518..4272a20742 100644 --- a/design/architecture/system-architecture-redis-ops-access.md +++ b/design/architecture/system-architecture-redis-ops-access.md @@ -10,10 +10,12 @@ The target control-plane and maintenance contract in this document is ahead of t - The live implementation supports the current `{tenantId, gameInstanceId}` queue boundary; `regionId` is present in the proto contract but is currently rejected by the service implementation. - The bounded `coordination-maintenance ...` public surface remains target state, not a description of fully implemented repo-local tooling today. No public recovery scope is currently implemented and proven; recovery phases may be implemented and tested behind the high-level operation without becoming separate public commands. - The owning-service typed maintenance API, role-bound Redis helper surface, aggregated registry, descriptor validators, and ownership-enforcement checks described below are target state and are not implemented; current direct access remains subject to the generic runtime seam and the incident-only fallback. -- Reset-smoke isolation is a separate mechanism decision: the existing [Game Session readiness-only identity contract](./microservices/game-session-service/operations.md#readiness-and-liveness) and [synthetic player-flow canary contract](./system-architecture-logging-monitoring.md#synthetic-player-flow-canaries-target-state-prod-like-contract) do not define an isolated reset-smoke namespace or durable synthetic identity that can safely map to tick staging and ledger rows. Automation's separate [`isDryRun=true` namespace](./system-architecture-scripting-contracts.md#6-dry-run--test-traffic-safety) is explicitly non-committing and cannot reach tick queues, so it is not a reset-smoke identity. Until a reset-smoke mechanism decision is accepted and implemented, `RunPostResetSmokeCheck` is non-mutating for real PostgreSQL tick state, real Redis tick metadata/staging/pending, and real tick-ledger rows. It may perform only bounded sampled lease acquire/renew/release probes and, when the workflow affects the shared replay domain, a disposable probe through the target tagged `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `jti`, and `deny:jti` keys: one canonical consume script creates the marker and the same pinned connection obtains one configured `WAITAOF` local/replica durability acknowledgement before the probe returns `DURABLE_REPLAY_CONSUME_ACK`. The current writer's untagged replay marker remains migration-only drift and is not target proof. The probe must fail closed on timeout, malformed, below-threshold, or uncertain results and must not enter real staging or ledger paths. +- Reset-smoke isolation is a separate mechanism decision: the existing [Game Session readiness-only identity contract](./microservices/game-session-service/operations.md#readiness-and-liveness) and [synthetic player-flow canary contract](./system-architecture-logging-monitoring.md#synthetic-player-flow-canaries-target-state-prod-like-contract) do not define an isolated reset-smoke namespace or durable synthetic identity that can safely map to tick staging and ledger rows. Automation's separate [`isDryRun=true` namespace](./system-architecture-scripting-contracts.md#6-dry-run--test-traffic-safety) is explicitly non-committing and cannot reach tick queues, so it is not a reset-smoke identity. Until a reset-smoke mechanism decision is accepted and implemented, `RunPostResetSmokeCheck` is non-mutating for real PostgreSQL tick state, real Redis tick metadata/staging/pending, and real tick-ledger rows. It may perform only bounded sampled lease acquire/renew/release probes and, when the workflow affects the shared replay domain, a fresh canonical replay-consume invocation on the same pinned Redis connection. The invocation must return `1` and create a disposable replay marker through the target `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `jti`, and `deny:jti` keys, followed by one same-connection `WAITAOF` local/replica durability acknowledgement meeting configured thresholds. A `0` or `-1` result is non-mutating and cannot supply a second write acknowledgement; any cleanup is a separate guarded cleanup write/readback and is not part of `DURABLE_REPLAY_CONSUME_ACK`. The current writer's untagged replay marker remains migration-only drift and is not target proof. The probe must fail closed on timeout, malformed, below-threshold, or uncertain results and must not enter real staging or ledger paths. Use this doc as the canonical target-state contract for later reset/replay tooling, but do not assume every operation below is already available in the running codebase. Current operators, runbooks, Helm hooks, Jobs, and dashboards must not invoke the `coordination-maintenance` commands described below until that surface is implemented and end-to-end proven. +Current Gateway wiring is a frozen wrong-role exception: `GameplayHandshakeFilter` receives the generic reactive Redis template from the `spring.data.redis` binding, whose current profile uses `FIREMUD_REDIS_CACHE_HOST`, while writing only the untagged replay marker `gateway:connect-token:jti:*`. It has no current browser-deny, readiness, or replay-fence writer; those are target-only state. The replay prefix remains Coordination-owned in the target and must not be admitted as Cache state. A Cache reset inventory/readback that finds that prefix, or the generic Gateway writer, must abort without deletion. Target Gateway replay uses the named Coordination ACL and exact co-slotted keys `gateway:connect-token:{gatewayReplayDomain}:jti:*`, `gateway:connect-token:{gatewayReplayDomain}:deny:jti:*`, and `gateway:connect-token:{gatewayReplayDomain}:readiness`; migration requires quarantine, exact old replay-prefix inventory/readback, named Coordination client/ACL cutover, target-key readback, and same-connection `WAITAOF` proof before the current writer is drained and Cache reset admission can be considered safe. + ## Default Operator Surface - Use the **read-only ops user** for inspection. Coordination writes are never an ordinary operator action: when supported maintenance exists, operators invoke the owning service's authenticated typed maintenance API, while the service runtime performs the Redis mutation. Operators and generic tools never receive application credentials for this purpose. @@ -68,15 +70,23 @@ To keep ACL usage consistent across services and documentation, Redis deployment | ACL User (example) | Intended Role | Typical Consumers | | --- | --- | --- | | `coord_app` (logical profile; distinct principals) | Coordination application clients – may write and run Lua scripts against **Coordination Redis** only through their owner-local helper and within disjoint owner/contract key patterns | `account_coord_app` (Account-owned `session:auth:account:*`, `session:auth:tenant:*`, `session:auth:token:*`, `session:auth:generation:*`, legacy unversioned `session:connect-token:tenant:*`, and target `session:connect-token:v1:tenant:*`), `gateway_coord_app` (Gateway `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` only), `gamesession_coord_app` (Game Session `tick:*`, `timer:*`, `retry:*`, `session:game:*`, and the producer side of `tick-events:*`; stream publication uses `XADD` with bounded `MAXLEN`; any `tick-executor-lease:*` access is confined to the owner-local lease helper and its registered lease script, never to a workload-facing raw Redis path), and `automation_coord_app` (Automation-owned target coordination families such as `automation:timer:*` and `script-scheduler:*`; if a target scheduler consumes Redis Streams directly, its owner registration must bind the exact consumer-scoped `tick-events-offset:{tenantRegionTag}:` key, stream/consumer identity, caller principal, and registered script digest to one atomic compare-and-set helper. ACL/key patterns scope which keys and commands a principal may access but do not enforce compare-and-set semantics or restrict a script digest. Offset advancement must therefore go through one typed owner-local API/helper backed by that registered atomic CAS script, binding the exact consumer/key, expected current offset, monotonic next offset, script digest/version, and readback; no generic `SET` or direct Redis write call path is allowed. If direct Redis consumer access remains, its workload-facing principal is read-only (`GET`) for offset keys; the distinct owner-local executor path/principal is narrowly key-scoped and invoked only through the typed API. Its `tick-events:{tenantRegionTag}` stream pattern permits only `XREAD`/`XRANGE`, and its `tick-events-lease:{tenantRegionTag}` pattern permits only the owner-registered lease renewal/release script). Event-stream consumer identities, exact keys, and executable registrations must be complete before granting these latter permissions; absent that registration Automation uses the owner API/heartbeat contract and receives no direct stream or offset grant. Maintenance tooling is API-only and has no `coord_maintenance_app` principal. | + +| `entity_coord_app` | Entity Management's target Coordination Redis principal for its registered ConflictTracker entity producer; may write/run Lua only against `~conflict:entity:*` | Entity Management ConflictTracker producer scope; no `conflict:session:*` or other owner-family access | +| `gamesession_coord_app` | Game Session's target Coordination Redis principal for its registered tick/session families and ConflictTracker session producer; its ConflictTracker grant is exactly `~conflict:session:*` | Game Session tick/session owner paths plus Game Session ConflictTracker producer scope; no `conflict:entity:*` access | + | `coord_ops_ro` | Read-only coordination ops user – may inspect known coordination keys and container members but cannot enumerate the database, write, or run Lua | Human operators using `redis-cli`/RedisInsight, monitoring/exporter agents for Coordination Redis | -| `cache_app` (logical profile; distinct principals) | Cache/Rate-Limit application clients – may read/write **only** cache/rate-limit prefixes on **Cache/Rate-Limit Redis** within each service's disjoint key-pattern allowlist | `gateway_cache_app` (Gateway rate-limit/cache families), `gamesession_cache_app` (Game Session `view:room-look:*` only), `entity_cache_app`, `world_cache_app`, `social_cache_app`, and `automation_cache_app` (Automation `automation:queue:{tenantInstanceTag}:*` / `automation:quota:*` / `automation:tenant-budget:*` / `automation:test:capacity:*` / `automation:test:quota:*` / `automation:readiness:capacity:*`) | +| `cache_app` (logical profile; distinct principals) | Cache/Rate-Limit application clients – may read/write **only** cache/rate-limit prefixes on **Cache/Rate-Limit Redis** within each service's disjoint key-pattern allowlist | `gateway_cache_app` (Gateway rate-limit/cache families), `gamesession_cache_app` (Game Session `view:room-look:*` only; current `lookcache:*`, `screenbuffer:*`, `ipconn:
`, `sessionip:`, and `ratelimit:` writers require explicit inventory, binding, and drain/isolation evidence), `entity_cache_app`, `world_cache_app`, `social_cache_app`, and `automation_cache_app` (Automation `automation:queue:{tenantInstanceTag}:*` / `automation:quota:*` / `automation:tenant-budget:*` / `automation:test:capacity:*` / `automation:test:quota:*` / `automation:readiness:capacity:*`) | +| `automation_queue_rebuild_maint` | Target-only Cache/Rate-Limit maintenance principal – may write only registered `automation:queue:*` prefixes/scopes during an active external Cache maintenance operation, when bound to the same `operationId`, fence/generation, deployment generation, and exact scope; it cannot write other Cache/Rate-Limit or Coordination prefixes | External Cache reset/rebuild controller for the Automation owner; not a general cache or operator user | | `cache_ops_ro` | Read-only cache ops user – may inspect cache/rate-limit keys but never write to them | Human operators inspecting Cache/Rate-Limit Redis, cache-focused monitoring/exporters | +The ConflictTracker target grants above do not describe the current wiring: `RedisConflictTracker` is currently constructed with the generic `StringRedisTemplate`, and Entity Management and Game Session use separate `INCR`/`EXPIRE` calls with warning-only expiry failure. That generic client and mutation sequence are implementation drift; migration must introduce the named Coordination clients and the distinct principals before the target grants can be treated as deployed. + Per-service READMEs are expected to state which ACL user(s) each service uses and which Redis role(s) it connects to so configuration drift is easy to detect during reviews. CI and configuration checks should ensure that: - Services that only participate in coordination (for example Automation's tick-adjacent target path) never use cache ACL users. Game Session is the explicit target dual-role exception: its `gamesession_coord_app` principal and Coordination Redis client are separate from its `gamesession_cache_app` principal and Cache/Rate-Limit Redis client, and neither may be broadened to the other role's prefixes. -- Services that only use Cache/Rate-Limit Redis (for example Entity Management or World Management) never use coordination ACL users. Spring Cloud Gateway is another target dual-role exception: its `gateway_coord_app` replay/deny/readiness client uses a distinct principal, credential, and Coordination Redis deployment from its `gateway_cache_app` rate-limit/cache client; neither client may be broadened to the other role's prefixes. -- The logical `coord_app` profile is instantiated as distinct `account_coord_app`, `gateway_coord_app`, `gamesession_coord_app`, and `automation_coord_app` principals with disjoint key-pattern allowlists. No service may use a shared principal that can read/write another service's owner families; maintenance tooling has no Coordination Redis ACL principal and must use the owning service API. No ACL user may read/write both coordination and cache prefixes on the same deployment. +- Services that have no coordination participation never use coordination ACL users. Entity Management's dedicated `entity_coord_app` is the narrow exception for its registered ConflictTracker producer, with only `~conflict:entity:*`; its Cache/Rate-Limit client remains separate. Spring Cloud Gateway is another target dual-role exception: its `gateway_coord_app` replay/deny/readiness client uses a distinct principal, credential, and Coordination Redis deployment from its `gateway_cache_app` rate-limit/cache client; neither client may be broadened to the other role's prefixes. +- The logical `coord_app` profile is instantiated as distinct `account_coord_app`, `gateway_coord_app`, `entity_coord_app`, `gamesession_coord_app`, and `automation_coord_app` principals with disjoint key-pattern allowlists. The ConflictTracker grants are exact: `entity_coord_app` may access only `~conflict:entity:*`, while the Game Session grant is only `~conflict:session:*` for that diagnostic family (alongside Game Session's separately registered tick/session families); neither principal may access the other's conflict scope. No service or maintenance tool may use a shared principal that can read/write another service's owner families, and no ACL user may read/write both coordination and cache prefixes on the same deployment. +- `automation_queue_rebuild_maint` is admitted only for the externally fenced Automation queue reset/rebuild path; future non-Automation rebuilds require separate named owner principals and prefix contracts rather than reusing it. Game Session's target dual-role wiring is explicit: `gamesession_coord_app` uses `RedisCoordConfig` and a dedicated Coordination Redis connection for tick/session coordination families, while `gamesession_cache_app` uses `RedisCacheConfig` and a separate Cache/Rate-Limit Redis connection for `view:room-look:*` only. The clients, credentials, pools, and endpoint configuration are distinct. The current generic `firemud.redis.*` binding and shared Spring Redis template remain implementation drift and are not proof that role separation or the target ACLs are implemented. @@ -246,8 +256,8 @@ The public CLI surface listed above is target state only; it is not currently im - consumes the advertised supported scope selected by the recovery workflow and its maintenance lock token. - accepts either `--old-region-epoch ` for `--scope region` or `--old-region-epoch-map ` for tenant/cluster scopes. - owns `replay-first` convergence as well as old-epoch reset convergence: - - without an epoch bump, it drives in-epoch `SCHEDULED` ledger rows toward `APPLIED` or `ABANDONED` for the selected current-epoch scope only where the evidence policy permits; inconclusive rows remain non-terminal and reconciliation-required under their original root `EffectId`. - - after an epoch bump, it publishes `APPLIED`/`ABANDONED` reset outcomes for old-epoch rows only with the owner-fenced per-effect evidence/attestation required by the [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy); inconclusive old-epoch work remains non-terminal and reconciliation-required under its original root `EffectId`. + - without an epoch bump, it drives in-epoch `SCHEDULED` ledger rows toward `APPLIED` or `ABANDONED` for the selected current-epoch scope only where the evidence policy permits; inconclusive rows remain non-terminal and reconciliation-required under their original persisted mutation `EffectId`, with enclosing `rootEffectId` retained as lineage and reconciliation context. + - after an epoch bump, it publishes `APPLIED`/`ABANDONED` reset outcomes for old-epoch rows only with the owner-fenced per-effect evidence/attestation required by the [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy); inconclusive old-epoch work remains non-terminal and reconciliation-required under its original persisted mutation `EffectId`, with enclosing `rootEffectId` retained as lineage and reconciliation context. - may support `--discover-old-epochs` as an implementation convenience, but only if it resolves epochs from PostgreSQL and emits the discovered map in its audit output. - Internal command-convergence phase - consumes the same maintenance lock token as the prior internal phase. @@ -266,7 +276,7 @@ The public CLI surface listed above is target state only; it is not currently im - Internal session-rebind phase - accepts either `--region-epoch ` for `--scope region` or `--region-epoch-map ` for tenant/cluster scopes. - The Account-validated opaque `rebindHandle` must bind and match the binding's exact one-tenant `membershipVersion` map `{tenantId: version}`, independently from `authorityTuple.membershipAuthorityGeneration`, and the complete stream-key-ordered `outboxCheckpoints` set. Missing, extra, scalar, differently keyed, stale, regressed, contradictory, or aggregate-only membership or checkpoint evidence, or a mismatch in either independent predicate, fails closed; rebind never merges handle and binding values, reconstructs one carrier from the other, or drops checkpoint entries. - - is permitted when a region- or tenant-scoped reset's explicitly recorded session policy is `--preserve-sessions`; those scopes must record either `--preserve-sessions` or `--invalidate-sessions` rather than relying on scope inference. Cluster requests accept only explicit `--invalidate-sessions` and never enter this phase. For an eligible scope, the phase reads only the immutable `GameplayBindingInventory` snapshot identified by the operation's exact `inventorySnapshotRevision` and validates the complete recovery evidence carrier: parent operation fence, distinct `parentCoverageFence`, applicable linked child IDs/lifecycles/fences or explicit `NOT_APPLICABLE` markers, and later `coverageGeneration`. It recreates region-authoritative bindings through the durable inventory and session-to-region bridge, persists and validates that carrier on the rebind transition and readback, and must refresh the same maintenance lock rather than acquiring another lock. Affected tenant-owned `session:game:index:*` projections may be dropped under either policy and must reconcile and read back before release; the one global account index is exempt from tenant-local selector handling because its members are tenant-qualified, and it requires complete account-wide inventory and coverage before replacement. Untagged global issuer indexes are not narrow rebind or cleanup targets and require their complete owner-defined global inventory and coverage proof before replacement. Ordinary gameplay mutation intake remains blocked until this phase and that reconciliation succeed. Only an actually attempted valid-identity command with an established command record may be terminalized as `REGION_REBIND_REQUIRED` without gameplay mutation. + - is permitted when a region- or tenant-scoped reset's explicitly recorded session policy is `--preserve-sessions`; those scopes must record either `--preserve-sessions` or `--invalidate-sessions` rather than relying on scope inference. Cluster requests accept only explicit `--invalidate-sessions` and never enter this phase. For an eligible scope, the phase reads only the immutable `GameplayBindingInventory` snapshot identified by the operation's exact `inventorySnapshotRevision` and validates the complete recovery evidence carrier: parent operation fence, distinct `parentCoverageFence`, applicable linked child IDs/lifecycles/fences or explicit `NOT_APPLICABLE` markers, and later `coverageGeneration`. It recreates region-authoritative bindings through the durable inventory and session-to-region bridge, persists and validates that carrier on the rebind transition and readback, and must refresh the same maintenance lock rather than acquiring another lock. At tenant scope, affected tenant-owned `session:game:index:*` families may be dropped as whole families; at region scope, only exact affected keys or members are updated, removed, or recreated from durable inventory according to the owning index schema, preserving unrelated keys, members, regions, and tenants. All affected projections must reconcile and read back before release; the one global account index is exempt from tenant-local selector handling because its members are tenant-qualified, and it requires complete account-wide inventory and coverage before replacement. Untagged global issuer indexes are not narrow rebind or cleanup targets and require their complete owner-defined global inventory and coverage proof before replacement. Ordinary gameplay mutation intake remains blocked until this phase and that reconciliation succeed. Only an actually attempted valid-identity command with an established command record may be terminalized as `REGION_REBIND_REQUIRED` without gameplay mutation. - Before recreating a binding, it validates the complete [canonical preserved-session rebind predicate](./system-architecture-redis.md#session-and-region-binding-contract), including only a supported `schemaVersion=2` payload (missing, `schemaVersion=1`, unsupported, or incomplete versions fail closed), the payload's exact `issuanceFence`, `authorityTuple.membershipAuthorityGeneration`, exact one-tenant `membershipVersion` map, complete `outboxCheckpoints` set, exact equality of `authTokenIssuedAt`/`authTokenExpiresAt`/`tokenGeneration` to the registry `iat`/`exp`/`tokenGeneration`, and every token-registry, identity, authority, expiry, generation, epoch, and lease-fence predicate defined there. The rebind predicate is realm-specific: public production requires current membership and entitlement, and its bounded entitlement fallback is permitted only for the public-production entitlement read; private/playtest requires existing membership and the exact current Account-owned realm-grant identity and `grantVersion`, with no entitlement fallback or grant substitution. Missing, unavailable, stale, contradictory, or mismatched private/playtest grant evidence fails closed. The canonical gameplay-session record and pre-auth transport context are not authority substitutes; pre-auth context is outside the preservation policy. A reachable token-registry or Account-authority result of `AUTH_SESSION_REVOKED` or an invalid-token outcome, including missing, expired, malformed, revoked, or mismatched token authority, is a security failure: the phase marks the preserved session auth-revoked, closes its socket, and ends the current resume episode without emitting `REGION_REBIND_REQUIRED`. Unavailable or ambiguous Account evidence remains fenced under the outage policy and is not a region rebind gap. Only after every Account identity, token, authority, membership, lease, and delegation-JWT predicate has succeeded, with the applicable realm predicate satisfied by either a fresh public-production entitlement read or its qualifying bounded fallback, may a solely non-security region gap leave the session connected but not gameplay-admitted; a gameplay or admission command actually attempted after valid identity and command-record establishment may then receive terminal, non-applied `executionOutcome = REGION_REBIND_REQUIRED`. No command record or identity is synthesized for a missing, invalid, or unauthenticated request, and this command outcome does not close or terminalize the connected session. Any non-security predicate evidence that is missing, stale, ambiguous, mismatched, expired, partial, Redis-derived, or otherwise non-exact blocks rebind and reopen. - A failed non-security preserved-session predicate never implicitly changes the recorded session policy. The operation remains paused and fenced under the same `operationId` and `maintenanceLockToken`; an explicit audited preserve-to-invalidate transition may compare-and-set the policy under that same lock only after persisting and validating the complete recovery evidence carrier, including the parent operation fence, distinct `parentCoverageFence`, applicable linked child IDs/lifecycles/fences or explicit `NOT_APPLICABLE` markers, `inventorySnapshotRevision`, and later `coverageGeneration`. If that same-lock transition is unavailable, complete audited `release-lock` abandonment and start an explicit new `recover` operation with `--invalidate-sessions`. Rebind failure alone is never invalidation proof; the security failure above is the explicit auth-revocation transition. Any public-production entitlement-read-only outage fallback must also satisfy the canonical same-binding predicate; private/playtest never uses that fallback and requires the exact current Account realm-grant identity and `grantVersion`. A disconnected binding must carry its immutable `resumeDeadline`; a still-connected binding with no `resumeDeadline` must carry the trusted `connectedSessionFallbackProof` and immutable `connectedSessionDeadline` defined by the Redis session contract. The applicable bound is `min(continuityBindingExpiresAt, resumeDeadline)` or `min(continuityBindingExpiresAt, connectedSessionDeadline)`, respectively, followed by the `fallbackAt + 5 minutes` and `fallbackAt + session_expiration_ms` caps; ops tooling must not widen any bound. - Internal session-schema-cleanup phase @@ -455,7 +465,7 @@ The complete checklist and the applicable recovery release gates are mandatory f | Ledger convergence | No real tick-ledger row is created, advanced, or terminalized by smoke. The smoke check verifies that the real ledger is unchanged; `APPLIED`, `ABANDONED`, or other terminal outcomes from a synthetic durable row are not available until the separate isolation mechanism is decided. | | Cleanup | Any temporary probe lease or lock is released, no smoke-created `pending` state remains, and the sampled region is not considered in-flight. No durable batch or ledger cleanup is used as a substitute for isolation. | | Durable advancement | PostgreSQL `lastCommittedTickId`, the real tick ledger, and the real Redis tick metadata remain at their pre-smoke recovery values; real `tickId=0` is neither consumed nor authorized. | -| Replay-domain readiness | When the workflow affects the shared replay domain, `replayAdmissionFence` is advanced, the lifetime-plus-skew quarantine is observed, and a disposable probe uses the target tagged `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `jti`, and `deny:jti` keys through the canonical consume script on one pinned Redis connection. The script creates the marker and that same connection obtains one configured `WAITAOF` local/replica durability acknowledgement; only then may the probe yield `DURABLE_REPLAY_CONSUME_ACK` before the operation may reach `AWAITING_RESUME`. This post-reset replay revalidation and durable consume proof are separate from `post_reset_replacement_verification/v1` and Account projection evidence. Select and report implementation checks and runtime proof for this evidence under the shared [Validation and Runtime Proof workflow](../developer-workflows/validation-and-runtime-proof.md); this contract does not replace that workflow or claim current proof. The current untagged replay marker is migration-only drift and is not target proof. Timeout, malformed, below-threshold, or uncertain results fail closed. | +| Replay-domain readiness | When the workflow affects the shared replay domain, `replayAdmissionFence` is advanced, the lifetime-plus-skew quarantine is observed, and one fresh invocation of the canonical replay-consume script runs on the same pinned Redis connection using the target tagged `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `jti`, and `deny:jti` keys. The invocation must return `1` and create a disposable replay marker, followed by one same-connection `WAITAOF` local/replica durability acknowledgement meeting configured thresholds. A `0` or `-1` result is non-mutating and cannot supply a second write acknowledgement; any cleanup is a separate guarded cleanup write/readback and is not part of `DURABLE_REPLAY_CONSUME_ACK`. Only after that acknowledgement may the probe yield `DURABLE_REPLAY_CONSUME_ACK` before the operation reaches `AWAITING_RESUME`. This post-reset replay revalidation and durable consume proof are separate from `post_reset_replacement_verification/v1` and Account projection evidence. Select and report implementation and runtime proof using [Validation and Runtime Proof](../developer-workflows/validation-and-runtime-proof.md); the current untagged replay marker is migration-only drift and not target proof. Timeout, malformed, below-threshold, or uncertain results fail closed. | | Scope sampling | For tenant- or cluster-scoped resets, the smoke check samples at least one representative region per affected executor/shard group rather than only one global region. | The high-level recovery workflow must compose these phases without inventing alternate write paths or omitting required steps such as command-record convergence. @@ -464,17 +474,22 @@ The table above is the canonical post-reset verification checklist. Other runboo After recovery release, the first real fenced staging/release step separately verifies that the staging CAS advances exactly `-1 → 0` and `APPLIED → STAGED`; later ticks use the immediate-next terminal transition. -Direct `redis-cli` writes to coordination prefixes are reserved for **break-glass scenarios** and must follow the incident guidelines in `system-architecture-redis.md` (auditing, post-incident reset, and verification). As an additional guardrail: +**Target state only, once the canonical gated coordination-maintenance operation is implemented and proven:** Direct `redis-cli` writes to coordination prefixes are reserved for **break-glass scenarios** and must follow the incident guidelines in `system-architecture-redis.md` (auditing, post-incident reset, and verification). **Current deployments authorize no raw Coordination-prefix writes; any observed write is unsupported incident evidence and requires preserving the evidence, keeping the affected scope fenced, and escalating.** As an additional guardrail: - When target reset tooling exists, any break-glass write that mutates `tick:*`, `timer:*`, `retry:*`, `remote:*`, `session:*`, `tick-executor-lease:*`, `tick-events:*`, `tick-events-offset:*`, or `tick-events-lease:*` must be followed by a reset/cleanup scope that actually covers the mutated prefix before normal tick processing resumes. Without that tooling, preserve the incident evidence, keep the affected scope fenced, and escalate through [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) rather than attempting an unsupported follow-up reset: - - For region-scoped families (`tick:*`, `timer:*`, `retry:*`, `tick-executor-lease:*`), run a region- or tenant-scoped coordination reset as appropriate. + - For registered tagged region-scoped families (target `tick:{tenantRegionTag}:*`, excluding the legacy untagged `tick:lock::` family, plus `timer:*`, `retry:*`, and `tick-executor-lease:*`), run a region- or tenant-scoped coordination reset as appropriate. + - For legacy/unscoped families (`tick:lock:*`, `gamesession:tick:*`, `gamesession:notifydisconnect:dedup:*`, `gameplaypresence:*`, `accountrecentpresence:*`), follow the exact family row in the [Redis reset-policy matrix](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary): do not treat them as covered by tagged `tick:*` reset handling, and do not perform a narrow reset until that row's writer-drain, complete-scope/reconciliation, and readback gate is proven. Presence remains private-by-failure and disconnect deduplication remains fail-closed; use only an evidenced cluster reset where the matrix permits it. - For instance-scoped `remote:{tenantInstanceTag}:*`, run a tenant-scoped reset so the tooling resolves every affected game instance and removes each instance pattern with an audit trail; do not use a region-only reset or invent a tenant-only pattern. + - For gameplay session prefixes, follow the canonical reset-policy matrix in [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#session-policy-and-preserved-session-consequences): every region- and tenant-scoped reset must explicitly record either `--preserve-sessions` or `--invalidate-sessions`; `--preserve-sessions` applies only to `session:game:{tenantGameplayTag}::` and is the only policy that may enter preserved-session rebind after current identity, membership, and revocation validation. `--invalidate-sessions` is handled by the reset/cleanup phase for affected session invalidation and cleanup and never enters preserved-session rebind. Affected tenant-owned `session:game:index:*` projections are droppable under either policy and must reconcile and read back before release; narrow region/tenant recovery or break-glass cleanup may repair only affected members of those projections and must preserve unrelated members. Untagged global account and issuer indexes are not narrow cleanup targets and require complete account- or issuer-wide durable inventory, coverage proof, exact readback, and the maintenance-lock release gate before replacement. If break-glass mutates an untagged global account or issuer index, preserve the evidence, keep the affected index and dependent admission fenced, and escalate through the owner-defined [global index-family recovery consequence](./system-architecture-redis-reset-and-recovery.md#global-index-family-recovery-consequence); do not use a narrow reset as local repair. Pre-auth transport context is always invalidated or rebuilt. Every cluster reset must explicitly record `--invalidate-sessions` and rejects `--preserve-sessions`. Account-owned `session:auth:token:` records and the unversioned legacy plus target `session:connect-token:v1:*` issuance-result projections are separate authority/result domains: region- and tenant-scoped resets preserve them, while a cluster reset must close protected admission and complete the Account repair/reset cutover before deleting or recovering them under their owner contracts. A generic region/tenant reset is never a repair for Account token or connect-token issuance state. - For target-only tick-event families (`tick-events:{tenantRegionTag}`, `tick-events-offset:{tenantRegionTag}:{consumerId}`, and `tick-events-lease:{tenantRegionTag}`), direct mutation is prohibited under the current unavailable fallback: preserve evidence, keep the affected consumer/region fenced, and escalate. Once the owner tooling exists, owner reset/readback/fencing must cover the stream, exact consumer offset, and lease before resume; Automation must re-bootstrap from the canonical heartbeat/status and owner registration contract. Manual mutations of Account-owned `session:auth:account:*`, `session:auth:tenant:*`, `session:auth:generation:*`, or `session:auth:token:` are never repaired by a region- or tenant-scoped coordination reset. The operator must invoke Account-owned exact projection repair/readback (and token revocation/rotation tooling where applicable); target `session:auth:token:` repair is conditional on the target issued-token registry cutover being implemented. The target `session:connect-token:v1:*` projection requires Account repair from the exact SQL issuance operation/result and exact Redis readback; it cannot be reconstructed from a JWT or request fields. The unversioned legacy map is not a target repair source. Account may clean it only after quiescing and draining connect-token issuance/retries, preserving the legacy entries and reading them back through the configured TTL/retry horizon, then performing owner-authorized cleanup with exact absence/readback evidence. The cluster-reset/replay-quarantine/forced re-registration or reauthentication path is target-state-only until the Account repair, replay quarantine, and replacement tooling are implemented and proven. Under the current fallback, preserve the evidence, keep affected scopes fenced, and escalate whenever exact repair, token custody, replay continuity, or the affected token set cannot be proven; direct Redis edits are not a substitute for either path. - Operators must treat such writes as equivalent to “coordination state may be inconsistent” and use the Coordination Reset Model to bring the region/tenant/cluster back to a known-good state, rather than leaving ad-hoc edits in place as a permanent fix. + +- **Target state only, once the canonical gated coordination-maintenance operation is implemented and proven:** Operators must treat such writes as equivalent to “coordination state may be inconsistent” and use the Coordination Reset Model to bring the region/tenant/cluster back to a known-good state, rather than leaving ad-hoc edits in place as a permanent fix. + - When target reset tooling exists, break-glass flows should go through a small wrapper (CLI or Logging & Admin action) that: - Executes the minimal required Redis mutation. - Immediately triggers the appropriate scoped coordination reset. diff --git a/design/architecture/system-architecture-redis-reset-and-recovery.md b/design/architecture/system-architecture-redis-reset-and-recovery.md index f49122c6a9..04ddc2ee36 100644 --- a/design/architecture/system-architecture-redis-reset-and-recovery.md +++ b/design/architecture/system-architecture-redis-reset-and-recovery.md @@ -34,6 +34,7 @@ Coordination Redis is treated as a **long‑lived, measured-exposure coordinatio - **Region‑scoped reset** – affects a single ``: - Clears tick queues, timers, retry structures, and region‑scoped locks/leases for one region. - Does not clear Account-owned issued-token registry records, live legacy account/tenant auth projections, authority-generation projections, or target exact-input `session:connect-token:v1:*` issuance-result projections because these are not region-scoped coordination state. The unversioned legacy `session:connect-token:*` map is preserved/read back only while present through its configured TTL/retry horizon and then owner-cleaned; a missing, changed, or untrusted legacy entry leaves the affected handshake fenced and requires escalation, never reconstruction. A missing or untrusted target `session:connect-token:v1:*` projection remains subject to Account-owned exact durable repair and readback. + - Does not drop a whole tenant-tagged gameplay-index family. Game Session updates, removes, or recreates only exact affected keys or members from the durable binding inventory according to the owning index schema and preserves unrelated keys, members, regions, and tenants. - Leaves other regions and tenants untouched. - Typically used when: - A mis‑keyed script or bug has polluted tick state for one region. @@ -43,6 +44,8 @@ Coordination Redis is treated as a **long‑lived, measured-exposure coordinatio - Clears the affected tenant-scoped gameplay coordination prefixes for all regions under one tenant. - Preserves only `session:game:{tenantGameplayTag}::` records when operators explicitly choose `--preserve-sessions`; affected tenant-owned `session:game:index:*` projections are derived and may be dropped, but must reconcile before release. Untagged global account and issuer indexes are not narrow reset targets; replacement requires their complete owner-defined durable inventory, coverage proof, and exact readback before release. Pre-auth transport context is not covered by session preservation and is invalidated or rebuilt. - Does not clear Account-owned `session:auth:token:` records, live legacy account/tenant auth projections, authority-generation projections, or target exact-input `session:connect-token:v1:*` issuance-result projections. Region- and tenant-scoped resets preserve these families because they are not region-scoped coordination state. The unversioned legacy `session:connect-token:*` map is only preserved and read back while present through its configured TTL/retry horizon, then owner-cleaned; if it is missing, changed, or untrusted, the affected handshake remains fenced and operators escalate. A missing or untrusted target `session:connect-token:v1:*` projection requires Account exact durable repair and readback before the affected operation can release. A tenant reset may terminate affected gameplay bindings, but it must not turn a tenant-region coordination reset into account-wide token revocation. + - Preserves only `session:game:{tenantGameplayTag}::` records when operators explicitly choose `--preserve-sessions`; the complete affected tenant-tagged character, account-tenant, tenant, and realm-grant `session:game:index:*` families may be dropped at this tenant scope, but must reconcile before release. A region-scoped reset instead reconciles only exact affected keys or members from durable inventory. Untagged global account and issuer indexes are not narrow reset targets; replacement requires their complete owner-defined durable inventory, coverage proof, and exact readback before release. Pre-auth transport context is not covered by session preservation and is invalidated or rebuilt. + - Does not clear Account-owned `session:auth:token:` records, live legacy account/tenant auth projections, exact-input `session:connect-token:tenant::account::scope::request:` issuance-result/idempotency records, or authority-generation projections. Region- and tenant-scoped resets preserve those records because they are not region-scoped coordination state; if any preserved projection is missing or untrusted, Account must repair and read it back before the affected operation can release. A tenant reset may terminate affected gameplay bindings, but it must not turn a tenant-region coordination reset into account-wide token revocation or permit a live connect request to receive a different result on retry. - Often combined with an in‑game maintenance window or a revert/repin of tenant‑specific published content. - Used when: - A full in‑game reset is acceptable for a single tenant. @@ -117,12 +120,12 @@ Worked example (illustrative, non-normative, reset-local): region-scoped reset f > **Illustrative reset-local contract sketch; non-normative and unavailable today.** The `coordination-maintenance` commands below are not current operator instructions. Canonical reset ordering remains owned by [Redis Operations](./system-architecture-redis-operations.md#canonical-coordination-reset-sequence); recovery release/evidence remains owned by [Backup Recovery Evidence and Compliance](./system-architecture-backup-recovery-evidence-and-compliance.md#canonical-recovery-record) and the linked session/recovery evidence contracts. -1. The target-state command records `--preserve-sessions` and applies the reset-local effects for this region: it advances `region_epoch` from `12` to `13`, clears `tick:{tenantRegionTag}:*`, `timer:{tenantRegionTag}`, `retry:{tenantRegionTag}`, and `tick-executor-lease:{tenantRegionTag}`, and runs old-epoch ledger and accepted-but-unbound command reconciliation under the linked evidence policy. `APPLIED` or `ABANDONED` is permitted only when that policy proves the corresponding outcome; inconclusive effects remain reconciliation-required under their original `EffectId` rather than being bulk-terminalized. Preserved sessions remain fenced until the owner-defined session and recovery evidence contracts qualify them. +1. The target-state command records `--preserve-sessions` and applies the reset-local effects for this region: it advances `region_epoch` from `12` to `13`, clears `tick:{tenantRegionTag}:*`, `timer:{tenantRegionTag}`, `retry:{tenantRegionTag}`, and `tick-executor-lease:{tenantRegionTag}`, and runs old-epoch ledger and accepted-but-unbound command reconciliation under the linked evidence policy. `APPLIED` or `ABANDONED` is permitted only when that policy proves the corresponding outcome; inconclusive effects remain reconciliation-required under their original persisted mutation `EffectId`—the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child—with the enclosing `rootEffectId` retained separately as lineage and reconciliation context, rather than being bulk-terminalized. Preserved sessions remain fenced until the owner-defined session and recovery evidence contracts qualify them. 2. The first real tick in the new epoch is `tickId=0` only after the owner-defined recovery and release boundary; this example does not prescribe that boundary. Worked example (illustrative, non-normative, reset-local): tenant-scoped reset for `` with `--preserve-sessions` (target-state only; unavailable today) -1. The target-state command records `--preserve-sessions` and applies reset-local effects across the complete affected-region scope: it advances each `region_epoch`, clears affected tenant-scoped gameplay coordination prefixes while retaining only canonical `session:game:{tenantGameplayTag}::` records, drops affected tenant-owned `session:game:index:*` projections for reconciliation, always invalidates or rebuilds pre-auth transport context, removes affected `remote:{tenantInstanceTag}:*` hints from the durable game-instance scope, and runs old-epoch ledger and accepted-but-unbound command reconciliation under the linked evidence policy. `APPLIED` or `ABANDONED` is permitted only when that policy proves the corresponding outcome; inconclusive effects remain reconciliation-required under their original `EffectId` rather than being bulk-terminalized. Preserved sessions remain fenced until the owner-defined session and recovery evidence contracts qualify them and derived indexes reconcile; Account-owned token records and authorities are not tenant-reset state. The tenant reset also excludes untagged Account auth/generation families (`session:auth:token:*`, `session:auth:account:*`, `session:auth:tenant:*`, `session:auth:generation:*`, and `session:connect-token:*` issuance-result projections), the Game Session issuer-generation consumer projection (`session:game:auth:issuer-generation:v1:*`), and the shared Gateway replay domain (`gateway:connect-token:{gateway-connect-token-replay-v1}:*` and its readiness/fence record carrying `replayAdmissionFence`); those remain under their owner-specific validation and reprojection contracts. +1. The target-state command records `--preserve-sessions` and applies reset-local effects across the complete affected-region scope: it advances each `region_epoch`, clears affected tenant-scoped gameplay coordination prefixes while retaining only canonical `session:game:{tenantGameplayTag}::` records, drops only the affected tenant-tagged `session:game:index:character:{tenantGameplayTag}::`, `session:game:index:account-tenant:{tenantGameplayTag}:`, `session:game:index:tenant:{tenantGameplayTag}`, and `session:game:index:realm-grant:{tenantGameplayTag}:` projections for reconciliation, and leaves the untagged global `session:game:index:account:` and `session:game:index:issuer:{issuerIndexLayoutTag}::` families to their owner-specific account-wide or issuer-wide reconciliation. It always invalidates or rebuilds pre-auth transport context, removes affected `remote:{tenantInstanceTag}:*` hints from the durable game-instance scope, and runs old-epoch ledger and accepted-but-unbound command reconciliation under the linked evidence policy. `APPLIED` or `ABANDONED` is permitted only when that policy proves the corresponding outcome; inconclusive effects remain reconciliation-required under their original persisted mutation `EffectId`—the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child—with the enclosing `rootEffectId` retained separately as lineage and reconciliation context, rather than being bulk-terminalized. Preserved sessions remain fenced until the owner-defined session and recovery evidence contracts qualify them and derived indexes reconcile; Account-owned token records, exact-input connect-token issuance-result/idempotency records, and authorities are not tenant-reset state. The tenant reset also excludes untagged Account auth/generation families (`session:auth:token:*`, `session:auth:account:*`, `session:auth:tenant:*`, and `session:auth:generation:*`), the exact-input Account connect-token family (`session:connect-token:tenant::account::scope::request:`), the Game Session issuer-generation consumer projection (`session:game:auth:issuer-generation:v1:*`), and the shared Gateway replay domain (`gateway:connect-token:{gateway-connect-token-replay-v1}:*` and its readiness/fence record carrying `replayAdmissionFence`); those remain under their owner-specific validation and reprojection contracts. 2. This example is reset-local only: the canonical sequence, complete evidence, and release boundary are defined by the owner documents linked above. Worked example (illustrative, non-normative, reset-local): cluster-scoped reset (target-state only; unavailable today) @@ -179,14 +182,14 @@ Worked example (illustrative, non-normative, reset-local): cold start for ` **Illustrative reset-local contract sketch; non-normative and unavailable today.** The command below is not a current operator instruction. Current operators must keep the affected scope fenced and use the current fail-closed fallback above instead; the canonical recovery and release owners are not restated here. 1. Coordination Redis starts empty after loss of its data directory, while PostgreSQL still shows `RegionStatus(regionEpoch=13, lastCommittedTickId=41)` for `(7b3b074e-d597-4e9b-b96f-4f5946d26120, 9a2bb6d1-74c7-4f81-a9e8-418e65f6ad78, R7)`. -2. The target-state command records `--preserve-sessions`, advances `region_epoch` from `13` to `14`, establishes PostgreSQL `lastCommittedTickId = -1` separately from the fenced Redis `current_tick_id = -1`, `current_tick_state = APPLIED` baseline, and runs old-epoch durable-work and accepted-but-unbound-command reconciliation under the linked evidence policy. `APPLIED` or `ABANDONED` is permitted only when that policy proves the corresponding outcome; inconclusive effects remain reconciliation-required under their original `EffectId` rather than being bulk-terminalized. Preserved sessions remain fenced until the owner-defined evidence qualifies them. +2. The target-state command records `--preserve-sessions`, advances `region_epoch` from `13` to `14`, establishes PostgreSQL `lastCommittedTickId = -1` separately from the fenced Redis `current_tick_id = -1`, `current_tick_state = APPLIED` baseline, and runs old-epoch durable-work and accepted-but-unbound-command reconciliation under the linked evidence policy. `APPLIED` or `ABANDONED` is permitted only when that policy proves the corresponding outcome; inconclusive effects remain reconciliation-required under their original persisted mutation `EffectId`—the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child—with the enclosing `rootEffectId` retained separately as lineage and reconciliation context, rather than being bulk-terminalized. Preserved sessions remain fenced until the owner-defined evidence qualifies them. 3. After the owner-defined recovery boundary, the first fenced staging CAS advances exactly `-1 → 0` and `APPLIED → STAGED`, making the first real committable tick in epoch `14` `tickId=0`; later ticks use the immediate-next terminal transition. This example does not define that boundary. - **Reset** (intentional operational action) - A deliberate, scoped choice to discard volatile coordination state (region/tenant/cluster) and resume from PostgreSQL state plus new activity. - Target state only: apply a scoped reset through supported, implemented, and proven tooling for that exact scope and an explicit session policy. - Until that tooling exists, current handling is the [Current Operator Fallback](#current-operator-fallback): preserve evidence, keep the affected scope fenced, and escalate. - - Must follow the reset model and runbooks; ad‑hoc `redis-cli` edits are treated as “unknown resets” and require a follow‑up scoped reset. + - Must follow the reset model and runbooks; any observed ad‑hoc `redis-cli` edit is unsupported incident evidence (an “unknown reset”), not a current repair path. Preserve the mutation evidence, keep the affected scope fenced, and escalate through the current fallback. Design implications: @@ -206,7 +209,9 @@ This table is the **canonical reset-policy catalog** for the main Redis prefixes Service design docs and per-service READMEs should link to this matrix (or any future expanded key catalog derived from it) instead of duplicating their own reset-policy tables; when a service introduces new prefixes, the catalog is extended here first. -The six gameplay index families below are Game Session-owned derived coordination state, independent of the explicit gameplay-session policy and not authorization state or preserved-session state. A reset may drop affected tenant-owned families under either policy only after the affected scope is paused and fenced. Untagged global account and issuer families are not narrow reset targets; replacement or rebuild requires complete account- or issuer-wide durable inventory, coverage proof, exact readback, and the maintenance-lock release gate. The one untagged global account index is an explicit exception because each member carries a complete tenant-qualified binding reference; it remains a single account-wide projection rather than a tenant-local selector. All affected families remain non-admissible until Game Session completes the owner-defined inventory reconciliation and exact readback; release is not authorized while any affected index family is missing, stale, partial, or ambiguous. The exact index shapes, child/parent carriers, reservation/capacity proof, and admission predicates are owned by [Session and Region-Binding Contract](./system-architecture-redis.md#session-and-region-binding-contract), [Global Account Active-Binding Index](./system-architecture-session-behavior.md#global-account-active-binding-index), and the [canonical active-binding recovery evidence contract](./system-architecture-redis-ops-access.md#canonical-active-binding-recovery-evidence-contract). This reset catalog records only scope, drop behavior, and fencing consequences. +Cache/Rate-Limit reset execution additionally requires the external, generation-bound [Cache deployment maintenance gate](./system-architecture-redis-operations.md#external-cache-deployment-maintenance-gate); this gate is outside the Cache/Rate-Limit Redis deployment and is held through deletion, verification, and rebuild. + +The six gameplay index families below are Game Session-owned derived coordination state, independent of the explicit gameplay-session policy and not authorization state or preserved-session state. At tenant scope, the four tenant-tagged families (`character`, `account-tenant`, `tenant`, and `realm-grant`) may be dropped as whole families after the affected scope is paused and fenced. At region scope, only exact affected keys or members are updated, removed, or recreated from the durable binding inventory according to the owning index schema; unrelated keys, members, regions, and tenants are preserved. The untagged global account and issuer families remain untouched by narrow reset and require owner-specific account-wide or issuer-wide replacement/reconciliation with complete durable inventory, coverage proof, exact readback, and the maintenance-lock release gate. The one untagged global account index is an explicit exception because each member carries a complete tenant-qualified binding reference; it remains a single account-wide projection rather than a tenant-local selector. All affected families remain non-admissible until Game Session completes the owner-defined inventory reconciliation and exact readback; release is not authorized while any affected index family is missing, stale, partial, or ambiguous. The exact index shapes, child/parent carriers, reservation/capacity proof, and admission predicates are owned by [Session and Region-Binding Contract](./system-architecture-redis.md#session-and-region-binding-contract), [Global Account Active-Binding Index](./system-architecture-session-behavior.md#global-account-active-binding-index), and the [canonical active-binding recovery evidence contract](./system-architecture-redis-ops-access.md#canonical-active-binding-recovery-evidence-contract). This reset catalog records only scope, drop behavior, and fencing consequences. Entity cache rows below intentionally distinguish namespace-backed aggregates from explicitly instance-scoped S3 holders. Reset tooling may enumerate the complete affected namespace or instance/room scope and drop both families, but Redis remains only a disposable cache: PostgreSQL or the owning Entity lifecycle contract remains authoritative, and `playableStateScope` is separately validated evidence rather than a cache-key or reset-authority dimension. @@ -217,18 +222,26 @@ A region- or tenant-scoped reset parent cannot claim global account- or issuer-i | Prefix / Family | Role | Reset Policy (Coordination Reset) | Behavior When Dropped | Notes | | --- | --- | --- | --- | --- | | `tick:{tenantRegionTag}:pending` and `tick:{tenantRegionTag}:queue:*` | Coordination | **Reset-tolerant** | In-flight ticks and queued commands for affected regions are discarded; future ticks process only new commands. | `pending` effects are reconciled through the tick-effect ledger under the [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy): evidence may permit `APPLIED`/`ABANDONED`, while inconclusive work remains a reconciliation-required non-terminal marker under its original `EffectId`; reset does not bulk-terminalize it. Idempotency prevents double-apply. Only command records with `ackLevel` = `ACCEPTED_VOLATILE` in `RECEIVED`/`ENQUEUED` and no surviving batch/binding are intentionally **lost** and not reconstructed from PostgreSQL; `ACCEPTED_DURABLE` records follow their feature-specific durable replay or post-abandon re-drive contract, while inconclusive batch-bound work remains non-terminal/reconciliation-required. See the [canonical command outcome convergence](./system-architecture-tick-execution-flows.md#command-outcome-convergence-required). | +| `tick:{tenantRegionTag}:pending` and `tick:{tenantRegionTag}:queue:*` | Coordination | **Reset-tolerant** | In-flight ticks and queued commands for affected regions are discarded; future ticks process only new commands. | `pending` effects are reconciled through the tick effect ledger under the [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy): evidence may permit `APPLIED`/`ABANDONED`, while inconclusive work remains a reconciliation-required non-terminal marker under its original persisted mutation `EffectId`—the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child—with the enclosing `rootEffectId` retained separately as lineage and reconciliation context; reset does not bulk-terminalize it. Idempotency prevents double-apply. Only command records with `ackLevel` = `ACCEPTED_VOLATILE` in `RECEIVED`/`ENQUEUED` and no surviving batch/binding are intentionally **lost** and not reconstructed from PostgreSQL; `ACCEPTED_DURABLE` records follow their feature-specific durable replay or post-abandon re-drive contract, while inconclusive batch-bound work remains non-terminal/reconciliation-required. See the [canonical command outcome convergence](./system-architecture-tick-execution-flows.md#command-outcome-convergence-required). | | `tick:{tenantRegionTag}:meta` | Coordination | **Reset-tolerant** | Epoch/tick guard metadata is dropped; reset tooling re-establishes the new epoch baseline from durable RegionStatus state before normal progress. | The Redis metadata is a coordination view only; the reset handshake establishes the same new epoch and first-real-tick baseline in PostgreSQL and Redis. | | `tick:{tenantRegionTag}:session-binding:*` | Coordination | **Reset-tolerant with preserved-session rebind** | Region-local gameplay admission bindings are dropped. Preserved sessions remain fenced until the owner-defined session/recovery evidence contract qualifies them; invalidated sessions require fresh `LOGIN` / `PLAY`. | These keys are region-authoritative for gameplay command admission. The exact rebind, inventory, carrier, reservation, and admission predicates are owned by the [session and region-binding contract](./system-architecture-redis.md#session-and-region-binding-contract) and [active-binding recovery evidence contract](./system-architecture-redis-ops-access.md#canonical-active-binding-recovery-evidence-contract). | | `timer:{tenantRegionTag}` and `retry:{tenantRegionTag}` | Coordination | **Reset-tolerant** | Timers and retries for affected regions are discarded; future ticks process only newly scheduled timers/retries. | Only timers/retries that are also represented durably elsewhere (for example, PostgreSQL-backed automation schedules or durable follow-ups) are re-discovered after a reset; region-scoped timer/retry coordination keys themselves are not treated as reconstructible logs. | | `tick-executor-lease:{tenantRegionTag}` and tick lock keys (`tick:{tenantRegionTag}:lock:*`) | Coordination | **Reset-tolerant** | Existing leases/locks vanish; new executors reacquire leadership and locks as ticks resume. | Leases and locks are transient; executors reacquire leases and lock state after reset. | -| `session:game:index:character:{tenantGameplayTag}::` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | The target `{tenantId, playableStateNamespaceId, characterId}` character-to-session controller uniqueness entry is dropped; takeover, resume, and new admission using that character remain fenced until Game Session rebuilds the exact entry from the durable binding inventory and validates the server-derived `playableStateScope` binding/routing evidence plus value/evidence `{sessionId, gameInstanceId, bindingGeneration}` against the session record. An unbound-character decision requires that durable inventory readback to prove there is no active binding; an empty Redis key alone never proves availability. See [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). | Tenant-scoped and namespace-qualified, with the shard-local session CAS; `playableStateScope` remains binding/routing context. Rebuild removes stale entries, recreates missing entries, and rejects conflicting identities. The existing `:` index key is current implementation drift, not the target key. | +| `tick:lock::` | Coordination (current Entity legacy implementation drift; unscoped) | **Reset-sensitive; narrow reset forbidden until writer is removed or complete scope is proven** | The live Entity `TickLockServiceImpl` lock family is not the canonical region lock and has no game-instance/region/fence evidence. A reset must not delete or treat this family as covered by the tagged `tick:{tenantRegionTag}:lock:*` row; the affected scope remains fenced until the writer is drained/quarantined and no independent lock can authorize mutation. | Current Entity code uses a private TTL formula and an untagged tenant/entity key. It is not a second authority: target convergence routes locking through Game Session/shared full-runtime-scope helpers. | +| `conflict:entity::` and `conflict:session::` | Coordination (current shared diagnostic projection; generic-client placement and separate `INCR`/`EXPIRE` warning-only path are implementation drift) | **Reset-tolerant** | Conflict counters are disposable hotspot hints. Dropping them may temporarily hide or reset contention diagnostics but cannot authorize or deny gameplay, admission, or durable work. Reset inventory must include the complete registered family; unknown or misplaced copies on Cache/Rate-Limit Redis remain a role-collision finding. | `common-data-runtime` owns the shared helper; Entity Management and Game Session supply the producer scopes. The target role, finite per-scope cardinality, 300-second inactivity TTL, named Coordination client/`coord_app` ACL, and atomic increment/TTL convergence are defined in [Redis Architecture](./system-architecture-redis.md#coordination-vs-cache-prefixes). PostgreSQL and runtime locks remain authoritative. | +| `gamesession:tick:queue::`, `gamesession:tick:pending::`, `gamesession:tick:lock::`, and `gamesession:tick:mutation-lock::` | **Coordination (current legacy implementation drift; untagged)** | **Reset-sensitive (narrow reset forbidden until complete scope/reconciliation is proven)** | These live keys may contain queued work, pending state, or locks, but their key shape carries only `tenantId` and `gameInstanceId`; it does not prove the complete `` scope. A region- or tenant-scoped reset must not claim coverage or delete them from a wildcard pattern. If they may be in the affected deployment, the scope remains fenced until Game Session supplies complete durable inventory and exact readback; an explicitly cluster-scoped reset may drop them only as part of its evidenced cluster blast radius, with queued/pending work following the legacy-loss and reconciliation consequences above. | `TickQueueControlService` is the current builder owner. This family is not the target tagged `tick:{tenantRegionTag}:*` contract and must not be made narrow by guessing a region from `gameInstanceId`. Game Session must fence/drain the legacy writer, map any retained work through authoritative durable records, and migrate to registered canonical tagged builders before scoped reset tooling treats the target families as exhaustive. | +| `session::` | **Coordination (current legacy implementation drift; untagged)** | **Reset-sensitive** | This current Game Session runtime-state projection is derived from PostgreSQL/current ownership state, which remains authoritative. Missing, stale, partial, or ambiguous Redis state cannot authorize tick progress; Game Session must rebuild it and complete exact readback before resuming affected runtime operations. | `SessionStateService`/Game Session currently writes the projection for game-instance lifecycle state. It is distinct from target `session:game:*` gameplay bindings and from `sessionctx:*`; the current key has no canonical region scope and remains implementation drift. | +| `session:game:index:character:{tenantGameplayTag}::` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the target `{tenantId, playableStateNamespaceId, characterId}` character-to-session controller uniqueness entry may be dropped; at region scope, only the exact key for an affected binding is retained, removed, or recreated from durable binding inventory, preserving unrelated character keys, regions, and tenants. Takeover, resume, and new admission remain fenced until Game Session rebuilds or reconciles the exact entry and validates the server-derived `playableStateScope` binding/routing evidence plus value/evidence `{sessionId, gameInstanceId, bindingGeneration}` against the session record. An unbound-character decision requires that durable inventory readback to prove there is no active binding; an empty Redis key alone never proves availability. See [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#session-and-identity-management). | Tenant-scoped and namespace-qualified, with the shard-local session CAS; `playableStateScope` remains binding/routing context. Rebuild removes stale entries, recreates missing entries, and rejects conflicting identities. The existing `:` index key is current implementation drift, not the target key. | | `session:game:index:account:` | Coordination | **Reset-sensitive with mandatory account-wide reconciliation** | Account-wide lookup is unavailable while the global index is dropped; narrow parents do not rebuild the untagged key, and account-wide access remains fenced until the complete owner-defined recovery result is consumed. | This is the one retained untagged global account exception: every member is a complete tenant-qualified `accountIndexMember`, so the key is not a tenant-local selector. Its physical layout and member contract are owned by [Global Account Active-Binding Index](./system-architecture-session-behavior.md#global-account-active-binding-index); narrower resets preserve unrelated tenants and cluster reset rebuilds the complete key. | -| `session:game:index:account-tenant:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | The tenant-qualified account lookup is dropped; tenant-scoped resume, takeover, and bounded revocation remain fenced until Game Session rebuilds it from the durable inventory and the matching session/index obligations are acknowledged. Each index member remains an active `sessionId` value under the owner-defined schema. Reconciliation is inventory-led: it derives the exact expected active `sessionId` set from authoritative durable `GameplayBindingInventory` rows; each row's complete `bindingRef` and tenant/game/session identity supply `gameInstanceId` and directly address its canonical session record. Before deriving or writing a member or accepting readback, it exact-compares the row's canonical binding-owner `accountId` with the key's ``; a missing, malformed, or mismatched owner is rejected or quarantined and keeps the affected account/index scope fenced. It independently validates the exact session record, including controller identity `{tenantId, playableStateNamespaceId, characterId}`, server-derived `playableStateScope`, `gameInstanceId`, `bindingGeneration`, and lifecycle, then reads back the expected `sessionId` set before acknowledging the matching index/session obligations. Reconciliation never infers `gameInstanceId` from a bare member and does not use wildcard scans or invent a separate resolver. This consumes the existing owner-defined schema and producers; it does not change them. | Tenant-scoped and part of the shard-local session CAS. Reconciliation is limited to the gameplay tag and validates the canonical session record rather than treating index membership as authoritative. | -| `session:game:index:tenant:{tenantGameplayTag}` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | Tenant-wide active-session lookup is dropped; tenant revocation, inspection, and repair remain fenced until Game Session rebuilds and reads back the tenant index from durable inventory. | Tenant-scoped and shard-local. Reconciliation must not use the global account index as a substitute or admit a binding from tenant-local key presence alone. | -| `session:game:index:realm-grant:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | Lifecycle-bound private/playtest grant lookup is dropped; reset tooling enumerates the complete expected tuple set from the exact Account v1 inventory, obtains every key through the shared `grant/v1` lifecycle-qualified realm-grant index builder, and keeps realm admission and grant-driven revocation fenced until Game Session rebuilds and reads back those exact entries under current Account grant authority. | `grantScopeId` is the exact canonical scope ID for the complete Account-owned tuple. Reset and reconciliation never concatenate world/realm selectors or other tuple fields independently. The entries are tenant-scoped, shard-local bounded lookup evidence; Account state remains authoritative, and stale, wrong-lifecycle, or cross-tenant entries are removed. Public-production and unscoped bindings have no entry. | +| `session:game:index:account-tenant:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the tenant-qualified account lookup may be dropped; at region scope, the key remains and only members affected by the selected region are updated or reconciled from durable binding inventory, preserving unrelated regions and tenants. Tenant-scoped resume, takeover, and bounded revocation remain fenced until Game Session rebuilds it and the matching session/index obligations are acknowledged. Each index member remains an active `sessionId` value under the owner-defined schema. Reconciliation is inventory-led: it derives the exact expected active `sessionId` set from authoritative durable `GameplayBindingInventory` rows; each row's complete `bindingRef` and tenant/game/session identity supply `gameInstanceId` and directly address its canonical session record. Before deriving or writing a member or accepting readback, it exact-compares the row's canonical binding-owner `accountId` with the key's ``; a missing, malformed, or mismatched owner is rejected or quarantined and keeps the affected account/index scope fenced. It independently validates the exact session record, including controller identity `{tenantId, playableStateNamespaceId, characterId}`, server-derived `playableStateScope`, `gameInstanceId`, `bindingGeneration`, and lifecycle, then reads back the expected `sessionId` set before acknowledging the matching index/session obligations. Reconciliation never infers `gameInstanceId` from a bare member and does not use wildcard scans or invent a separate resolver. This consumes the existing owner-defined schema and producers; it does not change them. | Tenant-scoped and part of the shard-local session CAS. Reconciliation is limited to the gameplay tag and validates the canonical session record rather than treating index membership as authoritative. | +| `session:game:index:tenant:{tenantGameplayTag}` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the tenant-wide active-session lookup may be dropped; at region scope, the key remains and only members affected by the selected region are updated or reconciled from durable binding inventory, preserving unrelated regions and tenants. Tenant revocation, inspection, and repair remain fenced until Game Session rebuilds or reconciles and reads back the tenant index. | Tenant-scoped and shard-local. Reconciliation must not use the global account index as a substitute or admit a binding from tenant-local key presence alone. | +| `session:game:index:realm-grant:{tenantGameplayTag}:` | Coordination | **Reset-sensitive with mandatory binding reconciliation** | At tenant scope, the lifecycle-bound private/playtest grant lookup may be dropped; at region scope, the key remains and only members affected by the selected region are updated or reconciled from durable binding inventory, preserving unrelated regions and tenants. Reset tooling enumerates the complete expected tuple set from the exact Account v1 inventory, obtains every key through the shared `grant/v1` lifecycle-qualified realm-grant index builder, and keeps realm admission and grant-driven revocation fenced until Game Session rebuilds or reconciles and reads back those exact entries under current Account grant authority. | `grantScopeId` is the exact canonical scope ID for the complete Account-owned tuple. Reset and reconciliation never concatenate world/realm selectors or other tuple fields independently. The entries are tenant-scoped, shard-local bounded lookup evidence; Account state remains authoritative, and stale, wrong-lifecycle, or cross-tenant entries are removed. Public-production and unscoped bindings have no entry. | | `session:game:index:issuer:{issuerIndexLayoutTag}::` | Coordination | **Reset-sensitive with mandatory issuer-coverage rebuild** | Issuer cutoff and issuer-wide lookup remain fenced until the complete owner-defined issuer recovery result qualifies; region and tenant resets never flush a whole issuer partition. | Global per issuer across tenants and partitioned by the immutable issuer layout, not tenant-tagged. The inventory, capacity, acknowledgement, and coverage contract is owned by the linked Game Session evidence documents. | | `session:game:{tenantGameplayTag}::` | Coordination | **Reset-sensitive** | Region and tenant resets retain or invalidate this record only under their explicit session policy. Cluster scope requires `--invalidate-sessions`; preserved-session rebind is not a cluster option. | Authoritative for connection identity and reconnect/session CAS state, but not a substitute for the owner-defined rebind/admission contract. | | `sessionctx:*` | Coordination | **Reset-sensitive, not preservable** | Current Game Session bootstrap and lookup context is invalidated or rebuilt by any reset; it is never covered by `--preserve-sessions` and cannot authorize gameplay. | Game Session owns this live implementation-local family. Its reset consequence is local to the family; the canonical reset lifecycle and session policy remain defined above. | +| `gameplaypresence:session:`, `gameplaypresence:::sessions`, and `gameplaypresence::account::sessions` | **Current legacy projection (role unproved; not an accepted target prefix)** | **Reset-sensitive, private-by-failure until the target contract is proven** | These current live-presence value/index families are unavailable when missing, partial, stale, or ambiguous; `WHO` and account-presence reads must fail private-by-failure rather than expose stale or cross-scope presence. Game Session must fence the affected scope, rebuild an exact-scoped owner projection, and complete exact readback before presence is exposed again. | The current writer uses untagged keys and separate value/set mutations; it is implementation drift, not target authority. The target must choose and prove the Redis role, exact scope, atomic owner mutation, reset inventory, and readback contract. | +| `accountrecentpresence::` | **Current legacy projection (role unproved; not an accepted target prefix)** | **Reset-sensitive, private-by-failure until the target contract is proven** | Loss, partial state, stale state, or ambiguous routing evidence makes recent/offline presence unavailable/private; it must not be presented as a verified location or routing fact. Game Session must fence or suppress the affected projection and rebuild/read back the exact target owner projection before exposing it. | The current account recent-presence record is a direct untagged value with an implementation TTL; its storage role, exact retention, reset behavior, and owner readback are unproved. It remains a disposable current shape, not durable authority or target cache semantics. | +| `gamesession:notifydisconnect:dedup:` | **Coordination (current legacy drift; target sequencing contract unproved)** | **Reset-sensitive, fail-closed until the target contract is proven** | Dropping or losing the latest sequence must not permit an old duplicate `NotifyDisconnect` to remove presence, emit region exit, or suspend runtime state. Until exact connection/generation binding and durable sequencing are proven, the affected scope remains fenced and Redis loss/error cannot authorize fail-open stale effects. | Game Session owns the current sequence-dedup writer; the current one-hour key and Redis failure behavior are implementation drift. The target owner contract must define durable sequencing, binding validation before side effects, reset inventory, and exact readback. | | Pre-auth transport context | Coordination | **Reset-sensitive, not preservable** | Region and tenant resets invalidate or rebuild this context regardless of `--preserve-sessions`; cluster scope requires invalidation. | Pre-auth context is not gameplay authority and is outside the canonical gameplay-session preservation domain. | | `session:auth:token:` | Coordination | **Reset-sensitive by scope** | Region and tenant resets preserve these Account-owned records. For a destructive cluster reset, Account-owned authority/token cutover and immutable pre-wipe handoff evidence complete before the wipe; after reset, Account repairs and durably reads back the affected projections; replay quarantine and durable replay-consumption proof complete before replacement registration. Cleanup removes only old or stale projections, and replacement registry records remain after registration. Missing records deny protected use and require fresh authentication. | The exact-token registry is the runtime authority for that token, while Account durable generations remain the authority for issuer, compromise, and reset invalidation. Reset tooling must not infer scope from key names or recreate a record from a JWT. See `system-architecture-jwt-and-token-contracts.md` for full semantics. | | `session:auth:account::` | Coordination | **Reset-sensitive, Account-owned legacy projection** | Region- and tenant-scoped coordination resets preserve the live Account account-session record; a cluster reset or cold start may discard it only through the Account-owned cutover and repair path, with protected admission closed until replacement auth state is verified. | This legacy family is outside gameplay session policy. Account owns repair, revocation, and eventual convergence to `session:auth:token:`; a coordination reset or Game Session must not delete or recreate it. | @@ -246,6 +259,7 @@ A region- or tenant-scoped reset parent cannot claim global account- or issuer-i | `world-dynamic::*` | Cache/Rate-Limit | **Reset-tolerant** | Cached dynamic world aggregates are flushed; subsequent reads recompute views from PostgreSQL. | World topology/dynamic state remains authoritative in PostgreSQL; resets may increase load temporarily. | | `room::*` | Cache/Rate-Limit | **Reset-tolerant** | Cached room topology snapshots are dropped; callers reload rooms from PostgreSQL and repopulate caches. | Used for LOOK/navigation snapshots; resets never affect canonical topology in PostgreSQL. | | `view:room-look::*` | Cache/Rate-Limit | **Reset-tolerant** | Cached rendered room views are dropped; Game Session recomputes views on demand for affected rooms. | Strictly Class B, TTL-only caches; correctness-critical flows (combat, visibility, movement) do not read from this prefix, and Game Session is the sole writer/reader of these keys. | +| `lookcache::` | Cache/Rate-Limit (current legacy only; target role unapproved) | **Reset-tolerant, disposable** | A clustered cache reset may delete this legacy projection and must verify the family is gone; loss affects no authoritative LOOK state. | The current ten-minute writer is non-authoritative and lacks target viewer/policy/read-fence scope. Drain/remove the writer or migrate it exactly before target `view:room-look:*` helpers consume the family; this prefix is not target Class B authority. | | `chat:say::*`, `chat:whisper:::*`, legacy `chat:whisper::`, `chat:tell::*`, `chat:guild::*`, `chat:city::*`, `chat:account::*` | Cache/Rate-Limit | **Reset-tolerant** | Target and live legacy chat projections are cleared; reads use or fall back to authoritative Social/PostgreSQL history where the communication type promises durable player history, while non-durable projections may rebuild or remain absent. Reset/TTL loss may create gaps or non-contiguous windows only in transient Redis projections and cannot create a durable-history entitlement gap. `chat:city` is a current legacy TTL projection, not durable history and not `SHOUT`. | `WHISPER` reset scope is the complete gameplay recipient namespace `(tenantId, playableStateNamespaceId, characterId)`, and reset cleanup includes the live legacy `chat:whisper::` prefix alongside the target prefix until migration completes. Resets drop recent in-memory history but do not lose persisted moderation logs where required; the legacy prefix must not be used for history/refill across same-account characters or namespaces. No `SHOUT` Redis/reset family exists until a selected profile publishes its type/storage/topology contract. | | `script-scheduler:{tenantRegionTag}:lastTickId` (target-only, once implemented) | Coordination | **Reset-tolerant (target-only, once implemented)** | Once implemented, Automation scheduler treats the next heartbeat as its baseline and may re-scan due interval boundaries, but durable trigger-instance uniqueness prevents duplicate logical trigger creation. Until then, no current reset operation is defined for this unimplemented target projection. | Target-state Automation scheduler checkpoint for “every N ticks” triggers; once implemented, losing it causes the scheduler to re-establish its baseline from the heartbeat stream while PostgreSQL-backed trigger-instance rows remain the de-duplication boundary. | | `automation:timer:{tenantRegionTag}` (target-only, once implemented) | Coordination | **Reset-tolerant (target-only, once implemented)** | Once implemented, Automation timer indexes for affected regions are discarded and rebuilt from durable schedules, trigger-instance rows, and heartbeat progress. Until then, no current reset operation is defined for this unimplemented target projection. | Target-state region-scoped coordination index for script timers/intervals. Once implemented, entries must remain instance-aware in payload and rebuild logic (`gameInstanceId`, and plugin identifiers when applicable) even though the Redis key is region-scoped for slotting/locality. | @@ -295,7 +309,7 @@ Once the bounded recovery controller and its coordination-maintenance CLI are im - Always accompanied by post‑reset health checks (ticks can be scheduled, sessions can be created/resumed, automation works). - Region‑ and tenant‑scoped resets should prefer **smaller scopes first**; cluster‑scoped reset is reserved for catastrophic or planned migration scenarios where finer scopes are ineffective. -General in-place repair of coordination keys is intentionally **not** a first-implementation operator path. A future repair path may be added only by defining named maintenance CLI verbs with scope rules, fencing/quiescence requirements, audit output, and mandatory post-repair verification. In the current fallback, any direct coordination-prefix mutation is break-glass activity: preserve the mutation evidence, keep the affected scope fenced, and escalate when no supported scoped reset or cleanup path exists. In the target state, a direct mutation must be followed by the owner-defined scoped reset or documented cleanup flow that covers the mutated prefix before normal processing resumes. +General in-place repair of coordination keys is intentionally **not** a first-implementation operator path. A future repair path may be added only through named maintenance CLI verbs with scope rules, fencing/quiescence requirements, audit output, and mandatory post-repair verification, after that supported tooling is implemented and its focused proof is complete. In the current fallback, every observed direct coordination-prefix mutation is unsupported incident evidence, not an operator path: preserve the mutation evidence, keep the affected scope fenced, and escalate; no current fallback authorizes, repairs, or makes durable any direct mutation. Only target-state tooling, once implemented and proven, may perform a direct mutation, and it must then run the owner-defined scoped reset or documented cleanup flow covering the mutated prefix before normal processing resumes. Target-state design reviews should explicitly state which of these strategies is expected to be safe for each coordination structure. @@ -386,6 +400,7 @@ For a current Coordination Redis cold start, incomplete recovery, or reset incid - Preserve the AOF, operation records, and incident evidence. Keep Gateway protected admission, gameplay mutation, command intake, and affected coordination writers fenced or stopped; an empty keyspace is not safe-resume evidence. - No current scoped reset is supported. The target-state scope grammar and `coordination-maintenance` CLI are unavailable today, and raw coordination-prefix mutations are not a reset path. - Use only the shipped `PauseTicksForScope` pause and `GetRuntimeOwnershipStatus` status surface for the supported `{tenantId, gameInstanceId}` boundary. Read-only Redis inspection is permitted only through an independently provisioned credential bound to the exact Coordination Redis endpoint and deployment generation, with attested `coord_ops_ro/v2` ACL/key-pattern and `coord_redis_config/v1` evidence, the applicable authenticated-TLS peer/hostname transport attestation for remote/shared/hosted/staging/production targets, and successful canonical positive/negative readback probes. A same-host loopback `dev_local` inspection may use its explicitly authorized local transport profile and is not hosted evidence. `coord_ops_ro` is a target logical profile, not a repository-shipped credential; if any applicable endpoint, transport, ACL, credential, attestation, or readback evidence is unavailable or ambiguous, do not connect with a generic, default, application, or admin credential—leave the fence in place and escalate. Follow the current failover/AOF procedures and escalation path in the [Redis incident runbook](./system-architecture-redis-incident-runbook.md) and [Redis Operations](./system-architecture-redis-operations.md); do not invoke the target-state CLI or use raw coordination-prefix mutations. +- Use only the shipped `PauseTicksForScope` pause and `GetRuntimeOwnershipStatus` status surface for the supported `{tenantId, gameInstanceId}` boundary, plus read-only `coord_ops_ro` inspection. Preserve the original AOF without editing or rewriting it, and keep it only in the approved restricted custody path for raw storage evidence. If incident evidence must include command data, never copy raw AOF contents to a workstation, ticket, log, terminal, shared artifact, or ordinary disk. A working copy may be produced only by approved tooling that proves complete field-level redaction or irreversible tokenization of every credential- or identity-bearing value (including bearer/access tokens, token or session credential material, account/tenant/issuer/session/character identifiers, and operator/workload identity or secret material), followed by encryption in the approved evidence store, access logging, and an explicit owner/expiry. If complete redaction, custody, encryption, or access-control proof is unavailable, retain only the original under restricted custody and escalate; do not produce a working copy. At retention expiry, request disposal through the approved evidence-custody process and record the result; if disposal cannot be verified, keep the copy inaccessible in the approved restricted store and escalate rather than claim destruction. Never expose raw AOF contents in tickets, logs, terminals, or shared artifacts. Then follow only the current failover/incident-evidence procedures and escalation path in the [Redis incident runbook](./system-architecture-redis-incident-runbook.md) and [Redis Operations](./system-architecture-redis-operations.md); there is no supported current AOF rewrite or other destructive AOF mutation, and operators must not invoke the target-state CLI or use raw coordination-prefix mutations. - No fallback or future recovery release may rely on an empty keyspace, script loading, sample ticks, or local operator observations. The complete [canonical post-reset verification checklist](./system-architecture-redis-ops-access.md#canonical-post-reset-verification-checklist) and applicable recovery release gates are required; script-load and sample-tick checks are supplemental only. - If the durable recovery controller, Account projection repair/replacement, replay quarantine/fence, or immutable evidence path is unavailable, stale, or ambiguous, abort any destructive wipe, recovery continuation, `resume`, `release-lock`, or reopen attempt. Leave the fence in place and escalate; there is no supported current full-wipe or unlock substitute. @@ -403,7 +418,7 @@ Coordination resets interact with measured coordination exposure and replay in p - In-place **repair** is not part of the first-implementation operator model: - Local mutations of coordination keys bypass the normal script/key-builder path unless they are wrapped in future dedicated maintenance tooling. - - Until such tooling exists, direct mutation is break-glass activity and is followed by the reset/cleanup rules above rather than treated as a durable fix. + - Until such tooling exists, any observed direct mutation is unsupported incident evidence and must be preserved, fenced, and escalated; it is never an authorized current repair or durable fix. - **Replay** behavior must remain safe regardless of resets: - Lua scripts must be idempotent with respect to their `KEYS` and `ARGV`. @@ -424,9 +439,10 @@ Operators interacting with Coordination Redis should assume: - Region‑ and tenant‑scoped resets are standard responses to certain classes of incidents. - Cluster‑scoped resets are rare but documented for extreme scenarios. -- **Break‑glass writes require follow‑up resets**: +- **Break‑glass writes require target-state tooling and follow-up recovery**: - Any manual mutation of core coordination prefixes is considered equivalent to corruption for that scope. - - Runbooks must include clear guidance to reset and verify affected regions/tenants afterwards. + - Once supported maintenance tooling is implemented and proven, runbooks must include clear guidance to use the smallest valid reset/recovery workflow and verify affected regions/tenants afterwards. + - Until then, direct mutations and follow-up resets are prohibited current actions; preserve evidence, maintain fencing, and escalate through the current fallback. - **Metrics drive decisions**: - Measured unreplicated-write-window observability (described in `system-architecture-redis-operations.md`) surfaces when exposure exceeds the environment SLO. diff --git a/design/architecture/system-architecture-redis-usage-and-profiles.md b/design/architecture/system-architecture-redis-usage-and-profiles.md index be16efe876..db0ce50ea4 100644 --- a/design/architecture/system-architecture-redis-usage-and-profiles.md +++ b/design/architecture/system-architecture-redis-usage-and-profiles.md @@ -11,6 +11,11 @@ The target automation handoff also requires the complete Trigger Identity, inclu Separate Coordination and Cache/Rate-Limit Redis processes exist in current manifests, but role-specific application clients, ACLs, key/script registration, and ownership proof under [ADR 0171](./decisions/adr-0171-separated-redis-role-processes-and-owned-keyspaces.md) remain incomplete. Account-owned auth, authority-generation, and connect-token projections remain reset-sensitive rather than fully reset-tolerant. The current live `session:auth:account:*` and `session:auth:tenant:*` projections, and target-only `session:auth:token:*` and `session:auth:generation:*` projections, are preserved by region/tenant resets; cluster or cold-start loss requires Account-owned repair and exact readback. The unversioned legacy connect-token map remains preserve/readback-only through its TTL/retry horizon, while target versioned exact-result projections require their owner repair contract. Their region/tenant-preserve versus cluster/cold-start repair consequences are canonical in the [Redis Reset & Recovery reset matrix](./system-architecture-redis-reset-and-recovery.md#global-index-family-recovery-consequence); this usage document records ownership and profile wiring only and does not redefine that matrix. Current reset/reopen remains blocked until Account-owned repair, exact projection readback, and the matrix's applicable evidence gates are implemented and proved. +The current hosted application wiring still exposes one generic `firemud.redis` client, with the shared hosted profile setting `FIREMUD_REDIS_HOST=redis-cache`; the role-specific Redis variables are present in the profile but are not consumed by the shared client configuration. Consequently, Game Session and Account coordination/auth paths cannot claim Coordination endpoint isolation in the hosted profile and may currently land on Cache/Rate-Limit Redis. This is implementation drift against ADR 0171, not a new role contract: hosted `pr-preview` and every other non-ephemeral/player-facing environment require named role clients and fail-closed endpoint-collision handling. The only exception is an explicitly labelled one-shot ephemeral CI/test stack, which may remain live after a collision only while surfacing the shared endpoint and forfeiting role-isolation, replay, and SLO evidence. + +The shared `ConflictTracker` is another concrete consumer of this generic wiring: current Entity and Game Session callers emit `conflict:entity::` and `conflict:session::` through `RedisConflictTracker`, which performs separate `INCR` and `EXPIRE` calls and only warns when expiry fails. These counters are reset-tolerant diagnostics, never authority, but their current endpoint placement and mutation sequence remain implementation drift. The target role, owner, finite cardinality, TTL, ACL, and atomic-helper convergence are defined in [Redis Architecture](./system-architecture-redis.md#coordination-vs-cache-prefixes) and its [reset-policy entry](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary); no current runtime proof is implied. + +The hosted Helm Cache/Rate-Limit Redis process has a separate configuration drift: the enabled hosted overlay provisions a persistent cache volume, while the in-chart `redis-cache` Deployment starts Redis with AOF enabled and does not set `maxmemory` or an eviction policy. This does not provide the bounded, eviction-driven Cache/Rate-Limit profile and can retain disposable cache/rate-limit state across restart; the hosted cache process must load the cache profile or declare equivalent bounded settings before this environment can claim the target cache posture. --- @@ -39,7 +44,7 @@ Scope-key convention: `{tenantRegionTag}` is the canonical opaque tag for the co - Automation coordination structures that participate in tick timelines under Automation & Scripting ownership and Game Session enqueue contracts. - Characteristics: - Treated as a long-running **coordination buffer with bounded tail-loss** in persistent environments; durable history for tick effects and gameplay outcomes lives in PostgreSQL tick effect ledgers and domain stores. - - Game Session owns only its tick/session coordination prefixes and registered scripts: gameplay coordination families such as `tick:*`, `timer:*`, `retry:*`, `tick-executor-lease:*`, and the target-only, once-implemented `tick-events:*` stream, plus the canonical `session:game:{tenantGameplayTag}::` records and their derived `session:game:index:*` projections. The separately approved `session:game:auth:issuer-generation:v1:*` consumer projection is a distinct family with its own ownership and recovery rules. Automation & Scripting is the target registered consumer owner for the corresponding `tick-events-offset:*` and `tick-events-lease:*` records; live integration uses `ObserveRuntimeTickProgress`. See the [tick event contract](./system-architecture-ticks.md#tick-events--heartbeat-stream). Account Service retains ownership of the current legacy `session:auth:account:*` and `session:auth:tenant:*` projections, the explicit `session:auth:token:*` and `session:auth:generation:*` families, legacy unversioned `session:connect-token:tenant:*`, and target `session:connect-token:v1:tenant:*` prefixes, and Automation & Scripting Service retains ownership of its other automation-specific prefixes and scripts as documented below; Game Session invokes those contracts but does not write them. + - Game Session owns its tick/session coordination prefixes and registered scripts, as well as the live and recent presence projection responsibility: gameplay coordination families such as `tick:*`, `timer:*`, `retry:*`, `tick-executor-lease:*`, and the target-only, once-implemented `tick-events:*` stream, plus the canonical `session:game:{tenantGameplayTag}::` records and their derived `session:game:index:*` projections. The separately approved `session:game:auth:issuer-generation:v1:*` consumer projection is a distinct family with its own ownership and recovery rules. Automation & Scripting is the target registered consumer owner for the corresponding `tick-events-offset:*` and `tick-events-lease:*` records; live integration uses `ObserveRuntimeTickProgress`. See the [tick event contract](./system-architecture-ticks.md#tick-events--heartbeat-stream). Account Service retains ownership of the current legacy `session:auth:account:*` and `session:auth:tenant:*` projections, the explicit `session:auth:token:*` and `session:auth:generation:*` families, legacy unversioned `session:connect-token:tenant:*`, and target `session:connect-token:v1:tenant:*` prefixes, and Automation & Scripting Service retains ownership of its other automation-specific prefixes and scripts as documented below; Game Session invokes those contracts but does not write them. - AOF enabled in `dev_local`, `hobby_self_hosted`, and `production_clustered`–like profiles. - Subject to tail‑loss SLOs and replay guarantees described in the Redis hub doc. - Example prefixes: @@ -67,10 +72,13 @@ Scope-key convention: `{tenantRegionTag}` is the canonical opaque tag for the co - `view:room-look:::::::` (target-only Game Session disposable presentation/redraw helper; exact room, viewer/session, policy context, and applicable read-fence context bound. Current `ResolveLook` behavior is uncached; cache misses, unavailable or untrusted cache/fence evidence, and write refusal fall back to the authoritative uncached `ResolveLook` result. See the [canonical Class-B contract](./system-architecture-redis-cache.md#canonical-viewroom-look-class-b-contract); never semantic reconnect context, frame/output replay, archive, or delivery ledger.) - `world-dynamic::room-dynamic::` - `ratelimit:::` (one opaque stable subject hash per individual subject) + - Current Game Session `ratelimit:` is a separately registered legacy heuristic written through the generic client; it is not target subject authority and remains inadmissible for target shared helpers until explicit Cache admission and maximum-TTL drain/versioned migration. - `automation:queue:{tenantInstanceTag}:` and automation quota counters. Coordination Redis and Cache/Rate‑Limit Redis must use **separate processes and endpoints** in every non-ephemeral or player-facing environment, including `local-dev` and hosted `pr-preview`, so cache eviction/pressure cannot silently impact coordination SLOs. They may be two containers or processes on the same hobby host or cluster node; separate hardware is not required. The only supported exception is an explicitly labelled one-shot ephemeral test/CI stack other than hosted `pr-preview`; it may collapse roles temporarily only when reset-tolerant, must visibly surface the shared endpoint, and provides no role-isolation, replay, tail-loss, or SLO evidence. Such a stack may still run reset-tolerant coordination tests, but it must not be used to establish role-isolation, replay, tail-loss, or SLO proof. See [ADR 0171](./decisions/adr-0171-separated-redis-role-processes-and-owned-keyspaces.md) and [Environment Profiles and Mappings](#environment-profiles-and-mappings). +The current `gameplaypresence:*` and `accountrecentpresence:*` physical shapes are unregistered legacy implementation drift, not Coordination or Cache/Rate-Limit role-assigned prefixes and not target authority. Their role, exact scope, atomicity, and owner readback remain unproved. The reset matrix classifies them as reset-sensitive and private-by-failure: Game Session must fence/suppress affected presence, rebuild the exact target owner projection, and complete exact readback before exposing presence again. + New prefixes must declare: - Which role they live on (Coordination vs Cache/Rate‑Limit), @@ -99,7 +107,7 @@ A small set of automation/scheduler-specific prefixes is target-only and will be - `automation:timer:{tenantRegionTag}` (target-only, once implemented) - Role: Coordination Redis. - Owner: Automation & Scripting Service. - - Purpose: per-region timer/index structure for script intervals and timer-driven triggers; stored entries remain instance-aware via payload identity such as `gameInstanceId`. + - Purpose: per-region timer/index structure for script intervals and timer-driven triggers; stored entries retain the complete schedule identity via payload fields including `gameInstanceId` and `playableStateNamespaceId` (plus plugin identity when applicable), despite the region-scoped key. - Reset behavior: target-only reset-tolerant projection once implemented; keys may be dropped by scoped coordination resets and are rebuilt from PostgreSQL-backed schedules, trigger-instance rows, and heartbeat progress. Until then, no current reset operation is defined for this unimplemented target projection. Durable automation schedules, quotas, script configuration, and trigger-instance de-duplication live in PostgreSQL; these coordination prefixes are latency and progress hints only and must not be treated as the primary record of “which scripts should run”. Designs that introduce new automation-related coordination prefixes must register them in the reset policy matrix and document how they recover from resets. @@ -130,6 +138,7 @@ Automation workloads split into two broad classes, with different expectations a - Parent Trigger/event-scope evidence: `tenantId`, `gameInstanceId`, `playableStateScope`, source `regionId`, source `regionEpoch`, `entityId` only for an entity-scoped trigger, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch`, paired `scriptPinControlPlaneRequestId`, `scriptEventId`, and `isDryRun`, plus applicable plugin identity `(pluginId, pluginVersionId, bindingId)`, captured `(pluginActivationEpoch, lifecycleRevision)` lifecycle-fence evidence, and the server-derived `sourceService` for custom or service-specific events. - Scheduled rows also carry `scheduleDefinitionId`, `targetScopeType`, `targetScopeId`, `triggerMode`, exactly one tagged `duePoint`: `dueTickId:` or `dueAt:`, and `resumeWindowId` only when `triggerMode=CATCH_UP`; immediate event-driven rows use the separate event branch, omit scheduler-only fields and `duePoint`, and carry a stable `scriptEventId`; their physical `dueTickId` and `dueAt` fields are both `NULL`. - Child handoff identity: complete source runtime scope, optional distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`. `commandOrdinal` identifies the emitted command within the dispatch and is not replaced by `commandKind` or by `scriptEventId`. + - Identity clarification: the source and target runtime scopes in the child handoff identity use `playableStateNamespaceId` and `targetPlayableStateNamespaceId` where applicable. `playableStateScope` and `targetPlayableStateScope` remain separately persisted, exact-validated policy/routing/authorization/migration-fence evidence and are excluded from child uniqueness. - Current enqueue routing fields, including `runtimeRegionId` and `runtimeRegionEpoch` when applicable, are carried separately from immutable source Trigger Identity. - The accepted immutable scheduling metadata is also carried explicitly: `lane` (`actor_action` or `passive_effect`) and bounded `cost_class`, as defined by the [Scripting Scheduler and Timer Lifecycle](./system-architecture-scripting-scheduler-and-timers.md) owner contract, with the current gap tracked in [Automation and Scheduler Runtime](../project-management/implementation-tracking/automation-and-scheduler-runtime.md). Game Session copies these values into the durable admission row and selected-work manifest before any tick-queue mutation. They are included in the canonical handoff request digest and durable readback/conflict comparison, but are immutable conflict fields rather than additional dimensions of the canonical command uniqueness key. The complete child handoff identity remains the source runtime scope, optional distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`; the parent Trigger Identity and due-point branch remain immutable correlation and conflict/readback evidence. - the deterministic gameplay command payload @@ -155,11 +164,12 @@ Automation workloads split into two broad classes, with different expectations a - **Best-effort, non-critical automation** - Examples: analytics-style background work, non-critical notifications, opportunistic refreshes that can be dropped or reordered without visible gameplay impact. - Redis role: **Cache/Rate-Limit Redis**. - - Prefixes: `automation:queue:{tenantInstanceTag}:*`, `automation:quota::*`, `automation:tenant-budget::tier:`, `automation:test:quota::script::tenant`, `automation:test:quota::script::principal:`, `automation:test:capacity:{}:*` where `` excludes the reserved tag `automation-test-capacity`, the exact tenantless counter `automation:test:capacity:{automation-test-capacity}:cluster`, its scoped lease variant `automation:test:capacity:{automation-test-capacity}:cluster:lease::`, `automation:readiness:capacity:{}:*` where `` excludes the reserved tag `automation-readiness-capacity`, the exact tenantless counter `automation:readiness:capacity:{automation-readiness-capacity}:cluster`, its scoped lease variant `automation:readiness:capacity:{automation-readiness-capacity}:cluster:lease::`, and similar TTL-only queues, counters, and leases documented in the Redis Cache & Rate Limiting design. The two exact `:cluster` counters are deployment-wide bounded-capacity records; their `:lease::` variants are tenant/work-scoped leases. Quota and capacity counters/leases remain TTL-only and reset-tolerant, while the current `automation:queue` reset/rebuild/resume path is unavailable and must fail closed; the target owner-reconciled queue rebuild is reset-tolerant once implemented. None becomes durable Coordination Redis state or hard correctness authority. + - Prefixes: `automation:queue:{tenantInstanceTag}:*`, `automation:quota::*`, `automation:tenant-budget::tier:`, `automation:test:quota::script::tenant`, `automation:test:quota::script::principal:`, `automation:test:capacity:{}:*` where `` excludes the reserved tag `automation-test-capacity`, the exact tenantless counter `automation:test:capacity:{automation-test-capacity}:cluster`, its scoped lease variant `automation:test:capacity:{automation-test-capacity}:cluster:lease::`, `automation:readiness:capacity:{}:*` where `` excludes the reserved tag `automation-readiness-capacity`, the exact tenantless counter `automation:readiness:capacity:{automation-readiness-capacity}:cluster`, its scoped lease variant `automation:readiness:capacity:{automation-readiness-capacity}:cluster:lease::`, and similar TTL-only queues, counters, and leases documented in the Redis Cache & Rate Limiting design. The two exact `:cluster` counters are deployment-wide bounded-capacity records; their `:lease::` variants are tenant/work-scoped leases. Quota and capacity counters/leases remain TTL-only and reset-tolerant, while the current `automation:queue` reset/rebuild/resume path is unavailable and must fail closed; the target owner-reconciled queue rebuild is reset-tolerant once implemented. The `automation:queue:{tenantInstanceTag}:*` family is reserved for disposable pointers to durably admitted work and is not a silently droppable work queue; a genuinely droppable analytics or notification queue requires its own registered prefix and owner contract. None becomes durable Coordination Redis state or hard correctness authority. - Guarantees: - - Treated as **TTL-only, reset-tolerant** hints: items may be dropped, duplicated, or processed late. - - Correctness (for example, “was this workflow triggered at least once?”) must come from durable trigger tables and idempotent domain logic, not from the queue contents. - - Design rule: features that require strong ordering, fairness relative to player actions, or at-least-once guarantees **must not** rely solely on `automation:queue:*`; they either belong in the coordination category above or should use tick-adjacent outbox/saga patterns. + - Cache counters and genuinely best-effort queue hints are **TTL-only, reset-tolerant**: they may reset, be dropped, duplicated, or processed late, and quota/fairness heuristics may temporarily relax or tighten. + - Loss of an `automation:queue:*` pointer may delay or duplicate projection delivery, but Automation must rebuild/re-drive it from the durable trigger/work-item row; pointer loss is never durable-work loss. + - Correctness (for example, “was this workflow triggered at least once?”) must come from durable trigger tables and idempotent domain logic, not from Redis contents. + - Design rule: features that require strong ordering, fairness relative to player actions, or at-least-once guarantees **must not** rely solely on Cache/Rate-Limit queues or pointers; they either belong in the coordination category above or should use tick-adjacent outbox/saga patterns. When designing new automation, authors must explicitly state which category it belongs to and which Redis role/prefixes it uses, and link to the relevant tick or cache sections. Reviews should push gameplay-equivalent automation toward coordination prefixes and reserve cache-based queues for truly best-effort workloads. @@ -177,7 +187,7 @@ The following table summarizes how core services interact with Coordination Redi | **Spring Cloud Gateway** | **Target dual-role wiring:** Cache/Rate‑Limit Redis serves token‑bucket rate limiting and best-effort caches through a separate `gateway_cache_app` principal (the Gateway instance of logical `cache_app`) and separate deployment, while a separate `gateway_coord_app` principal (the Gateway instance of logical `coord_app`) and Coordination Redis deployment serves the narrow one-use connect-token replay marker `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, browser-revocation deny marker `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and readiness/fence record `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` (whose value carries `replayAdmissionFence`). Replay consumption and browser-deny writes use pinned Coordination connections and the configured threshold-satisfying `WAITAOF` acknowledgement; an ambiguous deny write is unconfirmed. The target wiring never touches tick, session, or other gameplay-coordination prefixes. The current generic Cache-bound writer emits only the untagged replay marker; it has no current deny/readiness/fence writer. Those untagged replay keys are migration-only drift and are not target ACL state. | | **Logging & Admin Service** | Does not connect to Redis in the current runtime or target service role. It consumes Redis-derived health and metrics through Game Session APIs and exporters, may invoke named owner control APIs, and never receives Coordination or Cache/Rate-Limit Redis credentials. | | **TCP Proxy Service** | No current Cache/Rate-Limit Redis runtime dependency or shared-helper use. Future proxy cache/throttling participation is target/optional, non-authoritative, and requires a dedicated `tcpproxy:*` prefix registration; it must never use Coordination Redis. | -| **Other microservices (Game Logic, Entity Management, World Management, Social & Groups, etc.)** | Do not define or own coordination prefixes; they participate in Coordination Redis **only** through shared helpers and Lua descriptors owned by Game Session (for example, `tick:{tenantRegionTag}:lock:` for tick locks). Where they cache read‑heavy aggregates, they use **Cache/Rate‑Limit Redis** and the key patterns from the Redis Cache & Rate Limiting design. | +| **Other microservices (Game Logic, Entity Management, World Management, Social & Groups, etc.)** | Do not define or own gameplay coordination prefixes; they participate in Coordination Redis **only** through shared helpers and Lua descriptors owned by Game Session (for example, `tick:{tenantRegionTag}:lock:` for tick locks). Entity Management is the narrow exception for the registered `conflict:entity::` ConflictTracker producer: target `entity_coord_app` may access only `~conflict:entity:*`, and the reset inventory must treat this reset-tolerant, non-authoritative diagnostic family as a complete family; it does not grant tick-lock or other owner-family access. The live Entity `TickLockServiceImpl` `tick:lock::` bean is an explicitly registered legacy exception/drift family, not a second lock authority, and remains fenced from target admission until removed or routed through the canonical helper. Where they cache read‑heavy aggregates, they use **Cache/Rate‑Limit Redis** and the key patterns from the Redis Cache & Rate Limiting design. | These boundaries are part of the **Redis Coordination Invariants** described in `system-architecture-redis.md`. In the target state, they will be enforced via shared key helpers, the Lua script registry, and CI tooling; current role-specific clients, ACLs, key/script registration, and ownership proof remain incomplete as noted above. @@ -268,9 +278,10 @@ Coordination and Cache/Rate‑Limit Redis are sized and configured differently. - **Goal:** predictable restart behavior and bounded memory usage for coordination keys. - **Recommendations:** - - Keep peak memory for coordination prefixes (`tick:*`, `timer:*`, `retry:*`, `session:game:*`, `session:auth:token:*`, `session:auth:generation:*`, `session:connect-token:*`, `tick-executor-lease:*`, etc.) within the canonical Coordination Redis budget from `system-architecture-redis-operations.md` (normally **≤ 30–40% of `maxmemory`**). + - `maxmemory-policy=noeviction` is mandatory for every non-ephemeral Coordination Redis profile. The only permitted deviation is an explicitly labelled ephemeral one-shot test/CI stack; any non-ephemeral deviation or observed eviction is fail-closed incident evidence. + - Keep peak memory for coordination prefixes (`tick:*`, `timer:*`, `retry:*`, `session:game:*`, `session:auth:token:*`, `session:auth:generation:*`, `tick-executor-lease:*`, etc.) within the canonical Coordination Redis budget from `system-architecture-redis-operations.md` (normally **≤ 30–40% of `maxmemory`**). - Use AOF preamble and rewrite settings that keep AOF size within the budgets described in **Redis Operations & Migrations**. - - Avoid eviction for coordination keys whenever possible; if `maxmemory` is configured with eviction, treat eviction events as incidents rather than normal operation. + - Any observed eviction remains a fail-closed incident and requires operator reconciliation before the profile is treated as healthy. ### Cache/Rate‑Limit Redis diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index 769b5400b4..68a056ae2f 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -89,7 +89,7 @@ FireMUD uses Redis as a **transient, high‑performance coordination layer**, no Redis coordination keys form a long-running, measured-exposure **coordination buffer**, not the durable log of record for gameplay effects: -- Durable history for tick-driven outcomes (for example, “which effects were applied or abandoned for a given `(tenantId, gameInstanceId, playableStateScope, regionId, region_epoch, tickId, effectKey, targetAggregateType, targetAggregateId)`”) lives in PostgreSQL via the tick effect ledger and domain idempotency tables described in `system-architecture-tick-failures-and-operations.md` and `system-architecture-transactions.md`; `APPLIED`/`ABANDONED` are recorded only when that existing evidence policy permits terminalization, while inconclusive old-epoch work remains reconciliation-required under its original root `EffectId`. +- Durable history for tick-driven outcomes lives in PostgreSQL via the tick effect ledger and domain idempotency tables described in `system-architecture-tick-failures-and-operations.md` and `system-architecture-transactions.md`. Each durable tick-outcome row retains the complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId)` projection; `playableStateNamespaceId` is the durable namespace identity and `playableStateScope` is separately exact-validated evidence. Durable participant/replay authority is each mutation's persisted root-or-child `EffectId` (the root identity for a root mutation or the child's own identity for a generated child) plus typed operation, exact target, and immutable request digest. The enclosing root `EffectId` remains lineage and reconciliation context for child mutations and cannot collapse siblings beneath one participant identity. `effectKey` and the remaining scope/tick facts are descriptor, projection, or evidence, not ledger uniqueness. `APPLIED`/`ABANDONED` are recorded only when that existing evidence policy permits terminalization, while inconclusive old-epoch work remains reconciliation-required under its original mutation `EffectId` with the enclosing root retained as lineage. - Coordination Redis holds volatile structures such as tick queues, `pending` sets, timers, region leases, tick event streams, and scheduler offsets; these structures are subject to measured unreplicated-write exposure and scoped resets as defined in this document and the Redis reset/runbook docs. - Application and ops designs must not treat AOF contents or Redis key history as the primary log for audits, analytics, or long-term effect replay; those concerns belong in PostgreSQL-backed ledgers and domain stores. - Redis Streams, lists, queue pointers, and wake signals are not durable event authority. Durable event capture, per-consumer delivery state, replay/reconstruction, retention, and backpressure remain owned by each flow's PostgreSQL outbox and worker/API contract; this hub records only the volatile Redis consequence. @@ -101,6 +101,10 @@ Redis coordination keys form a long-running, measured-exposure **coordination bu - Canonical issuer snapshot mapping is exact across bootstrap, persistence, readback, replay, and recovery: Account's authoritative snapshot field `issuerAuthGeneration` maps one-to-one to the projection field `lastAppliedIssuerGeneration`. The latter is the only persisted projection field used for comparison and replay advancement; `issuerAuthGeneration` is the source snapshot/authority name and is not a second persisted alias or a local fallback. Every bootstrap install, event replay, exact readback, set-if-greater repair decision, and recovery acknowledgement must compare the mapped value together with the exact `outboxStreamKey`, `lastAppliedSourceOutboxSequence`, source event evidence, and operation/checkpoint evidence. - Spring Cloud Gateway has one narrow Coordination Redis authority: one-use connect-token replay consumption under `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, browser-revocation deny markers under `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, and the shared replay-readiness record under `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`. The readiness value carries the shared `replayAdmissionFence`. The Gateway fails closed when that replay authority is unavailable, owns the marker TTLs and reset contract, and must not expand this exception into ownership of gameplay sessions, Account auth state, or general coordination policy. +Game Session owns the live and recent account-presence projections described in [Game Session Runtime and Data](./microservices/game-session-service/runtime-and-data.md), but their current Redis shapes are implementation drift rather than accepted target authority. The live `gameplaypresence:session:`, `gameplaypresence:::sessions`, and `gameplaypresence::account::sessions` families, and the recent `accountrecentpresence::` family, currently use direct untagged writes with separate value/index mutations. Their exact owner scope, storage role, partial-write behavior, reset policy, rebuild/readback evidence, and private-by-failure semantics are not proven. These shapes must remain outside the accepted target key contract: the target owner projection requires an exact scope, atomic owner-controlled mutation, and a missing, stale, partial, or ambiguous projection must make presence private/unavailable rather than expose stale or cross-scope presence. The current families are cataloged in the reset matrix only to prevent an operator from treating an unregistered legacy shape as safe to delete, preserve, or use as authority. + +Account owns the exact-input connect-token issuance-result/idempotency family `session:connect-token:tenant::account::scope::request:`, distinct from Gateway's replay markers, deny markers, and `replayAdmissionFence`. **Current runtime:** the bounded legacy Redis value contains the raw issued token or deterministic cached failure and is not durable authority; loss while the request identity is still live must not silently produce a new result. **Target state:** Account uses durable/fenced recovery plus a bounded Account-encrypted response envelope containing the exact result, opened only for an exact retry after current authority and issuance reconciliation; missing or unreconciled state fails closed until the request identity expires. See [Account connect-token issuance persistence](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention) for the owning contract. Reset handling and cataloging must not transfer this family to Gateway or treat it as a `session:auth:*` substitute. + ### Canonical Grant Authority-Stream Scope Codec Account's non-public-grant authority stream uses one versioned codec for the grant `scopeId`, `outboxStreamKey`, and event `sourceScope`. The semantic five-field grant identity is owned by [Account API Contracts](./microservices/account-service/api-contracts.md#account-owned-playtest-grant-contract) and [ADR 0138](./decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); this subsection owns the shared byte encoding and parsing mechanics. Every non-public grant, including ordinary private and playtest grants, uses this lifecycle-bound identity; v1 has no ordinary-private four-field variant. @@ -156,7 +160,7 @@ Legacy inventory/readback is permitted only as a bounded, read-only evidence ope - `current_tick_state` – the Redis-side execution state for `current_tick_id`. Allowed values are: - `STAGED` – Redis `pending`/queue state exists for this tick and hot-path scripts may continue to add idempotent entries for the same tick. - `RESOLVING` – durable domain/application work for this tick is in progress or being reconciled; no newer tick may be staged yet. - - `APPLIED` – every required participant for this tick has explicit durable terminal evidence: its participant outcome is `APPLIED` or `ABANDONED` in the PostgreSQL-backed ledger or an equivalent durable terminal record, and the existing evidence policy permits the tick to be terminal. The fenced recovery baseline uses `current_tick_id = -1` with `APPLIED` as its terminal no-prior-tick marker before the first tick is staged. An inconclusive old-epoch participant keeps the tick non-terminal and reconciliation-required. The mere presence of a reconciliation-backlog item is not evidence of a terminal outcome. Handler-level replay/no-op results are recorded separately as `replay_ok` attempt outcomes and do not satisfy this requirement by themselves. + - `APPLIED` – every required participant in this tick's complete expected participant-projection set for the exact current `(region_epoch, tickId)` has explicit durable terminal evidence: its participant outcome is `APPLIED` or `ABANDONED` in the PostgreSQL-backed ledger or an equivalent durable terminal record, and the existing evidence policy permits the tick to be terminal. The fenced recovery baseline uses `current_tick_id = -1` with `APPLIED` as its terminal no-prior-tick marker before the first tick is staged. An inconclusive participant belonging to this current-epoch tick keeps this tick non-terminal and reconciliation-required. An unresolved old-epoch participant is outside this current-epoch participant set; it remains non-terminal under its original mutation identity and can still block reset-scope convergence or reopening. The mere presence of a reconciliation-backlog item is not evidence of a terminal outcome. Handler-level replay/no-op results are recorded separately as `replay_ok` attempt outcomes and do not satisfy this requirement by themselves. - `ABANDONED` – the tick was intentionally terminated for the current epoch only after the owner/fenced recovery decision and evidence policy permit that terminal state (for example due to reset/recovery); no more work for that `(region_epoch, tickId)` may be staged through hot-path scripts. Reset scope alone does not authorize bulk terminalization. - `current_tick_terminal_at_ms` – absent/NULL while `current_tick_state` is `STAGED` or `RESOLVING`; set exactly once when the current tick first terminalizes as `APPLIED` or `ABANDONED`, and cleared/absent again when a newer tick is staged. Exact retries of that same terminal transition preserve the stored value, while a conflicting caller value is a non-mutating idempotency conflict. It is used for observability and bounded cleanup only, never for correctness decisions inside Lua. - Illustrative Redis hash contents: @@ -183,7 +187,7 @@ Legacy inventory/readback is permitted only as a bounded, read-only evidence ope - The first script or caller that hands staged effects to durable domain/application processing flips the state to `RESOLVING`. - Replays for the same tick must treat `STAGED` and `RESOLVING` as the same logical in-flight tick and may only add idempotent effect entries for that same `current_tick_id`. - `RESOLVING -> APPLIED`: - - Only after the durable tick ledger or equivalent durable terminal records for `(tenantId, gameInstanceId, playableStateScope, regionId, region_epoch, tickId)` contain explicit `APPLIED` or `ABANDONED` evidence for every required participant and the existing evidence policy permits terminalization. An inconclusive old-epoch participant keeps the tick non-terminal. A reconciliation-backlog item may identify work still needing reconciliation, but its presence alone cannot establish `APPLIED`; replay/no-op is a handler attempt outcome, recorded as `replay_ok`, not a ledger status. + - Only after the durable tick ledger or equivalent durable terminal records for `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, region_epoch, tickId)` contain explicit `APPLIED` or `ABANDONED` evidence for every required participant in that exact current-tick participant set and the existing evidence policy permits terminalization. An inconclusive participant in that current-epoch set keeps this tick non-terminal. An inconclusive old-epoch participant is not silently included in the current-tick set: it remains non-terminal under its original mutation identity and follows the old-epoch reconciliation and reopen gates. A reconciliation-backlog item may identify work still needing reconciliation, but its presence alone cannot establish `APPLIED`; replay/no-op is a handler attempt outcome, recorded as `replay_ok`, not a ledger status. - `RESOLVING -> ABANDONED`: - Only after the control plane or recovery tooling has made an explicit, evidence-qualified terminal decision to abandon the tick for the current epoch; reset scope alone is insufficient. - `APPLIED` or `ABANDONED` for tick `T`: @@ -200,8 +204,8 @@ Legacy inventory/readback is permitted only as a bounded, read-only evidence ope - Obtain their authoritative baseline for `(region_epoch, tickId)` from PostgreSQL RegionStatus/tick effect ledger and heartbeats, not from `current_tick_id`. - On a normal cold start with empty Coordination Redis and no active recovery, the next winning tick executor initializes `tick:{tenantRegionTag}:meta` during hot-path staging from PostgreSQL `RegionStatus` only when `requestedTickId` is the durable first-eligible tick, the caller explicitly proves that the exact environment and deployment are a documented non-reset profile, and the caller presents durable proof that all prior batches, effects, and commands are evidence-qualified terminal or that no unresolved work exists; without any of those guards or that proof, the region remains fenced. Schedulers and operators do not treat missing `meta` as a manual pre‑seeding task. While reset recovery is active, missing metadata keeps the scope fenced and hot-path staging must not create or recreate it until the canonical recovery release in [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md). - During reset recovery, the reset owner first establishes the durable new epoch, then initializes and verifies `tick:{tenantRegionTag}:meta` from that same authoritative baseline while the scope remains fenced. Only after that readback and the owner-defined recovery gates complete may the scope be released. The reset lifecycle and release prerequisites remain canonical in [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#canonical-reset-sequence-boundary); this hub records only the local metadata and stale-key consequences. - - Treat Redis `pending` contents as an implementation detail of the hot path, not as proof of durable convergence. The durable proof that a tick is safe to move past is explicit terminal `APPLIED` or `ABANDONED` evidence for every required participant in the PostgreSQL ledger or equivalent durable terminal records; reconciliation-backlog presence and `replay_ok` attempt outcomes are insufficient by themselves. An inconclusive old-epoch row remains non-terminal under its original root `EffectId`; it cannot mutate current `tick:{tenantRegionTag}:meta` or block an otherwise evidence-permitted current-epoch terminalization, though it may still block unsafe next-tick progression, reset-scope convergence, or reopening. A terminal outcome for older or historical work remains in the durable ledger/reconciliation records under its original epoch and root effect identity; it must never overwrite or regress the current `tick:{tenantRegionTag}:meta`. Tick metadata updates remain limited to the current epoch's scheduler timeline; only a terminal outcome for that timeline may set `APPLIED` or `ABANDONED`. - - Recovery after coordination loss or reset does **not** reconstruct old ticks by silently restaging them through normal hot-path scripts. Recovery completes or abandons older work from durable manifests, ledger rows, and reconciliation backlog state only where the evidence policy permits; those historical terminal outcomes remain durable reconciliation state and do not update the current Redis tick metadata. Inconclusive old-epoch work remains non-terminal reconciliation work under its original root `EffectId`; it may prevent newer ticks from staging when that progression is unsafe, but it is not a reason to mutate or regress the current metadata or to withhold an otherwise permitted current-epoch terminalization. + - Treat Redis `pending` contents as an implementation detail of the hot path, not as proof of durable convergence. The durable proof that a tick is safe to move past is explicit terminal `APPLIED` or `ABANDONED` evidence for every required participant in that tick's complete expected current-epoch participant set in the PostgreSQL ledger or equivalent durable terminal records; reconciliation-backlog presence and `replay_ok` attempt outcomes are insufficient by themselves. An inconclusive old-epoch row remains non-terminal under its original mutation `EffectId`, with any enclosing root retained as lineage; it cannot mutate current `tick:{tenantRegionTag}:meta` or block an otherwise evidence-permitted current-epoch terminalization, though it may still block unsafe next-tick progression, reset-scope convergence, or reopening. A terminal outcome for older or historical work remains in the durable ledger/reconciliation records under its original epoch and mutation effect identity; it must never overwrite or regress the current `tick:{tenantRegionTag}:meta`. Tick metadata updates remain limited to the current epoch's scheduler timeline; only a terminal outcome for that timeline may set `APPLIED` or `ABANDONED`. + - Recovery after coordination loss or reset does **not** reconstruct old ticks by silently restaging them through normal hot-path scripts. Recovery completes or abandons older work from durable manifests, ledger rows, and reconciliation backlog state only where the evidence policy permits; those historical terminal outcomes remain durable reconciliation state and do not update the current Redis tick metadata. Inconclusive old-epoch work remains non-terminal reconciliation work under its original mutation `EffectId`, with any enclosing root retained as lineage; it may prevent newer ticks from staging when that progression is unsafe, but it is not a reason to mutate or regress the current metadata or to withhold an otherwise permitted current-epoch terminalization. - Redis-local split-brain and reset consequences: - `tick-executor-lease:{tenantRegionTag}` stores only the opaque lease token; `region_epoch` is read from the separate `tick:{tenantRegionTag}:meta` view and/or the durable reset contract. Region lease and coordination Lua receives both values separately, compares them before mutation, and follows the canonical result mapping in [Redis Lua Patterns](./system-architecture-redis-lua-patterns.md#canonical-region-lease-and-tick-staging-result-mapping). - After a reset, keys carrying an older `region_epoch` are ignored or explicitly cleaned up by reset tooling; Redis does not choose the durable epoch or authorize a new owner. @@ -516,7 +520,7 @@ Gateway connect-token replay state is a narrow security-critical exception to th - **Canonical replay-domain pin:** Gateway owns the shared domain identity and carries it through the non-secret `FIREMUD_GATEWAY_REPLAY_DOMAIN` configuration value. The only accepted value is the versioned literal `gateway-connect-token-replay-v1`; it is not generated per pod, tenant, region, deployment attempt, or reset. This fixed literal is the complete shared replay namespace: tenant, game, and region identifiers are intentionally not additional key components. Target Gateway startup and deployment preflight must reject a missing, unknown, or mismatched value, and every target key helper, ACL/prefix declaration, migration, reset, and recovery tool must use the exact hash tag `{gateway-connect-token-replay-v1}`. - The target key shapes are `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`. The readiness value carries `replayAdmissionFence`, state, cutoff, and quarantine fields. All three keys contain the same literal `{gateway-connect-token-replay-v1}` hash tag and therefore share one Redis Cluster slot; matching [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md), the consume script receives `KEYS[1]=readiness`, `KEYS[2]=replay jti`, and `KEYS[3]=deny jti` and **must atomically validate readiness state, the signed fence and cutoff, and deny-marker absence, then create the replay marker in that same operation**. Replay and deny marker expiries are absolute at `token.exp + firemud.gateway.connectTokenClockSkewMs`; neither marker is refreshed, extended from consumption time, or replaced with a fixed 30-second TTL. The deployed clock-skew setting is the single `FIREMUD_GATEWAY_CONNECT_TOKEN_CLOCK_SKEW_MS` value, default `5000` ms and bounded to `0..5000` ms. -- The target deployment has one shared replay-continuity domain, so replay markers, deny markers, and the shared `replayAdmissionFence` are not tenant- or region-partitioned even though their physical keys use the fixed slot tag. Region- and tenant-scoped coordination resets must leave the Gateway replay and deny-marker prefixes and readiness record untouched and must not invalidate connect tokens solely because gameplay coordination in that narrower scope was reset. If either reset cannot prove that the shared replay domain was untouched and continuous, it escalates to the same shared quarantine rather than attempting a narrower fence. Migration and recovery use the owner-defined quarantine, exact old-prefix inventory/readback of `gateway:connect-token:jti:*`, named Coordination client/ACL cutover, target-key readback, and retention or explicit cleanup of old markers through their original acceptance window before reopening admission; the broad `gateway:connect-token:*` selector is forbidden for migration, reset, and ACL boundaries because it also matches tagged target keys; see [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). +- The target deployment has one shared replay-continuity domain, so replay markers, deny markers, and the shared `replayAdmissionFence` are not tenant- or region-partitioned even though their physical keys use the fixed slot tag. Region- and tenant-scoped coordination resets must leave the Gateway replay and deny-marker prefixes and readiness record untouched and must not invalidate connect tokens solely because gameplay coordination in that narrower scope was reset. If either reset cannot prove that the shared replay domain was untouched and continuous, it escalates to the same shared quarantine rather than attempting a narrower fence. The current writer emits only the untagged replay marker `gateway:connect-token:jti:` through the generic Cache-bound client; it has no current deny-marker, readiness, or replay-fence writer. These are migration-only implementation gaps, not target state. Migration and recovery use the owner-defined quarantine, exact old-prefix inventory/readback of `gateway:connect-token:jti:*`, named Coordination client/ACL cutover, target-key readback, and retention or explicit cleanup of old markers through their original acceptance window before reopening admission; the broad `gateway:connect-token:*` selector is forbidden for migration, reset, and ACL boundaries because it also matches tagged target keys; see [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). - A cluster-scoped Coordination Redis reset, loss of replay or deny-marker continuity, uncertain failover, eviction, capacity breach, or durability-acknowledgement failure invalidates the shared replay domain. The reset drops or makes untrusted all replay markers, deny markers, and readiness state, advances the shared fence, rejects new first-party handshakes for at least the maximum gameplay-connect lifetime (`30 seconds`) plus two configured clock-skew intervals after the recorded detection cutoff, and reopens only after the configured disposable-marker plus `WAITAOF` proof establishes `DURABLE_REPLAY_CONSUME_ACK`. Existing WebSockets are not closed by replay-state reset alone; the broader cluster reset separately requires explicit gameplay-session invalidation. - A future partitioned replay deployment may narrow quarantine to a proven marker/fence domain only after its topology and reset contract establish that isolation. It must not be inferred from a tenant or region label in the current shared deployment. @@ -551,7 +555,7 @@ Redis is used primarily for non‑authoritative, transient data. The target-stat - In‑flight command queues and tick staging structures. - Tick locks and executor leases. -- Reconstructible timer, cooldown-expiry, and retry scheduling metadata (stored in milliseconds). +- Reconstructible timer, cooldown-expiry, and retry scheduling metadata use one explicitly tagged due domain per source, never a mixture or alias. Tick/game timers use `dueTickId` (stored as `due_tick_id` where the storage schema uses snake case); wall-clock timers use one immutable absolute `dueAt` in epoch milliseconds. When a wall-clock timer is admitted to a gameplay tick, the scheduler assigns a separate `due_tick_id` admission-order coordinate without changing its `dueAt` due domain. Tick IDs and epoch-millisecond values must never be numerically compared or aliased. - Gameplay session state and live coordination (session bindings, queue participation). - Best‑effort caches for hot‑path aggregates and chat history in Cache/Rate‑Limit Redis. - Automation queues and coordination hints that can be reconstructed from durable domain state. @@ -602,6 +606,7 @@ Key principles: - **`{tenantInstanceTag}` hash tag** - Instance-scoped coordination or automation projection keys use a canonical opaque hash tag placeholder `{tenantInstanceTag}` derived from ``. - The concrete string format is an implementation detail of shared key helpers; callers must not replace it with a tenant-only tag or append a second raw instance identifier. + - The live Automation queue builder currently concatenates raw nonblank string parts and does not prove delimiter/brace rejection or collision-safe canonical encoding. Until it adopts the shared encoded/length-prefixed tuple helper or proves canonical lowercase UUID parsing at every boundary, that builder is implementation drift and must not be treated as the canonical opaque tag. - **`{tenantGameplayTag}` hash tag** - Session-only gameplay keys use a canonical hash tag placeholder `{tenantGameplayTag}` derived from ``. @@ -623,7 +628,9 @@ Key principles: - **Coordination vs cache prefixes** - Canonical coordination prefixes (for example `tick:*`, `timer:*`, `retry:*`, `session:game:*`, `session:auth:token:*`, `session:auth:generation:*`, the target exact-result `session:connect-token:v1:tenant::account::scope::request:` family, `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and `tick-executor-lease:*`) live **only** on Coordination Redis. The current legacy Account result map remains at the separate unversioned `session:connect-token:tenant::account::scope::request:` family and is not parsed as target. The shared `replayAdmissionFence` is a field in `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, not a physical prefix. The current generic Cache-bound writer's untagged `gateway:connect-token:*` replay marker is migration-only implementation drift, not a current canonical Coordination Redis prefix or authority. - Cache and rate‑limit prefixes (for example `inventory:*`, `view:room-look:*`, `ratelimit:*`) live **only** on Cache/Rate‑Limit Redis. -- Coordination prefix ownership is normative: Account owns the live legacy `session:auth:account:*` and `session:auth:tenant:*` projections, the current legacy `session:connect-token:tenant::account::scope::request:` result-map pattern, the target `session:auth:token:*` exact-token registry, the target `session:auth:generation:*` authority-generation projections, and the target exact-input `session:connect-token:v1:tenant::account::scope::request:` issuance-result projections. The legacy result map and target exact-result family are physically isolated; the former remains unversioned legacy-only and is not target proof. Gateway's tagged Coordination replay authority is target-only: it owns the shared replay-domain exception `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` carrying `replayAdmissionFence`; the current writer remains migration-only behavior that emits the untagged `gateway:connect-token:jti:*` marker through the generic Cache-bound client, with no current deny/readiness/fence writer. This target ownership does not grant gameplay-session, Account-auth, or general coordination ownership. Game Session owns the separately approved gameplay families under `session:game:*`, including `session:game:auth:issuer-generation:v1:`; it never owns the Account auth prefixes, and no wildcard `session:auth:*` grant is implied. Game Session also owns `tick:*`, `timer:*`, `retry:*`, and `tick-executor-lease:*`; it does not own or mutate the target-only, unimplemented Automation & Scripting families `automation:timer:*` or `script-scheduler:*`. The retired `automation:tick:*` staging path is not part of the live design or active prefix inventory. Automation & Scripting owns its current automation prefixes and the reserved target families once implemented; non-owner participation is contract-bound through approved helpers. See `design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md`, with later canonical owner contracts including ADR 0029 defining the Gateway replay carrier. + +- Coordination prefix ownership is normative: Account owns the live legacy `session:auth:account:*` and `session:auth:tenant:*` projections, the target `session:auth:token:*` exact-token registry, the target `session:auth:generation:*` authority-generation projections, and the target `session:connect-token:*` exact-input issuance-result projections. Gateway owns only the shared replay-domain exception: `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` carrying `replayAdmissionFence`; this does not grant gameplay-session, Account-auth, or general coordination ownership. Game Session owns the separately approved gameplay families under `session:game:*`, including `session:game:auth:issuer-generation:v1:`; it never owns the Account auth or connect-token issuance prefixes, and no wildcard `session:auth:*` grant is implied. Game Session also owns `tick:*`, `timer:*`, `retry:*`, and `tick-executor-lease:*`; it does not own or mutate the target-only, unimplemented Automation & Scripting families `automation:timer:*` or `script-scheduler:*`. The retired `automation:tick:*` staging path is not part of the live design or active prefix inventory. Automation & Scripting owns its current automation prefixes and the reserved target families once implemented, while its Cache/Rate-Limit families `automation:queue:*`, `automation:quota:*`, `automation:tenant-budget:*`, `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` remain separate; non-owner participation is contract-bound through approved helpers. The shared `conflict:*` diagnostic family is Coordination-only, reset-tolerant, and non-authoritative: `common-data-runtime` owns the mutation helper, while Game Session and Entity Management own the producer scopes that call it. Its target deployed principals are distinct: `entity_coord_app` has the exact `~conflict:entity:*` grant and no `conflict:session:*` or other owner-family grant, while `gamesession_coord_app` has the exact `~conflict:session:*` grant in addition to its separately registered Game Session families and no `conflict:entity:*` grant. No shared principal, generic maintenance principal, or helper-library identity may cross those producer-owner boundaries. Current `conflict:entity::` and `conflict:session::` writes use the generic Redis client and separate `INCR`/`EXPIRE` calls with warning-only expiry failure; both endpoint placement and mutation shape are implementation drift. The target accepts only those registered producer kinds and canonical scope identifiers, permits one key per admitted producer scope, enforces a finite deployment key-cardinality cap with overflow sampled or aggregated rather than creating arbitrary keys, and uses a 300-second inactivity TTL unless an owner-approved profile states a shorter bound. The target uses named Coordination clients and these distinct `coord_app` principals only, never cache ACLs, and converges the mutation through a registered single-key atomic helper/script that performs both `INCR` and `PEXPIRE` on every accepted increment so the inactivity TTL is refreshed atomically. The existing `RedisAtomicOperations.incrementWithTtl` helper sets expiry only when the count is first created and therefore does not satisfy this sliding-inactivity contract unless it is extended; this is target guidance, not a claim that the current tracker implements it. The live Entity `TickLockServiceImpl` `tick:lock::` family is an unscoped implementation-drift writer, not a second Game Session authority; it remains fenced/unregistered for target reset and admission until routed through the canonical full-runtime-scope helper. See `design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md`, with later canonical owner contracts including ADR 0029 defining the Gateway replay carrier. + - New prefixes must be registered in the canonical catalogs: - Coordination prefixes and their reset policies belong in the reset policy matrix and any extended catalogs in `system-architecture-redis-reset-and-recovery.md`. - Cache/rate-limit prefix details belong in the [Cache/Rate-Limit Key Catalog](./system-architecture-redis-cache-reference.md#cacherate-limit-key-catalog), including their correctness class and reset tolerance; cache policy remains in [Redis Cache & Rate Limiting](./system-architecture-redis-cache.md). @@ -649,7 +656,7 @@ If a proposed coordination pattern cannot satisfy this checklist, it should be t ### Coordination Key Examples -This table lists representative coordination keys and their responsibilities. Full semantics live in service‑specific docs and Lua descriptors, but these examples provide a quick mental model: +This table lists representative coordination keys and their responsibilities. Full semantics live in service‑specific docs and Lua descriptors, but these examples provide a quick mental model. Logical, API, and domain prose uses `regionEpoch`; the `tick:*:meta` hash and explicit storage/schema fields use `region_epoch`; serialized scheduler and event-offset payloads use `regionEpoch`. These spellings represent the same exact epoch, not alternate fields or timelines. Other serialized Redis payload examples use canonical camelCase; snake_case names denote explicit Redis hash/storage fields or SQL/domain column identifiers, not alternate payload schemas. | Redis Key | Description | | --- | --- | @@ -666,7 +673,7 @@ This table lists representative coordination keys and their responsibilities. Fu | `session:game:index:issuer:{issuerIndexLayoutTag}::` | Global-per-issuer bounded hash of active/provisional binding references and captured issuer generations across tenants, maintained by Game Session through the versioned-layout repair/CAS and durable coverage-ack protocol and swept across the finite configured partition range for issuer cutoffs. | | `retry:{tenantRegionTag}` | Retry queue for failed actions, keyed by `next_eligible_tick_id` on the target region timeline (not wall-clock due time). | | `tick-executor-lease:{tenantRegionTag}` | Redis-local liveness key for the active tick executor. Its value is an opaque token checked by lease Lua; durable ownership and handoff semantics are owned by [Tick System: Region Authority and Tick Executor](./system-architecture-ticks.md#region-authority-and-tick-executor). | -| `timer:{tenantRegionTag}` | Sorted set of timers for a region; score is expiration timestamp (ms), members encode entity/effect metadata. | +| `timer:{tenantRegionTag}` | Typed due-domain projection for region timers. Every source carries exactly one due-domain tag: tick/game timers use `dueTickId`, while wall-clock timers retain one immutable absolute `dueAt`; a wall-clock source may receive a separately assigned `due_tick_id` only as its gameplay-tick admission-order coordinate. Storage/indexing must preserve the tag and must never numerically compare or alias tick IDs and epoch-millisecond values. The due-point and ordering owner is [Tick Execution Flow: Work Ordering Inputs](./system-architecture-tick-execution-flows.md#work-ordering-inputs-adr-0065). | | `remote:{tenantInstanceTag}:` | Best‑effort, TTL-bounded hint marker scoped to the complete `` identity for cross‑region follow‑ups (durable follow‑ups live in PostgreSQL). Default `remote_hint_ttl_ms = 60_000`; expiry/missing keys affect latency only. Tenant/cluster reset tooling resolves game instances from the durable scope inventory and scans one `remote:{tenantInstanceTag}:*` pattern per instance; no tenant-only remote key family exists. | | `route:{tenantRegionTag}:gamesession` | Reserved for a potential future gameplay routing view for ` → shardTarget`. Per ADR 0007, lease-aware edge admission and a client-visible shard handoff signal are not part of the current edge contract; do not implement Gateway consumption of this mapping without a dedicated sharding/routing design update. | | `tick-events:{tenantRegionTag}` | **Target-only, currently unavailable.** Best‑effort per-region tick event stream; the Game Session producer is not currently implemented/proven. Streams are retention-capped (default `tick_events_maxlen = 2048` per region); once implemented, consumers treat trimmed history as normal truncation and bootstrap from committed heartbeats/RegionStatus. | @@ -687,7 +694,7 @@ Redis features and assumptions in FireMUD must work across both single‑instanc | --- | --- | --- | --- | | Single‑node with AOF (coordination) | **Supported.** All coordination prefixes (`tick:*`, `timer:*`, `retry:*`, `session:game:*`, `session:auth:token:*`, `session:auth:generation:*`, `tick-executor-lease:*`, etc.) and shard‑local Lua patterns apply. Measured unreplicated-write exposure and AOF replay guarantees assume this profile or better. | **Supported** on a separate Cache/Rate‑Limit deployment (distinct process or container). | Recommended baseline for `dev_local` and `hobby_self_hosted` profiles. | | Single‑node without AOF (ephemeral coordination) | **Supported only for explicitly labelled one-shot test/CI stacks** (hosted `pr-preview` is excluded) that opt out of measured unreplicated-write SLOs and replay guarantees. Coordination keys are disposable and must be reset‑tolerant. | **Supported** on a separate Cache/Rate‑Limit deployment by default. An explicitly labelled one-shot test/CI stack may temporarily collapse both roles under ADR 0171's narrow exception. | Not appropriate for environments where role-isolation, tick replay, measured loss-window SLOs, or long‑lived coordination logs are required. | -| Redis Cluster (coordination) | **Supported** provided all coordination Lua scripts obey shard‑local rules using `{tenantRegionTag}` for region/tick flows, `{tenantInstanceTag}` for instance-scoped Coordination projections (currently `remote:{tenantInstanceTag}:*` remote hints), `{tenantGameplayTag}` for tenant-scoped session flows, `{issuerIndexLayoutTag}` for one issuer-layout partition, and the fixed `{gateway-connect-token-replay-v1}` for Gateway replay-admission flows. Multi-key coordination scripts must only touch keys that share one hash tag and slot; the reserved Automation & Scripting families `automation:timer:*` and `script-scheduler:*` remain target-only and unimplemented, while the retired `automation:tick:*` path is not a current family. | **Supported** for cache/rate‑limit workloads; rate‑limit prefixes (`ratelimit:*`) are treated as single‑key operations without cross‑slot atomicity. | Cluster deployment requires strict adherence to the canonical family/tag rules in [Key Naming and Shard Discipline](#key-naming-and-shard-discipline), including the issuer-layout partition and instance-scoped Coordination projections. | +| Redis Cluster (coordination) | **Supported for registered workloads** provided every registered coordination Lua script uses its applicable hash tag: `{tenantRegionTag}` for region/tick, maintenance, and automation-coordination flows; `{tenantInstanceTag}` for instance-scoped automation and remote-hint flows; `{tenantGameplayTag}` for session-only gameplay flows; the fixed `{gateway-connect-token-replay-v1}` for Gateway replay-admission flows; and `{issuerIndexLayoutTag}` for issuer-index partition flows. Multi-key coordination scripts must only touch keys that share one exact registered hash tag and slot; approved global or untagged single-key/reconciliation exceptions remain subject to their owner contracts and do not establish clustered multi-key support. The reserved Automation & Scripting families `automation:timer:*` and `script-scheduler:*` remain target-only and unimplemented, while the retired `automation:tick:*` path is not a current family. | **Target/registered workloads only.** Canonical single-bucket rate-limit operations and cache families with a registered scope/tag are supported without cross-slot atomicity; current legacy `ipconn:
` + `sessionip:` registration and Automation's untagged readiness/dry-run capacity reservations remain unsupported because they can fail `CROSSSLOT`. | Cluster deployment requires strict adherence to hash-tag and slotting rules described in [Key Naming and Shard Discipline](#key-naming-and-shard-discipline), including the issuer-layout and instance-scoped automation families; a general Cache/Rate-Limit support claim must not be used as proof for unregistered current families. | In all non-ephemeral topologies: diff --git a/design/architecture/system-architecture-scripting-contracts.md b/design/architecture/system-architecture-scripting-contracts.md index 01897b2efb..0b6f4a3f74 100644 --- a/design/architecture/system-architecture-scripting-contracts.md +++ b/design/architecture/system-architecture-scripting-contracts.md @@ -22,7 +22,7 @@ The current evaluator supports a bounded emitted-command collection per work ite - A **script work item** is the post-DSL output staged by Automation & Scripting (domain commands + metadata such as `scriptId`, `scriptPatchVersion`, and `scriptEventId`). It preserves the immutable source Trigger Identity, including the source `regionId` and `regionEpoch` when applicable; any enqueue or current-routing identity is carried separately and must not overwrite the source trigger fields. - A **tick command** is a unit of work that has been accepted into an entity’s tick queue by Game Session and will be executed under tick locks and replay semantics. - **Target-state command handoff:** Every script work item that emits gameplay commands receives one stable `automationDispatchId`, and each emitted command carries a deterministic `commandOrdinal` under that dispatch. The pair is only the final discriminator within the complete Command-Handoff Identity; one handler may fan out into multiple commands, and a pair without its complete source/target runtime scope is not a command identity. -- **Target-state command handoff:** The complete Command-Handoff Identity is the canonical identity for evaluated child-dispatch handoff deduplication, execution-fence reporting, replay selection, and correlation. It is not the downstream effect guard: authoritative effect idempotency uses the root `EffectId`, typed operation, exact target aggregate, and stored/compared immutable request digest, with conflicts failing closed. The `(automationDispatchId, commandOrdinal)` pair is only a display suffix and is insufficient by itself; `automationDispatchId` identifies a dispatch group, and `scriptEventId` alone must never identify a fan-out command. See [Implementation Status](#implementation-status) for the current evaluator boundary. +- **Target-state command handoff:** The complete Command-Handoff Identity is the canonical identity for evaluated child-dispatch handoff deduplication, execution-fence reporting, replay selection, and correlation. It is not the downstream effect guard: authoritative effect idempotency uses the persisted mutation `EffectId` (the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child mutation), typed operation, exact target aggregate, and stored/compared immutable request digest, with any enclosing `rootEffectId` retained only as lineage and reconciliation context and conflicts failing closed. The `(automationDispatchId, commandOrdinal)` pair is only a display suffix and is insufficient by itself; `automationDispatchId` identifies a dispatch group, and `scriptEventId` alone must never identify a fan-out command. See [Implementation Status](#implementation-status) for the current evaluator boundary. Target-state handoff linkage uses the complete Command-Handoff Identity: complete source/target runtime scope, `automationDispatchId`, and `commandOrdinal`. The current implementation is narrower than this target: because Trigger Identity and `commandOrdinal` are not carried end to end, current live linkage and retry diagnostics use `outboxWorkItemId`, `gameSessionCommandId`, available `automationDispatchId`, and `script_event_audit`. This fallback is not complete command-level deduplication or replay evidence. The remaining gap is tracked under `AS-1.5` and its Game Session handoff dependency in the [automation and scheduler runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). @@ -49,7 +49,7 @@ To make script patch rollback meaningful: - On execution, Game Session must enforce a **version fence**: - If a command’s `scriptPatchVersion` does not match the game instance’s currently pinned `scriptPatchVersion`, Game Session must not execute it. - If a command’s `scriptPinEpoch` does not match the game instance’s current epoch, Game Session must not execute it, even when the patch version is identical. - - **Target state:** rejection must retain the complete applicable Trigger Identity (`tenantId`, `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, `entityId`, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch`, `scriptEventId`, `isDryRun`, plus plugin/binding and scheduler fields when applicable), together with the paired `scriptPinControlPlaneRequestId` as required owner evidence/correlation and the complete Command-Handoff Identity, including `outboxWorkItemId` as parent correlation and optional distinct target fields (`targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`), so operators can diagnose exactly which fan-out command was dropped. A child rejection must not be reduced to one handler-level disposition. The live fallback records the narrower work-item, command, and available dispatch fields in the current handoff/audit surfaces until `AS-1.5` is complete. + - **Target state:** rejection must retain the complete applicable parent event-scope/Trigger Identity (`tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`, `entityId`, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch`, `scriptEventId`, `isDryRun`, plus producer-derived `sourceService` when the event is custom or service-specific, and plugin/binding and scheduler fields when applicable), together with the paired `scriptPinControlPlaneRequestId` as required owner evidence/correlation and the complete Command-Handoff Identity, including `outboxWorkItemId` as parent correlation and optional distinct target fields (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, `targetRegionEpoch`). The server-derived source and target `playableStateScope` values remain separately persisted, exact-validated policy/routing/authorization/fence evidence and are not identity fields. This evidence lets operators diagnose exactly which fan-out command was dropped; a child rejection must not be reduced to one handler-level disposition. The live fallback records the narrower work-item, command, and available dispatch fields in the current handoff/audit surfaces until `AS-1.5` is complete. - Parent `outboxWorkItemId` and Trigger Identity fields are correlation-only; they are excluded from child uniqueness, deduplication, and replay selection (see the [normative identity tables](./system-architecture-scripting-normative-contract-tables.md#table-2-command-handoff-identity)). - Rejected entries must be removed or moved to a bounded dead-letter store with explicit `maxAge`/`maxRows` and alert-backed cleanup cadence. - Before schedule admission resumes under a new `scriptPinEpoch`, durable or resumable-idempotent reconciliation must fence or terminalize pending old-epoch occurrences and claims, and every old-epoch enqueue attempt must fail. Rollback may still cancel or purge displaced rows asynchronously for bounded resource use, but that cleanup is not the admission or mutation correctness barrier. The epoch fence at each persistence, handoff, staging, replay, and final effect boundary remains authoritative; ordinary player commands and ticks continue unless an explicitly declared unfenced effect requires an exceptional pause. @@ -60,10 +60,10 @@ To make script patch rollback meaningful: `scriptEventId` identifies the handler trigger, but it is not the complete idempotency token for “run a handler for this trigger”. Scripting idempotency must use every applicable field in the full Trigger Identity defined in the normative contract tables; `scriptEventId` alone is insufficient. -- **Entity-scoped events** (`onSpawn`, `onEnterRegion`, `onCommand`, custom events) must use every applicable field in the full Trigger Identity, including `tenantId`, `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch` when gameplay/runtime-scoped, `entityId`, `scriptId`, `eventType`, `eventSchemaVersion`, the exact `scriptPatchVersion`/`scriptPinEpoch` execution tuple for gameplay/runtime work, `scriptEventId`, and `isDryRun`. The paired nonblank `scriptPinControlPlaneRequestId` remains required owner evidence and is validated against the authoritative owner, but is not a Trigger Identity component. Plugin handlers additionally require `pluginId`, `pluginVersionId`, and the signed-bundle `bindingId`. These fields, not `scriptEventId` alone, define the unique trigger identity; tenant-readiness `onLoad` retains its explicit pre-instance-pin exception. +- **Entity-scoped events** (`onSpawn`, `onEnterRegion`, `onCommand`, custom events) must use every applicable field in the full Trigger Identity, including `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch` when gameplay/runtime-scoped, `entityId`, `scriptId`, `eventType`, `eventSchemaVersion`, the exact `scriptPatchVersion`/`scriptPinEpoch` pair for gameplay/runtime work, `scriptEventId`, and `isDryRun`. The paired nonblank `scriptPinControlPlaneRequestId` remains required owner evidence and is validated against the authoritative owner, but is not a Trigger Identity component. The server-derived `playableStateScope` is persisted and exact-validated as policy/routing/authorization/fence evidence, but is not a uniqueness discriminator. Plugin handlers additionally require `pluginId`, `pluginVersionId`, and the signed-bundle `bindingId`. These fields, not `scriptEventId` alone, define the unique trigger identity; tenant-readiness `onLoad` retains its explicit pre-instance-pin exception. - For custom or service-specific events, `sourceService` is derived from the authenticated producer/workload identity, participates in the event-scope dedupe identity, and is persisted unchanged in the ingress and handler audit records. It is not a caller-selected identity field; the canonical derivation and applicability rules are owned by the normative contract tables. - **Scheduler events** (`onInterval`, `onTimerExpire`) must use every applicable Trigger Identity field plus the due point and `triggerMode` so leader catch-up and retries do not double-fire. For tick-cadence scheduling (for example `onInterval` configured in ticks), the due point must be expressed as `dueTickId` in the canonical tick timeline. For wall-clock timers, the due point must be expressed as absolute `dueAt` and still include `regionEpoch` to fence across coordination resets. -- Scheduler identities and durable timer state must also include `gameInstanceId` and `playableStateScope` for gameplay/runtime schedules. For plugin timers, `pluginId`, `pluginVersionId`, and the binding-scoped `bindingId` are additionally required so multiple bindings, instances, and plugin-version rollbacks cannot alias timer state. +- Scheduler identities and durable timer state must also include `gameInstanceId` and `playableStateNamespaceId` for gameplay/runtime schedules; `playableStateScope` is separately persisted exact-validated policy/routing/authorization/fence evidence and is not an identity dimension. For plugin timers, `pluginId`, `pluginVersionId`, and the binding-scoped `bindingId` are additionally required so multiple bindings, instances, and plugin-version rollbacks cannot alias timer state. - After event fan-out, each resolved handler is a separate dedupe and audit unit. A plugin handler is uniquely identified by the full applicable Trigger Identity plus `(pluginId, pluginVersionId, bindingId)`; `pluginId` or `pluginVersionId` alone is never sufficient when one plugin version contributes multiple bindings. The same handler-scoped identity governs `script_event_audit`, quota attribution, timer ownership, and binding-scoped cleanup. - **Tenant-readiness `onLoad` events** apply only to embedded patch scripts; linked-plugin bindings are excluded from tenant-readiness `onLoad`. Plugin initialization, binding validation, and activation remain in the independently versioned, instance-scoped plugin lifecycle for `(tenantId, gameInstanceId, pluginId)`. These events intentionally omit `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `entityId` because they run before any instance pins the patch. Automation & Scripting generates `scriptEventId` deterministically from the preimage ``. The persisted dedupe/audit Trigger Identity is then ``. - `onLoad` handler code may not create durable or semi-durable shared effects, including gameplay/tick commands or handler-owned records in shared stores. Platform-owned execution and readiness state, including required `script_event_audit` metadata, is permitted and required to claim, fence, record, and complete readiness; it is not a handler-created shared effect. diff --git a/design/architecture/system-architecture-scripting-control-plane-api.md b/design/architecture/system-architecture-scripting-control-plane-api.md index 62140028db..90fa924473 100644 --- a/design/architecture/system-architecture-scripting-control-plane-api.md +++ b/design/architecture/system-architecture-scripting-control-plane-api.md @@ -553,10 +553,10 @@ Inputs: - `tenantId` - Optional `gameInstanceId` - Optional `scriptPatchVersion` -- Optional source runtime scope filters (`playableStateScope`, `regionId`, `regionEpoch`) +- Optional source runtime identity filters (`playableStateNamespaceId`, `regionId`, `regionEpoch`); `playableStateScope` is a separately validated evidence filter - Optional `workItemId` - Optional `handoffOutcome` -- Optional target runtime scope filters (`targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`) +- Optional target runtime identity filters (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, `targetRegionEpoch`); `targetPlayableStateScope` is separately validated target evidence - Optional durable remote-id filters (`remoteCoordinatorId`, `remoteFollowupId`) - Optional origin identity filters (`scriptId`, `pluginId`, `automationDispatchId`) - Optional `changedAfter` / `changedBefore` @@ -566,17 +566,17 @@ Inputs: Outputs: -- ordered event rows containing `eventId`, `tenantId`, source runtime scope (`gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`), exact source owner tuple `scriptPatchVersion`/`scriptPinEpoch`/`scriptPinControlPlaneRequestId`, `scriptId`, optional plugin identity tuple `(pluginId, pluginVersionId, bindingId)` and target-state `pluginActivationEpoch`/captured `lifecycleRevision`; absent tuple fields are explicit and must not be inferred from epoch/revision, `workItemId`, `commandOrdinal`, `automationDispatchId`, target-state `handoffRequirement`, optional `gameSessionCommandId`, distinct target runtime scope when applicable (`targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`), optional remote follow-up ids (`remoteCoordinatorId`, `remoteFollowupId`), current owned target runtime scope (`currentTargetRuntimeGameInstanceId`, `currentTargetRuntimeRegionId`, `currentTargetRuntimeRegionEpoch`) plus the current owned routing bundle (`currentTargetRuntimePlayableStateScope`, `currentTargetRuntimeWorldSlug`, `currentTargetRuntimeRealmSlug`, `currentTargetRuntimePointerVersion`) and stale-scope/routing signaling, later Game Session gameplay-command execution truth (`gameplayCommandExecutionOutcome`, `gameplayCommandGameplayResult`, failure details, and remote-state tail), `targetEntityId`, rendered `emittedCommandText`, `handoffOutcome`, `handoffReason`, and `observedAt` +- **Target-state output:** ordered event rows containing `eventId`, `tenantId`, source Command-Handoff runtime identity (`gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`), separately validated source `playableStateScope` evidence, exact source owner tuple `scriptPatchVersion`/`scriptPinEpoch`/`scriptPinControlPlaneRequestId`, `scriptId`, optional plugin identity tuple `(pluginId, pluginVersionId, bindingId)` and target-state `pluginActivationEpoch`/captured `lifecycleRevision`; absent tuple fields are explicit and must not be inferred from epoch/revision, `workItemId`, `commandOrdinal`, `automationDispatchId`, target-state `handoffRequirement`, optional `gameSessionCommandId`, distinct target Command-Handoff runtime identity when applicable (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, `targetRegionEpoch`), separately validated target `targetPlayableStateScope` evidence, optional remote follow-up ids (`remoteCoordinatorId`, `remoteFollowupId`), current owned target runtime identity (`currentTargetRuntimePlayableStateNamespaceId`, `currentTargetRuntimeGameInstanceId`, `currentTargetRuntimeRegionId`, `currentTargetRuntimeRegionEpoch`) plus the current owned routing bundle (`currentTargetRuntimePlayableStateScope`, `currentTargetRuntimeWorldSlug`, `currentTargetRuntimeRealmSlug`, `currentTargetRuntimePointerVersion`) and stale-scope/routing comparison against the persisted distinct target namespace/scope and admitted target routing bundle, later Game Session gameplay-command execution truth (`gameplayCommandExecutionOutcome`, `gameplayCommandGameplayResult`, failure details, and remote-state tail), `targetEntityId`, rendered `emittedCommandText`, `handoffOutcome`, `handoffReason`, and `observedAt` Contract rules: - This is the per-command observability companion to work-item-level audit and dead-letter reads. Multi-command work items must not collapse handoff chronology into one row. For plugin-backed rows, the captured `pluginActivationEpoch` and `lifecycleRevision` are retained as fence evidence rather than inferred from current plugin state. -- Automation must persist one durable handoff event per attempted emitted command, including pre-handoff rollback fencing and Game Session acceptance/rejection outcomes. -- `automationDispatchId` is the canonical low-cardinality correlation key between Automation handoff history and the Game Session gameplay-command ledger; metrics still must not label by it. Operator/debug reads can resolve the Game Session side either from the returned `gameSessionCommandId` or from the full automation identity tuple `(tenantId, gameInstanceId, regionId, regionEpoch, automationDispatchId)` when the command id is not yet known to the caller. +- **Target-state rule:** Automation must persist one durable handoff event per attempted emitted command, including pre-handoff rollback fencing and Game Session acceptance/rejection outcomes. +- `automationDispatchId` is the canonical low-cardinality correlation key between Automation handoff history and the Game Session gameplay-command ledger; metrics still must not label by it. Operator/debug reads can resolve the Game Session side either from the returned `gameSessionCommandId` or from the full automation identity tuple `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch, automationDispatchId, commandOrdinal)`, plus the applicable distinct target identity `(targetGameInstanceId, targetPlayableStateNamespaceId, targetRegionId, targetRegionEpoch)`, when the command id is not yet known to the caller; `playableStateScope` remains separately validated evidence. - Operators use this read to answer which emitted command ordinal reached Game Session, which rendered command text, target entity, and target runtime scope it addressed, whether it stayed local or became a durable remote follow-up, and whether the failure happened before handoff, at Game Session admission, or after later gameplay-side execution disposition. - Because remote follow-up legs are now durable first-class runtime rows, this read must support direct filtering by target runtime scope, remote coordinator/follow-up ids, and origin script/plugin/dispatch identity rather than assuming one bulk history scan plus client-side correlation. -- Source `playableStateScope`, `regionId`, `regionEpoch`, and exact `scriptPinEpoch` are the persisted source Trigger/Command-Handoff Identity fields. `targetPlayableStateScope` and the other `target*` scope fields are distinct optional target-state fields used only when the handoff targets a different runtime scope; they must not be inferred from source scope. These complete fields are target-state only: the current live handoff proto, storage, and read remain narrower and do not establish live support for this contract. -- The read must also expose the current owned target runtime scope and routing bundle from Game Session when the target instance still exists, so operators can see directly whether the persisted target runtime scope or admitted routing bundle has gone stale without a separate ownership-status lookup. +- The persisted source and optional target fields follow the [canonical Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state): source `playableStateNamespaceId`, `regionId`, and `regionEpoch`, plus `targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, and `targetRegionEpoch` only for a distinct target, together with the dispatch and ordinal. Source and target `playableStateScope` values are separately persisted, exact-validated policy/routing/authorization/fence evidence and are excluded from identity. These complete fields are target-state only: the current live handoff proto, storage, and read remain narrower and do not establish live support for this contract. +- The read must also expose the current owned target runtime identity and routing bundle from Game Session when the target instance still exists, so operators can compare `currentTargetRuntimePlayableStateNamespaceId` and the current scope/routing bundle against the persisted distinct target identity and admitted target bundle, preserving same-target semantics without a separate ownership-status lookup. - When `gameSessionCommandId` is known, the read should also expose the later Game Session gameplay-command execution outcome instead of stopping at handoff-time admission, so operator diagnostics can stay on one handoff-history surface through local and remote gameplay execution tails. #### `CancelPendingWorkItemsForPluginVersion` @@ -656,15 +656,15 @@ Inputs: Outputs: - **Current live output:** instance-scoped schedule entries include the observed exact `scriptPatchVersion`/`scriptPinEpoch` pair and associated owner request identity; they remain a narrower projection because namespace, staleness, and full scheduler identity fields are target-only. -- **Target-state output:** instance-scoped schedule entries contain the exact `scriptPatchVersion` and `scriptPinEpoch`, `scriptId`, plugin owner metadata, persisted `playableStateNamespaceId` and resolved `playableStateScope`, `scheduleDefinitionId`, event type, cadence, scheduler priority tag, target-scope identity (`targetScopeType`, `targetScopeId`), binding priority/exclusivity flags, materialization status, due-point fields, observed runtime version id, the pin operation's `controlPlaneRequestId`, pin observation time, row timestamps, and the current owned runtime scope (`currentRuntimePlayableStateNamespaceId`, `currentRuntimeGameInstanceId`, `currentRuntimeRegionId`, `currentRuntimeRegionEpoch`) plus the current owned routing bundle (`currentRuntimePlayableStateScope`, `currentRuntimeWorldSlug`, `currentRuntimeRealmSlug`, `currentRuntimePointerVersion`) and stale-namespace/scope/routing signaling beside the persisted scheduler row evidence. +- **Target-state output:** instance-scoped schedule entries contain the exact `scriptPatchVersion` and `scriptPinEpoch`, `scriptId`, plugin owner metadata, persisted identity `playableStateNamespaceId` plus separately validated `playableStateScope` evidence, `scheduleDefinitionId`, event type, cadence, scheduler priority tag, target-scope identity (`targetScopeType`, `targetScopeId`), binding priority/exclusivity flags, materialization status, due-point fields, observed runtime version id, the pin operation's `controlPlaneRequestId`, pin observation time, row timestamps, and the current owned runtime scope (`currentRuntimePlayableStateNamespaceId`, `currentRuntimeGameInstanceId`, `currentRuntimeRegionId`, `currentRuntimeRegionEpoch`) plus the current owned routing bundle (`currentRuntimePlayableStateScope`, `currentRuntimeWorldSlug`, `currentRuntimeRealmSlug`, `currentRuntimePointerVersion`) and stale-namespace/scope/routing signaling beside the persisted scheduler row evidence. Contract rules: - This is a read-only operator/debugging surface for the first durable scheduler substrate below Redis timer indexes. - The live implementation must report tick-aligned schedules honestly as not-yet-advanced when no heartbeat-derived due point exists; it must not invent synthetic tick coordinates. -- Reconciliation across repins is keyed by stable `scheduleDefinitionId` plus plugin owner metadata and binding target identity, not by inferred semantic similarity. +- Reconciliation across repins uses the canonical stable continuity key `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}`. Plugin ownership and binding metadata must resolve to and exact-match that complete immutable schedule identity; `scheduleDefinitionId` alone, a semantic similarity inference, or a binding without the namespace cannot select continuity. - The read must also expose the current owned runtime scope from Game Session when the instance still exists so operators can tell directly whether persisted scheduler scope has gone stale without a second runtime-state lookup. -- `playableStateNamespaceId` is immutable non-identity scope evidence, not a schedule, trigger, or command identity field. Missing or mismatched namespace evidence fails closed during materialization, due-candidate claim, retry, and reconciliation and remains visible on this read rather than being inferred or refreshed. +- **Target-state contract:** `playableStateNamespaceId` is the immutable playable-state identity/allocation dimension for applicable schedule, trigger, and command identities; `playableStateScope` remains separately persisted, exact-validated policy/routing/authorization/migration-fence evidence. Missing or mismatched namespace or scope evidence fails closed during materialization, due-candidate claim, retry, and reconciliation and remains visible on this read rather than being inferred or refreshed. See the [canonical Trigger Identity and Command-Handoff Identity tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). #### `ListScriptTimerAuditEvents` @@ -690,7 +690,7 @@ Contract rules: - The live implementation is sourced from durable `script_event_audit` rows, not reconstructed from metrics or volatile queue indexes. - The current implementation exposes both timer-fired work that reached durable work-item persistence and scheduler candidate decisions persisted as `SCHEDULE_DROPPED` through this read. In target state, the separate scheduler candidate-audit surface is authoritative for append-only candidate history; current `script_event_audit` rows must not be interpreted as that target surface. - The read must also expose the current owned runtime scope from Game Session when the instance still exists so operators can distinguish stale timer history from current-timeline timer activity without a second runtime-state lookup. -- Timer audit retains `playableStateNamespaceId` as the namespace evidence validated at claim/admission time. Missing or mismatched namespace evidence fails closed before firing and is never repaired by a current-owner read. +- **Target-state contract:** Timer audit retains `playableStateNamespaceId` as the identity field and `playableStateScope` as separately validated evidence from claim/admission time. Missing or mismatched namespace or scope evidence fails closed before firing and is never repaired by a current-owner read; the current output remains the narrower projection described above. #### `ListScriptDeadLetters` @@ -742,7 +742,7 @@ Contract rules: - Replay is fail-closed per work item. Eligibility requires exact current `(scriptPatchVersion, scriptPinEpoch)`, applicable plugin identity/version/binding and captured `(pluginActivationEpoch, lifecycleRevision)`, region/`regionEpoch`, and routing-bundle match to the immutable admitted evidence. For plugin work, the current scoped plugin activation/lifecycle, component-policy decision, capability-grant evidence, and signer/publication evidence must also be fresh and valid. - After exact-request idempotency and current `failureGeneration` resolution, immutable successful-recovery evidence bound to that same current generation returns `outcome=already_recovered` before aggregate-status or active-claim checks; `recovery_in_progress` applies only when no same-generation successful-recovery evidence exists and an active claim remains. After that precedence check, retained evidence proving that the selected parent's recovery inputs were purged—including `descriptorEvidencePurgedAt` for an `EVALUATED_COMMITTED` parent or the retained purge outcome for a pre-DSL row—returns `outcome=rejected` with `rejectionReason=stage_evidence_unavailable` and creates no claim/attempt. Using that internal identity, recovery compares-and-sets the current parent recovery aggregate `status=DEAD_LETTERED` together with a persisted recovery claim/attempt record containing `(tenantId, outboxWorkItemId, failureGeneration)`, the expected exact `(scriptPatchVersion, scriptPinEpoch)`, runtime scope, applicable plugin binding tuple and captured `(pluginActivationEpoch, lifecycleRevision)`, and `controlPlaneRequestId`, before evaluation or dispatch. A post-evaluation parent may retain its `EVALUATED_COMMITTED` descriptor marker and complete output/child ledger while this separate recovery aggregate is `DEAD_LETTERED`; that is the eligible `resumed_dispatch` case. A selected row in any other aggregate status remains unchanged and returns `outcome=rejected` with `rejectionReason=work_item_not_dead_lettered`. If a different `controlPlaneRequestId` targets a row with an active `IN_PROGRESS` claim for that generation, its stored deterministic request result is `outcome=rejected` with `rejectionReason=recovery_in_progress` and it creates no new claim/attempt, evaluation, or dispatch. If a created claim/attempt reaches terminal `FAILED`, its stored request result is `outcome=recovery_failed` with a required, bounded failureReason and no `rejectionReason`; an exact retry returns that stored result and reason without a new attempt. An expired claim is reclaimed under the same attempt record and identity (with a new owner fence when needed), never by inserting a duplicate recovery attempt or audit record; lease expiry alone does not allow a different request to create an attempt. A later new request may create one new attempt only after the prior attempt is terminal `FAILED` and fresh eligibility/fence checks pass. A prior successful recovery generation remains immutable; it is not `already_recovered` evidence for a newer current failure generation. -- Evaluation-stage recovery uses the frozen original trigger/input manifest and exact graph, preserving the original work-item and `scriptEventId` identity; before its winning evaluated-descriptor/outbox commit it allocates no dispatch or command-child identity. If it emits commands, that first atomic descriptor commit allocates and persists the `automationDispatchId` and deterministic ordinals; retries after a winning commit reuse them. A valid zero-command evaluation creates no dispatch identity. It may invoke the DSL evaluator again for eligible gameplay/runtime work outside normal admission. Tenant-readiness `onLoad` remains at-most-once and is excluded from evaluation replay. Post-evaluation recovery uses only the immutable evaluated output and complete child-dispatch ledger keyed by the full Command-Handoff Identity, preserving original child identities and per-child recovery state without invoking the DSL. `HANDED_OFF` (accepted), `CANCELED`, and `DEAD_LETTERED` children are terminal and no-op. An already `HANDOFF_IN_FLIGHT` child is fenced and reconciled against the durable downstream outcome, never blindly redispatched; if that outcome is ambiguous, the child remains active/unresolved, the same recovery attempt remains `IN_PROGRESS`, no temporary or terminal per-row application result is stored, and `resumed_dispatch` is not reported. The initiating request or an exact retry attaches to that same attempt until a terminal result is available or its transport deadline expires; a transport deadline does not store a different result. Immediately before evaluation, and immediately before each post-evaluation dispatch, it revalidates the immutable admitted source runtime scope `(tenantId, gameInstanceId, playableStateScope, regionId, regionEpoch)`, optional distinct target runtime scope `(targetGameInstanceId, targetPlayableStateScope, targetRegionId, targetRegionEpoch)`, exact `(scriptPatchVersion, scriptPinEpoch)`, and admitted routing bundle `(playableStateScope, worldSlug, realmSlug, pointerVersion)`, together with the recorded binding, captured `(pluginActivationEpoch, lifecycleRevision)`, and current scoped plugin activation/lifecycle, component-policy, capability-grant, and signer/publication evidence. For any revocable component, the retained component-revocation security-policy fence is independently revalidated at evaluation, each post-evaluation dispatch, and immediately before gameplay effects; it is not substituted by lifecycle or ordinary component-policy evidence. `DRAINING` blocks new trigger admission but does not invalidate already-admitted recovery; only a lifecycle transition that invalidates admitted work, such as `DISABLED`, revocation, or policy-driven disablement, uses `plugin_disabled`. Only after that dispatch-time revalidation succeeds may a `PENDING` or `INDEXED` child transition by durable compare-and-set to `HANDOFF_IN_FLIGHT` under the existing recovery claim/attempt fence and dispatch. Missing, stale, or temporarily unavailable evidence fails closed with the applicable established bounded reason (`authority_unavailable`, `component_policy_unavailable`, or `signer_policy_unavailable`); proven publication, component/capability, signer, tuple, epoch, or scope mismatches use `plugin_version_not_published`, `plugin_component_policy_blocked`, `signer_revoked`, `plugin_binding_mismatch`, `plugin_activation_epoch_mismatch`, `script_pin_epoch_mismatch`, or `runtime_scope_mismatch` as applicable. A `lifecycleRevision` mismatch outside the bounded `DRAINING` predecessor exception uses `plugin_binding_mismatch`; `plugin_disabled` remains reserved for an invalidating lifecycle transition. It never resolves a latest/local graph, and never regenerates an output after a child was accepted. +- Evaluation-stage recovery uses the frozen original trigger/input manifest and exact graph, preserving the original work-item and `scriptEventId` identity; before its winning evaluated-descriptor/outbox commit it allocates no dispatch or command-child identity. If it emits commands, that first atomic descriptor commit allocates and persists the `automationDispatchId` and deterministic ordinals; retries after a winning commit reuse them. A valid zero-command evaluation creates no dispatch identity. It may invoke the DSL evaluator again for eligible gameplay/runtime work outside normal admission. Tenant-readiness `onLoad` remains at-most-once and is excluded from evaluation replay. Post-evaluation recovery uses only the immutable evaluated output and complete child-dispatch ledger keyed by the full Command-Handoff Identity, preserving original child identities and per-child recovery state without invoking the DSL. `HANDED_OFF` (accepted), `CANCELED`, and `DEAD_LETTERED` children are terminal and no-op. An already `HANDOFF_IN_FLIGHT` child is fenced and reconciled against the durable downstream outcome, never blindly redispatched; if that outcome is ambiguous, the child remains active/unresolved, the same recovery attempt remains `IN_PROGRESS`, no temporary or terminal per-row application result is stored, and `resumed_dispatch` is not reported. The initiating request or an exact retry attaches to that same attempt until a terminal result is available or its transport deadline expires; a transport deadline does not store a different result. Immediately before evaluation, and immediately before each post-evaluation dispatch, it revalidates the immutable admitted source runtime identity `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch)`, optional distinct target runtime identity `(targetGameInstanceId, targetPlayableStateNamespaceId, targetRegionId, targetRegionEpoch)`, separately validated source/target `playableStateScope` routing/fence evidence, exact `(scriptPatchVersion, scriptPinEpoch)`, and the immutable admitted source routing bundle `(playableStateScope, worldSlug, realmSlug, pointerVersion)`; when the target is distinct, recovery also persists and exact-compares the target bundle `(targetPlayableStateScope, targetWorldSlug, targetRealmSlug, targetPointerVersion)` against that same target. Together with the recorded binding, captured `(pluginActivationEpoch, lifecycleRevision)`, and current scoped plugin activation/lifecycle, component-policy, capability-grant, and signer/publication evidence, these checks preserve the source bundle and same-target semantics. For any revocable component, the retained component-revocation security-policy fence is independently revalidated at evaluation, each post-evaluation dispatch, and immediately before gameplay effects; it is not substituted by lifecycle or ordinary component-policy evidence. `DRAINING` blocks new trigger admission but does not invalidate already-admitted recovery; only a lifecycle transition that invalidates admitted work, such as `DISABLED`, revocation, or policy-driven disablement, uses `plugin_disabled`. Only after that dispatch-time revalidation succeeds may a `PENDING` or `INDEXED` child transition by durable compare-and-set to `HANDOFF_IN_FLIGHT` under the existing recovery claim/attempt fence and dispatch. Missing, stale, or temporarily unavailable evidence fails closed with the applicable established bounded reason (`authority_unavailable`, `component_policy_unavailable`, or `signer_policy_unavailable`); proven publication, component/capability, signer, tuple, epoch, or scope mismatches use `plugin_version_not_published`, `plugin_component_policy_blocked`, `signer_revoked`, `plugin_binding_mismatch`, `plugin_activation_epoch_mismatch`, `script_pin_epoch_mismatch`, or `runtime_scope_mismatch` as applicable. A `lifecycleRevision` mismatch outside the bounded `DRAINING` predecessor exception uses `plugin_binding_mismatch`; `plugin_disabled` remains reserved for an invalidating lifecycle transition. It never resolves a latest/local graph, and never regenerates an output after a child was accepted. - Before claim acquisition, a committed lifecycle invalidation wins as `plugin_disabled`; when no such invalidation is committed, a directly proven signer or component-policy failure uses `signer_revoked` or `plugin_component_policy_blocked`, respectively. Rows with missing/contradictory stage evidence or any fence mismatch discovered before claim acquisition remain `DEAD_LETTERED` and return a deterministic per-row `outcome=rejected` with the applicable bounded `rejectionReason`, with no claim/attempt. If the same evidence failure occurs after a claim/attempt exists, the first failing stage's bounded `failureReason` is persisted and that attempt terminalizes as `FAILED`; later lifecycle changes do not rewrite it. The attempt returns/stores `outcome=recovery_failed` with no `rejectionReason`; an exact retry returns the stored deterministic result. A rejected row is not partially changed or counted as successful. - The request is bounded and idempotent by `controlPlaneRequestId`, actor, reason, and explicit work-item IDs. An exact retry of the same `controlPlaneRequestId` and canonical request fingerprint returns the identical stored per-row outcomes and stored generation, including `recovery_failed` with its stored `failureReason` or `rejected`, without evaluation, dispatch, or relabeling. Reusing a `controlPlaneRequestId` with a changed canonical request fingerprint is a request-level conflict detected before claim acquisition, evaluation, or dispatch; it cannot alter stored per-row results and is not represented as a per-row rejection. A new request that finds the current generation already recovered returns `outcome=already_recovered`; older-generation success does not block recovery of the current generation. No new Trigger Identity is introduced; a Command-Handoff Identity can first be allocated only by the winning descriptor commit, and later recovery never creates a second one. Purge is a separate operation and never masquerades as recovery. diff --git a/design/architecture/system-architecture-scripting-control-plane-operations.md b/design/architecture/system-architecture-scripting-control-plane-operations.md index e0962c9044..38f19eb885 100644 --- a/design/architecture/system-architecture-scripting-control-plane-operations.md +++ b/design/architecture/system-architecture-scripting-control-plane-operations.md @@ -259,7 +259,7 @@ Semantics: - `reason` is required and must be non-blank; Game Session validates it before reading the owned instance or purging queue or durable command state. - Idempotent. -- Under the shared queue mutation/tick lease, terminal-marks matching durable Game Session command rows before post-commit Redis queue/pending cleanup. Pre-batch commands use `executionOutcome = LOST_BEFORE_STAGING`; an explicitly retryable command with a durable prior tick-effect binding uses `executionOutcome = ABANDONED`. Both use `gameplayResult = NOT_APPLIED`, `failureCode = ROLLBACK_PURGED`, and the validated nonblank ingress `reason` as `failureMessage`. +- Under the shared queue mutation/tick lease, terminal-marks matching durable Game Session command rows before post-commit Redis queue/pending cleanup. `executionOutcome = LOST_BEFORE_STAGING` applies only to commands acknowledged `ACCEPTED_VOLATILE` whose ingress status is still `RECEIVED` or `ENQUEUED` and that have no surviving batch; `ACCEPTED_DURABLE` pre-batch work cannot use this outcome and remains under its durable retry/recovery contract. An explicitly retryable command with a durable prior tick-effect binding uses `executionOutcome = ABANDONED`. Both use `gameplayResult = NOT_APPLIED`, `failureCode = ROLLBACK_PURGED`, and the validated nonblank ingress `reason` as `failureMessage`. - Batch-bound work that is not in the explicit retry queue is not purged through this hook; it requires effect-ledger remediation or rollback recovery because it has crossed the tick-batch boundary. - Emits an operator-visible metric for purge activity and for version-fence drops; exact metric names, labels, and increment units follow [Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix), while audit and handoff diagnostics follow the observability contract. @@ -284,7 +284,7 @@ Inputs: `reason` is required and must be non-blank; Game Session validates it before reading the owned instance or purging queue/durable command state. -Semantics and outputs: same as `PurgeQueuedTickCommandsForScriptPatch`, including the pre-batch `LOST_BEFORE_STAGING` versus durably batch-bound retry `ABANDONED` outcome split, `gameplayResult = NOT_APPLIED`, `failureCode = ROLLBACK_PURGED`, and the validated nonblank ingress `reason` as `failureMessage`, scoped to plugin-produced commands by the `pluginId` and `pluginVersionId` provenance carried from Automation into Game Session during handoff. +Semantics and outputs: same as `PurgeQueuedTickCommandsForScriptPatch`, including `LOST_BEFORE_STAGING` only for commands acknowledged `ACCEPTED_VOLATILE` that remain `RECEIVED` or `ENQUEUED` with no surviving batch, while `ACCEPTED_DURABLE` pre-batch work remains under its durable retry/recovery contract; durably batch-bound retry uses `ABANDONED`. Both outcomes use `gameplayResult = NOT_APPLIED`, `failureCode = ROLLBACK_PURGED`, and the validated nonblank ingress `reason` as `failureMessage`, scoped to plugin-produced commands by the `pluginId` and `pluginVersionId` provenance carried from Automation into Game Session during handoff. ### Automation & Scripting: Drain/Purge Hooks (Rollback Support) diff --git a/design/architecture/system-architecture-scripting-dsl-for-designers.md b/design/architecture/system-architecture-scripting-dsl-for-designers.md index 579675848b..715d031fdd 100644 --- a/design/architecture/system-architecture-scripting-dsl-for-designers.md +++ b/design/architecture/system-architecture-scripting-dsl-for-designers.md @@ -175,7 +175,7 @@ The platform performs **extensive validation** at design time and at publish tim - For **editor-time issues**, fix the graph based on validation errors in the Game Design Service UI and re-run validation before publishing. - For **runtime issues**, start from the script’s recent entries in `script_event_audit` and the associated metrics in `design/architecture/system-architecture-scripting-quotas-and-operations.md`, then adjust quotas or disable/throttle the script using the operational flows described there. - For **safe test runs**, the ADR 0114 command-plan preview endpoint is the target-state path for the Game Design / Logging & Admin UIs. Its current implementation boundary is summarized in [Implementation Status](#implementation-status). Once implemented, it will be a separate non-committing path that exercises the same sandbox and validation logic without live work or tick-queue handoff. Test tools are **privileged** and subject to their own rate limits and budgets so they cannot overload the scripting cluster; avoid running unbounded batches of previews against production tenants. - - When working with support or operators, you can use `scriptEventId` as a “debug ticket” for a single trigger, but never use it alone. The ticket must carry the complete applicable [Trigger Identity](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). Base fields are `tenantId`, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptEventId`, and `isDryRun`; gameplay/runtime triggers additionally carry `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `entityId`; resolved plugin handlers additionally carry `pluginId`, `pluginVersionId`, and `bindingId`; scheduler triggers additionally carry `triggerMode`, `scheduleDefinitionId`, `targetScopeType`/`targetScopeId`, plus exactly one applicable due point (`dueTickId` or `dueAt`). Tenant-readiness `onLoad` tickets explicitly omit `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `entityId` because they are not tied to a running gameplay instance. Include command-level `outboxWorkItemId`, `automationDispatchId`, and `commandOrdinal` when a handoff child is in scope; those command-level fields are target-state until the Game Session handoff carries them end to end. + - When working with support or operators, use `scriptEventId` as a correlation ticket at the correct lifecycle layer after the applicable ingress has validated a supplied ID or allocated one, never by itself. A pre-resolution event-scope ticket or ingress-audit record carries the applicable fields available at that layer: `tenantId`, `eventType`, `eventSchemaVersion`, `isDryRun`, the exact `scriptPatchVersion`/`scriptPinEpoch` pair only after authoritative pin evidence is available, `scriptEventId` after the event-scope claim validates a supplied ID or allocates one, and, for gameplay/runtime events, `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, and `regionEpoch`; it also carries producer-derived `sourceService` where applicable. A fail-closed pre-admission audit retains any caller-supplied `scriptPatchVersion`/`scriptPinEpoch` only in explicitly marked unverified request-evidence fields on the existing ingress-audit surface, never as canonical ingress identity or exact pin evidence; it also retains a caller-supplied `scriptEventId` once the event-scope claim has validated it, including on a pre-handler denial. An unfired internally owned timer due candidate, including a `reload_failed` candidate, creates no `scriptEventId` and instead carries its event-scope `scheduleCandidateId`. The ticket does not invent ordinary handler-resolution fields. Owner-known exceptions are tenant-readiness `onLoad`, which includes its `scriptId`, and scheduler/timer candidates, which include schedule-owned `scriptId`, plugin provenance `(pluginId, pluginVersionId, bindingId)` when the durable schedule already owns that binding, and `pluginActivationEpoch` for plugin-owned candidate identity; `resumeWindowId` appears for `CATCH_UP` candidates, while captured `lifecycleRevision` travels as non-identity fence evidence. These are candidate/event identity fields, not resolved handler fields. After handler resolution, the ticket carries the complete applicable [Trigger Identity](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields), including `entityId` when entity-scoped and the resolved plugin/binding fields. Scheduler triggers additionally carry `triggerMode`, `scheduleDefinitionId`, `targetScopeType`/`targetScopeId`, plus exactly one applicable due point (`dueTickId` or `dueAt`). Tenant-readiness `onLoad` tickets explicitly omit `scriptPinEpoch`, `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `entityId` because they are pre-instance readiness work. Include command-level `outboxWorkItemId`, `automationDispatchId`, and `commandOrdinal` when a handoff child is in scope; those command-level fields are target-state until the Game Session handoff carries them end to end. The Game Design and Logging & Admin audit/log views (for example `script_event_audit` queries and trace/log search) should support filtering by these fields so a single trigger can be followed end-to-end without ambiguity. Use the `AS-1.1` and `AS-1.5` entries in the [automation and scheduler runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status) to distinguish the live identity/read surfaces from target-state command-handoff coverage. For the detailed loop safety algorithm and runtime budget enforcement, see: @@ -208,7 +208,7 @@ Recurring and advisory timer handlers such as `onInterval` (or an advisory `onTi - Each authored timer declares its clock and recovery class. Tick/game time is the only default clock; no recovery class is inferred by default. Recurring timers explicitly select one recovery policy: `SKIP_MISSED` advances to the next valid future occurrence without firing missed occurrences, while `COALESCE_ONE` permits one bounded synthetic firing for missed time. A correctness-bearing one-shot explicitly selects the correctness-bearing one-shot class. See the [canonical timer semantics matrix](./system-architecture-scripting-normative-contract-tables.md#table-3-timer-semantics-matrix) for the recovery-class contract. - When a recurring or advisory timer becomes due, the scheduler tries to fire it subject to per-script quotas, per-tenant budgets, and cluster ceilings. Under heavy load or when limits are reached, individual firings may be **skipped** and are not automatically replayed later, even if the timer continues to run at its configured cadence. -- After downtime or leader failover, a recurring `COALESCE_ONE` timer may emit at most one coalesced firing for each complete stable schedule-instance identity in one Automation-owned durable `resumeWindowId` identified by ``; it never replays one firing per cadence boundary. Same-window retries and takeovers reuse that mode-specific ID, while a later recovery episode receives a new generation only after the prior window's selected and cap-excluded outcomes are durable. The tenant-local `SCRIPT_TIMER_CATCH_UP_MAX_FIRINGS_PER_RESUME` cap is evaluated separately inside each such full runtime-scope-and-mode `resumeWindowId` (that one-tenant, one-mode ID): tenant-local describes the window's tenant owner, not a tenant-wide pool, so a schedule in another game instance, playable-state scope, region, or epoch cannot consume this window's cap. Selected candidates still pass through tenant-first shared scheduler/cluster admission; a tenant or cluster capacity denial is a durable terminal skip for that catch-up candidate and is not retried, deferred, backfilled, or reminted, while its next ordinary future cadence remains eligible. Candidates excluded by the catch-up cap are likewise dropped and audited rather than deferred as an unbounded backlog. Recurring `SKIP_MISSED` timers emit no catch-up firing. +- After downtime or leader failover, a recurring `COALESCE_ONE` timer may emit at most one coalesced firing for each complete stable schedule-instance identity in one Automation-owned durable `resumeWindowId` identified by ``; the server-derived `playableStateScope` is retained as immutable policy/routing/authorization/fence evidence and is exact-validated alongside that identity. It never replays one firing per cadence boundary. Same-window retries and takeovers reuse that mode-specific ID, while a later recovery episode receives a new generation only after the prior window's selected and cap-excluded outcomes are durable. The tenant-local `SCRIPT_TIMER_CATCH_UP_MAX_FIRINGS_PER_RESUME` cap is evaluated separately inside each such full runtime-identity-and-mode `resumeWindowId` (that one-tenant, one-mode ID): tenant-local describes the window's tenant owner, not a tenant-wide pool, so a schedule in another game instance, playable-state namespace, region, or epoch cannot consume this window's cap. Selected candidates still pass through tenant-first shared scheduler/cluster admission; a tenant or cluster capacity denial is a durable terminal skip for that catch-up candidate and is not retried, deferred, backfilled, or reminted, while its next ordinary future cadence remains eligible. Candidates excluded by the catch-up cap are likewise dropped and audited rather than deferred as an unbounded backlog. Recurring `SKIP_MISSED` timers emit no catch-up firing. - Infrastructure hiccups (for example, Redis or gRPC outages) do not promise that a recurring or advisory cadence firing will eventually run. Before the `EVALUATED_COMMITTED` descriptor-commit boundary, an admitted evaluation may rerun only under the same full Trigger Identity and must converge on the same durable work-item and child identities. After `EVALUATED_COMMITTED`, recovery replays durable descriptors and never re-enters the DSL; the audit `finalStage` and outcome remain tied to the last confirmed durable stage. Correctness-bearing one-shot timers instead retry or terminalize under their durable intent identity and must not duplicate the effect. - As a result, recurring timer callbacks should be treated as **bounded scheduling signals**, not per-cadence ledgers. Design timer handlers so they can tolerate missed or delayed firings and recompute from current world state instead of assuming that every interval has executed exactly once. 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 8d9f33b295..e278b1595d 100644 --- a/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md +++ b/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md @@ -62,8 +62,8 @@ For designer-oriented guidance on building and debugging scripts in the visual e ## Terminology Glossary -- **`{tenantRegionTag}` hash tag** – an opaque placeholder produced by shared Redis key builders from the complete `` scope documented in [Redis Architecture](./system-architecture-redis.md#key-naming-and-shard-discipline). It exists for shard locality across region-scoped keys; it is not a replacement for those identity fields and does not define a competing schedule or tenant key family. `playableStateScope` is intentionally not part of this existing tag topology; it remains in durable Trigger Identity and command/effect identity and must not be inferred from the tag. -- **`{tenantInstanceTag}` hash tag** – an opaque placeholder produced by shared Redis key builders from ``. It scopes instance-wide automation projections and cross-region coordination hints such as `automation:queue:{tenantInstanceTag}:` and `remote:{tenantInstanceTag}:`; it must not be substituted for the region-scoped `{tenantRegionTag}` where a region timeline or lease fence applies. +- **`{tenantRegionTag}` hash tag** – an opaque placeholder produced by shared Redis key builders from the complete `` scope documented in [Redis Architecture](./system-architecture-redis.md#key-naming-and-shard-discipline). It exists for shard locality across region-scoped keys; it is not a replacement for those identity fields and does not define a competing schedule or tenant key family. `playableStateScope` is intentionally not part of this existing tag topology; durable Trigger, scheduler, and command-handoff identities use `playableStateNamespaceId`, while scope remains immutable policy/routing/authorization/fence evidence and must not be inferred from the tag. Downstream mutation guards exact-validate applicable namespace/scope evidence separately from their own effect-guard uniqueness. +- **`{tenantInstanceTag}` hash tag** – an opaque placeholder produced by shared Redis key builders from ``. It scopes instance-wide automation projections: `automation:queue:{tenantInstanceTag}:` is a Cache/Rate-Limit disposable dispatch-pointer index rebuilt from eligible durable pre-DSL records, while `remote:{tenantInstanceTag}:` is a separate Coordination Redis wake-up hint. The tag must not be substituted for the region-scoped `{tenantRegionTag}` where a region timeline or lease fence applies. - **Game tick** – a region-scoped tick in the Game Session Service. Each `` advances through a monotonic `tickId` stream; game ticks are authoritative for gameplay state changes and use `tick:{tenantRegionTag}:...` keys and locks as described in [Tick System and Runtime Design](./system-architecture-ticks.md). - **Automation execution loop** – the durable executor path inside the Automation & Scripting Service. **Target state:** it claims committed descriptor children under a durable parent work item, evaluates no DSL again, and hands resulting commands to the Game Session Service so Game Session can enqueue **tick commands** into per-entity tick queues for later execution by game ticks. **Current implementation:** the scheduled queue-rebuild hook/configuration has been removed/disabled; the executor drains derived pointers and its durable claim filters to `PENDING_EVALUATION`, so `EVALUATING` pointers are not picked up, reclaimed, or re-entered into the DSL. Because there is no stale-owner/CAS recovery, queue reset/rebuild/resume remains unavailable and must fail closed; see [Scripting Runtime Execution: Current Queue-Rebuild Concurrency Gap](./system-architecture-scripting-runtime-execution.md#current-queue-rebuild-concurrency-gap). Atomic owner-reconciled recovery of safe post-DSL `PENDING` work is target-only. - **Automation queue** – an instance-aware, per-entity Redis queue (`automation:queue:{tenantInstanceTag}:`) that currently holds **derived pre-DSL parent-work indexes/pointers** for `PENDING_EVALUATION` and `EVALUATING` work, not an authoritative log of pending work. `PENDING_EVALUATION` pointers can be claimed for evaluation; `EVALUATING` pointers are inspection-only and cannot be picked up, reclaimed, or re-enter the DSL. The former rebuild hook/configuration is removed/disabled; queue reset/rebuild/resume remains unavailable and must fail closed. See [Scripting Runtime Execution: Current Queue-Rebuild Concurrency Gap](./system-architecture-scripting-runtime-execution.md#current-queue-rebuild-concurrency-gap). Target post-DSL descriptor recovery uses separate `PENDING`/`INDEXED` states and atomic owner-reconciled recovery of safe work; it is not implemented. @@ -184,7 +184,7 @@ Concrete supersession example: Implementers should treat explicit continuity declarations plus the stable logical key as the canonical answer to "should this schedule continue?" `scheduleDefinitionId` alone is not sufficient: -- If patch `P21` contains a patrol interval with stable key `{SCRIPT, patrol, patrol.main.v1, ENTITY, guard-9}` and patch `P22` declares compatible continuity for that same key, the scheduler may preserve the row only after validating the prior `(scriptPatchVersion, scriptPinEpoch)` tuple and the exact target tuple, `source.isDryRun == target.isDryRun`, and typed cadence, interval-kind, target-binding, and playable-scope checks. It rewrites ownership, persists the target patch provenance and exact epoch, and applies the normative resume calculation before admission resumes; continuity does not require source and target tuples to be equal, and `scheduleSemanticsHash` is diagnostic evidence only. +- If patch `P21` contains a patrol interval with stable key `{SCRIPT, patrol, patrol.main.v1, playableStateNamespaceId, ENTITY, guard-9}` and patch `P22` declares compatible continuity for that same key, the scheduler may preserve the row only after validating the prior `(scriptPatchVersion, scriptPinEpoch)` tuple and the exact target tuple, `source.isDryRun == target.isDryRun`, and typed cadence, interval-kind, target-binding, and playable-scope checks. It rewrites ownership, persists the target patch provenance and exact epoch, and applies the normative resume calculation before admission resumes; continuity does not require source and target tuples to be equal, and `scheduleSemanticsHash` is diagnostic evidence only. - If either side omits continuity, explicitly resets it, changes the key/cadence/target, or authoritative reconciliation proves the target schedule absent, the scheduler atomically retires/tombstones P21, terminalizes any proven-displaced candidate under its original identity, and creates no P22 row, due state, firing claim, or `scriptEventId`. If target-definition or other required authority is unavailable, contradictory, or ambiguous, it retains P21 and its candidates/claims fenced and nonterminal; it does not tombstone or create replacement state until reconciliation. When a validated target definition exists on the reset/incompatible path, it creates P22 with fresh due state. A distinct combat-alert timer uses a new key and fresh state. - Rollback applies exactly the same opt-in matrix. A matching `scheduleDefinitionId` or historical similarity never carries due state by itself, and a one-shot timer is not migrated by this interval rule. @@ -226,7 +226,7 @@ A coalesced core script receives one execution manifest assembled from the retai Governance requirements for ordering overrides and exclusivity: - Ordering policy overrides (`PLUGIN` ahead of `SCRIPT`) are operator-controlled policy, not designer-level script metadata. -- At most one binding in the complete resolved set for the full applicable event/Trigger scope may set `requiresExclusiveEvent=true`. For instance-bound events, that scope includes `tenantId`, `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, the concrete target identity, `eventType`, and `eventSchemaVersion` as applicable, plus the derived `sourceService` for custom or service-specific events; tenant-readiness `onLoad` uses its pre-instance-pin scope and intentionally omits instance, playable-state, region, and entity fields. Game Design validates publish-time-known conflicts and Automation revalidates the complete base-script plus active-plugin set at activation. Multiple or unauthorized exclusive claims fail closed; runtime does not select one by sort order. +- At most one binding in the complete resolved set for the full applicable event/Trigger scope may set `requiresExclusiveEvent=true`. For instance-bound events, that uniqueness scope includes `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`, the concrete target identity, `eventType`, and `eventSchemaVersion` as applicable, plus the derived `sourceService` for custom or service-specific events; the server-derived `playableStateScope` is retained and exact-validated as immutable policy/routing/authorization/fence evidence, not as a uniqueness discriminator. Tenant-readiness `onLoad` uses its pre-instance-pin scope and intentionally omits instance, playable-state namespace/scope, region, and entity fields. Game Design validates publish-time-known conflicts and Automation revalidates the complete base-script plus active-plugin set at activation. Multiple or unauthorized exclusive claims fail closed; runtime does not select one by sort order. - Plugin bindings are non-exclusive by default. Granting plugin exclusivity requires explicit operator authorization and audit evidence bound to the plugin version, binding, target policy scope, and granting actor. - `orderIndex` and `handlerSequence` define semantic effect order. Operational `priorityTag`, quota tiers, and capacity policy may affect execution timing but must not reorder final command application. - Admission records must include explicit, bounded reasons when exclusivity policy blocks a binding so operators can distinguish policy denial from quota/sandbox failures. @@ -238,7 +238,7 @@ Governance requirements for ordering overrides and exclusivity: Domain services can define **custom events** that feed into the scripting pipeline: - The visual DSL exposes event source nodes for any event types enabled for the current game. Under the hood, bindings are stored as ``. -- Service-specific events follow the same trigger → DSL run → automation queue → tick command flow as built-in events. +- Service-specific events follow the same pre-DSL trigger/outbox → DSL run → durable descriptor/outbox → tick command flow as built-in events; the Redis automation queue remains only a derived pointer to the pre-DSL trigger record. - Event schemas are versioned so scripts can be migrated when payloads change. Custom events must follow the same determinism and idempotency rules as built-in events; the applicable identity and ingress requirements are defined in the [normative contract tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). @@ -355,7 +355,7 @@ The tenant lifecycle governs patch readiness and eligibility. The instance lifec Runtime execution must still remain **instance-aware** even though patch readiness is tenant-scoped: - A tenant-scoped `READY` state means a patch is eligible to be pinned by instances in that tenant; it does not imply that every running instance must pause, reload, or switch together. -- Admission, timer scheduling, and runtime work/effect fencing must evaluate the effective runtime scope as ``, even if implementations batch internal work by tenant. Pin observation and pin convergence are instance-wide control-plane state carrying the exact `` tuple. Pin-transition admission pause for promotion and rollback is separate instance-wide control-plane state keyed by `` with the existing admission epoch as state/fence; the exact pin tuple is convergence and execution-fence evidence, not pause identity. Neither control-plane state splits by `playableStateScope`. Plugin activation/configuration remains materialized per ``; plugin trigger identity and plugin-owned derived schedule/work state still carry the effective `playableStateScope`. Region and epoch fields remain required for region/tick-aligned runtime timelines. +- Admission, timer scheduling, and runtime work/effect fencing must carry the complete runtime identity ``, even if implementations batch internal work by tenant. `playableStateScope` remains separately exact-validated immutable policy/routing/authorization/fence evidence rather than a durable identity field. A non-region tenant/control-plane event must use an existing non-gameplay branch; it must not fabricate sentinel region fields or use a gameplay/runtime Trigger Identity. Pin observation and pin convergence are instance-wide control-plane state carrying the exact `` tuple. Pin-transition admission pause for promotion and rollback is separate instance-wide control-plane state keyed by `` with the existing admission epoch as state/fence; the exact pin tuple is convergence and execution-fence evidence, not pause identity. Neither control-plane state splits by `playableStateScope`. Plugin activation/configuration remains materialized per ``; plugin trigger identity and plugin-owned derived schedule/work state carry `playableStateNamespaceId` as durable identity plus the effective `playableStateScope` as immutable fence evidence. Region and epoch fields remain required for gameplay/runtime timelines. - If a deployment wants stronger coupling, it must explicitly declare the invariant that all instances in a tenant share one exact pinned script tuple. Absent that declaration, instance isolation is the normative behavior. - Instance-scoped runtime state tracks **pin observation and pin-convergence control** for the exact tuple an instance is trying to run (for example `observedPinnedScriptPatchVersion`, `observedScriptPinEpoch`, `reloadState`, and convergence checkpoints). The separate admission, schedule, work, and effect fences apply the resolved `playableStateScope` and region/epoch to trigger-derived state. Instance pin state does **not** rerun tenant patch readiness or `onLoad`. - A single tenant-wide mutable `activePatchVersion` inside Automation & Scripting is therefore not sufficient. The service must keep tenant-scoped patch readiness separate from instance-scoped pin observation and scheduling state. @@ -366,8 +366,8 @@ Side-by-side lifecycle view: | --- | --- | --- | --- | --- | | Patch readiness | `` | Automation & Scripting | `PENDING_VALIDATION` -> `ONLOAD_RUNNING` -> `READY` / `FAILED`, terminal `SUPERSEDED` | Publish ingestion, static validation, tenant-scoped `onLoad`, newer accepted publish supersession | | Runtime pin observation | ``; current observed value/fence evidence is the exact `(scriptPatchVersion, scriptPinEpoch)` tuple | Game Session pin plus Automation observation | Observed exact tuple, `reloadState=RELOADING`, observed new tuple, `reloadState=FAILED`, scoped admission/convergence checkpoints | `SetPinnedScriptPatchVersion`, `RollbackScriptPatchVersion`, pin-change events, reload reconciliation, promotion and rollback pin-transition orchestration | -| Runtime admission, schedule, work, and effect fencing | `` | Automation and domain runtime owners | Admission, due-point, work-item, command, and effect fences | Resolved trigger scope, region ownership, epoch changes, reload/rollback barriers | -| Plugin activation | `` | Automation & Scripting runtime registry | Active, pending, draining, disabled plugin version state | Operator activation/disable/drain actions; plugin trigger-derived state retains `pluginVersionId`, `bindingId`, and `playableStateScope` | +| Runtime admission, schedule, work, and effect fencing | Complete `` runtime identity; `playableStateScope` is separate exact-validated fence evidence | Automation and domain runtime owners | Admission, due-point, work-item, command, and effect fences | Resolved trigger scope, region ownership, epoch changes, reload/rollback barriers | +| Plugin activation | `` | Automation & Scripting runtime registry | Active, pending, draining, disabled plugin version state | Operator activation/disable/drain actions; plugin trigger-derived state retains `pluginVersionId`, `bindingId`, `playableStateNamespaceId`, and immutable `playableStateScope` fence evidence | Interpretation rules: diff --git a/design/architecture/system-architecture-scripting-event-registry.md b/design/architecture/system-architecture-scripting-event-registry.md index 376a41d909..994009dde7 100644 --- a/design/architecture/system-architecture-scripting-event-registry.md +++ b/design/architecture/system-architecture-scripting-event-registry.md @@ -68,9 +68,9 @@ Required semantics for those fields: - The exact identity fields applicable to this event at each stage: the event-scope ingress subset before handler resolution and the full handler Trigger Identity after each handler resolves, as defined by the [normative identity tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). - Ordinary producer event-scope ingress must not require, fabricate, or use synthetic values for handler-only fields. In particular, `scriptId`, `pluginId`, `pluginVersionId`, and `bindingId` are unavailable before handler resolution; they become required only when the resolved handler's scope requires them. - Tenant-readiness `onLoad` is the deliberate exception for `scriptId`: its event-scope identity targets one script and includes that `scriptId` so Automation can derive the deterministic `scriptEventId` before handler resolution. This does not authorize fabricated runtime-ingress script IDs; `pluginId`, `pluginVersionId`, and `bindingId` remain post-resolution fields. - - Scheduler/timer due candidates are another deliberate pre-handler exception: because Automation already materialized a durable schedule with its owner identity, the scheduler firing identity and deterministic event-scope `scriptEventId` include the schedule-owned `scriptId`, any schedule-owned `pluginId`, `pluginVersionId`, and `bindingId`, and the exact Game Session `scriptPatchVersion` and positive `scriptPinEpoch`. For plugin-owned schedules, the target candidate/firing identity additionally carries the captured `pluginActivationEpoch`; the paired `lifecycleRevision` travels with it as execution-fence evidence, and both are revalidated without becoming handler Trigger Identity fields. The paired nonblank `scriptPinControlPlaneRequestId` remains mandatory owner and fence evidence, is exact-compared for candidate/firing claims, and is propagated to durable rows and audits, but is excluded from candidate, firing, work-item claim, and uniqueness keys as well as from the derived `scriptEventId` and logical Trigger Identity. The scheduler must not fabricate a field absent from that schedule. This scheduler-owned exception does not authorize ordinary producer ingress to supply handler-only identity. **Target-state only:** the current registry/runtime path does not yet persist and propagate the plugin lifecycle pair through every required boundary, so current plugin ingress must not be described as proving this fence. - - For gameplay-originated events, the producer must resolve shared-versus-isolated realm state before making the gameplay/runtime event-scope claim or attempting durable admission. This set must then include the resolved `playableStateScope` so durable ingress/work-item identity, timer follow-up work, and operator read models do not collapse distinct playable-state namespaces that happen to share the same tenant and instance identifiers; missing or unspecified scope fails closed. - - **Target-state exact-fence requirement:** For gameplay/runtime and scheduler events, durable admission evidence must include the exact Game Session `scriptPatchVersion`, `scriptPinEpoch`, and paired owner `scriptPinControlPlaneRequestId`; a version-only or partial tuple is incomplete and cannot be admitted after a repin. The owner request ID is evidence/correlation, not a third logical Trigger Identity component. + - Scheduler/timer due candidates are another deliberate pre-handler exception: because Automation already materialized a durable schedule with its owner identity, the scheduler firing identity and deterministic event-scope `scriptEventId` include the schedule-owned `scriptId` and any schedule-owned `pluginId`, `pluginVersionId`, and `bindingId`; plugin-owned candidates also include the captured `pluginActivationEpoch`, and `CATCH_UP` candidates include `resumeWindowId`. The captured `lifecycleRevision` travels alongside as required non-identity fence evidence and is not included in candidate, firing-claim, or `scriptEventId` identity. For gameplay/runtime and scheduler candidates, the paired nonblank `scriptPinControlPlaneRequestId` is retained and exact-compared as owner/fence evidence, but is excluded from candidate, firing-claim, work-item, and derived event identity. The scheduler must not fabricate a field absent from that schedule. This scheduler-owned exception does not authorize ordinary producer ingress to supply handler-only identity. + - For every gameplay-originated event, this set must unconditionally include `playableStateNamespaceId` in the applicable gameplay/runtime identity, regardless of whether the realm is shared or isolated. The producer must resolve that namespace authoritatively before admission; a missing, unresolved, stale, or contradictory namespace fails closed. An explicitly declared non-gameplay contract may omit it only when the registry entry is classified outside gameplay/runtime and uses the non-gameplay Trigger Identity branch. `playableStateScope` remains separately persisted, exact-validated policy/routing/authorization/migration-fence evidence; it is excluded from Trigger Identity, event-scope, handoff, schedule, and other uniqueness/deduplication keys. See the [normative identity tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). + - **Target-state exact-fence requirement:** For gameplay/runtime and scheduler events, this set must include the exact Game Session `scriptPatchVersion` plus `scriptPinEpoch` and the paired owner request evidence; a version-only or partial tuple is incomplete and cannot be admitted after a repin. - `snapshotAuthority` - Declares the owner-specific input source used to seed the handler-scoped input manifest. Its values remain: - `PRODUCER_SUPPLIED_TOKEN` diff --git a/design/architecture/system-architecture-scripting-examples-and-patterns.md b/design/architecture/system-architecture-scripting-examples-and-patterns.md index 7b65868700..713f810152 100644 --- a/design/architecture/system-architecture-scripting-examples-and-patterns.md +++ b/design/architecture/system-architecture-scripting-examples-and-patterns.md @@ -48,7 +48,7 @@ This example walks through how a typical `onEnterRegion` script executes end-to- 2. **`onEnterRegion` event is emitted** - After the move is committed and the player is now in the new region, the Game Session Service emits an `onEnterRegion` **script event** to the Automation & Scripting Service over gRPC. - Conceptually this is a unary `TriggerScriptEvent` call on the Automation & Scripting Service that carries: - - `tenantId`, `gameInstanceId`, `playableStateScope`, and `regionId`. + - `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, and `regionId`; `playableStateScope` is carried separately as exact-validated policy/routing/authorization/migration-fence evidence, not as an identity field. - Target `entityId` (for example, an NPC guarding the room). - `eventType=onEnterRegion`. - The exact currently pinned `(scriptPatchVersion, scriptPinEpoch)` tuple for that game. @@ -69,9 +69,9 @@ This example walks through how a typical `onEnterRegion` script executes end-to- - Scheduling follow-up timers (for example, delayed emotes or encounter escalation). 5. **Automation queue staging** - - Actions produced by the handler are evaluated within its one durable parent work item. Target evaluation atomically reaches `EVALUATED_COMMITTED` with one immutable command descriptor/child-dispatch row per emitted command, after which committed descriptor children are indexed into `automation:queue:{tenantInstanceTag}:`; current implementation persists pre-DSL parent work and indexes only the derived parent pointer. - - The firing admission links the durable firing claim, one applicable resolved-handler audit row for every resolved handler, parent work items and queue-pointer projections only for handlers admitted by all handler-scoped gates (including quota), and due-point advancement in one atomic durable transition or a resumable idempotent recovery operation. Zero-handler firings create no handler audit, parent work item, or queue-pointer projection; handlers denied by a handler-scoped gate, including quota-denied handlers, retain an audit row but create no parent work item or queue-pointer projection. Firing-claim and queue-link recovery completes missing links from the existing claim rather than re-evaluating the handler. - - Each durable parent work item carries the originating `scriptEventId`, `scriptId`, `gameInstanceId`, `playableStateScope`, exact `scriptPatchVersion`/`scriptPinEpoch`, and region context. In the target handoff contract, each immutable emitted-command child is keyed by the complete source runtime scope plus any distinct target runtime scope, the persisted `automationDispatchId`, and deterministic `commandOrdinal` from canonical output order; both child identities are reused for every handoff, retry, and downstream disposition. The full parent Trigger Identity (including `bindingId` where applicable), `outboxWorkItemId`, and `scriptEventId` remain correlation only, while bounded `workItemIds[]` are parent-row selectors rather than child identities. The target `ListScriptHandoffEvents` child records are keyed by the complete Command-Handoff Identity, with `(automationDispatchId, commandOrdinal)` retained only as its dispatch-group suffix, and retain the full parent Trigger Identity while the handler audit remains one row. See [Implementation Status](#implementation-status) for the current live handoff boundary. + - The committed pre-DSL trigger is projected into `automation:queue:{tenantInstanceTag}:` only as a rebuildable pointer. Actions produced by the handler are evaluated within its one durable parent work item. Target evaluation atomically reaches `EVALUATED_COMMITTED` with one immutable command descriptor/child-dispatch row per emitted command, after which committed descriptor children are indexed into the queue; current implementation persists pre-DSL parent work and indexes only the derived parent pointer. + - Firing admission links the durable firing claim, one applicable resolved-handler audit row for every resolved handler, parent work items and queue-pointer projections only for handlers admitted by all handler-scoped gates (including quota), and due-point advancement in one atomic durable transition or a resumable idempotent recovery operation. Zero-handler firings create no handler audit, parent work item, or queue-pointer projection; handlers denied by a handler-scoped gate retain an audit row but create no parent work item or queue-pointer projection. Firing-claim and queue-link recovery completes missing links from the existing claim rather than re-evaluating the handler. + - Each durable parent work item carries the originating `scriptEventId`, `scriptId`, `gameInstanceId`, `playableStateNamespaceId`, exact `scriptPatchVersion`/`scriptPinEpoch`, and region context. It retains `playableStateScope` separately as exact-validated policy/routing/authorization/migration-fence evidence, excluded from Trigger Identity, Command-Handoff Identity, uniqueness, and deduplication keys. In the target handoff contract, each immutable emitted-command child is keyed by the complete source runtime scope plus any distinct target runtime scope, the persisted `automationDispatchId`, and deterministic `commandOrdinal` from canonical output order; both child identities are reused for every handoff, retry, and downstream disposition. The full parent Trigger Identity (including `bindingId` where applicable), `outboxWorkItemId`, and `scriptEventId` remain correlation only, while bounded `workItemIds[]` are parent-row selectors rather than child identities. The target `ListScriptHandoffEvents` child records are keyed by the complete Command-Handoff Identity, with `(automationDispatchId, commandOrdinal)` retained only as its dispatch-group suffix, and retain the full parent Trigger Identity while the handler audit remains one row. See [Implementation Status](#implementation-status) for the current live handoff boundary. 6. **Automation ticks and tick command enqueue** - **Current legacy path:** For each emitted command, Automation calls Game Session over internal gRPC. For a same-scope target, Game Session admits the command idempotently and invokes tick enqueue; `ENQUEUED` means local queue admission and `DUPLICATE_NOOP` confirms prior local acceptance. For a distinct target scope, the successful `REMOTE_SCHEDULED` result records only remote follow-up scheduling and does not claim local tick-queue admission. @@ -80,7 +80,7 @@ This example walks through how a typical `onEnterRegion` script executes end-to- 7. **Execution, audit, and observability** - On subsequent ticks, the Game Session Service selects at most one root actor action per eligible entity in the `actor_action` lane; the separately bounded `passive_effect` lane includes passive, inbound, and actor-generated effect sources without consuming that actor-action slot. Both lanes follow their canonical fairness and conflict-resolution rules. - **Automation observability (Table 4 authority; current-vs-target status):** Canonical families such as `automation_script_triggers_total`, `automation_script_skips_total`, `automation_script_triggers_dropped_total`, and `automation_tick_events_enqueued_total` have names, finite labels, and increment units owned solely by [normative Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix); the quota counters `script_quota_allowed_total` and `script_quota_denied_total` are separately instrumented current evidence. The implemented evaluator's live `automation_script_work_item_outcomes_total` follows the Table 4 `service`, `stage`, `outcome`, `priority`, and bounded `source_class` label contract. Table 4 defines target materialized dry-run/test attempts with `automation_script_test_runs_total` (including capacity-denied results) and applicable test runtime, sandbox-failure, and `automation_script_test_capacity_denied_total` families; the canonical runs, runtime, and sandbox families remain unimplemented, while the current evaluator does emit a reused `automation_script_test_capacity_denied_total` metric with nonconforming labels. Current dry-run evidence also includes implementation-specific admission/capacity families `automation_script_test_runs_allowed_total`, `automation_script_test_runs_denied_total`, and `automation_script_test_capacity_{reserved,released}_total`; these current metrics do not prove Table 4 conformance, and dry-run terminal outcomes remain suppressed from the live family. **Target state:** an admitted live event resolving zero handlers contributes only metric-only `outcome=admitted_no_handlers`; **current implementation:** ingress still returns `admissionReason=admitted_no_handlers` and persists the ingress-audit row, with no handler-audit row. Tenant-readiness `onLoad` is separate and uses its readiness-owner `READY`/`FAILED` status and audit path, including `zero_handler_manifest_unverifiable` when applicable. The current ingress response/audit drift is documented in the [scripting observability contract](./system-architecture-scripting-observability-contract.md#ingress-audit-vs-handler-audit). - - An audit record is written to `script_event_audit` for each resolved handler Trigger Identity, with identifiers such as `scriptEventId`, `scriptId`, `tenantId`, `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `tickId`, plus stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`) so operators can distinguish “DSL evaluated” from “accepted into tick queues”, enabling replay and troubleshooting as described in the same quotas and operations document. + - An audit record is written to `script_event_audit` for each resolved handler Trigger Identity, with identifiers such as `scriptEventId`, `scriptId`, `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`, and `tickId`, plus separately persisted exact-validated `playableStateScope` evidence and stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`) so operators can distinguish “DSL evaluated” from “accepted into tick queues”, enabling replay and troubleshooting as described in the same quotas and operations document. ### Mixed Fan-Out Example @@ -123,8 +123,8 @@ The complete target fixed-cadence pipeline below—durable timer firing, evaluat - When the script is published, its compiled DSL graph, `intervalTicks` (or equivalent cadence configuration), and version metadata are stored in the Automation & Scripting Service database and exposed under the current `scriptPatchVersion` for that game. 2. **Scheduling the next interval** - - Target-state scheduler behavior: When the NPC spawns or when the script is first loaded, the Automation & Scripting Service's scheduler registers a durable interval row retaining patch/plugin provenance. A wall-clock row carries exactly one due point; a tick-aligned row may remain `PENDING_RUNTIME_PROGRESS` without a due point until Game Session supplies runtime region/epoch and tick progress. Its stable continuity key is `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, targetScopeType, targetScopeId}`; `scriptPatchVersion`, `scriptPinEpoch`, and `pluginVersionId` remain provenance and execution-fence metadata, while a plugin-owned row also captures the Automation-owned `(pluginActivationEpoch, lifecycleRevision)` pair as execution-fence evidence, not stable schedule or continuity identity. `pluginActivationEpoch` is Automation-owned, scheduler-carried candidate/firing evidence and an input to the derived `scriptEventId`, not a separate handler field; disable/re-enable therefore gets a fresh event ID, while a lifecycle-revision mismatch fences the candidate under its captured evidence without rewriting it. The [scheduler and timer owner](./system-architecture-scripting-scheduler-and-timers.md#explicit-continuity-across-script-transitions) defines the candidate/firing identity; continuity uses that owner's full typed compatibility/fencing matrix and exact target `(scriptPatchVersion, scriptPinEpoch)` tuple. `scheduleSemanticsHash` is diagnostic evidence only. The default transition is cancel-and-recreate. Runtime `regionId`/`regionEpoch` and due state remain mutable schedule state rather than continuity identity. - - Leaders track these interval entries alongside other automation timers using bounded scans. Event gates, the durable firing claim, handler resolution, and handler-scoped gates happen first; handlers admitted by all handler-scoped gates (including quota) become durable parent work items. The later execution scheduler applies `AUTOMATION_TICK_BUDGET_MS` to the canonical ordered prefix of queued parent work items. This reservation is not actual execution time, a per-run timeout, or a capacity lease. + - Target-state scheduler behavior: When the NPC spawns or when the script is first loaded, the Automation & Scripting Service's scheduler registers a durable interval row retaining patch/plugin provenance. A wall-clock row carries exactly one due point; a tick-aligned row may remain `PENDING_RUNTIME_PROGRESS` without a due point until Game Session supplies runtime region/epoch and tick progress. Its stable continuity key is `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}`; `scriptPatchVersion`, `scriptPinEpoch`, and `pluginVersionId` remain provenance and execution-fence metadata, while a plugin-owned row also captures the Automation-owned `(pluginActivationEpoch, lifecycleRevision)` pair as execution-fence evidence, not stable schedule or continuity identity. `pluginActivationEpoch` is Automation-owned, scheduler-carried candidate/firing evidence and an input to the derived `scriptEventId`, not a separate handler field; disable/re-enable therefore gets a fresh event ID, while a lifecycle-revision mismatch fences the candidate under its captured evidence without rewriting it. The [scheduler and timer owner](./system-architecture-scripting-scheduler-and-timers.md#explicit-continuity-across-script-transitions) defines the candidate/firing identity; continuity uses that owner's full typed compatibility/fencing matrix and exact target `(scriptPatchVersion, scriptPinEpoch)` tuple. `scheduleSemanticsHash` is diagnostic evidence only. The default transition is cancel-and-recreate. Runtime `regionId`/`regionEpoch` and due state remain mutable schedule state rather than continuity identity. + - Leaders track these interval entries alongside other automation timers using bounded scans. Event gates, the durable firing claim, handler resolution, and handler-scoped gates happen first; handlers admitted by all handler-scoped gates (including quota) become durable queued work. The later execution scheduler applies `AUTOMATION_TICK_BUDGET_MS` to the canonical ordered prefix of queued handler work. This reservation is not actual execution time, a per-run timeout, or a capacity lease. 3. **Firing `onInterval` and enforcing budgets** - When an interval becomes due, the scheduler first applies event-scope candidate gates (cadence, reload/version visibility, and applicable event-policy checks); a permanent or declared skip is recorded by a deterministic `scheduleCandidateId` derived from the complete event-scope due-candidate identity defined by the [scheduler and timer owner](./system-architecture-scripting-scheduler-and-timers.md#interval-entry-identity-and-due-point-persistence), including required `stableOwnerKind`/`stableOwnerId` and, only for `triggerMode=CATCH_UP`, `resumeWindowId` (whose only generation component is `resumeGeneration`), plus captured `(pluginActivationEpoch, lifecycleRevision)` evidence for plugin-owned schedules. For plugin-owned schedules, `pluginActivationEpoch` is the tagged candidate/firing/derived `scriptEventId` identity field and input to that deterministic derivation; `lifecycleRevision` travels as fence evidence only. Core schedules use the exact `(scriptPatchVersion, scriptPinEpoch)` tuple and do not imply a separate core generation. A transient reload/reconciliation/authority-fence outcome instead retains the same due-candidate state under the complete applicable exact fence predicate: the original exact tuple, runtime scope/region epoch, schedule-owned provenance and binding, owner evidence, and captured lifecycle pair when plugin-owned, with no terminal candidate audit or `finalStage`/`finalOutcome`; only when every predicate element still matches may it resume after reconciliation. A lifecycle-revision mismatch fences the candidate under its captured evidence; reconciliation never refreshes or rebinds it. If authoritative evidence proves any other predicate no longer matches, the candidate does not resume or rebind and follows the scheduler owner's applicable terminal candidate outcome/reason; unavailable or ambiguous authority remains fenced and nonterminal. Retries reuse the candidate, firing claim, and derived `scriptEventId` only while the complete applicable candidate identity and captured fence evidence remain unchanged; all other runtime scope/region epoch, exact pin tuple, schedule-owned binding/provenance, due point, catch-up window, and plugin activation-epoch mismatches remain fenced. Core schedules require the same exact pin tuple and no separate core generation. An activation-epoch or core exact-tuple transition fences the old identity and derives a fresh one only before the new candidate is admitted. A lifecycle-revision-only change never mints a replacement candidate: a `DRAINING` transition cannot start a new firing, while already-admitted work may retain the existing identity only with ADR 0119's winning admission/fence CAS committed before the durable drain barrier. Neither path creates a firing claim, `scriptEventId`, or handler identity until its candidate gates pass. The lifecycle pair is not part of stable schedule/continuity identity, handler Trigger Identity, or Command-Handoff Identity. After handlers are bound, all handler-scoped gates run; a quota denial is handler-scoped `ADMISSION/quota_denied` with no work item, queue projection, lease, or execution marker, while only handlers admitted by all handler-scoped gates (including quota) create durable queued work. The later execution scheduler considers queued handler work in canonical order for the artifact-estimate prefix reservation; its remainder remains durably queued/deferred. When a handler is selected, a separately fenced capacity lease is acquired and its fence, executor acceptance, execution-start marker, and `EXECUTING` transition commit in one Automation-owned durable transaction before evaluation. The firing transition records one audit row for every resolved handler, including denied handlers, and creates work/queue projections only for handlers admitted by all handler-scoped gates; firing-claim and queue-link retries do not re-run the DSL, while eligible pre-`EVALUATED_COMMITTED` evaluation recovery may re-run the frozen DSL under the original identity and evidence. @@ -136,7 +136,7 @@ The complete target fixed-cadence pipeline below—durable timer firing, evaluat - The `onInterval` handler runs inside the sandboxed DSL engine, evaluating conditions such as “is the NPC currently out of combat?” and “is the patrol still active?” before deciding on the next waypoint or behavior. - Actions produced by the handler (for example, “move to the next patrol room,” “play an emote,” “schedule an `onTimerExpire` follow-up”) are evaluated within one durable parent work item. Target evaluation atomically reaches `EVALUATED_COMMITTED` with one immutable command descriptor/child-dispatch row per emitted command, after which committed descriptor children are indexed into `automation:queue:{tenantInstanceTag}:`; current implementation persists pre-DSL parent work and indexes only the derived parent pointer. - **Request validation:** `payloadJson` is bounded before the event-scope claim; an oversized envelope returns non-OK gRPC `INVALID_ARGUMENT` with no claim, admission result/fields, queue work, `script_event_ingress_audit` row or ingress-drop metric, or handler `script_event_audit` row. It does not use `TRIGGER_ADMISSION_OUTCOME_OUTPUT_BUDGET_EXCEEDED`. **Handler-time behavior:** current command-count and per-entity ceilings are enforced while expanding legacy emitted commands. **Target-only behavior:** serialized generated-output byte/data-dependent metering is applied during DSL evaluation before descriptor commit and remains unavailable/unproven in the current runtime. A missing or conflicting artifact-cost digest is a distinct event-scope `OUTPUT_BUDGET_EXCEEDED` outcome, while a handler that exceeds an enforced runtime cap uses its handler-scoped `DSL_EVAL` outcome/reason. Handler-time output failures are bounded non-success outcomes rather than unbounded backlog. - - Target-state work-item behavior: Each durable parent work item carries the full applicable Trigger Identity, including `scriptEventId`, `scriptId`, `gameInstanceId`, `playableStateScope`, version metadata, and the immutable trigger-created `regionId` and `regionEpoch`. Plugin-backed work also retains its captured `(pluginActivationEpoch, lifecycleRevision)` pair unchanged through the durable queue, handoff, retry, replay, recovery, and final execution, revalidating it as fence evidence rather than handler or command identity. If current entity state is needed to route the work at enqueue time, persist separate fields such as `enqueueRegionId` and `enqueueRegionEpoch`; never overwrite the original trigger fields. Deduplication, fencing, and replay continue to use the original `regionId` and `regionEpoch`. In the target handoff contract, each immutable emitted-command child uses the complete source runtime scope plus any distinct target runtime scope, a persisted `automationDispatchId`, and deterministic `commandOrdinal` from canonical output order; retries reuse that complete child identity. Parent Trigger Identity, `outboxWorkItemId`, and `scriptEventId` remain correlation only. See [Implementation Status](#implementation-status) for the current live handoff boundary. + - Target-state work-item behavior: Each durable parent work item carries the full applicable Trigger Identity, including `scriptEventId`, `scriptId`, `gameInstanceId`, `playableStateNamespaceId`, version metadata, and the immutable trigger-created `regionId` and `regionEpoch`; it retains `playableStateScope` separately as exact-validated policy/routing/authorization/migration-fence evidence. Plugin-backed work also retains its captured `(pluginActivationEpoch, lifecycleRevision)` pair unchanged through the durable queue, handoff, retry, replay, recovery, and final execution, revalidating it as fence evidence rather than handler or command identity. If current entity state is needed to route the work at enqueue time, persist separate fields such as `enqueueRegionId` and `enqueueRegionEpoch`; never overwrite the original trigger fields. Deduplication, fencing, and replay continue to use the original `regionId` and `regionEpoch`. In the target handoff contract, each immutable emitted-command child uses the complete source runtime scope plus any distinct target runtime scope, a persisted `automationDispatchId`, and deterministic `commandOrdinal` from canonical output order; retries reuse that complete child identity. Parent Trigger Identity, `outboxWorkItemId`, and `scriptEventId` remain correlation only. See [Implementation Status](#implementation-status) for the current live handoff boundary. 5. **Execution, audit, and observability** - **Target state only/unimplemented:** Automation later claims each durable parent work item in `PENDING_EVALUATION`, transitions the parent to `EXECUTING` under the fenced capacity lease, and atomically commits emitted command descriptors/child-dispatch rows at `EVALUATED_COMMITTED`; it uses `automation:queue` only as a rebuildable pointer index over committed descriptor children and hands resulting commands to the Game Session Service over internal gRPC so Game Session can enqueue them into the appropriate `tick:{tenantRegionTag}:queue:`. **Current legacy:** Automation drains the pre-DSL `automation:queue` parent-pointer projection (with a durable-scan fallback), evaluates each bounded parent work item, and attempts one Game Session handoff per emitted command. For same-scope targets, `ENQUEUED` means Game Session accepted the command into the local tick queue and `DUPLICATE_NOOP` confirms prior local acceptance; for distinct target scopes, `REMOTE_SCHEDULED` means only that the remote follow-up was scheduled and does not claim local tick-queue admission. Target descriptor replay/recovery, a rebuildable evaluated-work projection, complete command identity/`commandOrdinal` propagation, and independent per-command progress are unavailable or unproved. @@ -158,7 +158,7 @@ Recurring timer-driven handlers such as `onInterval` produce at most one event-s `scheduleDefinitionId` participates in the stable compiled continuity key but does not by itself decide whether a logical timer survives publish, reload, or rollback. Initial materialization and default/incompatible reset transitions create a new physical durable row and retire the displaced row. A valid explicitly declared, typed-compatible continuity transition instead preserves the existing stable row, rewrites its target patch/plugin provenance and exact pin/epoch fencing metadata in place, and recalculates its due point without creating a replacement row or tombstone; the logical key must not be confused with a row or firing-claim identity: -For carry-forward, match the stable schedule-instance identity and the stable logical continuity key `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, targetScopeType, targetScopeId}` within the applicable tenant/instance scope, then apply the explicit typed compatibility checks. `scheduleSemanticsHash` and displaced/replacement patch or plugin versions are transition-mapping provenance and exact execution-fence evidence, not immutable continuity identity; matching only `scheduleDefinitionId` or semantic similarity is insufficient. +For carry-forward, match the stable schedule-instance identity and the stable logical continuity key `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}` within the applicable tenant/namespace scope, then apply the explicit typed compatibility checks. `scheduleSemanticsHash` and displaced/replacement patch or plugin versions are transition-mapping provenance and exact execution-fence evidence, not immutable continuity identity; matching only `scheduleDefinitionId` or semantic similarity is insufficient. - If patch `P11` and patch `P12` both define the NPC patrol timer as "run every 30 ticks while patrol is enabled", both explicitly declare the same stable continuity key, `source.isDryRun == target.isDryRun`, and cadence, target, and playable scope are compatible, Automation preserves the existing stable row, rewrites its target patch/plugin provenance and exact pin/epoch fencing metadata in place, and applies the resume calculation without creating a replacement row or tombstone. The in-place update is atomic or resumable/idempotent. After a due candidate passes admission, the scheduler creates a separate firing claim and `scriptEventId` keyed by the complete candidate identity; the stable schedule row remains distinct from the firing claim and event identity, while the old owner history is not reused as a new row. - If either side omits continuity, explicitly resets it, changes cadence/target/scope/key, or authoritative reconciliation proves the target definition absent, the scheduler atomically retires/tombstones P11 and terminalizes any proven-displaced candidate under its original identity. It creates no P12 replacement row, due state, firing claim, or `scriptEventId`; only a validated replacement definition, after target schedule reconciliation, may receive fresh due state and proceed to exact admission. If target-definition or other required authority is unavailable, contradictory, or ambiguous, P11 and its candidates/claims remain fenced and nonterminal and neither tombstoning nor replacement occurs until reconciliation. Existing P11 firing claims and candidate audits retain their original exact patch/epoch and resume-window metadata; only pending firing claims may be fenced or terminal-marked, while candidate-audit identities and outcomes remain immutable and are never rewritten or reused by P12. P12 claims are created only after target schedule reconciliation and exact admission. Rollback to P11 follows the same matrix; hash equality or historical similarity never grants continuity. diff --git a/design/architecture/system-architecture-scripting-normative-contract-tables.md b/design/architecture/system-architecture-scripting-normative-contract-tables.md index fef2c8ca39..26770ad87a 100644 --- a/design/architecture/system-architecture-scripting-normative-contract-tables.md +++ b/design/architecture/system-architecture-scripting-normative-contract-tables.md @@ -35,7 +35,11 @@ This ordering does not supersede accepted ADR decisions. Accepted ADRs remain bi ## Table 1: Trigger Identity (Required Fields) -Trigger Identity is the composite idempotency identity for logical work/effect materialization of this resolved handler for this trigger at most once, and the natural primary key for handler-scoped `script_event_audit` records. This logical at-most-once boundary does not prohibit a frozen-input DSL re-evaluation attempt for eligible gameplay/runtime work before `EVALUATED_COMMITTED`; after that boundary, recovery never re-enters the DSL. `scriptEventId` is the stable, producer-namespaced parent-event token within the applicable event scope; it is not a globally unique standalone execution identity or a substitute for all other applicable identity fields. Incoming requests use the separate event-scope identity defined below until handler resolution completes. The handler-scoped input manifest defined by the [DSL lifecycle owner](./system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract) is durable evaluation input, not an additional Trigger Identity field; its owner versions and causal floor must be retained with the handler record. For gameplay/runtime work, `scriptPatchVersion` and the Game Session-owned `scriptPinEpoch` are the inseparable exact execution tuple; matching patch text under a different epoch is a fence mismatch. The captured `scriptPinControlPlaneRequestId` is mandatory paired owner evidence/correlation for that tuple, retained immutably but excluded from logical identity and the trigger/candidate claim uniqueness and conflict keys governed here; it must still match the authoritative owner evidence through ingress, persistence, replay, and finalization. For plugin work, the captured `(pluginActivationEpoch, lifecycleRevision)` pair is required execution-fence evidence and is deliberately excluded from handler Trigger Identity. +Trigger Identity is the composite idempotency identity for logical handler work and handler-scoped evaluated-descriptor materialization of this resolved handler for this trigger at most once, and the natural primary key for handler-scoped `script_event_audit` records. It does not govern downstream gameplay effect materialization: authoritative effect idempotency belongs to the persisted mutation `EffectId` (the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child mutation), typed operation, exact target aggregate, and immutable request digest. Any enclosing `rootEffectId` is lineage and reconciliation context only. This logical at-most-once boundary does not prohibit a frozen-input DSL re-evaluation attempt for eligible gameplay/runtime work before `EVALUATED_COMMITTED`; after that boundary, recovery never re-enters the DSL. `scriptEventId` is the stable, producer-namespaced parent-event token within the applicable event scope; it is not a globally unique standalone execution identity or a substitute for all other applicable identity fields. Incoming requests use the separate event-scope identity defined below until handler resolution completes. The handler-scoped input manifest defined by the [DSL lifecycle owner](./system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract) is durable evaluation input, not an additional Trigger Identity field; its owner versions and causal floor must be retained with the handler record. For gameplay/runtime work, `scriptPatchVersion` and the Game Session-owned `scriptPinEpoch` are an inseparable exact execution tuple; matching patch text under a different epoch is a fence mismatch. For plugin work, the captured `(pluginActivationEpoch, lifecycleRevision)` pair is required execution-fence evidence and is deliberately excluded from handler Trigger Identity. + +For applicable gameplay/runtime identities, `playableStateNamespaceId` is the durable playable-state uniqueness/allocation dimension. The server-derived `playableStateScope` is immutable within one playable-state lifecycle and is policy/routing/authorization/migration-fence evidence that must be persisted and exact-validated; a missing, stale, or mismatched scope fails closed. `playableStateScope` is not a Trigger Identity, event-scope, handoff, schedule, resume-window, or other uniqueness/deduplication dimension. A presented scope mismatch therefore requires authoritative reconciliation before admission: only stale or incorrect evidence with unchanged authoritative scope may reuse the namespace-keyed identity; an authoritative scope-policy transition starts a new playable-state lifecycle and selects or allocates a new `playableStateNamespaceId` before fresh durable identity is admitted. + +Downstream gameplay effects emitted by a handler use Game Session's deterministic command-plan root contract, not Trigger Identity. Full Trigger Identity governs handler and handoff identity only. The frozen typed command or `ResolvedEffectPlan`-owned command/action contract supplies semantic root order; built-in commands declare an equivalent stable order, and ambiguous or duplicate order fails before admission. After the complete applicable Command-Handoff Identity is admitted/deduplicated and exact-maps to one durable target `commandId`, the durable command row freezes/binds its request fingerprint and resolved runtime scope, and Game Session persists the ordered plan manifest/digest plus an opaque root allocation row unique on `(tenantId, gameInstanceId, commandId, planOrdinal)`; the row binds the manifest digest and validates that frozen binding, with mismatches failing closed. Downstream authoritative mutation then uses the Game Session root `EffectId`, typed operation, exact target aggregate, and immutable request digest. For Automation, the complete applicable Command-Handoff Identity is the admission/deduplication identity that maps to the durable target command, not the root allocation key; ordinary player/built-in plans use their complete canonical admitted command/runtime identity. `scriptEventId`, the rest of Trigger Identity, and handler lineage remain separate correlation identities. A zero-command evaluation allocates no gameplay root. Ordinary producer event-ingress RPCs into Automation & Scripting (for example `TriggerScriptEvent`) use two-stage deduplication: @@ -48,8 +52,9 @@ Required Trigger Identity fields for all triggers: | --- | --- | --- | | `tenantId` | Yes | Tenant/project identity. | | `gameInstanceId` | Yes | Required to avoid collisions when a tenant has multiple instances. Must be carried through audit and downstream idempotency. | -| `playableStateScope` | Yes (gameplay/runtime) | Resolved admitted gameplay-state namespace. Shared and isolated realm state must not collide even when other runtime identity fields match. | -| `regionId` | Yes (gameplay/runtime) | Region context for the trigger. If a trigger is not region-scoped (rare), it must declare its own scope explicitly and still include `gameInstanceId`. | +| `playableStateNamespaceId` | Yes (gameplay/runtime) | Durable playable-state namespace used in Trigger Identity uniqueness/allocation. Shared, isolated, and playtest state namespaces must not collide even when other runtime identity fields match. | +| `playableStateScope` | Yes (gameplay/runtime) | Server-derived playable-state policy/routing/authorization/migration-fence evidence, immutable for the namespace during one playable-state lifecycle. Persist and exact-validate it with the handler record; a missing or mismatched value fails closed. It is required evidence but is excluded from Trigger Identity uniqueness/deduplication. An authority-proven scope transition requires a new playable-state lifecycle/namespace rather than reuse. | +| `regionId` | Yes (gameplay/runtime) | Region context for every gameplay/runtime trigger. Non-region tenant/control-plane events use an existing non-gameplay branch rather than a gameplay/runtime Trigger Identity. | | `regionEpoch` | Yes (gameplay/runtime) | Required for any trigger emitted from, aligned to, or fenced by the tick timeline. This includes standard gameplay lifecycle events emitted after tick commit (for example `onEnterRegion`, `onSpawn`, `onCommand`) and all scheduler/timer events. | | `entityId` | Yes (entity-scoped) | Required for entity-scoped triggers. | | `scriptId` | Yes | The script definition identity that will run. If bindings fan out, each `` is a distinct Trigger Identity. | @@ -78,7 +83,9 @@ Additional required fields for scheduler/timer triggers: Plugin-owned schedule rows, due candidates, firing claims, candidate audits, and timer-derived work retain the captured `lifecycleRevision` alongside `pluginActivationEpoch`. The revision is fence evidence only: before a new firing claim or handler admission, the scheduler must observe the exact current lifecycle tuple and require the current revision in `ENABLED`; it may not use the `DRAINING` predecessor exception for a new firing. A same-epoch lifecycle revision change fences the old candidate under its existing identity and does not mint a fresh candidate identity merely because the revision changed. Already-admitted work may use the narrowly retained immediately preceding `ENABLED` revision only with ADR 0119's durable pre-`DRAINING` admission/fence evidence and same-version/same-epoch rule. -Before handler resolution, a scheduler/timer firing claim is keyed by the complete durable schedule-instance identity, exact `scriptPatchVersion`, positive `scriptPinEpoch`, `isDryRun`, applicable runtime scope, target selector, trigger mode, and tagged due point; the paired nonblank `scriptPinControlPlaneRequestId` is retained immutably as owner evidence for validation/correlation but is excluded from this claim/conflict key and is not execution identity. When `triggerMode=CATCH_UP`, `resumeWindowId` is additionally required and participates in claim uniqueness and `scriptEventId` derivation, and it is absent otherwise. It therefore includes schedule-owned `scriptId` and any schedule-owned `pluginId`, `pluginVersionId`, and `bindingId`; for plugin-owned candidates, the captured `pluginActivationEpoch` is an additional tagged field in the local `scheduleCandidateId`/firing-claim uniqueness key, while core-script candidates omit it. Same-epoch retries reuse that candidate identity only while the complete captured fence evidence remains current; for plugin-owned schedules, a same-version disable/re-enable derives a fresh candidate identity from the newer `pluginActivationEpoch`. `pluginActivationEpoch` is not a separate handler Trigger Identity field: it is included in the candidate, firing-claim, and candidate-audit identities and is an input to the scheduler-derived `scriptEventId`, so a fresh activation epoch yields a fresh event ID transitively in every resolved handler identity. Core schedule transition identity changes only through the accepted exact `scriptPatchVersion`/`scriptPinEpoch` contract; no separate core epoch is implied. It must not fabricate fields absent from the durable schedule. Candidate audits use that same complete due-candidate identity, including the exact patch, positive epoch owner evidence, and `isDryRun`, captured plugin activation epoch when applicable, and `resumeWindowId` only for `CATCH_UP`; the owner request ID is retained/read back for validation and correlation but does not expand execution identity. This owner-known firing identity is distinct from the ordinary producer event-ingress key below and derives the one event-scope `scriptEventId` propagated to resolved handlers. After resolution, each plugin child uses the captured handler execution identity above; only scheduler candidate/firing-claim/audit identities include activation epoch directly, while the scheduler-derived `scriptEventId` makes it differ transitively in the handler Trigger Identity. `lifecycleRevision` is retained and revalidated alongside it as non-identity fence evidence and is not added to those identities. Neither lifecycle value is part of Command-Handoff Identity, stable schedule-row identity, or the stable continuity key. Durable schedule rows, due candidates, firing claims, candidate audits, and list/read projections persist and expose the exact plugin activation epoch and captured lifecycle revision as fence evidence; `scriptPinEpoch` remains execution/fence metadata and is excluded from the stable continuity key. +Before handler resolution, a scheduler/timer firing claim is keyed by the complete durable logical schedule/event identity: the stable logical schedule continuity fields together with exact `scriptPatchVersion` and `scriptPinEpoch`, `isDryRun`, applicable runtime scope, target selector, trigger mode, and tagged due point; when `triggerMode=CATCH_UP`, `resumeWindowId` is additionally required and participates in claim uniqueness and `scriptEventId` derivation, and it is absent otherwise. The physical `scheduleInstanceId` is retained only as immutable row-generation metadata for durable lookup and reconciliation; it is explicitly excluded from `scheduleCandidateId`, firing-claim uniqueness, and `scriptEventId` derivation. The logical identity therefore includes schedule-owned `scriptId` and any schedule-owned `pluginId`, `pluginVersionId`, and `bindingId`; for plugin-owned candidates, the captured `pluginActivationEpoch` is an additional tagged field in the local `scheduleCandidateId`/firing-claim uniqueness key, while core-script candidates omit it. Same-epoch retries reuse that candidate identity only while the complete captured fence evidence remains current; for plugin-owned schedules, a same-version disable/re-enable derives a fresh candidate identity from the newer `pluginActivationEpoch`. `pluginActivationEpoch` is not a separate handler Trigger Identity field: it is included in the candidate, firing-claim, and candidate-audit identities and is an input to the scheduler-derived `scriptEventId`, so a fresh activation epoch yields a fresh event ID transitively in every resolved handler identity. Core schedule transition identity changes only through the accepted exact `scriptPatchVersion`/`scriptPinEpoch` contract; no separate core epoch is implied. It must not fabricate fields absent from the durable schedule. Candidate audits use that same complete due-candidate identity, including the exact patch and epoch, `isDryRun`, captured plugin activation epoch when applicable, and `resumeWindowId` only for `CATCH_UP`. This owner-known firing identity is distinct from the ordinary producer event-ingress key below and derives the one event-scope `scriptEventId` propagated to resolved handlers. After resolution, each plugin child uses the captured handler execution identity above; only scheduler candidate/firing-claim/audit identities include activation epoch directly, while the scheduler-derived `scriptEventId` makes it differ transitively in the handler Trigger Identity. `lifecycleRevision` is retained and revalidated alongside it as non-identity fence evidence and is not added to those identities. Neither lifecycle value is part of Command-Handoff Identity, stable schedule-row identity, or the stable continuity key. Durable schedule rows, due candidates, firing claims, candidate audits, and list/read projections persist and expose the exact plugin activation epoch and captured lifecycle revision as fence evidence; `scriptPinEpoch` remains execution/fence metadata and is excluded from the stable continuity key. + +For scheduler/timer identities, the applicable `playableStateNamespaceId` is the durable playable-state identity component carried in the schedule instance, due candidate, firing claim, candidate audit, and derived `scriptEventId`. The server-derived `playableStateScope` is retained alongside those records as separately persisted exact-validated policy/routing/authorization/migration-fence evidence; it is not added to schedule, candidate, firing-claim, event-scope, or handler uniqueness. Missing or mismatched scope evidence fails closed and fences admission until authoritative reconciliation. Only a stale or incorrect presented scope with unchanged authoritative scope may resume the existing namespace-keyed identity; an authority-proven scope transition starts a new playable-state lifecycle and namespace before fresh schedule state is admitted. | Field | Required | Notes | | --- | --- | --- | @@ -97,7 +104,7 @@ Additional required fields and exceptions for tenant-readiness lifecycle trigger | `scriptPatchVersion` | Yes | Pending patch being validated for tenant readiness. | | `scriptEventId` | Yes | Deterministically generated by Automation & Scripting from all non-generated applicable onLoad identity fields, including ``. | | `isDryRun` | Yes | Must be `false` for readiness `onLoad`; dry-run/test `onLoad` probes use the dry-run/test ingress contract instead. | -| `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, `entityId` | No | `onLoad` is tenant-readiness work and is not tied to a running instance, gameplay-state namespace, region, tick epoch, or entity. These fields must be absent rather than populated with sentinel values. | +| `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, `regionEpoch`, `entityId` | No | `onLoad` is tenant-readiness work and is not tied to a running instance, playable-state namespace, playable-state policy, region, tick epoch, or entity. These fields must be absent rather than populated with sentinel values. | Ordinary producer event-scope ingress identity before handler resolution: @@ -105,7 +112,8 @@ Ordinary producer event-scope ingress identity before handler resolution: | --- | --- | --- | | `tenantId` | Yes | Tenant/project identity. | | `gameInstanceId` | Yes (runtime ingress) | Required for runtime ingress fences such as reload, rollback pause, and pin visibility. | -| `playableStateScope` | Yes (gameplay/runtime ingress) | Resolved admitted gameplay-state namespace carried before handler fan-out. | +| `playableStateNamespaceId` | Yes (gameplay/runtime ingress) | Durable playable-state namespace identity carried before handler fan-out and included in the event-scope uniqueness key. | +| `playableStateScope` | Yes (gameplay/runtime ingress) | Server-derived policy/routing/authorization/migration-fence evidence carried before handler fan-out, immutable for the namespace during one playable-state lifecycle, persisted with the ingress claim/audit, and exact-validated. It is excluded from the event-scope uniqueness key; a mismatch fails closed. Only unchanged authoritative scope permits reuse; an authority-proven transition requires a new lifecycle/namespace. | | `regionId`, `regionEpoch`, `entityId` | Yes when the incoming event is gameplay/runtime-scoped | These fields describe the source event before handler fan-out. | | `eventType` | Yes | Logical event key being admitted for handler resolution. | | `eventSchemaVersion` | Yes | Version of the event and payload contract being admitted. | @@ -118,7 +126,9 @@ Ordinary producer event-scope ingress identity before handler resolution: ### Remote Follow-Up Tuple Binding (Normative) -A remote follow-up whose source and target game instances differ carries two exact pin roles, each with its paired owner request evidence. The originating `sourceScriptPatchVersion`/`sourceScriptPinEpoch`/`sourceScriptPinControlPlaneRequestId` fields are captured when the source event/follow-up is admitted and remain immutable source provenance, owner evidence, and the source rollback fence; the source request ID is evidence/correlation, not execution identity. Before target-side Automation admission, Game Session revalidates that complete source evidence against the authoritative source instance, reads and freezes the target instance's current `targetScriptPatchVersion`/`targetScriptPinEpoch`/`targetScriptPinControlPlaneRequestId`, and durably binds both source and target records to the target delivery/claim and its immutable request/dedupe evidence. The target record, not the source record, populates the target event-scope and resolved-handler Trigger Identity and all target-side script admission and execution fences; target `scriptPinControlPlaneRequestId` remains paired owner evidence and is not substituted into execution identity. Source evidence remains separately named provenance/fence and is never substituted into that target identity. Retries reuse both frozen source/target records. Source or target displacement, a conflicting retry, or a changed owner record fails closed; unavailable authority is retryable and creates no target admission, while semantic target `UNPINNED` creates no target script work. When source and target are the same game instance, one authoritative `scriptPatchVersion`/`scriptPinEpoch` record plus its paired owner request evidence serves both roles and no distinct second record is fabricated. +For remote playable-state handoff, the source `playableStateNamespaceId` is the source durable identity dimension, while the server-derived source `playableStateScope` is separately persisted exact-validated policy/routing/authorization/migration-fence evidence. The target `targetPlayableStateNamespaceId` is the target durable identity dimension; `targetPlayableStateScope` is separately persisted exact-validated target evidence and is excluded from target uniqueness/deduplication. A missing, stale, or mismatched source or target scope fails closed and requires authoritative reconciliation; only stale or incorrect presented evidence with unchanged authoritative scope may reuse the existing handoff identity. An authority-proven scope-policy transition starts a new playable-state lifecycle and selects or allocates the corresponding target namespace before fresh handoff identity is admitted. + +A remote follow-up whose source and target game instances differ carries two exact pin roles. The originating `sourceScriptPatchVersion`/`sourceScriptPinEpoch` pair is captured when the source event/follow-up is admitted and remains immutable source provenance and the source rollback fence. Before target-side Automation admission, Game Session revalidates that source pair against the authoritative source instance, reads and freezes the target instance's current exact `scriptPatchVersion`/`scriptPinEpoch` pair, and durably binds both pairs to the target delivery/claim and its immutable request/dedupe evidence. The target pair, not the source pair, populates the target event-scope and resolved-handler Trigger Identity and all target-side script admission and execution fences; the source pair remains separately named provenance/fence and is never substituted into that target identity. Retries reuse both frozen pairs. Source or target displacement, a conflicting retry, or a changed tuple fails closed; unavailable authority is retryable and creates no target admission, while semantic target `UNPINNED` creates no target script work. When source and target are the same game instance, one authoritative exact pair serves both roles and no distinct second tuple is fabricated. For semantic target `UNPINNED`, Game Session's existing `remote_followup_result` transaction is the sole result owner: it persists exactly one terminal row under `resultId=remote-result:` with `outcome=ABANDONED`, `resultErrorCode=REMOTE_TARGET_UNPINNED`, canonical empty `resultPayloadJson={}`, and no `resultCommandId`; the same transaction updates the existing follow-up and coordinator identities and creates no Automation event, work item, or command. An exact retry returns that row without work. A retry whose existing scope, source/target tuple or identity, outcome, or normalized result-authority fingerprint differs conflicts and cannot overwrite it; this reuses the existing persisted fields and adds no digest column or outcome family. `authority_unavailable` persists no terminal result and does not terminalize delivery: it remains non-admitted/retryable under the same follow-up identity after authority recovers. This is distinct from the finalized no-script result. ### Event-Scope Claim and Retry Semantics (Normative) @@ -136,7 +146,7 @@ The durable event-scope claim has an `IN_PROGRESS` phase, a retry-eligible trans - A retry or duplicate delivery with the same terminal finalized event-scope key returns the exact stored admission result, without re-evaluating admission or materializing duplicate handler work. Permanent denials and successful results are terminal finalized results; a retry-eligible transient denial is the explicit exception and may be reclaimed only through the bounded lifecycle above. - `resolvedHandlerCount` is the count of enabled bindings that matched and were resolved for the admitted event scope, including dry-run/test claims. It is not a count of persisted work items, emitted commands, successful handlers, or handler audit rows, and it is immutable in the finalized claim result. A resolved handler may have no work item when its handler-scoped admission decision denies it. - An admitted live claim with zero resolved handlers returns the normal admitted result with `resolvedHandlerCount=0`; `admitted_no_handlers` is emitted only as the Table 4 metric-only outcome. A dry-run/test claim with zero resolved handlers emits no live trigger metric. The finalized value is returned in the ingress response and stored on the claim and `script_event_ingress_audit`; it is not stored in handler-scoped `script_event_audit` rows. -- A request that reuses `scriptEventId` but changes any other applicable key field is an identity conflict, not a retry. Reject it deterministically, preserve the original claim and outcome, and do not materialize handlers. +- A request that reuses `scriptEventId` must perform a producer-scoped collision lookup against the complete ordered event-scope key above, including every applicable runtime, namespace, region/epoch, event, pin, dry-run, and producer field. If it changes any other applicable key field, or presents required scope evidence that does not exactly match the authoritative bound evidence, it is an identity/evidence conflict, not a retry. Reject or fence it deterministically, preserve the original claim and outcome, and do not write a competing audit or materialize handlers until authoritative reconciliation completes. - A rejected claim has no handler materialization and remains represented only by its one event-scope ingress-audit row. Event-scope ingress outcomes are recorded in the existing `script_event_ingress_audit` surface using its event-scope identity, `scriptEventId` correlation, `createdAt` retention anchor, mutable `claimStartedAt` lease, and `admissionOutcome`/`admissionReason` fields, not in handler-scoped `script_event_audit`. Stale `IN_PROGRESS` recovery compares the claim's current row-version fence and lease timestamp before advancing the fence, so an abandoned owner's finalization is rejected as a stale write and operators can identify the reclaim through its bounded durable reason. Transport authentication/authorization and request/schema validation occur before the event-scope claim and use canonical non-OK gRPC status; they do not create a claim, finalized ingress-audit result, or ingress-drop metric. After the claim exists, genuine event-scope/domain decisions such as stale pin state, reload backpressure, rollback pause, or version unavailability may use typed admission fields and the matching ingress audit/drop metric. Once the event is accepted for handler resolution, each resolved handler produces its own full applicable Trigger Identity and `script_event_audit` row. Pre-resolution event-scope decisions must not invent a synthetic `scriptId`, `bindingId`, or command identity. Scheduler due-candidate skips use the candidate-audit rule in Table 3 instead of event-scope ingress audit. @@ -159,12 +169,14 @@ Notes: - If an implementation wants to treat some gameplay lifecycle events as “not tick-aligned”, it must define that exception explicitly in this table (not only in prose docs) and document why it is safe across scoped coordination resets. The default contract is that gameplay lifecycle triggers are fenced by `regionEpoch`. - Dry-run/test ingress must use a namespace separate from live ingress (`isDryRun=true`) regardless of whether `scriptEventId` is caller-generated or server-generated. -- Downstream service calls made from scripts must propagate a per-command idempotency token derived from the full applicable Trigger Identity plus tick context when applicable (for example `tickId`), the emitted command's `automationDispatchId` (or an equivalent command-level identity), and the target aggregate type and ID, following `design/architecture/system-architecture-transactions.md`; `scriptEventId` alone is insufficient for fan-out. +- Full Trigger Identity governs handler and Command-Handoff identity only. After the complete applicable Command-Handoff Identity is admitted/deduplicated and exact-maps to one durable target `commandId`, downstream authoritative service calls must use the mutation's persisted root-or-child `EffectId`, typed operation, exact target aggregate, and immutable request digest under `design/architecture/system-architecture-transactions.md`; a generated child uses its own persisted child identity while retaining the enclosing root only as lineage/reconciliation context. `scriptEventId`, `automationDispatchId`, and tick context remain correlation or admission metadata and cannot substitute for that mutation guard. ## Table 1A: Event Ingress `scriptEventId` Ownership Matrix The ingress endpoint determines who owns `scriptEventId` generation and retry behavior. Implementations must reject requests that violate these ownership rules. +In the scheduler/timer ingress row, `runtime scope` means the durable runtime identity, including `playableStateNamespaceId` where applicable; the server-derived `playableStateScope` travels as separately persisted exact-validated policy/routing/authorization/migration-fence evidence and is excluded from the event-scope due-candidate identity. Missing or mismatched scope evidence fails closed before candidate or `scriptEventId` derivation. Only stale or incorrect presented evidence with unchanged authoritative scope may reuse an existing candidate; an authority-proven scope-policy transition starts a new playable-state lifecycle and namespace before fresh candidate identity is derived. + | Ingress surface | `scriptEventId` owner | Required behavior | | --- | --- | --- | | Live external ingress (`TriggerScriptEvent`) | Caller | Caller must supply `scriptEventId` and must reuse it across retries for the same trigger identity. Missing ID is a deterministic validation error. | @@ -216,15 +228,17 @@ Additional non-committing terminal outcome rules: ### Command-Handoff Identity (Target-State) The command collection uses one complete command-handoff identity for each evaluated child dispatch: -``. -The source scope fields are required for gameplay/runtime commands; the target scope fields are included exactly when the emitted command is routed to a distinct target runtime scope, and `targetPlayableStateScope` is included whenever that distinct target scope has its own shared/isolated playable-state namespace. Absent optional fields remain absent. For command-capable gameplay/runtime evaluations, before DSL evaluation the pre-DSL/evaluation claim allocates no `automationDispatchId` or command-child identity. If evaluation emits commands, the first atomic durable evaluated-descriptor/outbox commit allocates and persists one opaque `automationDispatchId`; a valid zero-command evaluation creates no dispatch identity. Pre-commit evaluation retries preserve the original Trigger Identity, work-item identity, and frozen inputs and allocate none; retries after a winning commit reuse its dispatch ID and canonical ordinals. Tenant-readiness `onLoad` is non-emitting and does not allocate or expose a command dispatch identity. Before an evaluated descriptor exists, the pre-DSL trigger has no child identity or `commandOrdinal` and must not expose an `automationDispatchId` as a synthetic child/handoff reference. Once descriptors are emitted, `commandOrdinal` is deterministic from canonical emitted-command order: the first emitted command under a dispatch is `0`, followed by `1`, and so on. The first durable descriptor/outbox commit enforces uniqueness on the complete Command-Handoff Identity above. The complete source/target runtime scope, dispatch ID, and ordinal together prevent unrelated evaluations from converging; `automationDispatchId` is not assumed to be globally unique. `outboxWorkItemId`, the parent Trigger Identity, and `scriptEventId` are correlation-only and excluded from command-child uniqueness. The complete identity above is the canonical identity for evaluated command-child handoff deduplication, execution-fence reporting, replay selection, and child correlation; it is not the downstream authoritative effect identity. Downstream effect idempotency instead uses the stable root `EffectId`, typed operation, and exact target aggregate, with the immutable request digest stored and compared; a conflicting operation, target, or digest fails closed. The `(automationDispatchId, commandOrdinal)` pair is only a suffix and is insufficient without the complete source/target scope; `script_event_audit` remains a separate one-row-per-handler surface. +``. +The source runtime identity fields are required for gameplay/runtime commands; the server-derived source `playableStateScope` is separately persisted exact-validated policy/routing/authorization/migration-fence evidence and is excluded from Command-Handoff Identity uniqueness/deduplication. The target runtime identity fields are included exactly when the emitted command is routed to a distinct target runtime scope, and `targetPlayableStateNamespaceId` is included whenever that distinct target has its own playable-state namespace. `targetPlayableStateScope` is separately persisted exact-validated target policy/routing/authorization/migration-fence evidence and is excluded from target uniqueness/deduplication. Missing, stale, or mismatched source or target scope evidence fails closed and requires authoritative reconciliation; only stale or incorrect presented scope evidence with unchanged authoritative scope may reuse the existing child identity. An authority-proven scope-policy transition starts a new playable-state lifecycle and selects or allocates the corresponding target namespace before fresh child identity is admitted. Absent optional identity fields remain absent. For command-capable gameplay/runtime evaluations, before DSL evaluation the pre-DSL/evaluation claim allocates no `automationDispatchId` or command-child identity. If evaluation emits commands, the first atomic durable evaluated-descriptor/outbox commit allocates and persists one opaque `automationDispatchId`; a valid zero-command evaluation creates no dispatch identity. Pre-commit evaluation retries preserve the original Trigger Identity, work-item identity, and frozen inputs and allocate none; retries after a winning commit reuse its dispatch ID and canonical ordinals. Tenant-readiness `onLoad` is non-emitting and does not allocate or expose a command dispatch identity. Before an evaluated descriptor exists, the pre-DSL trigger has no child identity or `commandOrdinal` and must not expose an `automationDispatchId` as a synthetic child/handoff reference. Once descriptors are emitted, `commandOrdinal` is deterministic from canonical emitted-command order: the first emitted command under a dispatch is `0`, followed by `1`, and so on. The first durable descriptor/outbox commit enforces uniqueness on the complete Command-Handoff Identity above. The complete source/target runtime identity, separately validated scope evidence, dispatch ID, and ordinal together prevent unrelated evaluations from converging; `automationDispatchId` is not assumed to be globally unique. `outboxWorkItemId`, the parent Trigger Identity, and `scriptEventId` are correlation-only and excluded from command-child uniqueness. The complete identity above is the canonical identity for evaluated command-child handoff deduplication, execution-fence reporting, replay selection, and child correlation; it is not the downstream authoritative effect identity. Downstream effect idempotency instead uses the persisted mutation `EffectId` (the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child mutation), typed operation, and exact target aggregate, with the immutable request digest stored and compared; any enclosing `rootEffectId` is lineage and reconciliation context only, and a conflicting operation, target, or digest fails closed. The `(automationDispatchId, commandOrdinal)` pair is only a suffix and is insufficient without the complete source/target runtime identity; `script_event_audit` remains a separate one-row-per-handler surface. A command-handoff reference exists only for an emitted evaluated descriptor. Pre-DSL trigger records have no child Command-Handoff Identity or `commandOrdinal` and must not be represented by an `automationDispatchId`, parent `outboxWorkItemId`, parent Trigger Identity, or `scriptEventId` as a synthetic child/handoff reference. Read-only inspection may expose an emitted descriptor reference with the complete identity above, including `commandOrdinal`; mutation APIs currently accept bounded explicit `workItemIds[]` only. Descriptor references and filter selectors are listing/preview inputs, and descriptor-level replay or purge remains deferred until preview plus stable per-row proof. +The downstream plan root remains a separate Game Session identity: after the complete applicable Command-Handoff Identity is admitted/deduplicated and exact-maps to one durable target `commandId`, Game Session consumes the frozen command/action semantic order, persists the ordered plan manifest/digest, and assigns `planOrdinal` plus an opaque root `EffectId` allocation row unique on `(tenantId, gameInstanceId, commandId, planOrdinal)` in its local durable plan/staging transaction. The durable command row's frozen request fingerprint and resolved runtime scope are validated, and the allocation row binds the manifest digest; reuse requires the same command row identity, frozen binding, ordinal, and manifest digest, otherwise failing closed. For Automation, the complete applicable Command-Handoff Identity, including optional distinct target runtime fields, is the admission/deduplication identity that maps to the target command, not the root allocation key; it is not reduced to `(automationDispatchId, commandOrdinal)`. Full Trigger Identity governs handler/handoff identity only, while `scriptEventId` and handler lineage remain correlation identities. Automation does not allocate a competing root. A zero-command evaluation has no downstream plan root. + Supplementary post-handoff correlation rule: -- **Target-state command-ordinal contract:** execution-time version/plugin fence drops that happen after tick handoff must not be left as metrics-only signals. They must be exposed on the affected per-command handoff disposition keyed by the complete Command-Handoff Identity, including `targetPlayableStateScope` when a distinct target runtime scope applies, with the parent Trigger Identity and its exact `scriptPatchVersion`/`scriptPinEpoch` pair retained for correlation, using bounded reasons such as `script_patch_mismatch` or `plugin_binding_mismatch`; use `plugin_activation_epoch_mismatch` specifically when the captured plugin activation epoch mismatches current authoritative epoch evidence. -- **Current live fallback:** the Game Session handoff currently carries `automationDispatchId`, command id/text, selected provenance fields, and parent work-item correlation, but not `commandOrdinal` or the complete Trigger Identity. Current diagnostics use those fields and must be labeled as the narrower fallback rather than as proof of the target-state contract. +- **Target-state command-ordinal contract:** execution-time version/plugin fence drops that happen after tick handoff must not be left as metrics-only signals. They must be exposed on the affected per-command handoff disposition keyed by the complete Command-Handoff Identity, including `targetPlayableStateNamespaceId` when a distinct target playable-state namespace applies; retain source and target `playableStateScope`/`targetPlayableStateScope` as separately persisted exact-validated policy/routing/authorization/fence evidence, excluded from uniqueness, with the parent Trigger Identity and its exact `scriptPatchVersion`/`scriptPinEpoch` pair retained for correlation. Missing or mismatched scope evidence fails closed. Use `plugin_binding_mismatch` only for a proven plugin/lifecycle binding mismatch; use `plugin_activation_epoch_mismatch` for a captured activation-epoch mismatch, `plugin_disabled` for a lifecycle disablement or revocation that invalidates admitted work, `plugin_version_not_published` for publication failure, `plugin_component_policy_blocked` for a proven component-policy block, `signer_revoked` for signer revocation, and `authority_unavailable`, `component_policy_unavailable`, or `signer_policy_unavailable` when the applicable evidence is unavailable or unverifiable. `script_patch_mismatch` remains the script-version reason. +- **Current live fallback:** the Game Session handoff currently carries `automationDispatchId`, command id/text, selected provenance fields, and parent work-item correlation, but not `commandOrdinal`, the complete Trigger Identity, or the deterministic plan-root `planOrdinal`/root binding. Current diagnostics use those fields and must be labeled as the narrower fallback rather than as proof of the target-state contract. Per-command handoff correlation rule: @@ -270,7 +284,7 @@ Deprecated aliases: If Game Session rejects a queued command because its embedded `(scriptPatchVersion, scriptPinEpoch)` does not match the currently pinned exact tuple, because work referencing a revocable component lacks matching fresh component-revocation security-policy evidence, or because a plugin-produced command's execution evidence `(pluginId, pluginVersionId, bindingId)` plus captured `(pluginActivationEpoch, lifecycleRevision)` does not match fresh current activation-epoch, binding, and lifecycle evidence together with authoritative publication, signer-policy, component-policy, and capability-grant evidence for its scoped instance, or because any required component-revocation, activation-epoch, binding, lifecycle, publication, signer-policy, component-policy, or capability-grant evidence is unavailable, stale, contradictory, or unverifiable, it must fail closed and: -- Record the drop on the affected command-handoff record keyed by the complete Command-Handoff Identity: required source scope (`tenantId`, `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`), the dispatch-group suffix (`automationDispatchId`, `commandOrdinal`), and the optional distinct target scope (`targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`) when applicable. `automationDispatchId` is retained as dispatch-group correlation and is not a standalone child key; parent `outboxWorkItemId`, the parent Trigger Identity, and `scriptEventId` remain correlation-only. Retain `scriptId` and the exact `(scriptPatchVersion, scriptPinEpoch)` tuple for diagnosis; retain `entityId` only for entity-scoped commands and keep it absent otherwise, plus the applicable component-revocation fence evidence and, for a plugin handler, `pluginId`, `pluginVersionId`, `bindingId`, and captured `(pluginActivationEpoch, lifecycleRevision)` as execution evidence, not Command-Handoff Identity. For a plugin tuple, binding, lifecycle, publication, or policy identity/evidence mismatch, this disposition uses bounded `reason=plugin_binding_mismatch`; when the captured `pluginActivationEpoch` itself mismatches current authoritative epoch evidence, it uses bounded `reason=plugin_activation_epoch_mismatch`. +- Record the drop on the affected command-handoff record keyed by the complete Command-Handoff Identity: required source runtime identity (`tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`), the dispatch-group suffix (`automationDispatchId`, `commandOrdinal`), and the optional distinct target runtime identity (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, `targetRegionEpoch`) when applicable. Retain the server-derived source `playableStateScope` and, when applicable, `targetPlayableStateScope` as separately persisted exact-validated policy/routing/authorization/fence evidence, excluded from uniqueness; missing or mismatched scope evidence fails closed and requires authoritative reconciliation. `automationDispatchId` is retained as dispatch-group correlation and is not a standalone child key; parent `outboxWorkItemId`, the parent Trigger Identity, and `scriptEventId` remain correlation-only. Retain `scriptId` and the exact `(scriptPatchVersion, scriptPinEpoch)` tuple for diagnosis; retain `entityId` only for entity-scoped commands and keep it absent otherwise, plus the applicable component-revocation fence evidence and, for a plugin handler, `pluginId`, `pluginVersionId`, `bindingId`, and captured `(pluginActivationEpoch, lifecycleRevision)` as execution evidence, not Command-Handoff Identity. Use bounded `reason=plugin_binding_mismatch` only for a proven plugin/lifecycle binding mismatch; use `plugin_activation_epoch_mismatch`, `plugin_disabled`, `plugin_version_not_published`, `plugin_component_policy_blocked`, or `signer_revoked` for the applicable proven epoch, disabled/revoked, publication, component-policy, or signer failure, and `authority_unavailable`, `component_policy_unavailable`, or `signer_policy_unavailable` when the applicable evidence is unavailable or unverifiable. - For a proven tuple, binding, lifecycle, publication, policy, or component-revocation mismatch, remove the rejected queue entry or move it to a bounded dead-letter store so terminal failures cannot accumulate unboundedly after a rollback. When required component-revocation or other authority evidence is temporarily unavailable or unverifiable without proving a permanent mismatch, retain the entry retryable under its original complete Command-Handoff Identity, record the applicable established bounded disposition such as `component_policy_unavailable`, `authority_unavailable`, or `signer_policy_unavailable`, and create no recovery claim/attempt or replacement identity. Retry timing and reconciliation use the owning queue/handoff policy and its existing lease/fence checks; the bounded dead-letter `maxAge`/`maxRows`, cleanup cadence, and alert thresholds are defined in [Scripting Quotas & Operations](./system-architecture-scripting-quotas-and-operations.md#auditability--metrics). Once evidence proves a component is blocked/revoked or another permanent mismatch, terminalize it under the applicable bounded disposition. These dispositions are distinct and do not create a new outcome or validator family. - Apply the corresponding Table 4 version-fence metric consequence for script-patch, plugin-version/binding, or plugin-activation-epoch mismatches; Table 4 owns the exact family, labels, and increment unit. - Dead-letter retention for rejected queue entries must be bounded and explicit: @@ -304,22 +318,23 @@ The matrix below defines what the scheduler does when a firing becomes due under | Recurring/advisory `reloadState=RELOADING` | Do not admit new timer firings or backfill while `RELOADING`; use the transient due-candidate lifecycle above and retry only after the exact pin tuple, runtime scope, and owner evidence reconcile. | Keep the due-candidate state/claim fenced and nonterminal: no `finalStage`, `finalOutcome`, terminal candidate audit, firing claim, handler Trigger Identity, or `scriptEventId` while fenced; settle once under the original exact tuple as above. | | Recurring/advisory `reloadState=FAILED` | Fail closed until durable recovery reconciles the current pin, schedule, scope/epoch, and due evidence and returns the scope to `IDLE`; do not backfill from the prior patch. | Record the non-admitted due candidate under deterministic `scheduleCandidateId` with `finalStage=ADMISSION`, `finalOutcome=version_unavailable`, and `finalReason=reload_failed`; do not create a firing claim, handler Trigger Identity, or `scriptEventId`. | | Recurring/advisory `PAUSED_FOR_ROLLBACK` | Do not admit new timer firings until the exact pin/artifact, schedule rows, due candidates, displaced/firing projections, and current list/read projections reconcile; only terminal old-execution evidence cleanup remains asynchronous/diagnostic and does not gate resumption. This Automation admission barrier does not pause ordinary gameplay ticks. While the original exact tuple remains current, retain the due candidate and its canonical due point as nonterminal state; if rollback displaces that tuple, keep the old candidate fenced under its original identity and derive any fresh candidate only from reconciled target schedule/due state. Follow the owner-defined [scheduler and timers transition rules](./system-architecture-scripting-scheduler-and-timers.md#explicit-continuity-across-script-transitions) for due-point advancement and replacement. | While the original tuple remains current, retain the deterministic `scheduleCandidateId` with no `finalStage`, `finalOutcome`, terminal candidate audit, firing claim, handler Trigger Identity, or `scriptEventId`; retry the same candidate only after exact evidence reconciles. When rollback displaces it, terminalize the old candidate under its original identity as `finalStage=ADMISSION`, `finalOutcome=canceled`, `finalReason=rollback_epoch_advanced` when required, and create any target candidate with a fresh deterministic identity only after reconciliation. | -| Recurring/durable-recurring leader failover or short downtime | Apply each complete stable schedule-instance identity's declared `SKIP_MISSED` or `COALESCE_ONE` policy. A coalescing schedule instance may admit at most one synthetic firing in the one Automation-owned durable timer-recovery resume window identified by ``; at creation, that durable window freezes the effective numeric `SCRIPT_TIMER_CATCH_UP_MAX_FIRINGS_PER_RESUME` cap and the selection-policy revision defining grouping, ordering, round-robin passes, and tie breaks. Those frozen values govern every scan, retry, takeover, selection, and cap-excluded outcome until the window reaches `COMPLETE`; a later configuration or policy change applies only to a later window. The deterministic fair tenant-local cap applies across independent schedule instances within that one-tenant, one-mode `resumeWindowId`, grouped by the stable schedule-instance identity defined in the scheduler lifecycle (including target scope and dry-run mode), not by `scheduleDefinitionId` alone. `pluginVersionId` and `bindingId` remain due-candidate provenance, fencing, and deduplication dimensions and do not split stable fairness groups. Durable compare-and-set creates or reuses one `OPEN` window per runtime scope, epoch, and `isDryRun` mode; same-window retries and takeovers revalidate and reuse that mode-specific identity and its frozen policy inputs. Excluded candidates are dropped and never deferred as backlog. A candidate selected within that cap still enters ADR 0166 tenant-first shared scheduler/cluster admission. Tenant or cluster capacity denial terminally skips that candidate under the same due-candidate and mode-specific `resumeWindowId` identity, consumes its deterministic selection slot, creates no firing claim, handler Trigger Identity, or `scriptEventId`, and is not retried, deferred, backfilled, or reminted as catch-up. Atomically persist that terminal candidate audit, advance the recurring schedule's canonical due state to its next ordinary future occurrence, and record the resume-window denial outcome; a resumable idempotent reconciliation keyed by `(scheduleCandidateId, resumeWindowId)` is required when one transaction is unavailable, and an incomplete settlement remains fenced. | Catch-up firings use `triggerMode=CATCH_UP` and deterministic identity from the coalesced due point and mode-specific `resumeWindowId`. The firing-claim uniqueness/comparison, candidate audit, and tenant-local-cap accounting all include `isDryRun` and `resumeWindowId`; same-window retries and takeovers reuse them. An epoch transition moves each prior epoch's `OPEN` window out of `OPEN` independently for each mode before creating the corresponding new-epoch window. The window completes only after selected candidates' firing or shared-admission-denial outcomes and all cap-excluded outcomes are durable, and only a later recovery episode allocates the next `resumeGeneration`. For `isDryRun=false`, a tenant-ceiling denial records candidate-audit `finalStage=ADMISSION`, `finalOutcome=tenant_budget_exceeded`, and `finalReason=tenant_budget_exceeded`, then increments `automation_script_skips_total` once with `scope="tenant"` and `reason="tenant_budget_exceeded"`; this candidate-level route does not invoke `ScriptTenantBudgetService` or increment `automation_script_tenant_budget_denied_total`. A cluster-ceiling denial records candidate-audit `finalStage=ADMISSION`, `finalOutcome=quota_denied`, and `finalReason=cluster_limit_reached`, then increments `automation_script_skips_total` once with `scope="cluster"` and `reason="cluster_limit_reached"`. Both live metrics use the remaining bounded Table 4 labels. For `isDryRun=true`, neither live-only family is emitted: no dedicated test-only candidate-ceiling metric is currently defined, so the settled candidate audit and mode-specific resume-window outcome are the complete observability surface; the handler-scoped test families are not used because the denial occurs before handler materialization. Neither denial increments `automation_script_timer_catchup_truncated_total`; cap-excluded candidates use that truncation family instead. | -| Recurring/advisory runtime scope / epoch change before due-point admission | Do not remint stale due points under the newer `(tenantId, gameInstanceId, playableStateScope, regionId, regionEpoch)` timeline. A `playableStateScope` change is a schedule/runtime migration fence even when the other runtime fields are unchanged: create or confirm the new scope-owned schedule entry before retiring the old entry, as one atomic durable result or a resumable idempotent operation, then advance to the new scope's next valid due point without reusing the stale one. | Record the dropped candidate at event scope under deterministic `scheduleCandidateId` with `finalStage=ADMISSION`, `finalOutcome=canceled`, and `finalReason=runtime_scope_changed` (or `playable_state_scope_changed` for that specific fence), and emit the runtime-fence metric. Because admission did not occur, do not create a firing claim, handler Trigger Identity, or `scriptEventId`. | -| Correctness-bearing one-shot runtime scope / epoch change | Keep the durable intent and any effect under the original identity and fence it from ordinary execution on the new timeline. Reconcile it under authority-fenced owner evidence; never rebind or remint it into the new scope/epoch. Only after the original intent/effect and source claim conclusively permit `ABANDONED` may an authorized recovery create a fresh current-scope identity with revalidation and durable lineage under [ADR 0067](./decisions/adr-0067-abandon-old-epoch-work-and-reschedule-with-new-lineage.md). | Retain the original identity, old scope/epoch, reconciliation evidence, terminal outcome when proven, and any fresh lineage link. Inconclusive old work remains nonterminal and blocks affected-scope reopen rather than being reported as skipped or silently replaced. | -| Recurring/advisory timer preserved across reload/rollback | Apply the owner-defined resume rule only when its runtime-region, scope, and epoch preconditions match; otherwise fence the old due point and derive a new due point after the replacement schedule entry is durable. Do not reuse a stale due point or Trigger Identity. | Preserve the dropped old due-point evidence and the exact identity; see [Timer Resume Rule](./system-architecture-scripting-scheduler-and-timers.md#timer-resume-rule-normative). | +| Recurring/durable-recurring leader failover or short downtime | Apply each complete stable schedule-instance identity's declared `SKIP_MISSED` or `COALESCE_ONE` policy. A coalescing schedule instance may admit at most one synthetic firing in the one Automation-owned durable timer-recovery resume window identified by ``; the server-derived `playableStateScope` is retained as immutable exact-validated policy/routing/authorization/migration-fence evidence for that window and is excluded from its identity, with missing or mismatched evidence fencing admission. At creation, that durable window freezes the effective numeric `SCRIPT_TIMER_CATCH_UP_MAX_FIRINGS_PER_RESUME` cap and the selection-policy revision defining grouping, ordering, round-robin passes, and tie breaks. Those frozen values govern every scan, retry, takeover, selection, and cap-excluded outcome until the window reaches `COMPLETE`; a later configuration or policy change applies only to a later window. The deterministic fair tenant-local cap applies across independent schedule instances within that one-tenant, one-mode `resumeWindowId`, grouped by the stable schedule-instance identity defined in the scheduler lifecycle (including target `playableStateNamespaceId` identity and dry-run mode; target scope remains evidence), not by `scheduleDefinitionId` alone. `pluginVersionId` and `bindingId` remain due-candidate provenance, fencing, and deduplication dimensions and do not split stable fairness groups. Durable compare-and-set creates or reuses one `OPEN` window per namespace/runtime identity, epoch, and `isDryRun` mode; same-window retries and takeovers revalidate and reuse that namespace identity, exact scope evidence, and frozen policy inputs. Excluded candidates are dropped and never deferred as backlog. A candidate selected within that cap still enters ADR 0166 tenant-first shared scheduler/cluster admission. Tenant or cluster capacity denial terminally skips that candidate under the same due-candidate and mode-specific `resumeWindowId` identity, consumes its deterministic selection slot, creates no firing claim, handler Trigger Identity, or `scriptEventId`, and is not retried, deferred, backfilled, or reminted as catch-up. Atomically persist that terminal candidate audit, advance the recurring schedule's canonical due state to its next ordinary future occurrence, and record the resume-window denial outcome; a resumable idempotent reconciliation keyed by `(scheduleCandidateId, resumeWindowId)` is required when one transaction is unavailable, and an incomplete settlement remains fenced. | Catch-up firings use `triggerMode=CATCH_UP` and deterministic identity from the coalesced due point and mode-specific `resumeWindowId`. The firing-claim uniqueness/comparison, candidate audit, and tenant-local-cap accounting all include `playableStateNamespaceId`, `isDryRun`, and `resumeWindowId`; same-window retries and takeovers reuse them while revalidating the separately persisted exact scope evidence. An epoch transition moves each prior epoch's `OPEN` window out of `OPEN` independently for each mode before creating the corresponding new-epoch window. The window completes only after selected candidates' firing or shared-admission-denial outcomes and all cap-excluded outcomes are durable, and only a later recovery episode allocates the next `resumeGeneration`. For `isDryRun=false`, a tenant-ceiling denial records candidate-audit `finalStage=ADMISSION`, `finalOutcome=tenant_budget_exceeded`, and `finalReason=tenant_budget_exceeded`, then increments `automation_script_skips_total` once with `scope="tenant"` and `reason="tenant_budget_exceeded"`; this candidate-level route does not invoke `ScriptTenantBudgetService` or increment `automation_script_tenant_budget_denied_total`. A cluster-ceiling denial records candidate-audit `finalStage=ADMISSION`, `finalOutcome=quota_denied`, and `finalReason=cluster_limit_reached`, then increments `automation_script_skips_total` once with `scope="cluster"` and `reason="cluster_limit_reached"`. Both live metrics use the remaining bounded Table 4 labels. For `isDryRun=true`, neither live-only family is emitted: no dedicated test-only candidate-ceiling metric is currently defined, so the settled candidate audit and mode-specific resume-window outcome are the complete observability surface; the handler-scoped test families are not used because the denial occurs before handler materialization. Neither denial increments `automation_script_timer_catchup_truncated_total`; cap-excluded candidates use that truncation family instead. | +| Recurring/advisory runtime scope / epoch change before due-point admission | Do not remint stale due points under the newer `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch)` identity timeline. The server-derived `playableStateScope` is separately persisted exact-validated policy/routing/authorization/migration-fence evidence and is immutable for a namespace during one playable-state lifecycle. A presented `playableStateScope` mismatch remains a schedule/runtime migration fence even when the identity fields are unchanged: fence admission and require authoritative reconciliation of the scope evidence. Only when authority proves the scope itself is unchanged and the presented evidence was stale or incorrect may the existing namespace-keyed schedule advance to its next valid due point; if authority proves a scope-policy transition, it must start a new playable-state lifecycle and select or allocate a new namespace under the existing retire/create ordering, never reuse the old identity. | For stale or incorrect presented scope evidence, or unavailable or ambiguous authority, keep the candidate fenced and nonterminal with no final audit (`finalStage`, `finalOutcome`, or `finalReason`) and no runtime-fence metric; retry only after authoritative reconciliation. When authority confirms the scope is unchanged, reuse the namespace-keyed identity and advance the due point without recording a scope-change cancellation or metric. Only an authority-proven runtime epoch change, scope-policy transition, or other displacement records the dropped candidate at event scope under deterministic `scheduleCandidateId` with `finalStage=ADMISSION`, `finalOutcome=canceled`, and `finalReason=runtime_scope_changed` (or `playable_state_scope_changed` for that specific fence), and emits the runtime-fence metric. Because actual displacement did not admit the candidate, do not create a firing claim, handler Trigger Identity, or `scriptEventId`. | +| Correctness-bearing one-shot runtime scope / epoch change | Keep the durable intent and any effect under the original identity and fence it from ordinary execution on the new timeline. Reconcile it under authority-fenced owner evidence; a presented `playableStateScope` mismatch remains separately validated fence evidence and does not by itself mint a new identity, while an authority-proven scope-policy transition starts a new playable-state lifecycle/namespace and is never silently rebound into the old intent. Only after the original intent/effect and source claim conclusively permit `ABANDONED` may an authorized recovery create a fresh current-namespace identity with revalidation and durable lineage under [ADR 0067](./decisions/adr-0067-abandon-old-epoch-work-and-reschedule-with-new-lineage.md). | Retain the original identity, old namespace/scope/epoch, reconciliation evidence, terminal outcome when proven, and any fresh lineage link. Inconclusive old work remains nonterminal and blocks affected-scope reopen rather than being reported as skipped or silently replaced. | +| Recurring/advisory timer preserved across reload/rollback | Apply the owner-defined resume rule only when its runtime-region, playable-state namespace, exact scope evidence, and epoch preconditions match; otherwise fence the old due point and derive a new due point after the replacement schedule entry is durable. A presented scope mismatch requires reconciliation and fences stale work; only unchanged authoritative scope permits reuse of the namespace-keyed Trigger Identity. An authority-proven scope-policy transition starts a new playable-state lifecycle/namespace and follows the existing replacement ordering. Do not reuse a stale due point or Trigger Identity. | Preserve the dropped old due-point evidence and the exact identity; see [Timer Resume Rule](./system-architecture-scripting-scheduler-and-timers.md#timer-resume-rule-normative). | | Recurring/advisory long downtime or sustained overload | No guarantee of eventual execution for every firing; the system converges by running future firings once capacity returns. | Missed firings must be visible as skips/drops in metrics and audit. | -| Infrastructure error after admission | Before `EVALUATED_COMMITTED`, an admitted evaluation may retry only under the same full Trigger Identity and must converge on the same parent work-item and child identities. After `EVALUATED_COMMITTED`, recovery replays the durable descriptors and never re-enters the DSL. Correctness-bearing one-shot recovery must converge under its durable intent identity to one execution or an explicit terminal outcome. Downstream retries remain idempotent. | Preserve the `finalStage` reached by the failed or committed operation; do not record `handoff_accepted` without full durable acceptance of every required child. | +| Infrastructure error after admission | Before `EVALUATED_COMMITTED`, an admitted evaluation may retry only under the same full Trigger Identity and must converge on the same parent work item, full Trigger Identity, and frozen inputs; no dispatch or child identity exists before the winning evaluated-descriptor/outbox commit. After `EVALUATED_COMMITTED`, recovery replays the durable descriptors and never re-enters the DSL. Correctness-bearing one-shot recovery must converge under its durable intent identity to one execution or an explicit terminal outcome. Downstream retries remain idempotent. | Preserve the `finalStage` reached by the failed or committed operation; do not record `handoff_accepted` without full durable acceptance of every required child. | ### Preserved-Timer Resume Rule -The exact resume formula, modulo-zero boundary behavior, and runtime scope/epoch preconditions are owned by [Scripting Scheduler and Timer Lifecycle](./system-architecture-scripting-scheduler-and-timers.md#timer-resume-rule-normative). This table records the resulting candidate-audit and identity requirements only: a preserved timer uses the original scope/epoch identity when those preconditions hold; a changed scope or epoch fences the old due point and does not reuse its Trigger Identity. +The exact resume formula, modulo-zero boundary behavior, and runtime scope/epoch preconditions are owned by [Scripting Scheduler and Timer Lifecycle](./system-architecture-scripting-scheduler-and-timers.md#timer-resume-rule-normative). This table records the resulting candidate-audit and identity requirements only: a preserved timer uses the original `playableStateNamespaceId`/runtime identity when those preconditions and unchanged authoritative scope evidence hold; a presented stale or incorrect scope fences admission until reconciliation, while an authority-proven scope-policy transition starts a new playable-state lifecycle/namespace, fences the old due point, and never reuses its Trigger Identity. ### Version-Owned Durable Schedule Migration (Normative) -- `scheduleDefinitionId` participates in the stable logical continuity key but is not the durable row or trigger-claim identity. The continuity key is `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, targetScopeType, targetScopeId}`; `pluginId` is the stable plugin owner while `pluginVersionId`, `scriptPatchVersion`, and `scriptPinEpoch` remain provenance and exact execution-fence metadata. +- `scheduleDefinitionId` participates in the stable logical continuity key but is not the durable row or trigger-claim identity. For a playable-state-scoped schedule, the continuity key is `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}`; `playableStateScope` is separately persisted exact-validated policy/routing/authorization/migration-fence evidence and is not a continuity-key component. `pluginId` is the stable plugin owner while `pluginVersionId`, `scriptPatchVersion`, and `scriptPinEpoch` remain provenance and exact execution-fence metadata. - By default, a version transition tombstones the displaced interval and creates a target interval with fresh due state when a validated target definition exists. When authoritative reconciliation proves the target definition is absent, reconciliation follows the [scheduler owner rule](./system-architecture-scripting-scheduler-and-timers.md#explicit-continuity-across-script-transitions): it fences admission and atomically tombstones the displaced interval, terminalizes any proven-displaced candidates under their original identities as applicable, creates no replacement row, due state, firing claim, or `scriptEventId`, and never rebinds existing candidates or claims. If target-definition or other required authority is unavailable, contradictory, or ambiguous, reconciliation must not tombstone or create replacement state; it retains the displaced row, candidates, and claims fenced and nonterminal until authority reconciles. Only a later validated target reconciliation may create fresh state and identities. Carrying due state requires explicit compatible continuity declarations on both sides, `source.isDryRun == target.isDryRun`, typed interval/cadence/target/playable-scope checks, and the exact pin/epoch transition identity. A same-version repin is still a new epoch transition: the transition must atomically or resumably reconcile the stable row and retire or rewrite all displaced mutable schedule state, due candidates, and current list/read projections before admission resumes. Old-epoch firing claims retain their original exact `(scriptPatchVersion, scriptPinEpoch)` and `resumeWindowId`, and only pending claims may be fenced or terminal-marked; claims already in handoff reconcile the downstream outcome under their original exact fence. Neither pending-claim fencing/terminalization nor in-handoff reconciliation creates a new firing claim, handler identity, or `scriptEventId`. Immutable candidate-audit identity, outcome, exact tuple, and `resumeWindowId` are never rewritten. A transient due-candidate state/claim keyed by `scheduleCandidateId` may remain fenced while reconciliation is pending. It may settle into the one firing path only while its original exact `(scriptPatchVersion, scriptPinEpoch)` tuple and every applicable authoritative binding, runtime-scope, owner, and plugin lifecycle fence (including the captured `(pluginActivationEpoch, lifecycleRevision)` pair when applicable) remain current, or into one immutable terminal candidate audit. If authoritative evidence proves any applicable fence displaced, terminalize the candidate under its original identity with the applicable bounded terminal outcome/reason and create no firing claim or `scriptEventId`; if authority is unavailable, contradictory, or ambiguous, retain the fenced candidate as nonterminal until reconciled. It is never rebound to a new scope or epoch. `scheduleSemanticsHash` is diagnostic evidence only; equality cannot grant continuity. Replacement creation and retirement are one atomic durable result or a resumable, idempotent operation keyed by `controlPlaneRequestId`. -- The new version/scope-owned entry must derive a new scheduler trigger claim and `scriptEventId`; a matching `scheduleDefinitionId`, due point, handler, or old `playableStateScope` must never be used to reuse a Trigger Identity across the migration. +- The preceding playable-scope checks validate separately persisted server-derived policy/routing/authorization/fence evidence; they do not add `playableStateScope` to continuity, candidate, or Trigger Identity. A presented scope mismatch remains fenced until authoritative reconciliation; only unchanged authoritative scope permits the existing namespace-keyed identity, while an authority-proven scope-policy transition starts a new playable-state lifecycle and namespace. +- A new version/namespace-owned entry, or a target entry created after a namespace transition, must derive a new scheduler trigger claim and `scriptEventId`; a matching `scheduleDefinitionId`, due point, handler, or old `playableStateNamespaceId` must never be used to reuse a Trigger Identity across the migration. A presented `playableStateScope` mismatch remains an admission/migration fence requiring authoritative reconciliation and exact evidence validation; an authority-proven transition must allocate the new namespace before fresh identity, and no path may silently reuse the old identity while fenced. For plugin-owned migration evidence, displaced rows, due candidates, firing claims, and candidate audits retain and revalidate the captured `(pluginActivationEpoch, lifecycleRevision)` pair alongside the exact script pin. `pluginActivationEpoch` participates in due-candidate, firing-claim, and derived `scriptEventId` identity as specified above; `lifecycleRevision` is execution-fence evidence only and is not added to the stable schedule, continuity, Trigger, or Command-Handoff identity. diff --git a/design/architecture/system-architecture-scripting-observability-contract.md b/design/architecture/system-architecture-scripting-observability-contract.md index 623e2a971d..c03b4224d4 100644 --- a/design/architecture/system-architecture-scripting-observability-contract.md +++ b/design/architecture/system-architecture-scripting-observability-contract.md @@ -60,13 +60,15 @@ Write behavior requirements: - Conflicting concurrent writes for the same Trigger Identity must converge on a single row with deterministic precedence (higher stage wins). - Handler-scoped admission rejections and backpressure outcomes (for example `quota_denied`, `script_disabled`, timer-scope `skipped_reloading`, post-resolution `rollback_paused`, or plugin `disabled_due_to_errors`) must still produce the row for that Trigger Identity with `finalStage=ADMISSION`; plugin breaker denials use canonical bounded `finalReason=failure_rate_breaker` and retain `breakerState=DISABLED_DUE_TO_ERRORS` with the exact plugin version/runtime scope. When present on that row or a runtime read, `breakerReason` carries the same bounded `failure_rate_breaker` value as runtime-state evidence; it is not a competing audit reason. Handler retries reuse that full identity and propagated `scriptEventId`. Pre-resolution event-scope denials belong in the ingress audit/logging surface described above and follow the [event-scope claim retry lifecycle](./system-architecture-scripting-normative-contract-tables.md#event-scope-claim-and-retry-semantics-normative). Timer/cadence candidate skips remain on the `scheduleCandidateId` candidate-audit surface rather than becoming event-scope claims. -Audit records must include at least: +The following is the canonical target `script_event_audit` field list (with the stated conditional absences): - Identity and versioning - `tenantId` - `gameInstanceId` (absent for tenant-readiness `onLoad`) - - `regionId` - - `regionEpoch` (required for gameplay/runtime and scheduler triggers; exceptions must be explicitly documented in the normative Trigger Identity table) + - `playableStateNamespaceId` (required for gameplay/runtime; absent for tenant-readiness `onLoad`) + - `playableStateScope` (separately persisted server-derived policy/routing/authorization/migration-fence evidence required for gameplay/runtime; explicitly excluded from identity) + - `regionId` (required for gameplay/runtime; absent for tenant-readiness `onLoad`) + - `regionEpoch` (required for gameplay/runtime and scheduler triggers; absent for tenant-readiness `onLoad`) - `entityId` (for entity-scoped events) - `scriptId` - `pluginId`, `pluginVersionId`, and `bindingId` (required for resolved plugin handlers) @@ -77,6 +79,9 @@ Audit records must include at least: - `scriptEventId` - `isDryRun` (boolean) - `sourceService` (derived from authenticated producer/workload identity for custom/service-specific events; the same value used in ingress dedupe and persisted unchanged in ingress and handler audit; omitted for built-in events that originate entirely within Automation & Scripting) + +Tenant-readiness `onLoad` uses the non-gameplay Trigger Identity branch defined by the [normative Trigger Identity table](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields): `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `scriptPinEpoch` are absent, rather than represented by sentinels or inferred current-runtime values. Gameplay/runtime audit records use the namespace as identity and retain scope only as separately validated evidence. + - Scheduling context (when applicable) - `triggerMode` (for example `NORMAL` vs `CATCH_UP`) - Exactly one of `dueTickId` or `dueAt` (for timers/intervals); the alternate field is absent/`NULL` @@ -174,7 +179,7 @@ Rules: During rollback, operator views must show the handler's `finalStage`/`finalOutcome` beside the `commandHandoffDispositions[]` returned from `ListScriptHandoffEvents`. A `TICK_HANDOFF` with `finalOutcome=handoff_accepted` therefore remains visible even when one or more individual commands later receive `version_fence_dropped`; a child result must never overwrite the handler result or collapse sibling command records. -Concrete example. Both child records below carry the complete `T123` Trigger Identity (`tenantId=11111111-1111-4111-8111-111111111111`, `gameInstanceId=44444444-4444-4444-8444-444444444444`, `playableStateScope=isolated`, `regionId=R2`, `regionEpoch=14`, `entityId=npc-guard-9`, `scriptId=guard-on-enter`, `eventType=onEnterRegion`, `eventSchemaVersion=1`, `scriptPatchVersion=P22`, `scriptPinEpoch=23`, `scriptEventId=evt-7f4c`, `isDryRun=false`) for correlation and diagnosis. The paired owner/audit evidence is `scriptPinControlPlaneRequestId=pin-req-22`; it is retained on each audit/child record and is not a Trigger Identity field. Each child is keyed by the complete Command-Handoff Identity: complete source/target runtime scope plus `automationDispatchId` and `commandOrdinal`. Parent Trigger Identity fields, `outboxWorkItemId`, and `scriptEventId` are not child uniqueness, deduplication, or replay keys. `automationDispatchId=dispatch-9` identifies the dispatch group, while `outboxWorkItemId=work-9` is parent correlation only. The `(automationDispatchId, commandOrdinal)` notation in the bullets is a display suffix, not a standalone key. This is a same-instance, same-runtime-scope example; the optional target fields (`targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`) are intentionally absent because no distinct target scope applies. +Concrete example. Both child records below carry the complete `T123` Trigger Identity (`tenantId=11111111-1111-4111-8111-111111111111`, `gameInstanceId=44444444-4444-4444-8444-444444444444`, `playableStateNamespaceId=55555555-5555-4555-8555-555555555555`, `regionId=R2`, `regionEpoch=14`, `entityId=npc-guard-9`, `scriptId=guard-on-enter`, `eventType=onEnterRegion`, `eventSchemaVersion=1`, `scriptPatchVersion=P22`, `scriptPinEpoch=23`, `scriptEventId=evt-7f4c`, `isDryRun=false`) for correlation and diagnosis. The same records retain `playableStateScope=isolated` as separately validated policy/routing/authorization/migration-fence evidence; the paired `scriptPinControlPlaneRequestId=pin-req-22` is also retained as owner evidence and is not part of Trigger Identity. Each child is keyed by the complete Command-Handoff Identity: complete source/target runtime identity plus `automationDispatchId` and `commandOrdinal`. Parent Trigger Identity fields, `outboxWorkItemId`, and `scriptEventId` are not child uniqueness, deduplication, or replay keys. `automationDispatchId=dispatch-9` identifies the dispatch group, while `outboxWorkItemId=work-9` is parent correlation only. The `(automationDispatchId, commandOrdinal)` notation in the bullets is a display suffix, not a standalone key. This is a same-instance, same-runtime-scope example; the optional target fields (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`) are intentionally absent because no distinct target scope applies. - `script_event_audit` row for Trigger Identity `T123` ends with `finalStage=TICK_HANDOFF`, `finalOutcome=handoff_accepted`. - The handler emitted two commands. Later, Game Session rejects only the child ending in `(automationDispatchId=dispatch-9, commandOrdinal=1)` under the same complete command-handoff scope during rollback convergence and appends a child disposition with `outcome=version_fence_dropped`, `reason=script_patch_mismatch`, `sourceService=game-session`, and `recordedAt=...`; the child ending in `(automationDispatchId=dispatch-9, commandOrdinal=0)` remains a separate sibling record. @@ -186,6 +191,7 @@ Illustrative record shape: { "tenantId": "11111111-1111-4111-8111-111111111111", "gameInstanceId": "44444444-4444-4444-8444-444444444444", + "playableStateNamespaceId": "55555555-5555-4555-8555-555555555555", "playableStateScope": "isolated", "regionId": "R2", "regionEpoch": 14, @@ -231,6 +237,7 @@ Illustrative record shape: { "tenantId": "11111111-1111-4111-8111-111111111111", "gameInstanceId": "44444444-4444-4444-8444-444444444444", + "playableStateNamespaceId": "55555555-5555-4555-8555-555555555555", "regionId": "R2", "regionEpoch": 14, "entityId": "npc-guard-9", @@ -260,6 +267,7 @@ Illustrative record shape: { "tenantId": "11111111-1111-4111-8111-111111111111", "gameInstanceId": "44444444-4444-4444-8444-444444444444", + "playableStateNamespaceId": "55555555-5555-4555-8555-555555555555", "regionId": "R2", "regionEpoch": 14, "entityId": "npc-guard-9", diff --git a/design/architecture/system-architecture-scripting-operations-cookbook.md b/design/architecture/system-architecture-scripting-operations-cookbook.md index 06e6721fa8..d1ca3dc930 100644 --- a/design/architecture/system-architecture-scripting-operations-cookbook.md +++ b/design/architecture/system-architecture-scripting-operations-cookbook.md @@ -167,7 +167,7 @@ For pending and dead-lettered work, use control-plane APIs rather than direct da - Replay phase semantics are stage-aware. A pre-claim authority or policy-unavailability result is `outcome=rejected`, records the bounded `rejectionReason`, creates no recovery claim or attempt, and leaves the row `DEAD_LETTERED`. Once a recovery claim/attempt is durably created, any failed evaluation or dispatch attempt must terminalize that attempt as `FAILED` and return `outcome=recovery_failed` with its persisted bounded `failureReason`; it must not be relabeled as a pre-claim rejection. A new request may create another attempt only after the prior attempt is terminal `FAILED` and fresh eligibility/fence checks pass; an `IN_PROGRESS` or unreconciled claim remains ineligible. Each requested ID returns exactly one bounded result (`retried_evaluation`, `resumed_dispatch`, `already_recovered`, `recovery_failed`, or `rejected`) with the canonical `failureGeneration` when a generation is resolved, bound to `(tenantId, outboxWorkItemId, failureGeneration)`, plus its applicable reason. The recovery claim/attempt has its own persisted attempt identity; this API does not expose a separate recovery-attempt generation, so no second generation field should be inferred. One row's result never changes another row's outcome or aggregate count. - **Target-state only and capability-gated:** `PurgeOutboxWorkItems(tenantId=11111111-1111-4111-8111-111111111111, scriptPatchVersion=P22, scriptPinEpoch=41, workItemIds=[work-9], controlPlaneRequestId=PURGE-42, actor=operator:alice, reason="rollback RB-42")` is auditable cleanup only when each selected work item matches the displaced exact tuple, is terminal (`HANDED_OFF`, `CANCELED`, or `DEAD_LETTERED`), and its configured retention horizon has elapsed. For evaluated descriptor/output evidence, the parent must be `EVALUATED_COMMITTED`, the parent and every child/evidence record must be retention-eligible, and every child must be terminal before that evidence is purged; a same-version repin with a newer epoch does not by itself make terminal rows from the displaced tuple ineligible, but the selector must remain the displaced exact tuple so current-epoch rows cannot be selected. For a pre-DSL `DEAD_LETTERED` row with no committed descriptor, purge may remove only terminal, retention-eligible trigger/failure payloads after the recovery eligibility window has expired, after resolving the current `failureGeneration` and atomically CASing recovery claim/attempt state. Any current-generation `IN_PROGRESS` claim, including an expired claim not yet canonically reclaimed, rejects with `recovery_in_progress` and deletes no evidence; only when no current-generation claim exists or its claim/attempt is terminal may purge proceed. For that pre-DSL path, no new schema marker is introduced: the retained purge audit/idempotency outcome is the durable evidence and makes the row permanently non-recoverable, so later replay rejects deterministically with `rejectionReason=stage_evidence_unavailable`; its immutable identity/digest, failure-stage, corresponding `script_event_audit`, and recovery-causation evidence remain retained under their owning retention contracts. When terminal descriptor/evaluated-output evidence is purged under the retained parent, the same transaction persists durable `descriptorEvidencePurgedAt`; that marked parent is non-recoverable and non-replayable, and consumers reject it deterministically rather than treating missing children as recoverable. The purge does not mutate active or nonterminal work. -For command-level diagnosis, use the [Scripting & Automation Observability Contract](./system-architecture-scripting-observability-contract.md) and [Command Identity and Live Handoff Boundary](./system-architecture-scripting-rollout-and-rollback.md#command-identity-and-live-handoff-boundary). The target query is `ListScriptHandoffEvents`; child replay and deduplication use the complete source runtime scope plus any distinct target runtime scope, the persisted `automationDispatchId`, and deterministic `commandOrdinal` from canonical output order. The full parent Trigger Identity (including `bindingId` where applicable), `outboxWorkItemId`, and `scriptEventId` are correlation only; bounded `workItemIds[]` are parent-row selectors only and cannot replace the child identity. When a distinct target runtime exists, its complete query/reference identity includes `targetGameInstanceId`, optional `targetPlayableStateScope`, `targetRegionId`, and `targetRegionEpoch`. The current live fallback is the correlation of `script_event_audit`, narrower Automation handoff/work-item rows, `outboxWorkItemId`, `automationDispatchId`, `gameSessionCommandId`, and the Game Session command/result/fence fields currently exposed. Do not infer complete Trigger Identity or downstream per-command disposition from that fallback. +For command-level diagnosis, use the [Scripting & Automation Observability Contract](./system-architecture-scripting-observability-contract.md) and [Command Identity and Live Handoff Boundary](./system-architecture-scripting-rollout-and-rollback.md#command-identity-and-live-handoff-boundary). The target query is `ListScriptHandoffEvents`; child replay and deduplication use the [canonical Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state): ``. When a distinct target runtime scope applies, `targetGameInstanceId`, `targetRegionId`, and `targetRegionEpoch` are required; include `targetPlayableStateNamespaceId` only when the target owns a playable-state namespace. Source and target `playableStateScope` values remain separately validated evidence, not identity fields. The full parent Trigger Identity (including `bindingId` where applicable), `outboxWorkItemId`, and `scriptEventId` are correlation only; bounded `workItemIds[]` are parent-row selectors only and cannot replace the child identity. The current live fallback is the correlation of `script_event_audit`, narrower Automation handoff/work-item rows, `outboxWorkItemId`, `automationDispatchId`, `gameSessionCommandId`, and the Game Session command/result/fence fields currently exposed. Do not infer complete Trigger Identity or downstream per-command disposition from that fallback. For the canonical rollback and version-fence requirements, follow [Scripting & Automation: Rollout and Rollback](./system-architecture-scripting-rollout-and-rollback.md#patch-rollback-operator-driven-required) and [Scripting & Automation: Cross-Service Contracts](./system-architecture-scripting-contracts.md#3-version-fencing-rollback-safety). diff --git a/design/architecture/system-architecture-scripting-quotas-and-operations.md b/design/architecture/system-architecture-scripting-quotas-and-operations.md index 847966b64c..48720005d3 100644 --- a/design/architecture/system-architecture-scripting-quotas-and-operations.md +++ b/design/architecture/system-architecture-scripting-quotas-and-operations.md @@ -157,7 +157,7 @@ Per-script scheduling knobs control how often scripts are allowed to run and how - Queued triggers retain their durable admission charge but hold no execution capacity. An event-scope limiter may reject an incoming trigger before handler resolution, but that is not a per-script quota charge and uses event-scope ingress audit and drop metrics. After handler resolution, `ScriptQuotaService` records one charge for each resolved handler and may deny it with `script_event_audit.finalStage=ADMISSION`, `finalOutcome=quota_denied`, and the handler outcome metric rather than the dropped-ingress metric. - **`priorityTag`** – assigns a priority tier (`high`, `normal`, `background`) that interacts with per-tenant budgets and cluster ceilings. When capacity is tight, the scheduler applies tenant fairness first, then admits `high`-priority work preferentially within each tenant's allocated share, deferring or dropping lower-priority triggers according to budget and quota rules. -Timer and interval limits are evaluated against the canonical runtime scope tuple ``. A per-tenant or per-game-instance timer limit must not substitute for that tuple and accidentally couple unrelated instances or regions; any broader aggregate ceiling is an additional explicitly named safety limit. `playableStateScope` remains part of trigger identity and handler/work fencing, but it does not replace the scheduler's runtime scope tuple for these timer-capacity limits. +Timer and interval limits are evaluated against the canonical mode-specific per-namespace runtime scope tuple ``. A per-tenant or per-game-instance timer limit must not substitute for that tuple and accidentally couple unrelated playable-state namespaces, regions, or live/test modes; any separately named broader aggregate ceiling (for example, a cluster-wide safety limit) is an additional safety limit. `playableStateScope` is server-derived and must be exact-validated against the authoritative namespace/routing proof, then retained unchanged as separately persisted policy/routing/authorization/migration-fence evidence on event-scope ingress, durable schedules, due-candidate records, firing claims, candidate-audit records, mode-specific resume-window records, handler/work items, and per-command handoff records. This persistence list is non-exhaustive; the complete timer identity and recovery projections are owned by [Scripting Scheduler and Timer Lifecycle](./system-architecture-scripting-scheduler-and-timers.md#target-state-design) and the [normative timer semantics matrix](./system-architecture-scripting-normative-contract-tables.md#table-3-timer-semantics-matrix). Logs, audit rows, and traces may carry bounded correlation copies for diagnosis, but those copies do not become authority and must not be used to reconstruct or override the retained evidence. Scope evidence does not replace the scheduler's runtime scope tuple or become a Trigger Identity, uniqueness, or deduplication input; see the [normative identity tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). ### `onLoad` Initialization Capacity @@ -265,7 +265,7 @@ The **target-state** canonical `script_event_audit` schema includes: - `sourceService` – producing service identity for custom/service-specific events so operators can diagnose routing and authorization problems. - `tickId` – canonical tick identifier associated with the trigger when the trigger is tick-aligned or once commands are accepted into the tick system. -For tenant-readiness `onLoad` triggers, `gameInstanceId`, `playableStateScope`, `regionId`, `regionEpoch`, `entityId`, and `scriptPinEpoch` are omitted; they must not be populated with sentinel values. Their existing identity remains ``. Gameplay/runtime triggers require `scriptPinEpoch` with `scriptPatchVersion` and include the other fields when applicable according to the normative Trigger Identity table. +For tenant-readiness `onLoad` triggers, `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, `regionEpoch`, `entityId`, and `scriptPinEpoch` are omitted; they must not be populated with sentinel values. Their existing identity remains ``. Gameplay/runtime triggers require `scriptPinEpoch` with `scriptPatchVersion` and include the other fields when applicable according to the normative Trigger Identity table. Current instance-scoped ingress validates the exact owner tuple before handler work is admitted, Automation persists that tuple on work-item and handoff-audit evidence, and the local Game Session handoff, durable staging/replay, and final execution boundaries revalidate it. The remaining downstream gap is distinct-instance remote source/target binding and remote final-effect fencing; see the [Automation & Scripting Service implementation status](./microservices/automation-scripting-service/runtime-and-data.md#implementation-status). @@ -325,7 +325,7 @@ Plugin executions use the Table 4 bounded plugin classifications rather than raw Script execution spans several services (Game Design, Game Session, Automation & Scripting, Game Logic, Logging & Admin). To support end-to-end debugging and replay, the system relies on a shared set of identifiers: - `tenantId`, `gameInstanceId`, and `regionId` – identify the running game instance and region. -- `playableStateScope` (gameplay/runtime only) – identifies the resolved admitted gameplay-state namespace; shared and isolated realm state must not collide. Retain it in applicable audit/log/trace correlation, not as a metric label. See the [normative Trigger Identity table](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields); tenant-readiness `onLoad` intentionally omits it. +- `playableStateNamespaceId` (gameplay/runtime only) – identifies the durable playable-state namespace in applicable Trigger Identity and deduplication. `playableStateScope` is separately persisted and exact-validated policy/routing/authorization/migration-fence evidence; retain it in applicable audit/log/trace correlation, not as an identity or metric label. See the [normative Trigger Identity table](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields); tenant-readiness `onLoad` intentionally omits both fields. - `regionEpoch` – fences triggers and tick effects across scoped coordination resets. - `entityId` – identifies the target entity for script-driven work. - `scriptId` and `scriptPatchVersion` identify the script definition; gameplay/runtime rows also require `scriptPinEpoch` to identify the Game Session selection epoch. Tenant-readiness `onLoad` rows omit `scriptPinEpoch`. @@ -341,8 +341,8 @@ These identifiers are intended to appear in the following observability surfaces A typical troubleshooting flow for a problematic script or plugin is: -1. Start from a player-visible issue or a game tick log that includes `tenantId`, `gameInstanceId`, `playableStateScope` when gameplay/runtime-scoped, `regionId`, `regionEpoch`, `entityId`, and `tickId`. -2. Join the tick log, `script_event_audit`, and logs/traces by the complete applicable Trigger Identity: `tenantId`, `gameInstanceId`, `playableStateScope` when gameplay/runtime-scoped, `regionId`, `regionEpoch`, `entityId` when applicable, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch` when applicable, `scriptEventId`, `isDryRun`, and plugin/scheduler fields when applicable. `scriptEventId` and `correlationId` are scoped filters that narrow a search; neither is a standalone execution identity and neither may be used as the join key without the remaining applicable fields. Do not rely on `scriptEventId` as a metric label; use metrics to understand aggregate rates by bounded `scope` / `script_kind` / `event_class` dimensions and use audit/log/trace queries for per-trigger correlation. +1. Start from a player-visible issue or a game tick log that includes `tenantId`, `gameInstanceId`, `playableStateNamespaceId` when gameplay/runtime-scoped, `regionId`, `regionEpoch`, `entityId`, and `tickId`; retain `playableStateScope` separately as exact-validated policy/routing/authorization/migration-fence evidence. +2. Join the tick log, `script_event_audit`, and logs/traces by the complete applicable Trigger Identity: `tenantId`, `gameInstanceId`, `playableStateNamespaceId` when gameplay/runtime-scoped, `regionId`, `regionEpoch`, `entityId` when applicable, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch` when applicable, `scriptEventId`, `isDryRun`, and plugin/scheduler fields when applicable. Retain `playableStateScope` as separately persisted, exact-validated policy/routing/authorization/migration-fence evidence for filtering/readback, not as identity or a join-key dimension. `scriptEventId` and `correlationId` are scoped filters that narrow a search; neither is a standalone execution identity and neither may be used as the join key without the remaining applicable fields. Do not rely on `scriptEventId` as a metric label; use metrics to understand aggregate rates by bounded `scope` / `script_kind` / `event_class` dimensions and use audit/log/trace queries for per-trigger correlation. 3. From the identity-matched records, identify the responsible `scriptId`, `scriptPatchVersion`, and, where applicable, `pluginId`/`pluginVersionId`/`bindingId`. 4. Cross-reference the associated publish or plugin enable/disable actions in Game Design and Logging & Admin using the same identifiers. @@ -421,7 +421,7 @@ The **authoritative, up-to-date list of environment variables and defaults** liv - **Quota knobs** – control per-script and per-tenant quota windows and budgets used by `ScriptQuotaService` and the multi-level budgeting model (for example, limits on how many triggers a script or tenant may execute per window). - **Execution batch knobs** – bound how much automation work the durable executor performs per scheduling window, including batch sizes, per-window budgets, and cluster-wide ceilings on automation events. -- **Timer and scheduling knobs** – influence `onInterval` / `onTimerExpire` behavior, including cadence and maximum timers evaluated per canonical runtime scope tuple ``, plus any backoff or delay settings applied when regions are degraded. +- **Timer and scheduling knobs** – influence `onInterval` / `onTimerExpire` behavior, including cadence and maximum timers evaluated per canonical mode-specific per-namespace runtime scope tuple ``, plus any separately named broader aggregate ceilings and backoff or delay settings applied when regions are degraded. - **Audit and retention knobs** – govern how long `script_event_audit` and related records remain available for troubleshooting, and how large those tables are allowed to grow before automated cleanup; retention is typically controlled via `SCRIPT_EVENT_AUDIT_RETENTION_DAYS` and `SCRIPT_EVENT_AUDIT_MAX_ROWS`, with exact defaults and semantics documented in [Automation & Scripting Service Configuration](./microservices/automation-scripting-service/configuration.md#service-specific-variables). For the exact variable names, defaults, and any future additions, always refer to [Automation & Scripting Service Configuration](./microservices/automation-scripting-service/configuration.md#service-specific-variables) rather than the README or this document. diff --git a/design/architecture/system-architecture-scripting-runtime-execution.md b/design/architecture/system-architecture-scripting-runtime-execution.md index 6e621f0da8..87a627f326 100644 --- a/design/architecture/system-architecture-scripting-runtime-execution.md +++ b/design/architecture/system-architecture-scripting-runtime-execution.md @@ -68,13 +68,13 @@ For a local instance-scoped core-script Automation command, the execution identi This section records current implementation boundaries, not target-state authority. The normative contracts below and the linked owning documents remain canonical. Metric names, labels, and increment units are owned by [Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix); audit fields and handoff diagnostics are owned by the [Scripting & Automation Observability Contract](./system-architecture-scripting-observability-contract.md). Normative audit stage/outcome semantics and final lifecycle statuses remain owned by the normative audit and scripting lifecycle/rollout documents. -The current runtime now includes a first durable work-item executor instead of stopping at ingress-only outbox materialization. During ingress, after handler resolution, Automation acquires per-script quota for live `STANDARD_RUNTIME` handlers before persisting `PENDING_EVALUATION` work. The executor claims `PENDING_EVALUATION` rows without re-charging that per-script quota; it separately applies tenant-budget, publish-readiness, or isolated dry-run capacity controls as applicable before loading the persisted script definition, evaluating a current-boundary command-emission format, and handing emitted commands to Game Session through `EnqueueAutomationCommandIfAbsent`. The target durable full-Trigger-Identity charge record and separate exactly-once admission/execution-start markers remain unimplemented. The replay and evaluated-descriptor layers described by the target lifecycle are target-only. The current implementation still uses one `script_work_items` row spanning the pre-DSL trigger and later handoff processing; it does not yet implement the target separation between durable trigger state and evaluated command descriptors or descriptor-only replay. +The current runtime now includes a first durable pre-DSL trigger-record executor instead of stopping at ingress-only outbox materialization. During ingress, after handler resolution, Automation acquires per-script quota for live `STANDARD_RUNTIME` handlers before persisting `PENDING_EVALUATION` trigger records. The executor claims `PENDING_EVALUATION` rows without re-charging that per-script quota; it separately applies tenant-budget, publish-readiness, or isolated dry-run capacity controls as applicable before loading the persisted script definition, evaluating a current-boundary command-emission format, and handing emitted commands to Game Session through `EnqueueAutomationCommandIfAbsent`. The target full-Trigger-Identity admission and execution-start charge markers on the same durable pre-DSL trigger-record/work-item row remain unimplemented. The replay and evaluated-descriptor layers described by the target lifecycle are target-only. The current implementation still uses one `script_work_items` row spanning the pre-DSL trigger record and later handoff processing; it does not yet implement the target separation between durable trigger records and evaluated script work items or descriptor-only replay. ### Current evaluator boundary The current evaluator supports a bounded emitted-command collection per work item, assigns deterministic local ordinals in emitted-command order, and attempts handoff for each emitted command. An actual configured output-count or per-entity limit is rejected before output/descriptor persistence or handoff; the pre-DSL parent work item was claimed from `PENDING_EVALUATION` and is `EVALUATING` at evaluation time, then its durable terminal transition and audit row record `finalStage=DSL_EVAL`, `finalOutcome=sandbox_error`, and the exact bounded limit reason (`command_count_exceeded` or `per_entity_command_limit_exceeded`). The target contract remains canonical in [Scripting & Automation: Cross-Service Contracts](./system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary), including deterministic identity under the complete [Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state). -That current-boundary execution format is intentionally narrow but no longer raw-text-only: script definitions may expose `emitCommands` at the top level or under `eventHandlers..emitCommands`, and each emitted command may currently carry either direct `commandText` or a structured `commandAlias` plus templated `arguments`, along with an optional target entity or bounded `targetEntityIds[]` list, optional explicit target runtime scope (`targetGameInstanceId`, `targetRegionId`, `targetRegionEpoch`), `requiresSoloTick`, and optional `dueTickId`. The evaluator may expand `targetEntityIds[]` locally and attempt one command per listed target. If no target is present, the command targets the triggering work item's entity; if explicit target runtime scope is absent, the command defaults to the triggering work item's owned gameplay scope. Each resulting command receives a local ordinal and is attempted through the handoff service, but this local expansion is not the target-state multi-target fan-out contract: the live wire does not carry the complete per-target identity or target `playableStateScope`, so complete handoff identity, scope validation, deduplication, and end-to-end progress remain unproved. Command nodes may also carry bounded `when` / `unless` predicate maps over durable work-item metadata and flat primitive payload fields; target-state command ordinals and optional `targetPlayableStateScope` distinguish emitted commands after handoff identity is widened. Template substitution is still limited to durable work-item metadata and flat primitive payload fields such as `{{payload.commandName}}`. Richer graph execution and broader DSL semantics remain target-state work above this first production evaluator path. +That current-boundary execution format is intentionally narrow but no longer raw-text-only: script definitions may expose `emitCommands` at the top level or under `eventHandlers..emitCommands`, and each emitted command may currently carry either direct `commandText` or a structured `commandAlias` plus templated `arguments`, along with an optional target entity or bounded `targetEntityIds[]` list, optional explicit target runtime scope (`targetGameInstanceId`, `targetRegionId`, `targetRegionEpoch`), `requiresSoloTick`, and optional `dueTickId`. The evaluator may expand `targetEntityIds[]` locally and attempt one command per listed target. If no target is present, the command targets the triggering pre-DSL trigger record's entity; if explicit target runtime scope is absent, the command defaults to the triggering pre-DSL trigger record's owned gameplay scope. Each resulting command receives a local ordinal and is attempted through the handoff service, but this local expansion is not the target-state multi-target fan-out contract: the live wire does not carry the complete per-target identity or target `playableStateScope`, so complete handoff identity, scope validation, deduplication, and end-to-end progress remain unproved. Command nodes may also carry bounded `when` / `unless` predicate maps over durable pre-DSL trigger-record metadata and flat primitive payload fields; target-state command ordinals and optional `targetPlayableStateNamespaceId` distinguish emitted commands after handoff identity is widened, while target `playableStateScope` remains separately exact-validated evidence. Template substitution is still limited to durable pre-DSL trigger-record metadata and flat primitive payload fields such as `{{payload.commandName}}`. Richer graph execution and broader DSL semantics remain target-state work above this first production evaluator path. The current claim boundary is the atomic PostgreSQL transition from `PENDING_EVALUATION` to `EVALUATING`; the existing Game Session lease rules govern region-owned tick execution, not Automation work-item claims. The current implementation has no evaluation lease expiry, fencing generation, descriptor-commit marker, or recovery owner. Its `GetAutomationDrainStatus` projection selects the counted epoch set by mode: `NORMAL` includes only rows whose `workItem.admissionEpoch` equals the current `admissionEpoch`, while `PAUSED_FOR_ROLLBACK` includes rows whose `workItem.admissionEpoch <= 0` or `workItem.admissionEpoch < current admissionEpoch`, excluding positive current-epoch rows. Within that set `activeExecutionCount` counts `EVALUATING` and `HANDOFF_IN_FLIGHT`, including unresolved stale `EVALUATING`, and `pendingCancelableWorkItemCount` counts `PENDING_EVALUATION`. These are current implementation gaps: the current runtime retains unresolved work and keeps the Automation admission barrier closed; ordinary gameplay ticks continue except within a separately declared unfenced-effect workflow. It cannot safely resume or promise terminal audit from lease age alone. The target mapping and recovery behavior are defined below, and current tooling must not infer reclaim, terminalization, or re-entry to the DSL. @@ -89,14 +89,14 @@ Target local instance admission and replay use Automation's bounded-fresh exact **Target-state remote-follow-up consequence:** When a follow-up crosses to a distinct target game instance, the source work retains the originating exact `(scriptPatchVersion, scriptPinEpoch)` as immutable provenance and source rollback-fence evidence, with its paired `scriptPinControlPlaneRequestId` retained separately as immutable source pin-owner evidence rather than as an operation-scoped request ID. Before target-side Automation admission, Game Session revalidates that source tuple and owner evidence, reads and freezes the target instance's current exact tuple and paired owner request evidence, and binds both roles to the target delivery/claim and immutable request/dedupe evidence. Target event/handler Trigger Identity and target-side script admission/execution fences use the target tuple, not the source tuple; the paired request IDs remain non-identity evidence. Retries reuse both frozen tuples and their paired owner evidence; source or target displacement/conflict fails closed, authority unavailability remains retryable with no target admission, and target `UNPINNED` creates no target script work. A same-instance cross-region follow-up uses one exact tuple and paired owner evidence for both roles. For semantic target `UNPINNED`, Game Session applies the owner-defined durable/replayable result encoding and exact-retry/conflict rules; the target creates no Automation event, work item, or command. See the [Game Session remote-follow-up result contract](./microservices/game-session-service/api-contracts.md#service-interactions). Authority unavailability remains retryable and non-admitted rather than becoming that finalized result. -Current dedupe, rejection, and status diagnostics use the available `outboxWorkItemId`/parent work-item correlation, persisted `automationDispatchId`, Game Session `commandId`/persisted `gameSessionCommandId`, command text, selected provenance, and `script_event_audit`. `outboxWorkItemId` is not a per-command discriminator. This is a live diagnostic and retry fallback only; it does not claim end-to-end complete Trigger Identity, `commandOrdinal`, independent per-command progress, or target command-level deduplication/fence proof. +Current dedupe, rejection, and status diagnostics use the available `outboxWorkItemId`/parent pre-DSL trigger-record correlation, persisted `automationDispatchId`, Game Session `commandId`/persisted `gameSessionCommandId`, command text, selected provenance, and `script_event_audit`. `outboxWorkItemId` is not a per-command discriminator. This is a live diagnostic and retry fallback only; it does not claim end-to-end complete Trigger Identity, `commandOrdinal`, independent per-command progress, or target command-level deduplication/fence proof. ## Pre-DSL Trigger and Evaluated Descriptor Boundary The durable pre-DSL trigger state and the post-DSL evaluated command descriptor/outbox are separate durable roles: - The target lifecycle for the **pre-DSL trigger record** is `PENDING_EVALUATION` -> `EXECUTING` -> `EVALUATED_COMMITTED`, with explicit terminal cancellation/dead-letter transitions only where the cancellation and stale-recovery rules below permit them. The record owns the complete applicable Trigger Identity, event payload, pinned script/configuration and artifact references, the immutable handler-scoped input manifest, admission epoch, evaluation lease, fencing generation, and the durable descriptor-commit marker/status. Before that descriptor commit, a command-capable gameplay/runtime evaluation has no `automationDispatchId` or command-child identity. It contains no evaluated gameplay command descriptors. The manifest is the deterministic read input; an owner-specific `read_snapshot_token`, when applicable, is one recorded manifest entry rather than universal authority. -- The **evaluated command descriptor/outbox** is created only after DSL evaluation. It contains the immutable evaluated descriptor for each emitted command, including `automationDispatchId` and `commandOrdinal`, plus parent `outboxWorkItemId` correlation, the applicable trigger/configuration inputs, and optional `targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, and `targetRegionEpoch` when the command has a distinct target runtime scope needed for handoff and replay. +- The **evaluated command descriptor/outbox** is created only after DSL evaluation. It contains the immutable evaluated descriptor for each emitted command, including `automationDispatchId` and `commandOrdinal`, plus parent `outboxWorkItemId` correlation, the applicable trigger/configuration inputs, and optional `targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, and `targetRegionEpoch` when the command has a distinct target runtime scope needed for handoff and replay. The target `playableStateScope` remains separately persisted and exact-validated as policy/routing/authorization/migration-fence evidence. **Target state only:** Before DSL evaluation, the worker acquires the separately fenced, reclaimable capacity lease and uses one Automation-owned durable executor-acceptance transaction to revalidate the current fence, durably accept/claim the run for the executor, persist the exactly-once execution-start marker, and compare-and-set the pre-DSL trigger to `EXECUTING` with a monotonically increasing fencing generation. Evaluation begins only after that transaction commits. Tenant-readiness `onLoad` is non-emitting and neither allocates nor exposes a command dispatch identity. The worker may commit evaluated descriptors only while that lease and generation are current. If commands are emitted, the descriptor rows, their parent outbox record, the persisted `automationDispatchId` and canonical ordinals, the terminal evaluation outcome, and the audit update are committed atomically with a compare-and-set transition from `EXECUTING` to `EVALUATED_COMMITTED` in one transaction; a valid zero-command evaluation creates no dispatch identity. A non-cancellation retry after that commit boundary loads the committed descriptors and replays handoff; it never re-enters the DSL. If executor acceptance cannot commit, the transition does not occur, the lease is released or reclaimed, and no execution charge is recorded. @@ -107,11 +107,11 @@ Target-state cancellation of pre-DSL trigger states is durable and fencing-aware - `PENDING_EVALUATION` transitions by compare-and-set to terminal `CANCELED` without entering the DSL. The same durable transition records `cancelReason` and updates `script_event_audit` to `finalStage=ADMISSION`, `finalOutcome=canceled`, and the applicable bounded reason, such as `operator_canceled` or `rollback_epoch_advanced`. - `EXECUTING` cancellation first fences the claimed attempt and reads the descriptor-commit marker/status. If the state is or becomes `EVALUATED_COMMITTED`, cancellation never resumes or re-dispatches a committed child: evaluated `PENDING` and `INDEXED` children compare-and-set to `CANCELED` with durable `cancelReason`, `finalStage=WORK_ITEM_PERSIST`, and `finalOutcome=canceled`; `HANDOFF_IN_FLIGHT` fences further retry and reconciles the durable downstream outcome, remaining active/unresolved when that outcome is ambiguous; and `HANDED_OFF`, `CANCELED`, or `DEAD_LETTERED` children retain their outcome and no-op. Recovery of that committed state is a separate path owned by the control-plane recovery contract and may replay only the stored child ledger; cancellation itself does not dispatch. If no descriptor was committed, explicit cancellation compare-and-sets the trigger to terminal `CANCELED` and records `cancelReason`, `finalStage=DSL_EVAL`, `finalOutcome=canceled`, and the applicable bounded cancellation reason; this terminal cancellation is never replay-eligible. If the lease is instead expired and stale, only the distinct recovery-owner transition may make the row terminal `DEAD_LETTERED` with `finalStage=DSL_EVAL`, `finalOutcome=canceled`, and `finalReason=stale_execution_fenced`. -Cancellation and automatic stale-executor recovery never invoke or re-enter the DSL. Separately, control-plane evaluation-stage recovery may re-enter the DSL only when the persisted failure class is retryable under [Failure Modes and Error Handling](#failure-modes-and-error-handling), no descriptor has committed, and frozen manifest/graph evidence and the original work-item/Trigger Identity are present; non-retryable classes remain terminal/ineligible. Once a descriptor is committed, control-plane recovery replays the stored child ledger without DSL re-entry. These cancellation and automatic stale-recovery paths operate only on durable trigger state, descriptor-commit evidence, and already committed descriptors. +Cancellation and automatic stale-executor recovery never invoke or re-enter the DSL. Separately, control-plane evaluation-stage recovery may re-enter the DSL only when the persisted failure class is retryable under [Failure Modes and Error Handling](#failure-modes-and-error-handling), no descriptor has committed, and frozen manifest/graph evidence and the original pre-DSL trigger record/Trigger Identity are present; non-retryable classes remain terminal/ineligible. Once a descriptor is committed, control-plane recovery replays the stored child ledger without DSL re-entry. These cancellation and automatic stale-recovery paths operate only on durable trigger state, descriptor-commit evidence, and already committed descriptors. ## Work Item Outbox Contract (Normative) -The Automation & Scripting Service must treat Redis automation queues (`automation:queue:*`) as derived indexes/pointers only. The authoritative record of admitted post-DSL work is the durable work item outbox. Queue ownership, command handoff, and cross-service retry invariants are defined in the [scripting cross-service contracts](./system-architecture-scripting-contracts.md); this section retains the local outbox schema and projection behavior. +The Automation & Scripting Service must treat Redis automation queues (`automation:queue:*`) as derived indexes/pointers only. The authoritative record of admitted post-DSL work is the durable evaluated script work item outbox. Queue ownership, command handoff, and cross-service retry invariants are defined in the [scripting cross-service contracts](./system-architecture-scripting-contracts.md); this section retains the local outbox schema and projection behavior. This section defines the minimum contract that makes "persist -> index -> drain -> handoff" interoperable and rollback-safe across services and operational tooling. @@ -124,14 +124,14 @@ Each evaluated descriptor/outbox record must include: - Trigger Identity fields from [Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) (including `gameInstanceId` and, for gameplay/runtime triggers, `regionEpoch`). - The exact local `(scriptPatchVersion, scriptPinEpoch, scriptPinControlPlaneRequestId)` captured from the authoritative Game Session pin. A local active/latest pointer, version-only match, or unpaired owner request ID is insufficient. - `outboxWorkItemId` (stable parent correlation identifier; not descriptor identity). -- The unique child identity for each evaluated command descriptor: the complete Command-Handoff Identity, including optional `targetPlayableStateScope` and the other target runtime fields when a distinct target scope applies. `outboxWorkItemId` is parent correlation only and is excluded from command identity, uniqueness, and deduplication keys. +- The unique child identity for each evaluated command descriptor: the complete Command-Handoff Identity, including optional `targetPlayableStateNamespaceId` and all other target runtime fields whenever a distinct target runtime scope applies, including same-namespace cross-region handoff. Target `playableStateScope` remains separately persisted and exact-validated evidence and is excluded from command identity, uniqueness, and deduplication keys. `outboxWorkItemId` is parent correlation only and is excluded from command identity, uniqueness, and deduplication keys. - `createdAt` and `updatedAt`. - `workItemStatus` (per evaluated descriptor/command; see below, not a pre-DSL trigger or parent aggregate status). - The immutable evaluated command descriptor (one descriptor per emitted command, stored durably), including immutable `lane`, bounded `cost_class`, and `handoffRequirement` (`REQUIRED` or `OPTIONAL`) metadata. - `commandCount` (the immutable total number of committed descriptors for the parent `outboxWorkItemId`, for budgeting/inspection; it is not per-descriptor progress). - `cancelReason` (nullable; required when canceled). -`outboxWorkItemId` is the Automation-owned parent correlation identifier. At the current Game Session boundary, Automation produces `EnqueueAutomationCommandIfAbsentRequest.automationWorkItemId` with this same value, and Game Session consumes/reports it under the wire field name `automationWorkItemId`; these are boundary-specific names for one parent identifier, not separate work-item records. It is not the per-command discriminator and must not be used as command-level dedupe. +`outboxWorkItemId` is the Automation-owned parent correlation identifier. At the current Game Session boundary, Automation produces `EnqueueAutomationCommandIfAbsentRequest.automationWorkItemId` with this same value, and Game Session consumes/reports it under the wire field name `automationWorkItemId`; these are boundary-specific names for one parent identifier, not separate parent records or identities. In the current single-row model this identifier locates the pre-DSL trigger record; in the target model it locates the evaluated script work-item descriptor set. It is not the per-command discriminator and must not be used as command-level dedupe. Target-state per-command progress follows the [cross-service command boundary](./system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary): descriptor identity is the complete Command-Handoff Identity and is linked to the parent `outboxWorkItemId`. Each emitted command has independent durable progress, so a retry resumes only unresolved commands and cannot drop an unattempted command or replay a command already accepted or terminally rejected. A queue pointer may be deduplicated by parent `outboxWorkItemId` for index hygiene, but that does not deduplicate commands. The current live executor attempts each bounded emitted command, but the narrower handoff boundary above does not establish this target per-command identity or progress behavior end to end. @@ -141,7 +141,7 @@ Each emitted command is also represented by one durable child dispatch row under **Target-state handoff-requirement contract:** Evaluation commits the `handoffRequirement=REQUIRED|OPTIONAL` classification required by the accepted [durable per-dispatch handoff decision](./decisions/adr-0063-durable-per-dispatch-script-handoff.md) and persists it on both the evaluated descriptor and child dispatch before handoff. The value is bound by the immutable command digest but is not part of Command-Handoff Identity. Every emitted command must carry exactly one recognized value; missing, unknown, or contradictory descriptor/child evidence fails closed, and retry, readback, and recovery preserve the committed value rather than defaulting or reclassifying it. A valid zero-command evaluation creates no synthetic child. Parent convergence and optional-child retry follow that decision. -When a work item is handed to Game Session, the local wire boundary is: +When an evaluated script work item is handed to Game Session, the local wire boundary is: - `EnqueueAutomationCommandIfAbsent` carries the local handoff fields described in [Current Implementation Status](#current-implementation-status), and its response returns the live Game Session `commandId`/admission outcome. The target handoff identity and fenced acceptance rule are owned by the [cross-service scripting contracts](./system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary). @@ -191,9 +191,9 @@ For plugin-owned schedule-derived work, rebuilding a due candidate or firing cla Target-state rule: stable schedule rows carry the mutable current reconciled `(pluginActivationEpoch, lifecycleRevision)` pair for their current owner; due candidates, firing claims, candidate audits, and timer-derived work retain the immutable captured pair as execution-fence evidence across every mapping below. New evaluator or firing admission requires the exact current `(pluginActivationEpoch, lifecycleRevision)` under `ENABLED`; work may use only the immediately preceding `ENABLED` revision during same-version/same-epoch `DRAINING` when its winning admission CAS durably committed that revision before the durable Automation-owned `DRAINING` admission barrier was created. A non-executable or epoch-advancing transition supplies no predecessor exception. The current implementation does not yet persist and propagate this complete plugin fence across these surfaces; see [Current Implementation Status](#current-implementation-status) and the [Automation and Scheduler Runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). -The current `script_work_items` statuses span two target layers. `workItemStatus` on an evaluated descriptor is per descriptor/command; pre-DSL trigger status and any parent aggregate are separate scopes. Tooling must not collapse them into one command-outbox state machine: +The current `script_work_items` table is a pre-DSL trigger-record table, while its status vocabulary spans two target layers. `workItemStatus` on an evaluated script work item/descriptor is per descriptor/command; pre-DSL trigger status and any parent aggregate are separate scopes. Tooling must not collapse them into one command-outbox state machine: -Current legacy single-row marker: when the current executor completes a live non-`onLoad` zero-command evaluation on the `completed_no_commands` path, it stores that work item with `status=HANDED_OFF` as a terminal storage marker even though no command dispatch or Game Session handoff occurred. The authoritative outcome remains `finalStage=DSL_EVAL` / `finalOutcome=completed_no_commands`, with no dispatch identity; `HANDED_OFF` in this legacy single-row context is not evidence of a command handoff or `handoff_accepted`. This is implementation drift from the target two-layer status model and must not be treated as the target descriptor meaning below. +Current legacy single-row marker: when the current executor completes a live non-`onLoad` zero-command evaluation on the `completed_no_commands` path, it stores that pre-DSL trigger record with `status=HANDED_OFF` as a terminal storage marker even though no command dispatch or Game Session handoff occurred. The authoritative outcome remains `finalStage=DSL_EVAL` / `finalOutcome=completed_no_commands`, with no dispatch identity; `HANDED_OFF` in this legacy single-row context is not evidence of a command handoff or `handoff_accepted`. This is implementation drift from the target two-layer status model and must not be treated as the target descriptor meaning below. | Current or target status | Canonical target meaning | Drain and rebuild treatment | | --- | --- | --- | @@ -219,15 +219,15 @@ Recovery revalidates the exact admitted `(scriptPatchVersion, scriptPinEpoch)` e Replay preserves and revalidates the captured plugin lifecycle tuple at the stage boundary: `ENABLED` requires the exact current `lifecycleRevision`, while same-version/same-epoch `DRAINING` may resume only work whose winning admission CAS durably committed the immediately preceding `ENABLED` revision before the durable Automation-owned `DRAINING` admission barrier was created. It never refreshes a dead letter to an arbitrary lower revision, and a displaced item remains dead-lettered after a non-executable or epoch-advancing transition. -Recovery selection, eligibility, stage mapping, idempotency, and the atomic recovery claim/attempt owner are defined by [Control Plane Operations](./system-architecture-scripting-control-plane-operations.md#replaydeadletteredworkitems); that owner persists and revalidates the expected exact fence/binding and `controlPlaneRequestId`, including same-attempt claim reclaim. This runtime section records only local consequences: command-capable gameplay/runtime evaluation-stage recovery may invoke the DSL evaluator again only when the persisted failure class is retryable under [Failure Modes and Error Handling](#failure-modes-and-error-handling), using the original work-item and `scriptEventId`, original persisted payload, frozen manifest/graph evidence, exact admitted immutable graph and artifact references, and recorded digests, while remaining outside the normal admission path. Before its winning descriptor commit it allocates no dispatch or command-child identity; if commands are emitted, that first atomic evaluated-descriptor/outbox commit allocates and persists the `automationDispatchId` and ordinals, while retries after a winning commit reuse them. A valid zero-command evaluation creates no dispatch identity. Non-retryable classes remain terminal/ineligible, and recovery must never refresh to the latest/default payload, manifest, graph, or artifact. Post-evaluation recovery reads the immutable evaluated output and complete child-dispatch ledger keyed by the full Command-Handoff Identity, preserving original child identities, ordinals, downstream acknowledgements/outcomes, and per-child recovery state, and never invokes the DSL. A parent recovery aggregate marked `DEAD_LETTERED` because of a permanent required-child failure resumes this retained ledger as `resumed_dispatch`; a required-child cancellation does not mark that aggregate `DEAD_LETTERED`, so the canceled parent/children are not replay-eligible. Recovery never replaces or clears the `EVALUATED_COMMITTED` descriptor marker. Successful recovery clears only the separate parent recovery aggregate; purge may remove eligible descriptor evidence and writes `descriptorEvidencePurgedAt`, but retains the marker. `DRAINING` remains valid for recovery only when the work has ADR 0119's durable pre-`DRAINING` admission/fence evidence and exact plugin fences and policy evidence pass; a lifecycle state that invalidates admitted work fails closed. Evaluated-output and command digests are integrity evidence only, not substitutes for retained output or identity; `outboxWorkItemId`, the parent Trigger Identity, and `scriptEventId` remain correlation-only. Neither stage reopens the original audit row. +Recovery selection, eligibility, stage mapping, idempotency, and the atomic recovery claim/attempt owner are defined by [Control Plane Operations](./system-architecture-scripting-control-plane-operations.md#replaydeadletteredworkitems); that owner persists and revalidates the expected exact fence/binding and `controlPlaneRequestId`, including same-attempt claim reclaim. This runtime section records only local consequences: command-capable gameplay/runtime evaluation-stage recovery may invoke the DSL evaluator again only when the persisted failure class is retryable under [Failure Modes and Error Handling](#failure-modes-and-error-handling), using the original pre-DSL trigger record and `scriptEventId`, original persisted payload, frozen manifest/graph evidence, exact admitted immutable graph and artifact references, and recorded digests, while remaining outside the normal admission path. Before its winning descriptor commit it allocates no dispatch or command-child identity; if commands are emitted, that first atomic evaluated-descriptor/outbox commit allocates and persists the `automationDispatchId` and ordinals, while retries after a winning commit reuse them. A valid zero-command evaluation creates no dispatch identity. Non-retryable classes remain terminal/ineligible, and recovery must never refresh to the latest/default payload, manifest, graph, or artifact. Post-evaluation recovery reads the immutable evaluated output and complete child-dispatch ledger keyed by the full Command-Handoff Identity, preserving original child identities, ordinals, downstream acknowledgements/outcomes, and per-child recovery state, and never invokes the DSL. A parent recovery aggregate marked `DEAD_LETTERED` because of a permanent required-child failure resumes this retained ledger as `resumed_dispatch`; a required-child cancellation does not mark that aggregate `DEAD_LETTERED`, so the canceled parent/children are not replay-eligible. Recovery never replaces or clears the `EVALUATED_COMMITTED` descriptor marker. Successful recovery clears only the separate parent recovery aggregate; purge may remove eligible descriptor evidence and writes `descriptorEvidencePurgedAt`, but retains the marker. `DRAINING` remains valid for recovery only when the work has ADR 0119's durable pre-`DRAINING` admission/fence evidence and exact plugin fences and policy evidence pass; a lifecycle state that invalidates admitted work fails closed. Evaluated-output and command digests are integrity evidence only, not substitutes for retained output or identity; `outboxWorkItemId`, the parent Trigger Identity, and `scriptEventId` remain correlation-only. Neither stage reopens the original audit row. **Target-state only:** The control-plane recovery mutation accepts bounded explicit `workItemIds[]` only; descriptor references and filter selectors remain deferred until preview plus stable per-row proof. A `DEAD_LETTERED` evaluation-stage trigger with no committed descriptor may retry only when its persisted failure class is retryable under [Failure Modes and Error Handling](#failure-modes-and-error-handling), and its original work-item, `scriptEventId`, frozen manifest/graph evidence, and exact admitted immutable graph are present; a missing or contradictory stage record remains ineligible, and non-retryable classes remain terminal/ineligible. A parent recovery aggregate marked `DEAD_LETTERED` after a permanent required-child failure retains its `EVALUATED_COMMITTED` marker and may resume only the stored output/child ledger. The current mutation selects parent `workItemIds` and requeues eligible `script_work_items` rows, so it does not yet prove independent descriptor recovery. Command-capable gameplay/runtime evaluation-stage recovery may invoke the DSL evaluator again only for that retryable failure class, under the original identity and evidence, remains outside the normal admission path, allocates no dispatch or command-child identity before a winning descriptor commit, and must converge on the original work item. If commands are emitted, that first atomic descriptor commit allocates and persists the `automationDispatchId` and canonical ordinals; retries after a winning commit reuse them. A valid zero-command evaluation creates no dispatch identity. Post-evaluation recovery must resume only the stored output/child ledger and never invoke the DSL. Recovery must never move a dead-lettered item into a fresh admission path, regenerate output after the evaluation boundary, or append new history to the original audit row. Before recovery, the service must revalidate the current exact `(scriptPatchVersion, scriptPinEpoch)` execution identity, the paired `scriptPinControlPlaneRequestId` owner evidence, runtime `regionId`/`regionEpoch`, and admitted routing bundle (`playableStateScope`, world/realm identity, and pointer version); for plugin work, it must also revalidate the immutable `(pluginId, pluginVersionId, bindingId)` tuple, the captured `(pluginActivationEpoch, lifecycleRevision)` pair against the current Automation-owned lifecycle evidence, and fresh applicable activation/lifecycle, publication, component-policy, capability-grant, and signer evidence against the same scoped ``. `DRAINING` blocks new trigger admission; recovery requires ADR 0119's canonical durable pre-`DRAINING` admission-CAS/fence evidence and otherwise only remains eligible for a lifecycle state that does not invalidate admitted work. A captured-epoch mismatch returns `plugin_activation_epoch_mismatch`. A `DISABLED`, revoked, or policy-driven invalidation of admitted work returns `plugin_disabled`. If any authoritative fence or plugin-policy read is temporarily unavailable, return the applicable established bounded reason (`authority_unavailable`, `component_policy_unavailable`, or `signer_policy_unavailable`), leave the already-`DEAD_LETTERED` item unchanged with no recovery claim/attempt record, and persist the request-level rejected result so an exact retry of the same request replays it; only a later request with a new `controlPlaneRequestId` may retry after the evidence recovers. A proven fence, binding, publication, policy, or revocation mismatch remains terminal/ineligible, leaves the item `DEAD_LETTERED`, and produces no recovery claim/attempt record. -Target-state recovery is idempotent by stable `controlPlaneRequestId` for each original work item and Automation-owned `failureGeneration`. The first atomic parent recovery-aggregate transition into `DEAD_LETTERED` initializes generation `1`; a later re-entry advances it exactly once in that same transition, including a permanent required-child failure after the retained `EVALUATED_COMMITTED` marker, while an exact retry/no-op or failed recovery attempt that leaves the parent in the same generation does not advance it. Retrying the same operator request returns its stored per-work-item result and generation unchanged and creates no second recovery attempt or audit history. A new request resolves the current generation atomically: only same-generation successful-recovery evidence returns `outcome=already_recovered`; an older generation's success remains immutable and neither satisfies nor blocks recovery of a newer current generation. Claims are unique per current `(tenantId, outboxWorkItemId, failureGeneration)`, stale owners/generations fail CAS, and failure generation is not reused as a Trigger Identity or Command-Handoff Identity. Missing or contradictory stage evidence remains dead-lettered. +Target-state recovery is idempotent by stable `controlPlaneRequestId` for each original parent record and Automation-owned `failureGeneration`. The first atomic parent recovery-aggregate transition into `DEAD_LETTERED` initializes generation `1`; a later re-entry advances it exactly once in that same transition, including a permanent required-child failure after the retained `EVALUATED_COMMITTED` marker, while an exact retry/no-op or failed recovery attempt that leaves the parent in the same generation does not advance it. Retrying the same operator request returns its stored per-parent result and generation unchanged and creates no second recovery attempt or audit history. A new request resolves the current generation atomically: only same-generation successful-recovery evidence returns `outcome=already_recovered`; an older generation's success remains immutable and neither satisfies nor blocks recovery of a newer current generation. Claims are unique per current `(tenantId, outboxWorkItemId, failureGeneration)`, stale owners/generations fail CAS, and failure generation is not reused as a Trigger Identity or Command-Handoff Identity. Missing or contradictory stage evidence remains dead-lettered. ## `scriptEventId` Lifecycle and Deduplication -Trigger Identity, endpoint-specific `scriptEventId` ownership, audit uniqueness, and command-level retry identity are defined in the [normative contract tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) and [cross-service scripting contracts](./system-architecture-scripting-contracts.md#4-scripteventid-identity-and-at-most-once-dedupe). Runtime persistence carries the applicable identity on the durable work item and preserves it across queue projection, claims, and handoff attempts. +Trigger Identity, endpoint-specific `scriptEventId` ownership, audit uniqueness, and command-level retry identity are defined in the [normative contract tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) and [cross-service scripting contracts](./system-architecture-scripting-contracts.md#4-scripteventid-identity-and-at-most-once-dedupe). Runtime persistence carries the applicable identity on the durable pre-DSL trigger record and resulting evaluated script work item, preserving it across queue projection, claims, and handoff attempts. ## Runtime Deployment & Versioning @@ -253,19 +253,19 @@ Scripts do not execute inside the tick system. The Automation & Scripting Servic - Script-generated commands may fail due to lock contention or target remote regions, and Game Session handles those cases via its normal tick rescheduling and cross-region routing logic. - The Automation & Scripting Service only determines which commands to inject. It never mutates entity or world data directly. -For a non-exclusive multi-handler event, Automation assigns the resolved handlers a durable `handlerSequence` under [ADR 0118](./decisions/adr-0118-preselected-exclusive-handlers-and-durable-fanout-ordering.md). The event resolution record or equivalent durable manifest identifies the complete ordered set. That sequence and each handler's local command ordinal are preserved on work items, generated-command persistence, handoff records, Game Session command admission, retries, and final application. Consumers must not infer semantic order from enqueue time, database identity, Redis list position, worker claim order, scheduling priority, or arrival time. +For a non-exclusive multi-handler event, Automation assigns the resolved handlers a durable `handlerSequence` under [ADR 0118](./decisions/adr-0118-preselected-exclusive-handlers-and-durable-fanout-ordering.md). The event resolution record or equivalent durable manifest identifies the complete ordered set. That sequence and each handler's local command ordinal are preserved on evaluated script work items, generated-command persistence, handoff records, Game Session command admission, retries, and final application. Consumers must not infer semantic order from enqueue time, database identity, Redis list position, worker claim order, scheduling priority, or arrival time. This is target-state behavior. The current live Game Session handoff does not yet carry or prove the durable handler sequence and complete resolution evidence through handoff, Game Session admission, retry, and final application; it also lacks `commandOrdinal` and the complete Trigger/Command-Handoff Identity. Existing local ordinals and parent correlation are only current handoff bookkeeping and diagnostics, not semantic ordering authority or a fallback when target metadata is missing. A handler's terminal failure or empty output closes its sequence position and allows later non-exclusive handler commands to proceed without canceling them. A delayed lower sequence is not equivalent to a terminal failure; downstream application must retain or reconstruct enough resolution state to avoid applying a higher sequence prematurely. Missing or contradictory sequence/completeness metadata fails explicitly rather than degrading to arrival order. -Automation first resolves and seals the complete applicable core/plugin binding set, rejecting missing or contradictory completeness evidence, multiple exclusive claims, or unauthorized exclusive claims. It then selects an authorized exclusive binding before work-item fan-out; that binding is the only handler materialized for the event scope. If it fails or is denied, no sibling fallback is created. +Automation first resolves and seals the complete applicable core/plugin binding set, rejecting missing or contradictory completeness evidence, multiple exclusive claims, or unauthorized exclusive claims. It then selects an authorized exclusive binding before pre-DSL trigger-record fan-out; that binding is the only handler materialized for the event scope. If it fails or is denied, no sibling fallback is created. ## Output Budgeting and Command Fan-Out Admission and sandboxing must bound not only how often a handler runs, but also how much work a single admitted run can emit: -- Each DSL run must enforce explicit output budgets before a work item is persisted, including `maxCommandsPerRun`, `maxCommandsPerEntityPerTrigger`, and `maxSerializedWorkItemBytes`, plus any bounded payload ceilings needed for known large command families. +- Each DSL run must enforce explicit output budgets before an evaluated script work item is persisted, including `maxCommandsPerRun`, `maxCommandsPerEntityPerTrigger`, and `maxSerializedWorkItemBytes`, plus any bounded payload ceilings needed for known large command families. - Exceeding an output budget must fail deterministically with a non-success stage-aware outcome. A generated-output meter or cap violation discovered while evaluating a resolved handler is a handler-scoped `DSL_EVAL` outcome; an independent serialization or durable persistence transaction failure is a `WORK_ITEM_PERSIST` outcome. In either case, `finalReason` must use bounded canonical codes such as `command_count_exceeded`, `per_entity_command_limit_exceeded`, or `work_item_size_exceeded`. - A non-exclusive handler failure closes only that handler's durable sequence position. It does not cancel sibling work or change their Trigger Identities and outcomes. - Output budgets apply equally to core scripts and plugins. @@ -289,25 +289,25 @@ Every compiled script artifact must carry enough normalized output-cost metadata Runtime metering is incremental and happens before constructing each generated command or data-dependent collection. The evaluator charges the artifact-pinned conservative prospective serialized-byte bound together with cumulative command count, per-entity count, payload/collection bounds, and every data-dependent cap declared by the pinned metadata before construction or allocation. After bounded descriptors are staged, their exact serialized size is checked against the pinned ceiling immediately before atomic persistence. A run that would exceed any cap stops with the stage-correct `DSL_EVAL` non-success outcome and bounded reason; an independent serializer or persistence transaction failure remains `WORK_ITEM_PERSIST`. It must not construct an unbounded intermediate result and discover a cap violation only at handoff. -Generated output is atomic per resolved handler: either every bounded descriptor for that handler is durably persisted with its parent evidence, or none of that handler's generated output is persisted or handed off. A failed output-meter check, serialization check, or persistence transaction discards all staged output for that handler; it must not leave a partial command set that a retry could interpret as successful work. Event-scope ingress may reject a missing or conflicting artifact-cost digest with its ingress `OUTPUT_BUDGET_EXCEEDED` outcome, while a handler that exceeds a runtime cap records the canonical handler-scoped `DSL_EVAL` outcome and reason from [Table 2](./system-architecture-scripting-normative-contract-tables.md#table-2-script_event_audit-stages-and-outcomes). +Generated output is atomic per resolved handler: either every bounded descriptor for that handler is durably persisted with its parent evidence, or none of that handler's generated output is persisted or handed off. A failed output-meter check, serialized-size ceiling check, or persistence transaction discards all staged output for that handler; an output-limit failure therefore prevents evaluated descriptor/work-item/child-handoff persistence, while the owning pre-DSL trigger-record/work-item row still commits the terminal `DSL_EVAL` audit outcome and the separate durable handler charge record preserves any admission/execution-start charge markers already reached. It must not leave a partial command set that a retry could interpret as successful work. Event-scope ingress may reject a missing or conflicting artifact-cost digest with its ingress `OUTPUT_BUDGET_EXCEEDED` outcome, while a handler that exceeds a runtime cap records the canonical handler-scoped `DSL_EVAL` outcome and reason from [Table 2](./system-architecture-scripting-normative-contract-tables.md#table-2-script_event_audit-stages-and-outcomes). ## Budget Charge Points The canonical charge lifecycle is owned by [Scripting Quotas & Operations](./system-architecture-scripting-quotas-and-operations.md#budget-accounting-rules). Runtime execution consumes its result and must not introduce another charge point: -- The durable handler charge record is keyed by the full applicable Trigger Identity, including each resolved `onLoad` handler. Its exactly-once admission and execution-start markers are reused by duplicate and recovery attempts. -- A queued handler holds no sandbox capacity. Runtime acquires a separately fenced, reclaimable capacity lease only when execution is about to start, then in one Automation-owned durable executor-acceptance transaction revalidates the current fence, durably accepts/claims the run for the executor, persists the exactly-once execution-start marker, and transitions the work item to `EXECUTING`; DSL evaluation begins only after that commit. If the executor cannot accept the run, the transition does not commit, the lease is released or reclaimed, and no execution charge is recorded. A crash after commit recovers from the durable executor claim and may reacquire a lease but never creates a second marker. -- A failed run does not refund an already committed admission charge or execution-start charge. Lease reclamation is capacity recovery, not a quota refund, and cannot create a second charge record or execution-start marker. +- **Target-state only:** For each resolved handler, including each `onLoad` handler, Automation creates or reuses one separate durable handler charge record keyed by the full applicable Trigger Identity. That record is the sole charge authority and persists the exactly-once admission and execution-start markers; the pre-DSL trigger-record/work-item row is durably linked to it and is not a second charge point. Duplicate and recovery attempts reuse the same charge record and markers. +- **Target-state only:** A queued handler holds no sandbox capacity. Runtime acquires a separately fenced, reclaimable capacity lease only when execution is about to start, then in one Automation-owned durable executor-acceptance transaction revalidates the current fence, durably accepts/claims the run for the executor, persists the exactly-once execution-start marker on the handler charge record, and transitions the pre-DSL trigger record to `EXECUTING`; DSL evaluation begins only after that commit. If the executor cannot accept the run, the transition does not commit, the lease is released or reclaimed, and no execution charge is recorded. A crash after commit recovers from the durable executor claim and may reacquire a lease but never creates a second marker. +- A failed run does not refund an already committed admission charge or execution-start charge. Lease reclamation is capacity recovery, not a quota refund, and cannot create a second charge row or execution-start marker. - Runtime persists the resolved `quotaClass` on durable work so execution follows the admission decision. `PUBLISH_READINESS` remains isolated from ordinary live quota and capacity; its readiness lease and outcome are local runtime consequences, not a new live charge path. - Target-state scheduler reservations are separate from the durable admission/execution charges and fenced occupancy lease described here; the current runtime does not implement that reservation. ## Ordering Between Player and Script Commands -Game Session owns the combined per-entity tick queue and its enqueue/order invariants as defined in the [cross-service scripting contracts](./system-architecture-scripting-contracts.md#1-tick-queue-ownership-tick). At this runtime boundary, the current handoff preserves `scriptId` and optional `dueTickId` when present. `commandOrdinal`, `triggerMode`, `scheduleDefinitionId`, and scheduler/ordinal propagation are target-only and are not current ordering guarantees. `scriptEventId` remains on the Automation-owned durable work item and `script_event_audit`; it is omitted from the current Game Session handoff. Target command identity and complete Trigger Identity propagation remain subject to the widened handoff contract. +Game Session owns the combined per-entity tick queue and its enqueue/order invariants as defined in the [cross-service scripting contracts](./system-architecture-scripting-contracts.md#1-tick-queue-ownership-tick). At this runtime boundary, the current handoff preserves `scriptId` and optional `dueTickId` when present. `commandOrdinal`, `triggerMode`, `scheduleDefinitionId`, and scheduler/ordinal propagation are target-only and are not current ordering guarantees. `scriptEventId` remains on the Automation-owned durable pre-DSL trigger record and resulting evaluated script work item/audit; it is omitted from the current Game Session handoff. Target command identity and complete Trigger Identity propagation remain subject to the widened handoff contract. ## Redis Key Summary for Scripting -The current Redis keys used by the Automation & Scripting Service, together with reserved target-only keys, are: +The current implementation has no scheduler/timer Coordination Redis projections; its current Redis projection in this section is the queue below. Durable schedule/timer state and runtime progress are PostgreSQL-backed. Separate live quota/budget/test-capacity/readiness-capacity families (`automation:quota:*`, `automation:tenant-budget:*`, `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*`) are also used through Cache/Rate-Limit Redis; see [Scripting Quotas & Operations](./system-architecture-scripting-quotas-and-operations.md#implementation-status). The `automation:timer:{tenantRegionTag}` and `script-scheduler:{tenantRegionTag}:lastTickId` entries are target-state projections only: those Redis families are unimplemented in the current runtime, no supported current manual-write or reset operation exists for them, and raw coordination-prefix mutation is prohibited. | Key pattern | Owner / service | Purpose | Hash tag / shard scope | TTL / retention expectations | | --- | --- | --- | --- | --- | @@ -315,7 +315,9 @@ The current Redis keys used by the Automation & Scripting Service, together with | `automation:timer:{tenantRegionTag}` | Automation & Scripting scheduler (target-only, once implemented) | Reserved target-only region-scoped index of script timers and intervals for the full `` scope represented by the opaque tag. No current key or reset operation is defined. | Hash-tagged on the shared `{tenantRegionTag}` derived by key helpers; the tag is not a competing identity family. | Reset-tolerant derived index once implemented; durable schedules remain authoritative. | | Scheduler leadership state | Automation & Scripting scheduler (live heartbeat-driven scheduling; target-only Redis projection) | Current live scheduling is driven by Game Session's `ObserveRuntimeTickProgress` call after each committed tick and durable PostgreSQL schedule rows; no independent Redis leadership key or checkpoint is implemented. The target scheduler checkpoint is explicitly reserved as `script-scheduler:{tenantRegionTag}:lastTickId`; it carries the current `regionEpoch` and `latestTickId` discovery hint, while the per-consumer `tick-events-offset:{tenantRegionTag}:` record remains the sole stream-offset owner. A future target projection may align scheduler ownership to the canonical runtime and region-scoped coordination model; do not assume a separate first-class `script-leader:*` prefix unless a later Redis design update explicitly introduces it. | The reserved checkpoint is target-only and has no current Redis slot/key or reset operation. Any future projection must follow the same slotting and reset rules as the documented scheduler coordination families. | No current Redis retention. A future projection is short-lived and reset-tolerant; durable schedules and firing state remain authoritative. | -`{tenantRegionTag}` is owned by the shared Redis key builders under [Redis Architecture](./system-architecture-redis.md#key-naming-and-shard-discipline) and is intentionally limited to full `` locality. `playableStateScope` remains a first-class field in durable Trigger Identity, command/effect identity, and handoff diagnostics; it must not be inferred from, or added to, this tag without an owning Redis design and key-builder change. +`{tenantRegionTag}` is owned by the shared Redis key builders under [Redis Architecture](./system-architecture-redis.md#key-naming-and-shard-discipline) and is intentionally limited to full `` locality. `playableStateNamespaceId` is the playable-state uniqueness component in durable Trigger Identity and Command-Handoff Identity. `playableStateScope` remains separately persisted and exact-validated as policy/routing/authorization/migration-fence evidence for durable trigger, descriptor, and handoff diagnostics; it is excluded from those uniqueness keys and must not be inferred from, or added to, this tag without an owning Redis design and key-builder change. Where current repository or schema uniqueness includes `playableStateScope`, that is current implementation drift and not target identity authority. + +Scheduler leadership remains an explicit, bounded runtime concern rather than state stored in `lastTickId`; the target design does not introduce a first-class `script-leader:*` Redis prefix. Any future leadership lease or projection must be separately specified and registered under the owning coordination/reset contracts. ## Failure Modes and Error Handling @@ -329,8 +331,8 @@ Routine core-script component safety classification is fixed at validation and r Target-state retry behavior (see [Current Implementation Status](#current-implementation-status)): -- Logical failures are treated as final for a trigger. Before `EVALUATED_COMMITTED`, infrastructure retry, including admitted timer evaluation, may re-run evaluation only under the same full Trigger Identity and must converge on the same work-item and frozen inputs; it allocates no dispatch or command-child identity before the first durable descriptor commit. If commands are emitted, that winning commit allocates/persists the dispatch ID and canonical ordinals; retries after the commit reuse them. It must never create a duplicate logical command. After `EVALUATED_COMMITTED`, recovery replays the durable descriptors and never re-enters the DSL. The audit `finalStage` remains the last stage actually reached rather than being advanced by an attempted retry. -- **Pre-commit replay evidence:** For event and timer evaluation retries before `EVALUATED_COMMITTED`, the executor reloads the original durable trigger payload, frozen dependency/manifest snapshot, immutable graph and artifact references with recorded digests. For plugin-backed work it also compares the exact plugin provenance and captured `(pluginActivationEpoch, lifecycleRevision)` pair; for the same-version/same-epoch `DRAINING` predecessor exception, the durable winning pre-`DRAINING` admission/fence CAS evidence is part of the immutable comparison and must be present. Missing, changed, capture-only, or unreadable evidence fails closed before DSL evaluation; the retry preserves the full Trigger Identity and original work-item identity, allocates no command-child identity, and can only reuse dispatch/ordinal identities after a winning descriptor commit with the same lifecycle evidence. +- Logical failures are treated as final for a trigger. Before `EVALUATED_COMMITTED`, infrastructure retry, including admitted timer evaluation, may re-run evaluation only under the same full Trigger Identity and must converge on the same pre-DSL trigger record and frozen inputs; it allocates no dispatch or command-child identity before the first durable descriptor commit. If commands are emitted, that winning commit allocates/persists the dispatch ID and canonical ordinals; retries after the commit reuse them. It must never create a duplicate logical command. After `EVALUATED_COMMITTED`, recovery replays the durable descriptors and never re-enters the DSL. The audit `finalStage` remains the last stage actually reached rather than being advanced by an attempted retry. +- **Pre-commit replay evidence:** For event and timer evaluation retries before `EVALUATED_COMMITTED`, the executor reloads the original durable trigger payload, frozen dependency/manifest snapshot, immutable graph and artifact references with recorded digests. For plugin-backed work it also compares the exact plugin provenance and captured `(pluginActivationEpoch, lifecycleRevision)` pair; for the same-version/same-epoch `DRAINING` predecessor exception, the durable winning pre-`DRAINING` admission/fence CAS evidence is part of the immutable comparison and must be present. Missing, changed, capture-only, or unreadable evidence fails closed before DSL evaluation; the retry preserves the full Trigger Identity and original pre-DSL trigger-record identity, allocates no command-child identity, and can only reuse dispatch/ordinal identities after a winning descriptor commit with the same lifecycle evidence. - Any work referencing a revocable component, including embedded/core-script and plugin-backed work, carries the component-revocation security-policy fence through evaluation, persistence, dispatch, staged/final effects, retry, replay, and recovery and is checked immediately before gameplay effects. Missing, stale, unavailable, or mismatched evidence fails closed with the established bounded component/authority disposition. Plugin-backed work additionally carries and revalidates the independent `(pluginActivationEpoch, lifecycleRevision)` fence pair; neither lifecycle fence substitutes for the other or for component-revocation evidence. The captured plugin lifecycle pair and exact recovery fences are revalidated immediately before evaluation, before descriptor/outbox persistence, before each post-evaluation dispatch, and at every applicable boundary. Applicable current signer, component, capability, publication, and lifecycle policy evidence is revalidated at evaluation, each dispatch, final effect, and activation/resume/recovery as owned by ADR 0119, using the canonical durable pre-`DRAINING` admission-CAS evidence for the narrowly retained predecessor exception. Proven lifecycle, publication, component/capability, signer, tuple, or scope mismatches remain terminal/ineligible with their applicable bounded reason. - For event ingress, pre-handler rollback pause is an ingress-audit backpressure outcome only. Timer candidates use the Table 3 candidate-audit rule instead. Post-resolution handler backpressure such as `skipped_reloading` and `rollback_paused` is not treated as final for low-rate external events. - Infrastructure errors may be retried by lower layers following platform-wide retry policies and idempotency contracts. @@ -343,7 +345,7 @@ Rollback of a script patch must not allow previously queued work from the displa ## Timer Failure Semantics -Timer admission, due-point identity, catch-up, reload, and failure outcomes follow the [normative timer semantics](./system-architecture-scripting-normative-contract-tables.md#table-3-timer-semantics-matrix). In the target state, before `EVALUATED_COMMITTED`, an admitted timer evaluation may retry only under the same full Trigger Identity, allocates no dispatch or command-child identity before the first durable descriptor commit, and must converge on the same work-item and frozen inputs. If commands are emitted, that atomic commit allocates/persists the `automationDispatchId` and canonical ordinals; retries after the commit reuse them. After that commit boundary, recovery replays durable descriptors and never re-enters the DSL; independently idempotent downstream operations may still retry. Recurring/advisory firings remain bounded scheduling signals rather than guaranteed cadence ledgers, while correctness-bearing one-shot timers converge to one execution or an explicit terminal outcome. +Timer admission, due-point identity, catch-up, reload, and failure outcomes follow the [normative timer semantics](./system-architecture-scripting-normative-contract-tables.md#table-3-timer-semantics-matrix). In the target state, before `EVALUATED_COMMITTED`, an admitted timer evaluation may retry only under the same full Trigger Identity, allocates no dispatch or command-child identity before the first durable descriptor commit, and must converge on the same pre-DSL trigger record and frozen inputs. If commands are emitted, that atomic commit allocates/persists the `automationDispatchId` and canonical ordinals; retries after the commit reuse them. After that commit boundary, recovery replays durable descriptors and never re-enters the DSL; independently idempotent downstream operations may still retry. Recurring/advisory firings remain bounded scheduling signals rather than guaranteed cadence ledgers, while correctness-bearing one-shot timers converge to one execution or an explicit terminal outcome. ## `onLoad` Semantics and Failure Handling diff --git a/design/architecture/system-architecture-scripting-scheduler-and-timers.md b/design/architecture/system-architecture-scripting-scheduler-and-timers.md index 84d3ede33a..8204e60924 100644 --- a/design/architecture/system-architecture-scripting-scheduler-and-timers.md +++ b/design/architecture/system-architecture-scripting-scheduler-and-timers.md @@ -16,8 +16,13 @@ The current implementation provides the following substrate: - Wall-clock timers persist `nextDueAt`; in the live schema/entity, `next_due_at`/`nextDueAt` is the current equivalent of target canonical `dueAt`, while `nextRunAt` is only a derived projection, not the canonical persisted due point. Tick-aligned schedules remain `PENDING_RUNTIME_PROGRESS` until Game Session reports `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)` through `ObserveRuntimeTickProgress`; Automation then stores `runtimeRegionId`, `runtimeRegionEpoch`, `lastObservedTickId`, `lastRuntimeProgressObservedAt`, and the next future `nextDueTickId`. - Game Session advances durable `lastCommittedTickId` on the runtime-ownership row that also carries `regionId`, `regionEpoch`, and `executorFence`, exposes that state through runtime ownership status, and publishes it after successful tick cycles. True region partitioning remains target-state; the live ownership row currently carries a transitional non-empty `regionId` scope marker, but consumers must not derive or reconstruct that value from `gameInstanceId`. - Runtime observations stamp the fenced region scope onto wall-clock timers as well as tick schedules. Due tick and wall-clock candidates emit deterministic timer-derived `ScriptWorkItem` rows through the normal durable work-item, audit, and `automation:queue:*` projection path, then advance or clear the consumed due point. -- A newer observation that proves the runtime scope changed fences the stale due point instead of reminting it under the new epoch. The service records `runtime_scope_changed` against the old Trigger Identity and increments `automation_script_timer_runtime_fence_dropped_total`. -- Due candidates are selected in round-robin passes across complete stable schedule-instance identities and capped by `script.scheduler.max-catch-up-firings-per-observation`; this current per-observation behavior does not yet prove the accepted one-per-schedule-instance durable resume-window cap across repeated observations. `ObserveRuntimeTickProgress` reports updated rows, fired work items, and truncated candidates; timer-fired, catch-up-truncated, and runtime-fence metrics expose aggregate outcomes. +- Current wall-clock timer work serializes the absolute `dueAt` into `payloadJson`, and the evaluator exposes primitive payload fields to template variables and command conditions/arguments. Consequently `{{payload.dueAt}}` can affect emitted gameplay commands. This is implementation drift from the wall-clock scheduler-only contract above: `dueAt` must remain internal durable identity/seed/fence/audit metadata, while DSL inputs expose only canonical tick/game-time context. The existing wall-clock test assertion for `dueAt` in the work-item payload is not proof of the target boundary; convergence requires metadata/input separation and focused proof that wall-clock values cannot affect DSL output. +- Current re-observation also resets millisecond `nextDueAt` unconditionally during schedule reconciliation, even for an existing row. `validatePinnedPatch` invokes runtime observation on every gameplay ingress, so a fired one-shot timer whose due point was cleared can be reseeded to its original `pinObservedAt + cadence`; the duplicate-work branch then returns without clearing or advancing that overdue point. This can rediscover the same timer indefinitely or re-fire it after terminal cleanup. It is drift from the preserve/derive-only-when-absent rule below; convergence requires preserving consumed due state across ordinary observation and focused re-observation, duplicate-work, and one-shot proof. +- A newer observation that proves the runtime region/epoch, active-instance binding, or current legacy `playableStateScope` changed fences the stale due point instead of reminting it under the new epoch. The live service currently writes a handler-shaped `ScriptEventAudit` with `finalStage=ADMISSION`, `finalOutcome=canceled`, and `finalReason=runtime_scope_changed`, then increments `automation_script_timer_runtime_fence_dropped_total`, even though no handler was admitted. That is implementation drift from the target candidate-audit boundary: the old `scheduleCandidateId` and captured due/fence evidence must receive that terminal candidate outcome without creating a handler Trigger Identity, firing claim, or `scriptEventId`. Current implementation also does not yet carry authoritative `playableStateNamespaceId` or distinguish stale presented scope evidence from an authority-proven scope transition; the target contract below permits same-namespace reuse only when authoritative scope is unchanged and otherwise starts a new playable-state lifecycle and namespace. +- Current timer candidate identity and the durable work-item uniqueness projection omit `targetScopeType`/`targetScopeId`; non-entity bindings therefore collapse to the same empty `entityId`. Distinct GLOBAL, REGION, or other bindings sharing a schedule and due point can produce one work item while the other candidate is treated as a duplicate. Target identity requires the complete target selector in the scheduler claim and candidate identity; convergence requires carrying it through work/audit uniqueness and focused cross-binding negative proof. +- Due candidates are selected in round-robin passes across complete stable schedule-instance identities and capped by `script.scheduler.max-catch-up-firings-per-observation`; however, the live `ScriptScheduleInstanceServiceImpl` comparator orders the wall-clock lane, then the due point within that lane (`dueTickId` for tick candidates or epoch-millisecond `dueAt` for wall-clock candidates), then `priorityTag`, and finally the schedule key. Round-robin grouping occurs after that ordering, so lane/due precedence can outrank bounded priority; this is drift from the target bounded priority-first, stable-identity round-robin fairness algorithm. This current per-observation behavior also does not yet prove the accepted one-per-schedule-instance durable resume-window cap across repeated observations. `ObserveRuntimeTickProgress` reports updated rows, fired work items, and truncated candidates; current timer instrumentation exposes aggregate outcomes, but its producer labels are noncanonical and the fired family is not defined in the metrics catalog. +- The comparator's clock-lane key is `wallClock ? 1 : 0`, so tick candidates sort before wall-clock candidates; the drift is that this lane key and the due point both precede `priorityTag`, not that wall-clock candidates universally sort first. +- The current timer metric producer emits raw `eventType` plus optional `reason`, and also emits an undocumented `automation_script_timer_fired_total` family. This does not satisfy the canonical bounded timer labels or the defined metric-family catalog in [Normative Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix); the status claim above is current instrumentation only, not canonical observability proof. Convergence requires bounded-label producer changes, a decision on the fired family, and focused metric-schema proof. - Control-plane timer audit reads expose scheduler-owned `script_event_audit` rows, including plugin ownership, admitted routing, due-point coordinates, and skipped-versus-persisted outcomes. Plugin-owned definitions retain `pluginId`/`pluginVersionId`/`bindingId`, and materialization admits only the enabled runtime plugin version and resolved signed-bundle binding. - The live `TimerFiringCandidate` captures plugin-owned `pluginActivationEpoch` as candidate/firing identity and `lifecycleRevision` as non-identity fence evidence. Candidate materialization and retry validate the complete captured/current plugin state, version, epoch, and revision before quota/DSL evaluation; broader replay/recovery, remote handoff, policy coordination, and final gameplay-effect fencing remain gaps. - Current timer work-item materialization retains authored target-scope fields, but only the `ENTITY` target path has an end-to-end entity selector in the firing path. `REGION` and `GLOBAL` timer targets remain unproven target-state behavior and must not be reported as supported until their selector semantics, durable identity, handler resolution, and execution proof are implemented. @@ -27,6 +32,18 @@ The current implementation provides the following substrate: The sections below define the target-state scheduler contract. Current behavior remains limited to the implementation facts listed in the dedicated status section above unless a bullet explicitly identifies a target-state requirement. +### Runtime Replacement Classification + +The following classification applies to Automation-owned scheduler data; it does not assign all runtime or player state one blanket class: + +- Authored schedule definitions are versioned control-plane/catalog data outside the runtime S1/S2/S3 scheme. Their tenant/version retention is governed by publish and version lifecycle rules, not runtime replacement. +- Durable schedule instances and due state are S2 mapping-dependent runtime state. Their durable identity uses the tenant, `playableStateNamespaceId`, and owning schedule identity; the persisted `gameInstanceId` is separately exact-validated active-instance authorization evidence. Replacement requires explicit continuity or replacement mapping, exact target validation, and that active-instance fence. A namespace transition retires the old generation before target admission and never reuses its due point implicitly. +- Correctness-bearing one-shot intent is retained under its owner-defined durable identity (S1 when namespace-owned); an in-flight claim remains fenced and reconciled under its original instance, namespace, epoch, and pin evidence rather than being remapped into a new runtime. +- Durable recurring candidate/claim evidence remains under its original identity until its declared firing, skip, or reconciliation outcome. Advisory/cosmetic candidate state is S3-disposable only where the authored recovery policy permits dropping it; a retained candidate audit is immutable history, not replay authority. +- Redis timer indexes, scheduler progress hints, queue pointers, and other rebuildable projections are S3 coordination state. Reset, epoch, namespace, or leader changes may discard them, but only durable owner state may rebuild or authorize scheduling. + +Old-instance schedule state and correctness-bearing claims therefore block cleanup while nonterminal or reconciliation-required. A new target row or identity may admit only after the applicable old generation is fenced and the target's exact namespace, runtime, pin, and owner evidence has been validated. + ### Script Timers vs Tick Timers Plugin timer admission carries the owner lifecycle fence as evidence separate from schedule identity: the stable schedule row carries the mutable current reconciled `(pluginActivationEpoch, lifecycleRevision)` pair, while each due candidate and firing claim captures the pair as immutable evidence; a new firing requires the exact current tuple. `DRAINING` cannot authorize a new firing; only same-version/same-epoch work whose winning admission CAS durably committed the immediately preceding `ENABLED` revision before the durable Automation-owned `DRAINING` admission barrier was created may retain it under ADR 0119. A revision change alone does not create a new candidate identity. @@ -42,16 +59,16 @@ Every authored timer declares both its clock unit and recovery class. Tick/game - **Advisory or cosmetic**: missed occurrences may drop and the timer resumes with a future occurrence under its declared cadence. - Redis timer indexes, due indexes, leader checkpoints, and wake-up hints are rebuildable coordination projections. Durable timer identity, due state, recovery policy, resume-window identity, and required terminal or skipped outcomes live outside Redis. - A correctness-bearing one-shot must durably terminalize under its original identity with one of the accepted outcomes: `applied`, `canceled`, `superseded`, `expired`, or a feature-defined terminal outcome. A scheduler or worker crash may reclaim a fenced lease, but an inconclusive one-shot remains nonterminal; it must not be silently marked skipped or reminted under a newer scope. -- For timer catch-up, Automation owns one durable timer-recovery resume-window record per ``. Including `isDryRun` in this key keeps live and dry-run/test catch-up candidates in separate windows and caps. A durable compare-and-set creates or returns the one `OPEN` record; its `resumeWindowId` is ``. At creation, the record freezes recovery start and through observations, the effective numeric tenant-local cap, and the selection-policy revision that defines grouping, ordering, round-robin passes, and tie breaks; it also retains the authoritative `playableStateNamespaceId` as immutable non-identity scope evidence. Creation, reuse, retry, observation, and takeover revalidate the same `isDryRun` mode and namespace/binding evidence, then reuse the frozen cap and selection-policy revision unchanged. A policy or configured-cap change applies only to a later window allocated after this one reaches `COMPLETE`; it cannot alter selection or cap-excluded outcomes within the existing `resumeWindowId`. Missing or mismatched mode or namespace evidence fails closed and cannot be refreshed, inferred, or added to `resumeWindowId`. Leader, worker, takeover, and attempt IDs are not identity inputs; retries and takeovers reuse the same mode-specific `resumeWindowId`, and only a later recovery episode after completion allocates the next generation. +- For timer catch-up, Automation owns one durable timer-recovery resume-window record per ``. Including `isDryRun` in this key keeps live and dry-run/test catch-up candidates in separate windows and caps. The server-derived `playableStateScope` is persisted separately as immutable policy/routing/authorization/migration-fence evidence and is exact-validated; it is not part of the window identity. A durable compare-and-set creates or returns the one `OPEN` record; its `resumeWindowId` is ``. At creation, the record freezes recovery start and through observations, the effective numeric tenant-local cap, and the selection-policy revision that defines grouping, ordering, round-robin passes, and tie breaks. Creation, reuse, retry, observation, and takeover revalidate the same `isDryRun` mode, namespace identity, exact scope evidence, and binding evidence, then reuse the frozen cap and selection-policy revision unchanged. A policy or configured-cap change applies only to a later window allocated after this one reaches `COMPLETE`; it cannot alter selection or cap-excluded outcomes within the existing `resumeWindowId`. Missing or mismatched mode, namespace, or scope evidence fails closed and cannot be refreshed, inferred, or added to `resumeWindowId`. Leader, worker, takeover, and attempt IDs are not identity inputs; retries and takeovers reuse the same mode-specific `resumeWindowId`, and only a later recovery episode after completion allocates the next generation. - An epoch transition atomically moves each prior epoch's `OPEN` resume window for each `isDryRun` mode out of `OPEN` before creating the corresponding new-epoch `OPEN` window; prior claims remain fenced and reconciled under their original epoch and resume-window identity and cannot enter the new window, as owned by [ADR 0072](./decisions/adr-0072-class-specific-timer-durability-and-recovery.md). -- `playableStateNamespaceId` is intentionally separate non-identity scope evidence, but a namespace transition is a new playable-state lifecycle under [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). If target materialization were allowed to update or reuse the prior schedule row, due point, or `OPEN` resume window before fencing the old namespace, the canonical candidate identity could collide—especially when the replacement has the same due point—and uniqueness could suppress the target firing. Namespace transitions therefore use a retire-before-materialize fence, which takes precedence over ordinary playable-scope replacement ordering: one atomic durable operation, or a resumable idempotent operation under the same `controlPlaneRequestId`, first fences and retires/tombstones every prior-namespace schedule row, moves its mode-specific `OPEN` resume windows out of `OPEN`, and preserves prior due candidates, firing claims, and candidate audits with their immutable old namespace evidence and original identities for settlement. No target-namespace schedule row or `OPEN` window may be materialized until that retirement barrier is durable. Target rows then receive fresh due state (the next future tick boundary or a transition-seeded wall-clock due point), never the old due point; namespace remains excluded from candidate, firing-claim, and `scriptEventId` identity, and the fresh due point ensures a same-due-point replacement cannot be suppressed by prior uniqueness. A crash or ambiguous retry leaves target admission fenced until this same operation converges; prior evidence is never rewritten or refreshed. +- `playableStateNamespaceId` is the durable schedule, candidate, firing, and event identity dimension, while `playableStateScope` is separately persisted exact-validated policy/routing/authorization/migration-fence evidence. A namespace transition is a new playable-state lifecycle under [ADR 0122](./decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), and an authoritative scope-policy transition therefore selects or allocates a new namespace before fresh state is admitted. If target materialization were allowed to update or reuse the prior schedule row, due point, or `OPEN` resume window before fencing the old namespace, the canonical candidate identity could collide—especially when the replacement has the same due point—and uniqueness could suppress the target firing. Namespace transitions therefore use a retire-before-materialize fence, which takes precedence over ordinary playable-scope replacement ordering: one atomic durable operation, or a resumable idempotent operation under the same `controlPlaneRequestId`, first fences and retires/tombstones every prior-namespace schedule row, moves its mode-specific `OPEN` resume windows out of `OPEN`, and preserves prior due candidates, firing claims, and candidate audits with their immutable old namespace identity, scope evidence, and original identities for settlement. No target-namespace schedule row or `OPEN` window may be materialized until that retirement barrier is durable. Target rows then receive fresh due state (the next future tick boundary or a transition-seeded wall-clock due point), never the old due point; the target namespace participates in candidate, firing-claim, and `scriptEventId` identity, while `playableStateScope` remains separately persisted evidence. The fresh due point and new namespace ensure a same-due-point replacement cannot be suppressed by prior uniqueness. A crash or ambiguous retry leaves target admission fenced until this same operation converges; prior evidence is never rewritten or refreshed. - Missed firings are handled in a bounded, deterministic way: - - `COALESCE_ONE` schedule instances may enqueue at most one synthetic firing for that complete stable schedule-instance identity within one `resumeWindowId` (and therefore one `isDryRun` mode); `SKIP_MISSED` schedule instances enqueue none. The window's frozen tenant-local cap and selection-policy revision govern every scan, retry, takeover, deterministic selection, and cap-excluded outcome across independent schedule instances within that same full runtime-scope-and-mode ID. Tenant-local identifies the window's tenant owner and does not create a tenant-wide pool, so another runtime scope cannot consume this window's cap. Excluded candidates are dropped rather than deferred as backlog. + - `COALESCE_ONE` schedule instances may enqueue at most one synthetic firing for that complete stable schedule-instance identity within one `resumeWindowId` (and therefore one `isDryRun` mode); `SKIP_MISSED` schedule instances enqueue none. The window's frozen tenant-local cap and selection-policy revision govern every scan, retry, takeover, deterministic selection, and cap-excluded outcome across independent schedule instances within that same full runtime-scope-and-mode ID, whose durable identity includes `playableStateNamespaceId`; `playableStateScope` remains separately persisted exact-validated evidence. Tenant-local identifies the window's tenant owner and does not create a tenant-wide pool, so another runtime scope or namespace cannot consume this window's cap. Excluded candidates are dropped rather than deferred as backlog. - Tenant-local catch-up selection is not shared scheduler admission. A selected candidate still passes through ADR 0166 tenant-first scheduling and the applicable tenant and cluster ceilings. Capacity denial there terminally skips that due candidate within the same `resumeWindowId`: a tenant-ceiling denial records candidate-audit `finalStage=ADMISSION`, `finalOutcome=tenant_budget_exceeded`, and `finalReason=tenant_budget_exceeded`; a cluster-ceiling denial records candidate-audit `finalStage=ADMISSION`, `finalOutcome=quota_denied`, and `finalReason=cluster_limit_reached`. Either denial consumes its deterministic catch-up selection slot, creates no firing claim, handler Trigger Identity, or `scriptEventId`, and is not deferred, retried, backfilled, or reminted as catch-up. The terminal candidate audit, advance of the recurring schedule's canonical due state to its next ordinary future occurrence, and resume-window denial outcome are one atomic owner transaction; when one storage transaction is unavailable, a resumable idempotent reconciliation keyed by `(scheduleCandidateId, resumeWindowId)` must complete all three before the denial is settled or the window can complete. A partial or crashed denial therefore remains fenced and cannot be rediscovered from the unchanged overdue due point. That durable denial counts toward resume-window completion and does not suppress the schedule's next ordinary future occurrence. For live candidates (`isDryRun=false`), emit `automation_script_skips_total` with `scope="tenant"` and `reason="tenant_budget_exceeded"` for a tenant-ceiling denial, or `automation_script_skips_total` with `scope="cluster"` and `reason="cluster_limit_reached"` for a cluster-ceiling denial, using every other required bounded label from [normative Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix). For dry-run/test candidates (`isDryRun=true`), neither live-only family is emitted: no dedicated test-only candidate-ceiling metric is currently defined, so the settled candidate audit and mode-specific resume-window outcome are the complete observability surface. The handler-scoped test families are not used because the denial occurs before handler materialization. These candidate-level outcomes do not invoke `ScriptTenantBudgetService` or increment `automation_script_tenant_budget_denied_total`; do not increment the catch-up-truncation family for either shared-admission denial. Retryable authority, reload, or reconciliation fences remain governed by the separate nonterminal candidate lifecycle below and are not capacity denials. - After a due candidate passes admission, and before enqueueing that firing, the scheduler must claim or insert a durable trigger-instance row keyed by an instance-aware uniqueness projection. For `triggerMode=CATCH_UP`, the firing claim uniqueness and comparison include `resumeWindowId`, and the candidate-audit record carries the same ID, so failover or duplicate consumers cannot create duplicate logical triggers or consume a later window's cap. - - The projection must define the event-scope due-candidate identity, including `tenantId`, `gameInstanceId`, `playableStateScope`, mandatory `stableOwnerKind` and `stableOwnerId`, `regionId`, `regionEpoch`, `eventType`, `eventSchemaVersion`, the exact `scriptPatchVersion`, positive `scriptPinEpoch`, `isDryRun`, `scheduleDefinitionId`, the persisted due point (`dueTickId` or `dueAt`), and `triggerMode`; include `entityId` only when the schedule target scope is entity-scoped, and `resumeWindowId` for catch-up claims. The paired nonblank `scriptPinControlPlaneRequestId` remains immutable owner evidence retained on each durable candidate, claim, and candidate audit and is exact-compared against authoritative pin evidence, but is excluded from `scheduleCandidateId`, firing-claim, and `scriptEventId` derivation. Each durable row, candidate, claim, and candidate audit also retains and revalidates the authoritative `playableStateNamespaceId` as immutable non-identity scope evidence; it does not participate in `scheduleCandidateId`, firing-claim, `scriptEventId`, Trigger Identity, or Command-Handoff Identity derivation. A core-script schedule must carry its durable `scriptId`; a plugin-owned schedule must carry `pluginId`, `pluginVersionId`, its schedule-owned `bindingId`, and the captured `(pluginActivationEpoch, lifecycleRevision)` pair. `pluginActivationEpoch` is the tagged candidate/firing-claim field; `lifecycleRevision` is required non-identity fence evidence. Core-script candidates omit both plugin lifecycle fields. Missing applicable namespace, durable owner, provenance, or either plugin lifecycle field, or namespace evidence that mismatches the authoritative namespace/scope and active-instance/region binding, rejects the candidate before deriving `scheduleCandidateId`, the firing claim, or `scriptEventId`; a legacy or corrupt row missing any applicable required field is not a candidate: record one deterministic non-candidate schedule-reconciliation outcome keyed by the existing durable `scheduleInstanceId` (the natural key or surrogate row ID defined below) plus the originating `controlPlaneRequestId` from its pin operation or Automation runtime transition, with bounded missing-field reason codes; quarantine or tombstone it, create no `scheduleCandidateId`, `scriptEventId`, ingress audit, firing claim, or handler audit, and never replay it. A handler-only binding field not present on the schedule remains absent until handler resolution. The firing claim derives one event-scope `scriptEventId` from the event identity with owner request evidence excluded, and propagates that ID unchanged into every resolved handler's full Trigger Identity; the request ID remains in the durable candidate/firing-claim evidence for exact owner comparison. Globally unique schedule IDs do not replace runtime scope, exact pin tuple, explicit `isDryRun`, or timeline fencing. - - Candidates denied by a permanent or declared-skip cadence, reload, version, or event-policy outcome before handler binding are terminally consumed; they are recorded as event-scope `scheduleCandidateId` audits with no firing claim or `scriptEventId` and are not replayed later. A transient retryable reload, reconciliation, or authority fence instead retains a durable due-candidate state/claim keyed by `scheduleCandidateId` and the canonical due point under its original exact tuple and captured `(pluginActivationEpoch, lifecycleRevision)` pair, when applicable, as fenced/nonterminal evidence; this transient state is not a terminal candidate audit and carries no `finalStage`, `finalOutcome`, firing claim, handler Trigger Identity, or `scriptEventId` while fenced. Same-epoch retries reuse the candidate identity only while its complete captured fence evidence remains current. A lifecycle-revision mismatch fences the candidate under its original captured pair; reconciliation never refreshes or rebinds that candidate evidence. Unavailable, contradictory, or ambiguous owner evidence keeps it nonterminal. Once authoritative evidence proves that the captured revision is displaced and the ADR 0119 pre-`DRAINING` admission exception cannot apply, reconciliation terminalizes the candidate once under its original identity; it advances or retires a recurring/advisory row's canonical due state in the same durable reconciliation before any later candidate is admitted, while a correctness-bearing one-shot retains its original durable intent until an explicit terminal outcome and is never reminted. `DRAINING` cannot create a new firing; only already-admitted same-version/same-epoch work with the pre-barrier winning admission/fence CAS remains eligible under ADR 0119. A displaced old scope, region epoch, exact pin tuple, or plugin activation epoch remains fenced under its original candidate identity and is never reused on the new timeline; target reconciliation derives a fresh candidate identity for the changed identity tuple before admission. The durable candidate ID is derived from the complete event-scope due-candidate identity: tenant/instance/playable scope, stable schedule-owned script/plugin/binding identity when present, region and region epoch, exact script patch, positive pin epoch, event type and schema version, explicit `isDryRun`, schedule definition, trigger mode, target selector when applicable, and, for plugin-owned schedules, the tagged captured `pluginActivationEpoch`, and, when `triggerMode=CATCH_UP`, `resumeWindowId`, and the tagged due point. The candidate retains the paired nonblank `scriptPinControlPlaneRequestId` as immutable owner evidence and exact-compares it before admission, but it is excluded from candidate, firing-claim, and `scriptEventId` identity. A candidate that passes those gates creates at most one event-scope firing claim and deterministic event-scope `scriptEventId` for that due candidate using the same identity fields, with the tagged plugin activation epoch included in that derivation, resolves handlers, and fans out zero or more handler work items, each with its own full Trigger Identity containing that same propagated ID; a pre-materialization handler quota denial is recorded per resolved handler with no handler work item, while an ordinary post-executor-claim `ScriptTenantBudgetService` denial records the existing handler identity and terminally cancels its already materialized work item before DSL evaluation. + - The projection must define the event-scope due-candidate identity, including `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, mandatory `stableOwnerKind` and `stableOwnerId`, `regionId`, `regionEpoch`, `eventType`, `eventSchemaVersion`, the exact `scriptPatchVersion` and `scriptPinEpoch`, `isDryRun`, `scheduleDefinitionId`, the persisted due point (`dueTickId` or `dueAt`), and `triggerMode`; include `entityId` only when the schedule target scope is entity-scoped, and `resumeWindowId` for catch-up claims. Each durable row, candidate, claim, and candidate audit also retains and revalidates the server-derived `playableStateScope` as immutable separately persisted policy/routing/authorization/migration-fence evidence; it does not participate in `scheduleCandidateId`, firing-claim, `scriptEventId`, Trigger Identity, or Command-Handoff Identity derivation. A core-script schedule must carry its durable `scriptId`; a plugin-owned schedule must carry `pluginId`, `pluginVersionId`, its schedule-owned `bindingId`, and the captured `(pluginActivationEpoch, lifecycleRevision)` pair. `pluginActivationEpoch` is the tagged candidate/firing-claim field; `lifecycleRevision` is required non-identity fence evidence. Core-script candidates omit both plugin lifecycle fields. Missing applicable namespace, durable owner, provenance, or either plugin lifecycle field, or namespace/scope evidence that mismatches the authoritative namespace, scope, and active-instance/region binding, rejects the candidate before deriving `scheduleCandidateId`, the firing claim, or `scriptEventId`; a legacy or corrupt row missing any applicable required field is not a candidate: record one deterministic non-candidate schedule-reconciliation outcome keyed by the existing durable `scheduleInstanceId` (the immutable physical row-generation reference, not the logical schedule/event identity) plus the originating `controlPlaneRequestId` from its pin operation or Automation runtime transition, with bounded missing-field reason codes; quarantine or tombstone it, create no `scheduleCandidateId`, `scriptEventId`, ingress audit, firing claim, or handler audit, and never replay it. A handler-only binding field not present on the schedule remains absent until handler resolution. The firing claim derives one event-scope `scriptEventId` from this complete due-candidate identity and propagates that ID unchanged into every resolved handler's full Trigger Identity. Globally unique schedule IDs do not replace runtime scope, exact pin tuple, explicit `isDryRun`, or timeline fencing. + - Candidates denied by a permanent or declared-skip cadence, reload, version, or event-policy outcome before handler binding are terminally consumed; they are recorded as event-scope `scheduleCandidateId` audits with no firing claim or `scriptEventId` and are not replayed later. A transient retryable reload, reconciliation, or authority fence instead retains a durable due-candidate state/claim keyed by `scheduleCandidateId` and the canonical due point under its original exact tuple and captured `(pluginActivationEpoch, lifecycleRevision)` pair, when applicable, as fenced/nonterminal evidence; this transient state is not a terminal candidate audit and carries no `finalStage`, `finalOutcome`, firing claim, handler Trigger Identity, or `scriptEventId` while fenced. Same-epoch retries reuse the candidate identity only while its complete captured fence evidence remains current. A lifecycle-revision mismatch fences the candidate under its original captured pair; reconciliation never refreshes or rebinds that candidate evidence. Unavailable, contradictory, or ambiguous owner evidence keeps it nonterminal. Once authoritative evidence proves that the captured revision is displaced and the ADR 0119 pre-`DRAINING` admission exception cannot apply, reconciliation terminalizes the candidate once under its original identity; it advances or retires a recurring/advisory row's canonical due state in the same durable reconciliation before any later candidate is admitted, while a correctness-bearing one-shot retains its original durable intent until an explicit terminal outcome and is never reminted. `DRAINING` cannot create a new firing; only already-admitted same-version/same-epoch work with the pre-barrier winning admission/fence CAS remains eligible under ADR 0119. A displaced old namespace, scope evidence, region epoch, exact pin tuple, or plugin activation epoch remains fenced under its original candidate identity and is never reused on the new timeline; target reconciliation derives a fresh candidate identity for the changed identity tuple before admission. The candidate ID is derived from the complete event-scope due-candidate identity: tenant/instance/playable-state namespace, stable schedule-owned script/plugin/binding identity when present, region and region epoch, exact script patch and pin epoch, event type and schema version, explicit `isDryRun`, schedule definition, trigger mode, target selector when applicable, and, for plugin-owned schedules, the tagged captured `pluginActivationEpoch`, and, when `triggerMode=CATCH_UP`, `resumeWindowId`, and the tagged due point. The server-derived `playableStateScope` is retained and exact-validated as separate policy/routing/authorization/migration-fence evidence and is not an identity input; an authority-proven scope transition starts a new lifecycle/namespace. A candidate that passes those gates creates at most one event-scope firing claim and deterministic event-scope `scriptEventId` for that due candidate, with the tagged plugin activation epoch included in that derivation, resolves handlers, and fans out zero or more handler work items, each with its own full Trigger Identity containing that same propagated ID; a pre-materialization handler quota denial is recorded per resolved handler with no handler work item, while an ordinary post-executor-claim `ScriptTenantBudgetService` denial records the existing handler identity and terminally cancels its already materialized work item before DSL evaluation. For plugin-owned candidates, the transient candidate state, reconciliation evidence, and retry/reload state retain the captured `(pluginActivationEpoch, lifecycleRevision)` pair. Reconciliation and retry revalidate both values against the current owner pair; `pluginActivationEpoch` is part of `scheduleCandidateId`, firing-claim, and derived `scriptEventId` identity, while `lifecycleRevision` is fence evidence only and is not added to those identities. @@ -61,7 +78,7 @@ Within that model: - The Game Session Service owns authoritative tick progression and tick timers, as described in [Tick System and Runtime Design](./system-architecture-ticks.md). - The Automation & Scripting Service owns script timers and intervals, which are scheduled against tick heartbeat information but do not own ticks themselves. -- Scheduler data structures such as `automation:timer:{tenantRegionTag}` are used to track when script timers should fire relative to tick progression. `{tenantRegionTag}` is the opaque shared-key-builder tag derived from the full `` scope; it is not a competing schedule identity. Durable script schedules and quotas live in the Automation & Scripting Service’s PostgreSQL schema, while Redis indexes are coordination structures that can be rebuilt or reset without changing which scripts should eventually run. +- **Target-state only:** Scheduler data structures such as `automation:timer:{tenantRegionTag}` and `script-scheduler:{tenantRegionTag}:lastTickId` are unimplemented Redis coordination projections; no current scheduler/timer authority or supported manual/reset operation exists for them. `{tenantRegionTag}` is the opaque shared-key-builder tag derived from the full `` scope; it is not a competing schedule identity. Current durable script schedules live in the Automation & Scripting Service’s PostgreSQL schema, and current tick progress/heartbeat authority remains in Game Session. Target-state firing-claim de-duplication and durable quota/charge and admission-marker ownership also belong in PostgreSQL. The current quota, tenant-budget, readiness/capacity, and queue-pointer decisions are Redis best-effort, reset-sensitive projections with no durable charge/admission markers. Redis indexes can be rebuilt or reset without changing durable schedule identity or correctness-bearing one-shot outcomes; best-effort recurring or advisory missed firings may be skipped, while future eligible cadence remains available. From the tick system’s perspective, script timers are a source of work that ultimately enters the tick scheduler. Every scheduler and timer source must declare immutable `lane` (`actor_action` or `passive_effect`) and bounded `cost_class` before admission, and must carry those fields unchanged through durable schedule state, firing claims, work items, retries, and recovery. Missing or changed values reject timer firing, admission, retry, or recovery rather than being inferred or reclassified. Under ADR 0051, `passive_effect` is bounded non-actor work governed by the passive lane’s budgets: status pulses, environmental changes, passive inbound or remote envelopes, actor-generated consequences, and retries of already-admitted passive effects. Root intentional player, AI, automation, movement, or other gameplay commands remain `actor_action`; a timer is `actor_action` when it makes an actor act. If a passive inbound envelope emits a gameplay command, that resulting command is `actor_action` and cannot grant another same-tick root action. The determinism rules in the DSL reference apply equally to timer-driven triggers, while lane selection and budgets remain owned by the tick contract. @@ -80,8 +97,8 @@ When an explicitly preserved tick-aligned interval keeps a logical timer alive a - `previousDueTickId` = the durable due point stored before pause or reconciliation. - `intervalTicks` = the preserved schedule cadence in ticks. - Preconditions: - - Apply the preserved-due-point formula only when the preserved row's `runtimeRegionId`, runtime scope (`gameInstanceId` and `playableStateScope`), and `runtimeRegionEpoch` match the resumed runtime's corresponding region, scope, and `regionEpoch`. - - If the runtime region, runtime scope, or region epoch differs, fence the old due point and derive a new due point on the new timeline after the replacement/new-scope schedule entry is durable; do not feed the stale `previousDueTickId` into this formula. + - Apply the preserved-due-point formula only when the preserved row's `runtimeRegionId`, runtime scope (`gameInstanceId` and `playableStateNamespaceId`), separately persisted `playableStateScope` evidence, and `runtimeRegionEpoch` match the resumed runtime's corresponding region, namespace, exact scope evidence, and `regionEpoch`. + - If the runtime region, namespace, authoritative scope, or region epoch differs, fence the old due point and derive a new due point on the new timeline after the replacement/new-namespace schedule entry is durable; do not feed the stale `previousDueTickId` into this formula. A merely presented stale scope may reuse the namespace only after authority proves the scope is unchanged; an authority-proven scope transition starts a new lifecycle and namespace. - Rule: - `intervalTicks` must be a positive integer. A schedule with `intervalTicks <= 0` is invalid and must be rejected before any modulo or due-point calculation. - if `previousDueTickId >= resumeTickId`, keep `nextTick = previousDueTickId`; @@ -89,17 +106,17 @@ When an explicitly preserved tick-aligned interval keeps a logical timer alive a - Consequences: - the scheduler resumes on the next valid cadence boundary at or after resume, never by replaying every missed firing from the paused window; - a preserved schedule may fire immediately after resume only when its next valid cadence boundary is exactly `resumeTickId`; - - reload and rollback preservation and downtime recovery remain distinct behaviors. The resume rule governs preserved timers after a version transition on the same runtime region, scope, and epoch; a scope or epoch migration fences the old due point and starts from the new timeline. The declared recovery class and durable resume-window policy govern missed firings after scheduler downtime within the same logical schedule instance and version. + - reload and rollback preservation and downtime recovery remain distinct behaviors. The resume rule governs preserved timers after a version transition on the same runtime region, `gameInstanceId`, `playableStateNamespaceId`, exact `playableStateScope` evidence, and epoch; a region, namespace, authoritative scope, or epoch migration fences the old due point and starts from the new timeline. The declared recovery class and durable resume-window policy govern missed firings after scheduler downtime within the same logical schedule instance and version. - Reset, incompatible, or newly materialized replacement rows do not use this rule and start with fresh due state; a preserved wall-clock timer does not use the tick formula, and compatible continuity retains its persisted absolute `dueAt` and regenerates `nextRunAt`. ### End-to-End `onInterval` Timer Lifecycle This section summarizes how a single `onInterval` timer behaves across normal operation, leader changes, and script reloads, and which Redis keys are authoritative at each step. -All durable timer identity and scheduler checkpoints must be instance-aware even when Redis keys are region-scoped for slotting and locality: +Timer, schedule, firing, and catch-up identities must be instance-aware even when Redis keys are region-scoped for slotting and locality. The per-region scheduler runtime-progress hint is intentionally namespace-independent: its opaque key tag carries the full tenant/game/region scope, while its payload carries only `{regionEpoch, latestTickId}`; it is derived progress, never timer, due, or admission identity. -- `gameInstanceId` is a required part of timer identity, deterministic scheduler `scriptEventId` derivation, catch-up deduplication, and checkpoint projection state. -- If a Redis key name omits `gameInstanceId`, the stored timer or checkpoint payload must still include it, and rebuild logic must treat instance mismatches as corruption rather than as reusable timer state. +- `gameInstanceId` and `playableStateNamespaceId` are required parts of timer identity, deterministic scheduler `scriptEventId` derivation, and catch-up deduplication. The server-derived `playableStateScope` is persisted separately as exact-validated policy/routing/authorization/migration-fence evidence, never as identity. +- For timer projections whose Redis key name omits `gameInstanceId`, the opaque `{tenantRegionTag}` must still encode the complete `` scope, and stored timer payloads must retain their full identity; rebuild logic must treat instance mismatches as corruption rather than as reusable timer state. - Plugin timers must additionally carry `pluginId`, `pluginVersionId`, and `bindingId` in their durable identity so sibling bindings and plugin rollback, disablement, or revocation cannot cross-contaminate interval state. #### Interval-Entry Identity and Due-Point Persistence @@ -108,22 +125,22 @@ A durable interval has two identities that must not be conflated. Stable schedule-instance row identity: -The stable durable row identity retains tenant, instance, playable-scope, stable-owner, definition, target-scope, and dry-run separation. Replaceable pin/provenance metadata remains on the row as mutable execution-fence evidence: +The stable durable row identity retains tenant, playable-state namespace, stable-owner, definition, target-scope, and dry-run separation. The persisted `gameInstanceId` is the active-instance authorization fence and is not part of this S2 durable identity. The server-derived playable-state scope remains separately persisted exact-validated policy/routing/authorization/migration-fence evidence. Replaceable pin/provenance metadata remains on the row as mutable execution-fence evidence: -`` +`` This row identity is distinct from the stable logical continuity key: -`{stableOwnerKind, stableOwnerId, scheduleDefinitionId, targetScopeType, targetScopeId}` +`{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}` For a core script, `stableOwnerId` is the durable script identity. For a plugin, it is `pluginId`; `pluginVersionId` remains provenance and an execution fence, not continuity identity. `scriptPatchVersion` and `scriptPinEpoch` are exact pin metadata and execution-fence fields, not continuity identity. -- `scheduleInstanceId` is an immutable surrogate row-generation identity allocated idempotently under the materializing `controlPlaneRequestId`; it is not the stable logical continuity key. Within one `(tenantId, gameInstanceId, isDryRun)` runtime scope, the natural continuity key above identifies at most one admitting, non-tombstoned row. A compatible continuity transition retains the same `scheduleInstanceId`; a reset or incompatible transition that still has a replacement target allocates a fresh one. Immutable non-identity namespace evidence (`playableStateNamespaceId`), mutable pin/provenance metadata, mutable runtime-region metadata (`runtimeRegionId`, `runtimeRegionEpoch`), and due point remain outside both the continuity key and the surrogate identity. `playableStateNamespaceId` remains persisted and exact-matched with `playableStateScope` and the active-instance/region owner binding on materialization, readback, due-candidate creation, claim, retry, and reconciliation; it is never inferred or refreshed onto an existing row. `pluginVersionId`, `bindingId`, `scriptPatchVersion`, and `scriptPinEpoch` remain persisted on the row as exact provenance and execution-fence fields; `runtimeRegionId`, `runtimeRegionEpoch`, `nextDueTickId`/`nextDueAt`, and last-observed progress are schedule state. Ordinary matching heartbeat evidence may advance those mutable fields on the active generation, but a namespace or active-instance/region binding transition creates a replacement generation rather than rewriting that evidence in place. +- `scheduleInstanceId` is an immutable surrogate row-generation identity allocated idempotently under the materializing `controlPlaneRequestId`; it is not the stable logical continuity key. Within one `(tenantId, playableStateNamespaceId, isDryRun)` namespace binding, the natural continuity key above identifies at most one admitting, non-tombstoned row for the exact current active-instance/region fence. `gameInstanceId` remains persisted and exact-validated active-instance authorization evidence rather than an S2 identity dimension; a replacement instance therefore maps or creates a distinct physical generation under the same namespace and retires the source before target admission. A compatible continuity transition retains the same `scheduleInstanceId`; a reset or incompatible transition that still has a replacement target allocates a fresh one. `playableStateNamespaceId` is part of the durable row identity and continuity key. The separately persisted `playableStateScope` evidence, mutable pin/provenance metadata, mutable runtime-region metadata (`runtimeRegionId`, `runtimeRegionEpoch`), and due point remain outside the identity and are exact-validated at materialization, readback, due-candidate creation, claim, retry, and reconciliation. Namespace and scope evidence are never inferred or refreshed onto an existing row. `pluginVersionId`, `bindingId`, `scriptPatchVersion`, and `scriptPinEpoch` remain persisted on the row as exact provenance and execution-fence fields; `runtimeRegionId`, `runtimeRegionEpoch`, `nextDueTickId`/`nextDueAt`, and last-observed progress are schedule state. Ordinary matching heartbeat evidence may advance those mutable fields on the active generation, but a namespace or active-instance/region binding transition creates a replacement generation rather than rewriting that evidence in place. - `scheduleDefinitionId` participates in the stable logical continuity key and is one component of the complete due-candidate/firing claim identity; it is never sufficient alone and does not replace that complete identity. `scriptPatchVersion` and `scriptPinEpoch` identify the exact Game Session pin under which the row may execute; plugin-owned entries additionally carry `pluginId`, `pluginVersionId`, and `bindingId`, and `isDryRun` separates test execution from live scheduling. Live durable interval entries persist `isDryRun=false`. - `duePoint` is exactly one mutable persisted value: `dueTickId` for tick-aligned schedules or `dueAt` for wall-clock timers. `nextTick` and `nextRunAt` are projections of that stored due point, not substitutes for it. -- Each due candidate has at most one event-scope durable firing claim and one deterministic event-scope `scriptEventId`, keyed by the complete event-scope due-candidate identity defined above, including `scheduleDefinitionId`, `eventType`/`eventSchemaVersion`, the tagged captured `pluginActivationEpoch` for plugin-owned schedules, and, for catch-up claims and candidate audits, `resumeWindowId`. Same-epoch retries reuse that candidate identity; for plugin-owned schedules, a same-version disable/re-enable derives a fresh candidate identity from the newer `pluginActivationEpoch`. Core schedule transition identity changes only through the accepted exact patch/pin epoch contract; no separate core generation is implied. The claim and candidate audit persist/expose that same exact identity; handler-only identity fields are added only after resolution. Advancing the schedule due point must never rewrite a prior claim or mint a second ID. +- Each due candidate has at most one event-scope durable firing claim and one deterministic event-scope `scriptEventId`, keyed by the complete event-scope due-candidate identity defined above, including `playableStateNamespaceId`, `scheduleDefinitionId`, `eventType`/`eventSchemaVersion`, the tagged captured `pluginActivationEpoch` for plugin-owned schedules, and, for catch-up claims and candidate audits, `resumeWindowId`. The server-derived `playableStateScope` is separately persisted and exact-validated as policy/routing/authorization/migration-fence evidence, not identity. Same-epoch retries reuse that candidate identity; for plugin-owned schedules, a same-version disable/re-enable derives a fresh candidate identity from the newer `pluginActivationEpoch`. Core schedule transition identity changes only through the accepted exact patch/pin epoch contract; no separate core generation is implied. The claim and candidate audit persist/expose that same exact identity; handler-only identity fields are added only after resolution. Advancing the schedule due point must never rewrite a prior claim or mint a second ID. -Every durable schedule-instance row, resume window, due candidate, firing claim, candidate audit, and scheduler list/read output must persist and expose `isDryRun` as an identity dimension, `playableStateNamespaceId` as separate non-identity scope evidence, and `scriptPinEpoch` alongside `scriptPatchVersion`. Namespace evidence must exact-match the authoritative namespace/scope and active-instance/region owner binding at each materialization, claim, retry, and reconciliation boundary; missing or mismatched evidence fails closed without changing any canonical identity tuple. The pin epoch is exact execution/fence metadata and is deliberately excluded from the stable logical continuity key above. A same-version repin creates a new exact tuple: before Automation admission resumes, reconciliation may rewrite or retire only mutable schedule state. It must never rewrite an old-epoch firing claim or candidate/audit identity or outcome; pending claims may be fenced or terminal-marked when required while preserving their original exact tuples. Same-version repin retries must remain idempotent and replay-safe by reusing existing claim/candidate identities rather than duplicating them. +Every durable schedule-instance row, resume window, due candidate, firing claim, candidate audit, and scheduler list/read output must persist and expose `isDryRun` and `playableStateNamespaceId` as identity dimensions, the exact `playableStateScope` as separately persisted policy/routing/authorization/migration-fence evidence, and `scriptPinEpoch` alongside `scriptPatchVersion`. Namespace and scope evidence must exact-match the authoritative namespace/scope and active-instance/region owner binding at each materialization, claim, retry, and reconciliation boundary; missing or mismatched evidence fails closed without changing any canonical identity tuple. The pin epoch is exact execution/fence metadata and is deliberately excluded from the stable logical continuity key above. A same-version repin creates a new exact tuple: before Automation admission resumes, reconciliation may rewrite or retire only mutable schedule state. It must never rewrite an old-epoch firing claim or candidate/audit identity or outcome; pending claims may be fenced or terminal-marked when required while preserving their original exact tuples. Same-version repin retries must remain idempotent and replay-safe by reusing existing claim/candidate identities rather than duplicating them. On every exact script pin selection change, including a same-patch/new-epoch repin, reconciliation moves each prior `OPEN` resume window (independently for each `isDryRun` mode) out of `OPEN` before target timer admission resumes. Existing firing claims and candidate/audit records retain their original mode-specific `resumeWindowId` and exact pin, remain fenced for settlement under those original identities, and cannot consume the next window's cap. Only after the new exact `(scriptPatchVersion, scriptPinEpoch)` and schedules reconcile may a still-required catch-up episode allocate the next `resumeGeneration` window for the candidate's mode; retries are idempotent under the reconciliation `controlPlaneRequestId`. @@ -133,7 +150,7 @@ The schedule-row requirement to persist and expose `scriptPinEpoch` alongside `s The interval admission, durable-claim, artifact-estimate reservation, and retry/deferral behavior described below is target-state unless explicitly identified as current. It must not be read as evidence that the current runtime already implements those guarantees; the current-state gaps above and in the quotas document remain authoritative. -- When an instance first observes an exact pinned tuple, Automation materializes the patch-owned schedules for that `(tenantId, gameInstanceId)` scope into durable `script_schedule_instances` rows keyed by the stable schedule-instance identity above, with plugin owner metadata and binding target identity. Each row stores the authoritative `playableStateNamespaceId` as immutable non-identity scope evidence, the exact `scriptPatchVersion`, positive `scriptPinEpoch`, and paired nonblank `lastObservedControlPlaneRequestId`, `isDryRun`, `scheduleDefinitionId`, cadence, unit, scheduler priority tag, normalized schedule metadata hash, the initiating pin or runtime-transition `controlPlaneRequestId`, and exactly one mutable due-point field (`dueTickId` or `dueAt`). Missing or mismatched namespace evidence rejects materialization without creating or updating a row. For an initially materialized or reset wall-clock row with an absent durable `dueAt`, Automation derives it once from the transition's immutable seed plus the schedule's authored wall-clock cadence (`cadence`/`unit`) after any explicit time scaling. A Game Session pin or rollback uses Game Session `pinnedAt` bound to that pin request ID; a schedule-creating or resetting plugin activation/enable or other non-pin replacement instead uses an immutable Automation transition commit timestamp durably bound to that same `controlPlaneRequestId` (the runtime transition's committed `lastChangedAt` may supply the seed) and must never look up Game Session `pinnedAt` using a non-pin request ID. Automation persists and reuses that seed and derived `dueAt` across retries and reconciliation; projection refresh or observation time is diagnostic only. Disablement or revocation without a replacement tombstones the displaced row and creates no replacement row or fresh due point. Compatible continuity retains an existing `dueAt`; ordinary reload or repin does not overwrite it except through the transition branch below, while reset, incompatible, or newly materialized replacement rows receive fresh due state. Tick-aligned schedules remain persisted but `PENDING_RUNTIME_PROGRESS` until Game Session's `ObserveRuntimeTickProgress` input supplies the current runtime region epoch and tick id from Game Session's durable runtime ownership row. At that point Automation exact-matches the stored namespace/scope evidence with current owner scope, records the runtime region fields, and derives the first future `dueTickId` as `observedTickId + cadenceValue`; later observations that reach or pass it revalidate the complete namespace/scope and active-instance/region binding before admitting the due candidate, creating at most one event-scope firing claim, and deriving one deterministic event-scope `scriptEventId` for that due candidate, then use the same durable work-item, audit, and queue projection path as other admitted script events. Plugin-owned schedules are materialized only for the plugin version currently enabled in Automation's runtime registry for that instance; other published or displaced plugin versions must not keep durable schedule ownership. Region-scoped Redis indexes such as `automation:timer:{tenantRegionTag}` remain a derived coordination layer above those durable rows rather than the first source of schedule identity. +- When an instance first observes an exact pinned tuple, Automation materializes the patch-owned schedules for that `(tenantId, gameInstanceId, playableStateNamespaceId)` runtime scope into durable `script_schedule_instances` rows keyed by the stable schedule-instance identity above, with the server-derived `playableStateScope` persisted as separate exact-validated policy/routing/authorization/migration-fence evidence, plugin owner metadata, and binding target identity. Each row stores the namespace identity, exact `scriptPatchVersion` and `scriptPinEpoch`, `isDryRun`, `scheduleDefinitionId`, cadence, unit, scheduler priority tag, normalized schedule metadata hash, the initiating pin or runtime-transition `controlPlaneRequestId`, and exactly one mutable due-point field (`dueTickId` or `dueAt`). Missing or mismatched namespace or scope evidence rejects materialization without creating or updating a row. For an initially materialized or reset wall-clock row with an absent durable `dueAt`, Automation derives it once from the transition's immutable seed plus the schedule's authored wall-clock cadence (`cadence`/`unit`) after any explicit time scaling. A Game Session pin or rollback uses Game Session `pinnedAt` bound to that pin request ID; a schedule-creating or resetting plugin activation/enable or other non-pin replacement instead uses an immutable Automation transition commit timestamp durably bound to that same `controlPlaneRequestId` (the runtime transition's committed `lastChangedAt` may supply the seed) and must never look up Game Session `pinnedAt` using a non-pin request ID. Automation persists and reuses that seed and derived `dueAt` across retries and reconciliation; projection refresh or observation time is diagnostic only. Disablement or revocation without a replacement tombstones the displaced row and creates no replacement row or fresh due point. Compatible continuity retains an existing `dueAt`; ordinary reload or repin does not overwrite it except through the transition branch below, while reset, incompatible, or newly materialized replacement rows receive fresh due state. Tick-aligned schedules remain persisted but `PENDING_RUNTIME_PROGRESS` until Game Session's `ObserveRuntimeTickProgress` input supplies the current runtime region epoch and tick id from Game Session's durable runtime ownership row. At that point Automation exact-matches the stored namespace/scope evidence with current owner scope, records the runtime region fields, and derives the first future `dueTickId` as `observedTickId + cadenceValue`; later observations that reach or pass it revalidate the complete namespace/scope and active-instance/region binding before admitting the due candidate, creating at most one event-scope firing claim, and deriving one deterministic event-scope `scriptEventId` for that due candidate, then use the same durable work-item, audit, and queue projection path as other admitted script events. Plugin-owned schedules are materialized only for the plugin version currently enabled in Automation's runtime registry for that instance; other published or displaced plugin versions must not keep durable schedule ownership. Region-scoped Redis indexes such as `automation:timer:{tenantRegionTag}` remain a derived coordination layer above those durable rows rather than the first source of schedule identity. - Leaders track these interval entries alongside other automation timers using bounded scans. Event scope applies cadence, reload, version, and event-policy gates, then creates at most one event-scope firing claim and one event-scope `scriptEventId` per due candidate before resolving handlers. Handlers admitted by all pre-materialization handler-scoped gates, including quota, become durable queued work, each with its own full Trigger Identity containing that same propagated ID; every resolved handler still receives an audit row, while a handler denied by a pre-materialization handler-scoped gate receives no work item, queue projection, lease, or execution marker. The later execution scheduler considers queued handler work in canonical order and reserves the artifact-estimate ordered prefix up to `AUTOMATION_TICK_BUDGET_MS`, leaving the remainder durably queued/deferred under unchanged handler identity. An ordinary post-executor-claim `ScriptTenantBudgetService` denial instead acts on an existing durable work item, terminally cancels it before DSL evaluation, and follows the handler-level budget outcome route. The reservation is not actual execution time, a per-run timeout, or a lease debit; actual runtime never changes the selected prefix or creates a same-tick refund, and the quota owner separately governs fenced capacity lease acquisition and recovery. - When an interval becomes due, the scheduler derives a deterministic `scheduleCandidateId` from the complete event-scope due-candidate identity defined above, including the captured `pluginActivationEpoch` for plugin-owned schedules. It applies cadence, reload, version, and event-policy gates at event scope before handler binding. A permanent or declared-skip gate failure is durably consumed with its `scheduleCandidateId`-keyed audit outcome: advance the canonical due point according to the cadence, or quarantine/tombstone the schedule when safe advancement is impossible; it creates no firing claim or `scriptEventId`. A transient retryable reload, reconciliation, or authority fence instead retains a durable due-candidate state/claim keyed by `scheduleCandidateId` and the canonical due point under its original exact tuple and captured `(pluginActivationEpoch, lifecycleRevision)` pair, when applicable, as fenced/nonterminal evidence without creating a firing claim or `scriptEventId`; this transient state is not a terminal candidate audit and carries no `finalStage` or `finalOutcome` while fenced. It may retry the same candidate only while the captured lifecycle pair remains current and after the exact pin tuple, runtime scope, and owner evidence reconcile, then compare-and-set once into the one firing path or one immutable terminal candidate audit. A displaced old scope, epoch, or plugin activation epoch remains fenced under its original candidate identity and is never reused; a plugin-owned same-version disable/re-enable derives a fresh candidate identity from the newer `pluginActivationEpoch` before admission. Core schedule transition identity changes only through the accepted exact patch/pin epoch contract. Once the candidate passes those event gates, the scheduler creates at most one event-scope durable firing claim and one event-scope `scriptEventId`, resolves handlers, and applies all pre-materialization handler-scoped gates. Handlers admitted by those gates, including quota, create durable queued work, each with its own full Trigger Identity containing that same propagated ID; every resolved handler receives an audit row, while a handler denied by a pre-materialization handler-scoped gate, including quota denial as `ADMISSION/quota_denied`, creates no work item, queue projection, lease, or execution marker. An ordinary post-executor-claim `ScriptTenantBudgetService` denial instead terminally cancels the already materialized and claimed handler work item before DSL evaluation with `ADMISSION/tenant_budget_exceeded`; it is not a pre-materialization denial. Before `EVALUATED_COMMITTED`, a failed handler evaluation may retry under that same full Trigger Identity and same propagated `scriptEventId` only for a retryable infrastructure or fencing failure; deterministic logical, validation, and sandbox outcomes are final. After the boundary, recovery replays its durable descriptors without re-entering the DSL. The later execution scheduler applies the artifact-estimate ordered-prefix reservation to queued handler work and defers the remainder without changing identity. @@ -141,16 +158,16 @@ The interval admission, durable-claim, artifact-estimate reservation, and retry/ #### Leader Changes -- Leaders advance a per-region notion of time by consuming the tick heartbeat stream and tracking how far they have progressed. In addition to the current heartbeat `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)`, schedulers maintain a derived discovery hint such as `script-scheduler:{tenantRegionTag}:lastTickId`. The opaque `{tenantRegionTag}` physically carries the full `` scope, while the payload stores `regionEpoch` and `latestTickId`. Consumers must compare the stored epoch with the authoritative current epoch before reusing the progress value. The separate per-consumer `tick-events-offset:{tenantRegionTag}:` record is the sole owner of that consumer's `streamOffset`. +- Leaders advance a per-region notion of time by consuming the tick heartbeat stream and tracking how far they have progressed. In addition to the current heartbeat `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)`, a target scheduler may maintain a derived discovery hint such as `script-scheduler:{tenantRegionTag}:lastTickId`; this Redis key is target-only and unimplemented, while Game Session's durable runtime-ownership status and heartbeat remain current authority. This runtime-progress hint is deliberately namespace-independent: the opaque `{tenantRegionTag}` physically carries the full `` scope, while the payload stores `regionEpoch` and `latestTickId`. It is derived progress only, never timer, due-point, or admission identity; a namespace transition therefore re-enumerates durable schedule state and cannot be authorized by this hint. Consumers must compare the stored epoch with the authoritative current epoch before reusing the progress value. The separate per-consumer `tick-events-offset:{tenantRegionTag}:` record is the sole owner of that consumer's `streamOffset`. - When leadership changes, the new leader: - reads the scheduler hint and canonical event-offset record for the current `regionEpoch`; - rejects either value when its stored `regionEpoch` does not match the current heartbeat/status epoch. It must not walk old-epoch ticks, reuse an old stream offset, or reuse old-epoch due points. The mismatch is recorded in scheduler audit with `reason=checkpoint_region_epoch_mismatch`; this stale coordination projection does not drop or terminalize a due point and does not increment `automation_script_timer_runtime_fence_dropped_total`; - discards each stale value, rebuilds the current-epoch scheduler hint and event-offset record from the authoritative durable status/heartbeat, and then reconciles durable due points under the bounded catch-up policy; and - - enumerates the authoritative PostgreSQL `script_schedule_instances` rows for the current runtime scope to determine which current-epoch "every N ticks" boundaries were crossed during the gap. The Redis region index `automation:timer:{tenantRegionTag}` may accelerate this scan, but it is rebuildable and must not be the source of truth; if it is missing or stale, rebuild it from the durable rows before admitting candidates. It obtains or creates the one `OPEN` durable resume-window record for the candidate's `isDryRun` mode by CAS, freezes that record's recovery start and through observations, and admits each due candidate before claiming or inserting a durable firing claim. Every firing-claim insert, lookup, and conflict comparison uses the complete event-scope due-candidate identity defined above, including the exact pin tuple, event/schema, explicit `isDryRun`, trigger mode, applicable target selector, schedule definition, tagged due point, and `resumeWindowId` for catch-up; only then may it enqueue an `onInterval` trigger. - - Each `COALESCE_ONE` schedule instance may enqueue at most one missed `onInterval` trigger before normal scheduling resumes; `SKIP_MISSED` schedule instances enqueue none. `SCRIPT_TIMER_CATCH_UP_MAX_FIRINGS_PER_RESUME` is evaluated as a tenant-local cap across complete stable schedule-instance identities within one durable, mode-specific `resumeWindowId`; the cap's boundary is that ID's full runtime scope and `isDryRun` mode, while tenant-local identifies the window's tenant owner rather than a tenant-wide pool. Live and dry-run/test windows apply the cap independently, and a schedule in another game instance, playable-state scope, region, or epoch cannot consume this window's cap. Candidates beyond this cap are dropped, not deferred, and surfaced through candidate audit plus exactly one `automation_script_timer_catchup_truncated_total{reason="resume_window_cap"}` increment when each candidate's durable settlement completes; they create no firing claim or firing. The window is marked `COMPLETE` only after selected candidates' firing or durable shared-admission-denial outcomes and all cap-excluded candidate outcomes are durable; only a later recovery episode then allocates the next generation. These are target-state recovery guarantees; the current runtime's bounded per-observation catch-up does not yet prove the durable resume-window enforcement described here. + - enumerates the authoritative PostgreSQL `script_schedule_instances` rows for the current runtime scope and `playableStateNamespaceId` to determine which current-epoch "every N ticks" boundaries were crossed during the gap. The Redis region index `automation:timer:{tenantRegionTag}` may accelerate this scan, but it is rebuildable and must not be the source of truth; if it is missing or stale, rebuild it from the durable rows before admitting candidates. It obtains or creates the one `OPEN` durable resume-window record for the candidate's `isDryRun` mode by CAS, freezes that record's recovery start and through observations, and admits each due candidate before claiming or inserting a durable firing claim. Every firing-claim insert, lookup, and conflict comparison uses the complete event-scope due-candidate identity defined above, including the namespace identity, exact pin tuple, event/schema, explicit `isDryRun`, trigger mode, applicable target selector, schedule definition, tagged due point, and `resumeWindowId` for catch-up. The separately persisted exact `playableStateScope` remains policy/routing/authorization/migration-fence evidence that is revalidated before admission, not an identity input; only then may it enqueue an `onInterval` trigger. + - Each `COALESCE_ONE` schedule instance may enqueue at most one missed `onInterval` trigger before normal scheduling resumes; `SKIP_MISSED` schedule instances enqueue none. Cadence, reload, version, and event-policy gates settle any rejected candidate durably before it joins the resume window's enumerated set. `SCRIPT_TIMER_CATCH_UP_MAX_FIRINGS_PER_RESUME` is evaluated as a tenant-local cap across complete stable schedule-instance identities within one durable, mode-specific `resumeWindowId`; the cap's boundary is that ID's full runtime scope, `playableStateNamespaceId`, and `isDryRun` mode, while the server-derived `playableStateScope` remains separately persisted exact-validated policy/routing/authorization/migration-fence evidence. Live and dry-run/test windows apply the cap independently, and a schedule in another game instance, namespace, region, or epoch cannot consume this window's cap. Candidates beyond this cap are dropped, not deferred, and surfaced through candidate audit plus exactly one `automation_script_timer_catchup_truncated_total{reason="resume_window_cap"}` increment when each candidate's durable settlement completes; they create no firing claim or firing. Every candidate included in the window's enumerated set must reach a durable outcome before completion: the window is marked `COMPLETE` only after selected candidates' firing or durable shared-admission-denial outcomes and all cap-excluded candidate outcomes are durable. Only a later recovery episode then allocates the next generation. These are target-state recovery guarantees; the current runtime's bounded per-observation catch-up does not yet prove the durable resume-window enforcement described here. - Leader changes and takeover reconciliation preserve each firing's declared lane and cost class and validate the current runtime epoch/fence before admitting it; stale or ambiguous claims are fenced and reconciled rather than reclassified or replayed as new work. - Catch-up truncation must use one stable fairness algorithm when due candidates exceed `SCRIPT_TIMER_CATCH_UP_MAX_FIRINGS_PER_RESUME`: - - Collapse each overdue schedule instance to its earliest missed tagged due point in its declared clock domain (`dueTickId` for tick/game time or `dueAt` for wall clock). Do not numerically compare tick IDs with wall-clock timestamps. Because each `resumeWindowId` is already scoped to one `` record, this cap is evaluated only within that full runtime-scope-and-mode window: tenant-local identifies its tenant owner and does not make it a tenant-wide pool, so candidates from another game instance, playable-state scope, region, or epoch never join this set. It is mode-isolated and does not arbitrate across tenants. Within that window's candidate set, order by bounded `priorityTag` (`high`, `normal`, `background`), then complete stable schedule-instance identity ASC. + - Collapse each overdue schedule instance to its earliest missed tagged due point in its declared clock domain (`dueTickId` for tick/game time or `dueAt` for wall clock). Do not numerically compare tick IDs with wall-clock timestamps. Because each `resumeWindowId` is already scoped to one `` record, this cap is evaluated only within that full runtime-scope-and-mode window; the server-derived `playableStateScope` is separately persisted exact-validated evidence and is not a uniqueness boundary. Tenant-local identifies its tenant owner and does not make it a tenant-wide pool, so candidates from another game instance, namespace, region, or epoch never join this set. It is mode-isolated and does not arbitrate across tenants. Within that window's candidate set, order by bounded `priorityTag` (`high`, `normal`, `background`), then complete stable schedule-instance identity ASC. - Admit catch-up firings in round-robin passes across distinct complete stable schedule-instance identities within that resume-window candidate set (the stable row identity defined above, including target scope and `isDryRun`), not merely `scheduleDefinitionId`, so independently materialized instances sharing one definition each receive an opportunity and one noisy instance cannot consume the entire resume window. `pluginVersionId` and `bindingId` remain due-candidate provenance, fence, and deduplication dimensions; they do not split stable fairness groups. Priority and every tie break retain stable schedule-instance identity ordering. Candidates admitted by tenant-local catch-up still enter the shared scheduler/cluster admission layer, where [ADR 0166](./decisions/adr-0166-attributable-script-breakers-and-tenant-first-fairness.md) tenant-first fairness precedes priority; catch-up cannot bypass per-tenant or cluster ceilings. - Admit at most one missed firing for any logical schedule instance in the complete `resumeWindowId`, using its earliest missed tagged due point as the coalesced identity. - Once the resume cap is reached, remaining overdue firings are truncated rather than deferred into an unbounded backlog; emit audit/metrics that distinguish how many were coalesced or dropped. @@ -165,13 +182,13 @@ The interval admission, durable-claim, artifact-estimate reservation, and retry/ - reconciles durable schedule definitions for the newly pinned exact `(scriptPatchVersion, scriptPinEpoch)` tuple before any timer is allowed to fire again, updating the instance-scoped `script_schedule_instances` rows first; - updates each explicitly preserved interval entry's authoritative due point (`dueTickId` or `dueAt`) after typed continuity compatibility checks: it applies the normative tick resume formula only to preserved tick timers, while compatible wall-clock continuity retains persisted `dueAt` and regenerates `nextRunAt`; reset, incompatible, or newly materialized replacement rows retain fresh due state; and - resumes normal scheduling for `onInterval` using the exact committed patch and pin epoch. No interval runs against a partially loaded script definition or a local active/latest pointer. -- If reload fails or durable reconciliation evidence is unavailable, the pending exact `(scriptPatchVersion, scriptPinEpoch)` tuple is retained with failed/fenced diagnostic state and any partially loaded schedule state is discarded. The affected runtime scope admits no new timer firing until reconciliation confirms the current exact pin tuple, schedule owner, scope, epoch, due state, and, for plugin-owned schedules, the captured `(pluginActivationEpoch, lifecycleRevision)` pair. Transient retryable reload, reconciliation, or authority-fence conditions retain each due candidate as durable nonterminal state/claim under the same `scheduleCandidateId` and canonical due point from the original exact tuple; while fenced, that state has no `finalStage`, `finalOutcome`, firing claim, or `scriptEventId`. If the captured exact tuple remains current when evidence reconciles, the same state may compare-and-set once into the firing path or one immutable terminal candidate audit; a lifecycle-revision mismatch fences that candidate under its captured pair, and reconciliation never refreshes or rebinds its historical evidence. `DRAINING` permits this only for already-admitted work whose winning admission/fence CAS committed before the durable drain barrier; a merely fenced candidate without that proof cannot create a firing. Only a changed identity tuple—such as patch, pin epoch, runtime region epoch, or `pluginActivationEpoch` (including a same-version plugin disable/re-enable)—displaces the old candidate, which remains fenced under its original identity and captured lifecycle pair (and may be terminal-marked as required), while target reconciliation derives a fresh, non-reused candidate identity only after durable reconciliation and before admission. Explicit continuity may carry stable schedule-row/due state but never rewrites candidate identity, and no `scriptEventId` is minted before the target candidate passes admission. A prior observed tuple may remain observable for diagnosis, but the scheduler must not use a "last known good" fallback to mint or execute new timer work. +- If reload fails or durable reconciliation evidence is unavailable, the pending exact `(scriptPatchVersion, scriptPinEpoch)` tuple is retained with failed/fenced diagnostic state and any partially loaded schedule state is discarded. The affected runtime scope admits no new timer firing until reconciliation confirms the current exact pin tuple, schedule owner, `playableStateNamespaceId`, separately persisted exact `playableStateScope` evidence, region epoch, due state, and, for plugin-owned schedules, the captured `(pluginActivationEpoch, lifecycleRevision)` pair. Transient retryable reload, reconciliation, or authority-fence conditions retain each due candidate as durable nonterminal state/claim under the same `scheduleCandidateId` and canonical due point from the original exact tuple; while fenced, that state has no `finalStage`, `finalOutcome`, firing claim, or `scriptEventId`. If the captured exact tuple remains current when evidence reconciles, the same state may compare-and-set once into the firing path or one immutable terminal candidate audit; a lifecycle-revision mismatch fences that candidate under its captured pair, and reconciliation never refreshes or rebinds its historical evidence. `DRAINING` permits this only for already-admitted work whose winning admission/fence CAS committed before the durable drain barrier; a merely fenced candidate without that proof cannot create a firing. Only a changed identity tuple—such as namespace, patch, pin epoch, runtime region epoch, or `pluginActivationEpoch` (including a same-version plugin disable/re-enable)—displaces the old candidate, which remains fenced under its original identity and captured lifecycle pair (and may be terminal-marked as required), while target reconciliation derives a fresh, non-reused candidate identity only after durable reconciliation and before admission. A presented scope mismatch is also fenced until authority proves the scope unchanged; an authority-proven scope transition starts a new lifecycle/namespace and cannot reuse the old candidate. Explicit continuity may carry stable schedule-row/due state but never rewrites candidate identity, and no `scriptEventId` is minted before the target candidate passes admission. A prior observed tuple may remain observable for diagnosis, but the scheduler must not use a "last known good" fallback to mint or execute new timer work. During reload, plugin-owned due candidates retain and revalidate the captured `(pluginActivationEpoch, lifecycleRevision)` pair alongside the exact script pin and runtime scope. A same-version/same-epoch `DRAINING` predecessor is usable only with ADR 0119's durable pre-`DRAINING` admission-CAS evidence; lifecycle revision remains non-identity evidence and does not authorize a new candidate. ### Explicit Continuity Across Script Transitions -The default for an authored interval at a script-patch, plugin-version, activation, disablement, rollback, or repin transition is cancel-and-recreate. Continuity is an explicit opt-in on both sides of the transition, keyed by `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, targetScopeType, targetScopeId}` and accepted only after typed interval/cadence/target compatibility checks. `pluginId` is the stable plugin owner; `pluginVersionId` and `scriptPatchVersion` remain exact provenance and execution-fence metadata. One-shot timers are outside this rule and must not be silently migrated or recreated because a `scheduleDefinitionId` matches. The full recovery clock and downtime contract remains in [ADR 0091](./decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md). +The default for an authored interval at a script-patch, plugin-version, activation, disablement, rollback, or repin transition is cancel-and-recreate. Continuity is an explicit opt-in on both sides of the transition, keyed by `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}` and accepted only after typed interval/cadence/target compatibility checks plus exact validation of the separately persisted `playableStateScope` policy/routing/authorization/migration-fence evidence. `pluginId` is the stable plugin owner; `pluginVersionId` and `scriptPatchVersion` remain exact provenance and execution-fence metadata. One-shot timers are outside this rule and must not be silently migrated or recreated because a `scheduleDefinitionId` matches. An authority-proven playable-state scope transition starts a new playable-state lifecycle and selects or allocates a new namespace before fresh schedule identity is admitted; stale presented scope evidence may reuse the namespace-keyed identity only when authoritative scope is unchanged. The full recovery clock and downtime contract remains in [ADR 0091](./decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md). Timer reconciliation on patch or plugin change is a required part of reload and rollback safety: @@ -184,9 +201,9 @@ For plugin-owned schedules, the stable schedule row carries the mutable current - Implementations must persist a `scheduleSemanticsHash` or equivalent canonical normalized fingerprint with each compiled definition as diagnostic evidence. Hash equality cannot grant continuity and hash inequality alone cannot deny an otherwise valid explicit declaration. - When an instance observes a newly pinned exact `(scriptPatchVersion, scriptPinEpoch)` tuple, the scheduler must compare the durable schedules for the previously observed tuple with those for the newly pinned tuple before resuming timer admission. Plugin activation, disablement, rollback, and revocation perform the same comparison for `(pluginId, pluginVersionId, bindingId)`. - Schedules that do not exist in the newly pinned patch must be tombstoned so they can no longer generate triggers. When there is no replacement owner, disablement or revocation must fence admission and tombstone the displaced row atomically under the same control-plane operation; it must not fabricate a replacement schedule. -- For the default or incompatible path, a patch, plugin-version, activation, disablement, rollback, or repin transition uses cancel-and-recreate: when a replacement owner exists, reconciliation creates or confirms the target schedule generation with fresh due state before retiring or tombstoning the displaced row; when no replacement owner exists, it fences and tombstones the displaced row without fabricating a replacement. Continuity is preserved only when both source and target explicitly declare compatible continuity for the same stable logical key `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, targetScopeType, targetScopeId}`, `source.isDryRun` equals `target.isDryRun`, and interval kind, cadence unit/value, target binding, playable-state scope, and runtime fencing are compatible, with exact equality of the authoritative `playableStateNamespaceId` and active-instance/region binding (including `gameInstanceId`, `regionId`, and `regionEpoch`); an ordinary executor-fence handoff that preserves that instance/region binding is not itself a transition. A namespace or active-instance/region binding transition is therefore incompatible with in-place continuity and routes to a fresh `scheduleInstanceId` under the applicable reset ordering. Namespace transitions follow the retire-before-materialize barrier above; other replacement-owner resets may prepare a fresh non-admitting generation before the atomic retirement/activation step below. Only when all continuity conditions hold is the existing generation updated in place with the target ownership/pin metadata and recalculated due point. A missing declaration, dry-run mode mismatch, changed key/cadence/target, explicit reset, absent target, disabled/revoked owner, namespace or active-instance/region binding mismatch, or ambiguity forces the reset path. A same-version repin is still a new epoch transition: for a continuity-preserved row, reconciliation adopts the target exact `(scriptPatchVersion, scriptPinEpoch)` and associated mutable current pin/owner/provenance metadata on the active row before admission resumes; for the reset path, it creates or confirms the target row with that exact metadata before retiring the displaced row. Only the active row and pending mutable schedule state may be retired or rewritten; old-epoch firing claims and candidate/audit identities and outcomes retain their original tuple and may only be fenced or terminal-marked, never rewritten. Rollback follows the same rule and never infers continuity from history or hash similarity. +- For the default or incompatible path, a patch, plugin-version, activation, disablement, rollback, or repin transition uses cancel-and-recreate: when a replacement owner exists, reconciliation creates or confirms the target schedule generation with fresh due state before retiring or tombstoning the displaced row; when no replacement owner exists, it fences and tombstones the displaced row without fabricating a replacement. Continuity is preserved only when both source and target explicitly declare compatible continuity for the same stable logical key `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}`, `source.isDryRun` equals `target.isDryRun`, and interval kind, cadence unit/value, target binding, separately persisted `playableStateScope` evidence, and runtime fencing are compatible, with exact equality of the authoritative namespace and active-instance/region binding (including `gameInstanceId`, `regionId`, and `regionEpoch`); an ordinary executor-fence handoff that preserves that instance/region binding is not itself a transition. A namespace or active-instance/region binding transition is therefore incompatible with in-place continuity and routes to a fresh `scheduleInstanceId` under the applicable reset ordering. An authority-proven playable-state scope transition likewise starts a new lifecycle and selects or allocates a new namespace; only stale presented scope evidence with unchanged authoritative scope may reuse the namespace-keyed identity. Namespace transitions follow the retire-before-materialize barrier above; other replacement-owner resets may prepare a fresh non-admitting generation before the atomic retirement/activation step below. Only when all continuity conditions hold is the existing generation updated in place with the target ownership/pin metadata and recalculated due point. A missing declaration, dry-run mode mismatch, changed key/cadence/target, explicit reset, absent target, disabled/revoked owner, namespace or active-instance/region binding mismatch, scope-evidence mismatch, or ambiguity forces the reset path. A same-version repin is still a new epoch transition: for a continuity-preserved row, reconciliation adopts the target exact `(scriptPatchVersion, scriptPinEpoch)` and associated mutable current pin/owner/provenance metadata on the active row before admission resumes; for the reset path, it creates or confirms the target row with that exact metadata before retiring the displaced row. Only the active row and pending mutable schedule state may be retired or rewritten; old-epoch firing claims and candidate/audit identities and outcomes retain their original tuple and may only be fenced or terminal-marked, never rewritten. Rollback follows the same rule and never infers continuity from history or hash similarity. - `controlPlaneRequestId` is the reconciliation idempotency key. The same nonblank value from the initiating patch pin, plugin activation, disable, rollback, or signer-revocation request must be persisted on and carried through every schedule-reconciliation step, including preserved-schedule updates, reset replacement, retirement, and retry; a sub-step must not mint a new reconciliation key. -- When explicit continuity is valid, reconciliation updates the existing stable row in place, adopting the exact target `(scriptPatchVersion, scriptPinEpoch)` and associated mutable current pin/owner/provenance metadata before admission resumes, while retaining immutable namespace evidence, and branches due-point recalculation by clock unit: preserved tick timers use the normative tick resume formula, while compatible wall-clock timers retain persisted `dueAt` and regenerate `nextRunAt` strictly as its projection. Target resume time does not alter the persisted deadline, and any wall-clock overdue state remains governed by its declared recovery/catch-up policy. Both branches retain the exact target metadata and reconciliation idempotency under `controlPlaneRequestId`; the tick branch must not retain an overdue point, neither branch restarts from deployment time nor replays every missed interval. The in-place update must be atomic or a resumable idempotent operation keyed by `controlPlaneRequestId`; it creates no replacement row, tombstone, firing claim, or `scriptEventId`. Previously captured candidate, firing-claim, audit, and work evidence remains immutable under its original tuple and identity; the scheduler mints firing claims and `scriptEventId` only after a due candidate passes admission. +- When explicit continuity is valid, reconciliation updates the existing stable row in place, retaining the exact `playableStateNamespaceId` identity and separately persisted `playableStateScope` evidence while adopting the exact target `(scriptPatchVersion, scriptPinEpoch)` and associated mutable current pin/owner/provenance metadata before admission resumes, and branches due-point recalculation by clock unit: preserved tick timers use the normative tick resume formula, while compatible wall-clock timers retain persisted `dueAt` and regenerate `nextRunAt` strictly as its projection. Target resume time does not alter the persisted deadline, and any wall-clock overdue state remains governed by its declared recovery/catch-up policy. Both branches retain the exact target metadata and reconciliation idempotency under `controlPlaneRequestId`; the tick branch must not retain an overdue point, neither branch restarts from deployment time nor replays every missed interval. The in-place update must be atomic or a resumable idempotent operation keyed by `controlPlaneRequestId`; it creates no replacement row, tombstone, firing claim, or `scriptEventId`. Previously captured candidate, firing-claim, audit, and work evidence remains immutable under its original tuple and identity; the scheduler mints firing claims and `scriptEventId` only after a due candidate passes admission. - For the reset or incompatible path when a replacement owner exists, replacement-before-retirement applies to plugin activation, repin, rollback, region/epoch changes, and other transitions except the namespace barrier above: reconciliation creates or confirms a fresh target `scheduleInstanceId` in a non-admitting prepared state with the target owner/binding and fresh due state, then one atomic durable transition, or resumable idempotent operation under the same `controlPlaneRequestId`, retires the displaced generation and makes the target the sole admitting row for its natural continuity key. The active-row uniqueness rule therefore never permits two generations to admit, and a prepared target cannot mint a candidate, firing claim, or `scriptEventId`. Namespace changes instead retire the source before any target row is materialized as required above. Disablement or signer revocation without a replacement fences admission and atomically tombstones the displaced row under the same `controlPlaneRequestId`. - Canceling outbox work items alone is insufficient for rollback safety; old-version timer schedules must also be reconciled so they cannot mint new `scriptEventId` values after the version has been displaced. @@ -195,7 +212,7 @@ Plugin example: - If plugin version `combat-helper@v4` and `combat-helper@v5` both compile a "reapply guard aura every 20 ticks" timer with `scheduleDefinitionId=combat-helper.guard-aura.v1`, explicit compatible continuity updates the existing stable schedule row from `v4` to `v5` ownership/pin metadata in place and recalculates its next due point before scheduling resumes; it does not create a replacement row. If continuity is absent or incompatible, the default reset path instead creates or confirms `v5` before retiring `v4`. The `v5` entry receives a firing claim and `scriptEventId` only after a due candidate passes admission. - If `combat-helper@v5` replaces that timer with a different logical schedule such as "pulse only while threat > 0" compiled to a different `scheduleDefinitionId`, reconciliation must create the new timer for `v5` before retiring the old `v4` timer under the same atomic-or-resumable rule. -Under this model, durable script schedules, quotas, and firing-claim de-duplication live in PostgreSQL, while `automation:timer:{tenantRegionTag}`, `script-scheduler:{tenantRegionTag}:lastTickId`, and related coordination keys form a reset-tolerant coordination layer for interval state. Stored entries and reconciliation logic remain instance-aware even though the Redis keys are region-scoped for slotting. The combination of tick heartbeat, durable firing claims, epoch-validated checkpoints, and script patch versioning preserves both correctness and determinism across failures and leader changes: losing or resetting these Redis keys may delay or slightly reshuffle timer firings within the tail-loss envelope but must not change which scripts are eventually scheduled according to their stored configurations or cause duplicate logical trigger creation. +Under this target-state model, durable script schedules, quotas, and firing-claim de-duplication live in PostgreSQL, while `automation:timer:{tenantRegionTag}`, `script-scheduler:{tenantRegionTag}:lastTickId`, and related coordination keys form a reset-tolerant coordination layer for interval state. Stored entries and reconciliation logic remain instance-aware even though the Redis keys are region-scoped for slotting. The combination of tick heartbeat, durable firing claims, epoch-validated checkpoints, and script patch versioning preserves durable identity and correctness-bearing one-shot outcomes across failures and leader changes: for best-effort recurring or advisory missed firings only, losing or resetting these Redis keys may delay, slightly reshuffle, or skip missed firings within the tail-loss envelope; future eligible cadence remains available. Correctness-bearing one-shots retain PostgreSQL-backed durable intent and settlement under their original identity, so Redis loss or reset cannot silently skip or remint them, and duplicate logical trigger creation is prevented. The current runtime does not yet prove this guarantee: re-observation can reseed a consumed one-shot, and current candidate/work-item identity omits `targetScopeType`/`targetScopeId`; those implementation gaps remain recorded above. ### Scheduler Leadership & Coordination @@ -221,7 +238,7 @@ See [Tick System and Runtime Design](./system-architecture-ticks.md) and [`autom - During reloads, triggers are paused or skipped while in-flight runs drain under existing concurrency settings: - New triggers for the affected runtime scope are not admitted; attempts to schedule additional runs receive explicit backpressure outcomes (`skipped_reloading` during `RELOADING`, `rollback_paused` during rollback pause). For a low-rate runtime event denied before handler resolution by rollback pause, ingress records `admissionOutcome=TRIGGER_ADMISSION_OUTCOME_BACKPRESSURE_ROLLBACK` and `admissionReason=rollback_pause` in `script_event_ingress_audit`; this is an event-scope outcome, not a handler `finalOutcome`. While that event-scope claim remains `IN_PROGRESS`, a concurrent retry may wait for the same claim to finalize or receive a retryable transport/application signal without an admission result; recovery resumes the same claim under fencing. Once finalized, a retry with the same event-scope identity replays permanent denials and successful final results exactly; an explicitly retryable transient backpressure denial stores retry eligibility and hint, and after that window the same identity may atomically reclaim and reopen the fenced claim for a new admission attempt, retaining the same `scriptEventId` and event identity. Once a handler has resolved, retries of that handler use its same full Trigger Identity and the same propagated `scriptEventId`; no separate handler ID is minted. A pre-handler `FAILED` reload is different: ingress records `admissionOutcome=TRIGGER_ADMISSION_OUTCOME_VERSION_UNAVAILABLE` and `admissionReason=reload_failed` with no retry hint, while timer candidates use the terminal `reloadState=FAILED` candidate-audit behavior in [Table 3](./system-architecture-scripting-normative-contract-tables.md#table-3-timer-semantics-matrix), with no firing claim or `scriptEventId` until durable recovery returns the scope to `IDLE`. Resolved-handler failures continue to use `finalOutcome` in `script_event_audit`. - In-flight runs remain bounded by each script’s configured `maxConcurrent` and `concurrencyPolicy` (for example, `queue_until_free`); any short per-script waiting queues are allowed to drain, but no new entries are added while `reloadState=RELOADING`. - - Pending timer-based triggers that became due during a transient retryable reload, reconciliation, or authority fence retain a durable due-candidate state/claim keyed by `scheduleCandidateId` and the canonical due point under the original exact tuple; scheduler timer indexes remain only rebuildable projections until exact version, epoch, and runtime-scope reconciliation completes. While fenced, this transient state has no `finalStage`, `finalOutcome`, firing claim, handler identity, or `scriptEventId`. If the captured exact tuple remains current when evidence reconciles, that state may compare-and-set once into the one firing path or one immutable terminal candidate audit; if a patch, plugin, or pin-epoch transition displaces the tuple, the old candidate remains fenced under its original identity (and may be terminal-marked as required), while the target schedule derives a new candidate identity only after durable reconciliation. Explicit continuity may carry stable schedule-row/due state but never rewrites candidate identity; the target candidate creates its firing claim and `scriptEventId` only after admission. Permanent or declared skips consume/drop their candidate under the declared policy, and an old scope or epoch remains fenced and is never reused. + - Pending timer-based triggers that became due during a transient retryable reload, reconciliation, or authority fence retain a durable due-candidate state/claim keyed by `scheduleCandidateId` and the canonical due point under the original exact tuple; scheduler timer indexes remain only rebuildable projections until exact version, epoch, namespace, separately persisted scope evidence, and runtime binding reconciliation completes. While fenced, this transient state has no `finalStage`, `finalOutcome`, firing claim, handler identity, or `scriptEventId`. If the captured exact tuple remains current when evidence reconciles, that state may compare-and-set once into the one firing path or one immutable terminal candidate audit; if a patch, plugin, or pin-epoch transition displaces the tuple, the old candidate remains fenced under its original identity (and may be terminal-marked as required), while the target schedule derives a new candidate identity only after durable reconciliation. A presented scope mismatch remains fenced until authority proves the scope unchanged; an authority-proven scope transition starts a new lifecycle/namespace. Explicit continuity may carry stable schedule-row/due state but never rewrites candidate identity; the target candidate creates its firing claim and `scriptEventId` only after admission. Permanent or declared skips consume/drop their candidate under the declared policy, and an old namespace, scope, or epoch remains fenced and is never reused. - On success, the scheduler observes the newly committed Game Session `(scriptPatchVersion, scriptPinEpoch)` for future triggers; on failure: - `activePatchVersion` remains an observed diagnostic value, but it does not authorize new timer work while reconciliation is unresolved; - the pending exact `(scriptPatchVersion, scriptPinEpoch)` tuple is marked failed/fenced along with an error reason, and leaders discard any partially loaded state for that tuple; diff --git a/design/architecture/system-architecture-spatial-and-ambient-effects-catalog.md b/design/architecture/system-architecture-spatial-and-ambient-effects-catalog.md index 53e06334a6..eb9e568296 100644 --- a/design/architecture/system-architecture-spatial-and-ambient-effects-catalog.md +++ b/design/architecture/system-architecture-spatial-and-ambient-effects-catalog.md @@ -10,13 +10,13 @@ The target `DROP`/`PICKUP` contracts below are not yet fully implemented or prov ## Common Requirements (All Effects) -- [Transaction Strategies](./system-architecture-transactions.md) owns split spatial authority and operation-bound effect behavior. [Identifier Glossary](./system-architecture-identifier-glossary.md#cross-service-effect-identity) owns root `EffectId` and participant guard identity, while its [causal-read fence contract](./system-architecture-identifier-glossary.md#cross-service-causal-read-fence-identity) owns the causal floor and composite component-version identity. This catalog retains only effect-local writes, guards, and reconciliation consequences. +- [Transaction Strategies](./system-architecture-transactions.md) owns split spatial authority and operation-bound effect behavior. [Identifier Glossary](./system-architecture-identifier-glossary.md#cross-service-effect-identity) owns root `EffectId` and participant guard identity, while its [causal-read fence contract](./system-architecture-identifier-glossary.md#cross-service-causal-read-fence-identity) owns the causal floor and composite component-version identity. This catalog retains only effect-local writes, guards, and reconciliation consequences. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative. - Every effect must be scoped by instance identifiers. For room-scoped effects, this is `RoomInstanceRef = (tenantId, gameInstanceId, roomInstanceId)`. See `design/architecture/system-architecture-identifier-glossary.md`. -- Game Session assigns one stable root `EffectId` to each logical effect. Each participating owner derives a deterministic participant-guard identity from that root, the typed operation, and the target aggregate, and binds it to the immutable request digest and stored outcome. Matching retries return the prior result; a changed operation, target, or digest fails closed under the owner contract in [Transaction Strategies](./system-architecture-transactions.md). -- The default reconciliation policy is **retry until convergence using the same root `EffectId`**. Do not generate compensating deletes inside the tick loop. +- Game Session assigns one stable root `EffectId` to each command-root logical effect. Each participating owner derives its participant-guard identity from the persisted mutation `EffectId`—the root for a root mutation or the persisted generated-child `EffectId` for a child, with the enclosing root retained only as lineage—plus the typed operation and target aggregate, within the owner-declared runtime-family partition: S1/S2 use `(tenantId, playableStateNamespaceId)`, explicit S3 uses `(tenantId, gameInstanceId)`, and an unknown or unclassified family fails closed. The guard binds to the immutable request digest and stored outcome. Matching retries return the prior result, while a changed operation, target, partition, or digest fails closed under the owner contract in [Transaction Strategies](./system-architecture-transactions.md). +- The default reconciliation policy is **retry until convergence using the same persisted mutation `EffectId`**, retaining the enclosing root lineage where applicable. Do not generate compensating deletes inside the tick loop. - Presentation reads follow the causal-floor and component-proof contract in [Identifier Glossary](./system-architecture-identifier-glossary.md). Current `worldSnapshotId`/`entitySnapshotId` values are scope markers only. Effect entries below record only local invalidation consequences; floor allocation, propagation, response acceptance, and composite-identity rules remain in the canonical contract. - For World-owned door, weather, and hazard effects, the participant guard, typed ambient-state mutation, and World component-version advance commit in one World-local transaction. A matching replay returns the stored outcome without applying the mutation or incrementing the component version twice. The canonical transaction rule belongs in [Transaction Strategies](./system-architecture-transactions.md); this catalog records only the effect-local consequence and proof obligation. -- Set-state reconciliation must resolve the participant guard by the current root `EffectId`, typed operation, exact target aggregate, and immutable `requestDigest`. A matching guard returns its stored outcome; mutable state already matching the requested value is not replay evidence by itself. When a new request has no matching guard but the state is already satisfied, the owner records a new guarded no-op under that request's current `EffectId` and immutable digest. A missing, conflicting, or ambiguous guard remains reconciliation-required rather than being inferred as replay. +- Set-state reconciliation must resolve the participant guard within the same owner-declared runtime-family partition by the current persisted mutation `EffectId`, typed operation, exact target aggregate, and immutable `requestDigest`. A matching guard returns its stored outcome; mutable state already matching the requested value is not replay evidence by itself. When a new request has no matching guard but the state is already satisfied, the owner records a new guarded no-op under that request's current `EffectId` and immutable digest. A missing, conflicting, or ambiguous guard remains reconciliation-required rather than being inferred as replay; an unknown or unclassified runtime family fails closed. ## Cross-Region Effects and Reconciliation @@ -49,10 +49,10 @@ Required writes: Reconciliation: -- Retry World Management using the same root `EffectId` and participant guard until the World location/occupancy mutation converges under the current epoch/fence. +- Retry World Management using the same command-root `EffectId` and participant guard until the World location/occupancy mutation converges under the current epoch/fence. - There is no Entity success/failure or retry branch for pure `MOVE`. An Entity leg exists only for a future MOVE variant that explicitly writes containment; that variant must declare Entity as a participant with its own write, guard, and reconciliation contract. -`MOVE` commits World location/occupancy before destination presentation. `DROP` and `PICKUP` commit entirely in Entity against the admitted room scope, using the shared actor-lock/executor-fence and durable-barrier contract defined in [Transaction Strategies](./system-architecture-transactions.md#drop-pickup-targeting-and-actor-fence-critical-section). Lock expiry or handoff cannot admit a conflicting `MOVE` while the barrier lacks terminal evidence; Game Session owns retry orchestration and invokes Game Logic to re-resolve stale evidence under the same root `EffectId`, preserving the `requestDigest`. This catalog records only the effect-local writes and reconciliation consequences. An item never has two holders and an actor never has two authoritative locations. +`MOVE` commits World location/occupancy before destination presentation. `DROP` and `PICKUP` commit entirely in Entity against the admitted room scope, using the shared actor-lock/executor-fence and durable-barrier contract defined in [Transaction Strategies](./system-architecture-transactions.md#drop-pickup-targeting-and-actor-fence-critical-section). Lock expiry or handoff cannot admit a conflicting `MOVE` while the barrier lacks terminal evidence; Game Session owns retry orchestration and invokes Game Logic to re-resolve stale evidence under the same command-root `EffectId`, preserving the `requestDigest`. This catalog records only the effect-local writes and reconciliation consequences. An item never has two holders and an actor never has two authoritative locations. ### Drop (Inventory → Ground) @@ -96,7 +96,7 @@ Required writes: Reconciliation: -- Retry the EMS move using the same root `EffectId` until applied. Treat an already-moved item as replay only when the stored participant guard matches the same root `EffectId`, immutable request digest, and exact actor-inventory destination. If the item is held by another actor/container or the destination differs, return a conflict/stale/reconciliation outcome rather than replay/no-op. +- Retry the EMS move using the same command-root `EffectId` until applied. Treat an already-moved item as replay only when the stored [participant guard identity](./system-architecture-identifier-glossary.md#cross-service-effect-identity) matches the `PICKUP` typed operation, the same persisted mutation `EffectId`, the owner-declared runtime-family partition (`(tenantId, playableStateNamespaceId)` for S1/S2 or an explicitly classified `(tenantId, gameInstanceId)` for S3), and the immutable `requestDigest`, with exact target semantics of `{item: itemInstanceId (or the canonical stack/item target), source: the synthetic room-ground container for this RoomInstanceRef, destination: the actor-inventory container for this actorEntityId}`. If the item is held by another actor/container or the destination differs, return a conflict/stale/reconciliation outcome rather than replay/no-op. ## Ambient Effects (World Management Authoritative) @@ -116,12 +116,12 @@ Required inputs: Required writes: - **World Management** - - Apply the door state mutation under the owner participant guard derived from the root `EffectId`, typed `DOOR_TOGGLE` operation, and target room/door aggregate, bound to the request digest and stored outcome. + - Apply the door state mutation under the owner participant guard for the persisted mutation `EffectId`, typed `DOOR_TOGGLE` operation, and target room/door aggregate, bound to the request digest and stored outcome. - **Target-state only:** advance the World-owned ambient component version used in the composite `LOOK` identity in that same local transaction so the Game Session presentation cache can invalidate. A matching guard replay returns the prior result without a second version increment. The current `worldSnapshotId` scope marker provides no freshness proof and is not a cache-invalidation authority. Reconciliation: -- Retry WMS with the same root `EffectId` until the participant guard and door mutation converge. The replay/no-op path is valid only when the stored guard matches `DOOR_TOGGLE`, the exact room/door target aggregate, and the immutable request digest. If no matching guard exists but the door is already in `targetState`, issue the current request under a new guard and record a guarded no-op; mutable door state alone never proves replay. A conflicting or ambiguous guard remains reconciliation-required. +- Retry WMS with the same persisted mutation `EffectId` until the participant guard and door mutation converge. The replay/no-op path is valid only when the stored guard matches `DOOR_TOGGLE`, the exact room/door target aggregate, and the immutable request digest. If no matching guard exists but the door is already in `targetState`, issue the current request under a new guard and record a guarded no-op; mutable door state alone never proves replay. A conflicting or ambiguous guard remains reconciliation-required. ### Weather Update @@ -139,7 +139,7 @@ Required writes: Reconciliation: -- After the selector is accepted, retry WMS with the same root `EffectId` until the participant guard and weather mutation converge. The replay/no-op path is valid only when the stored guard matches the typed weather operation, the exact World-selected target aggregate, and the immutable request digest. If no matching guard exists but weather is already at the requested value, issue the current request under a new guard and record a guarded no-op; mutable weather state alone never proves replay. Until the World weather contract defines the exact aggregate selector, every Weather request remains fenced/reconciliation-required and a same-state observation is not replay evidence. +- After the selector is accepted, retry WMS with the same persisted mutation `EffectId` until the participant guard and weather mutation converge. The replay/no-op path is valid only when the stored guard matches the typed weather operation, the exact World-selected target aggregate, and the immutable request digest. If no matching guard exists but weather is already at the requested value, issue the current request under a new guard and record a guarded no-op; mutable weather state alone never proves replay. Until the World weather contract defines the exact aggregate selector, every Weather request remains fenced/reconciliation-required and a same-state observation is not replay evidence. ### Hazard State Update (Gameplay-Authoritative) @@ -153,7 +153,7 @@ Required inputs: Required writes: - **World Management** - - Persist hazard state as typed ambient room state under the owner participant guard derived from the root `EffectId`, typed `HAZARD_STATE_UPDATE` operation, and target room/hazard aggregate, bound to the request digest and stored outcome. + - Persist hazard state as typed ambient room state under the owner participant guard for the persisted mutation `EffectId`, typed `HAZARD_STATE_UPDATE` operation, and target room/hazard aggregate, bound to the request digest and stored outcome. - **Target-state only:** advance the World-owned ambient component version used in the composite `LOOK` identity in that same local transaction so downstream LOOK/gameplay caches invalidate deterministically. A matching guard replay returns the prior result without a second version increment. The current `worldSnapshotId` scope marker provides no freshness proof and is not a cache-invalidation authority. Read/API contract: @@ -164,4 +164,4 @@ Read/API contract: Reconciliation: -- Retry WMS with the same root `EffectId` until the participant guard and hazard mutation converge. The replay/no-op path is valid only when the stored guard matches `HAZARD_STATE_UPDATE`, the exact room/hazard target aggregate, and the immutable request digest. If no matching guard exists but hazard state is already `targetState`, issue the current request under a new guard and record a guarded no-op; mutable hazard state alone never proves replay. A conflicting or ambiguous guard remains reconciliation-required. +- Retry WMS with the same persisted mutation `EffectId` until the participant guard and hazard mutation converge. The replay/no-op path is valid only when the stored guard matches `HAZARD_STATE_UPDATE`, the exact room/hazard target aggregate, and the immutable request digest. If no matching guard exists but hazard state is already `targetState`, issue the current request under a new guard and record a guarded no-op; mutable hazard state alone never proves replay. A conflicting or ambiguous guard remains reconciliation-required. diff --git a/design/architecture/system-architecture-temporal-workflows.md b/design/architecture/system-architecture-temporal-workflows.md index ed8ac794c8..b2c6b701d7 100644 --- a/design/architecture/system-architecture-temporal-workflows.md +++ b/design/architecture/system-architecture-temporal-workflows.md @@ -15,7 +15,7 @@ Current status (non-authoritative summary; [Shared Runtime, Service Contracts, a - 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. - `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`. Owner cleanup acknowledgements are read from durable owner state, and routine gameplay/tick paths never query Temporal or wait on cleanup. +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. ## Canonical Usage Boundary diff --git a/design/architecture/system-architecture-tick-concepts-and-invariants.md b/design/architecture/system-architecture-tick-concepts-and-invariants.md index dd81000216..3e5f8a3454 100644 --- a/design/architecture/system-architecture-tick-concepts-and-invariants.md +++ b/design/architecture/system-architecture-tick-concepts-and-invariants.md @@ -8,7 +8,7 @@ This document summarizes the **core concepts and invariants** of the FireMUD tic This document describes the target-state invariants. The target ownership model is a region-scoped Redis liveness lease paired with a durable executor fence and authority-fenced takeover/replay recovery for each ``. The live deployment has not yet converged on that region-scoped boundary: durable ownership is currently instance-scoped at `{tenantId, gameInstanceId}`, exposed through `RuntimeOwnershipStatus` with selected region fields and an opaque compare-and-match fence. True region-scoped lease/fence installation, `RegionStatus` authority, and takeover reconciliation remain target-state implementation and proof work. The invariants below therefore remain the canonical target contract and must not be read as a claim that the target recovery protocol is already live. -The exact `scriptPinEpoch` propagation and final same-version old-epoch rejection described above are target-state only. The live `EnqueueAutomationCommandIfAbsentRequest` carries `scriptPatchVersion` but not `scriptPinEpoch`, so the current Game Session boundary cannot reject same-version work from an older script pin epoch; the target invariant remains required and unimplemented at that boundary. +The exact `scriptPinEpoch` propagation and final same-version old-epoch rejection described above are now enforced for the live instance-bound Automation handoff and final Game Session execution. Complete source/target remote tuple binding and broader target command identity remain target-state gaps; the target invariant remains required at those boundaries. ## What This Covers @@ -44,7 +44,7 @@ When designing new tick-driven features, keep these invariants in mind: - **No cross-region locks** – cross-region interactions are modeled as messages, not shared locks or multi-region transactions. - **Idempotent side effects** – the region-scoped tick timeline `(region_epoch, tickId)` supplies ordering and fence context, while namespace-complete effect projections and owner-local effect guards ensure that replays after failure do not double-apply mutations. -The identifier glossary owns the stable root `EffectId` for a tick-driven mutation. A concrete ledger/guard/storage projection may include the namespace-complete tuple `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` for scope, ordering, and target lookup, but that tuple is a storage projection rather than the root identity. `playableStateScope` is separately persisted and exact-validated evidence, not a replacement for `playableStateNamespaceId`; `regionEpoch` and `tickId` are ordering/timeline metadata, not effect-guard uniqueness dimensions. The ADR-level `targetAggregateIdentity` is represented by the target aggregate type and ID (or an equivalent explicitly proven collision-safe encoding). Participant guard logical uniqueness is exactly the root `EffectId`, typed operation, and target aggregate. If an owner-local physical partition is used, it is storage placement only and cannot alter logical uniqueness or deduplication; the immutable request digest is bound to the logical identity, while durable outcome/evidence state is mutable guard-row state protected by CAS. A bare tick tuple or bare `effectKey` is not sufficient for that guard contract. Ordinary retries and replay preserve the root `EffectId`, original participant ledger projection, and collision-safe guard identity; retry eligibility/attempt metadata is separate and must not mutate the original `regionEpoch`, `tickId`, `effectKey`, or root/typed-operation/target projection. A future linked-attempt or supersession model requires an explicit contract. A fresh root is allowed only for a **post-abandon re-drive** after conclusive terminal `ABANDONED` plus source-claim terminalization, later coordinate allocation, and durable lineage. +The identifier glossary owns the stable root `EffectId` for a tick-driven mutation. A root mutation uses the root `EffectId`; a generated child retains its persisted deterministic child `EffectId` as `effectId` and the enclosing root as `rootEffectId` lineage and reconciliation context. A concrete ledger/guard/storage projection may include the namespace-complete tuple `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` plus `effectId` and `rootEffectId` for scope, ordering, target lookup, and lineage, but that tuple is a storage projection rather than the mutation identity. `playableStateScope` is separately persisted and exact-validated evidence, not a replacement for `playableStateNamespaceId`; `regionEpoch` and `tickId` are ordering/timeline metadata, not effect-guard uniqueness dimensions. The ADR-level `targetAggregateIdentity` is represented by the target aggregate type and ID (or an equivalent explicitly proven collision-safe encoding). Participant guard logical uniqueness uses the owner-declared runtime-family partition plus the persisted mutation `EffectId`—the root `EffectId` for root operations and the child `EffectId` for generated children—typed operation, and target aggregate: S1/S2 uses `(tenantId, playableStateNamespaceId)`, while only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)`; unknown or unclassified families fail closed. Additional physical partitioning used only for storage placement cannot alter this logical identity or deduplication. The immutable request digest is bound to the logical identity, while durable outcome/evidence state is mutable guard-row state protected by CAS. A bare tick tuple or bare `effectKey` is not sufficient for that guard contract. Ordinary retries and replay preserve the persisted mutation identity, original participant ledger projection, enclosing root lineage, and collision-safe participant-guard identity; retry eligibility/attempt metadata is separate and must not mutate the original `regionEpoch`, `tickId`, `effectKey`, or effect/typed-operation/target projection. A future linked-attempt or supersession model requires an explicit contract. A fresh root is allowed only for a **post-abandon re-drive** after conclusive terminal `ABANDONED` plus source-claim terminalization, later coordinate allocation, and durable lineage. The deterministic allocator and versioned fan-out binding in the pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) remain conditional and non-authoritative; they do not change this guard contract. The tick system adopts the same **coordination timeline** concept as the Redis architecture: for each `` there is a canonical timeline defined by `(region_epoch, tickId)`. Within a given `region_epoch`: @@ -67,13 +67,13 @@ The main tick document contains the detailed rules and Redis key shapes behind e Lane fairness and the “one root actor action per eligible entity per tick” rule apply to steady-state execution within a stable `region_epoch`. Around measured coordination exposure and explicit resets: - Redis coordination loss and scoped resets may cause some actions near the end of the coordination timeline to be delayed, dropped, replayed, or slightly re-ordered; `ticks_exposed` is diagnostic only. -- In these cases, the system prioritizes convergence of each concrete namespace-complete ledger/guard/storage projection `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, region_epoch, tickId, effectKey, targetAggregateType, targetAggregateId)` to durably `APPLIED` or `ABANDONED` when the evidence policy permits terminalization, while retaining its root `EffectId` and participant guard contract. `playableStateScope` remains separately exact-validated evidence, and `region_epoch`/`tickId` remain ordering metadata rather than uniqueness dimensions. Inconclusive old-epoch work remains reconciliation-required under the [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy). +- In these cases, the system prioritizes convergence of each concrete namespace-complete ledger/guard/storage projection `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, region_epoch, tickId, effectKey, targetAggregateType, targetAggregateId)` to durably `APPLIED` or `ABANDONED` when the evidence policy permits terminalization, while retaining its mutation `EffectId`, enclosing root lineage where applicable, and participant guard contract. `playableStateScope` remains separately exact-validated evidence, and `region_epoch`/`tickId` remain ordering metadata rather than uniqueness dimensions. Inconclusive old-epoch work remains reconciliation-required under the [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy). - Designers should treat fairness guarantees as strong within a healthy epoch and best-effort across failures and resets; if a feature requires stronger guarantees around resets, that requirement must be called out explicitly and validated against the measured unreplicated-write-window SLO and ADR 0058 outcome class. -Conceptually, domain services treat Redis locks and leases as **opaque tick-engine concerns**: handlers receive the root `EffectId`, typed operation, target aggregate, immutable request digest, and their own idempotency state. Ledger/guard/storage adapters may additionally expose the namespace-complete tick projection `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, region_epoch, tickId, effectKey, targetAggregateType, targetAggregateId)` for scope and ordering; `playableStateScope` is exact-validated evidence and the timeline coordinates are ordering metadata, not guard uniqueness. Handlers never read `tick:{tenantRegionTag}:lock:` or `tick-executor-lease:{tenantRegionTag}` to make application-level decisions, nor do they depend on Cache/Rate-Limit Redis keys (for example `inventory:*`, `view:*`, `ratelimit:*`) for correctness or ordering. Cache usage, when present, is encapsulated inside domain services and affects only latency, not the tick engine’s notion of “what happened” or “in which order”. +Conceptually, domain services treat Redis locks and leases as **opaque tick-engine concerns**: handlers receive the mutation `EffectId` (root or persisted child), enclosing root lineage where applicable, typed operation, target aggregate, immutable request digest, and their own idempotency state. Ledger/guard/storage adapters may additionally expose the namespace-complete tick projection `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, region_epoch, tickId, effectKey, targetAggregateType, targetAggregateId)` for scope and ordering; `playableStateScope` is exact-validated evidence and the timeline coordinates are ordering metadata, not guard uniqueness. Handlers never read `tick:{tenantRegionTag}:lock:` or `tick-executor-lease:{tenantRegionTag}` to make application-level decisions, nor do they depend on Cache/Rate-Limit Redis keys (for example `inventory:*`, `view:*`, `ratelimit:*`) for correctness or ordering. Cache usage, when present, is encapsulated inside domain services and affects only latency, not the tick engine’s notion of “what happened” or “in which order”. - **Target-state automation identity:** Script-generated child dispatch persists the complete Command-Handoff Identity separately from the effect ledger/storage projection. The child identity is the complete source/target runtime scope plus `(automationDispatchId, commandOrdinal)`, as defined by the [normative Command-Handoff Identity table](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state). The complete applicable parent Trigger Identity, including `bindingId` when applicable, and `outboxWorkItemId` are retained for correlation only and are excluded from child uniqueness, deduplication, and replay selection. `scriptEventId` alone cannot distinguish fan-out commands. `effectKey` may encode the child pair only as deterministic descriptor/correlation metadata and scheduler tie-break metadata. It never replaces the root `EffectId`, typed operation, exact target aggregate, immutable request digest, sealed participant/manifest context, or digest-conflict enforcement. -- **Current-live automation identity:** The Game Session handoff does not yet carry `commandOrdinal` or the full Trigger Identity. Live gameplay staging requires a present, nonblank durable `commandId`, and `TickStagingService` derives `effectKey` as `command:`. The target-state exact pin tuple and `automationDispatchId` plus `commandOrdinal` effect identity are implementation gaps, not current behavior. +- **Current-live fallback:** The Game Session handoff does not yet carry `commandOrdinal` or the full Trigger Identity. `TickStagingService` currently derives `effectKey` from `commandId`, falling back to a hash of command text plus the staging slot when no command id is available. This fallback is selection metadata only: durable tick batching rejects any queued entry without a `commandId` before staging or effect persistence. It is not the target-state automation identity and must not be documented as though `(automationDispatchId, commandOrdinal)` were enforced live. ### Coordination Exposure and Tick Replay Window @@ -91,12 +91,12 @@ Redis coordination state has an environment-measured unreplicated-write exposure The tick system and the Redis-measured exposure SLO combine into a simple contract: -- For the complete expected concrete participant-projection set for each root effect, including each namespace-complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, region_epoch, tickId, effectKey, targetAggregateType, targetAggregateId)` projection linked to its root `EffectId` and guard contract, every expected projection must eventually have exactly one **terminal** outcome in PostgreSQL (`APPLIED` or `ABANDONED`) when the existing evidence policy permits terminalization. `playableStateScope` is exact-validated evidence, and `region_epoch`/`tickId` are ordering metadata; neither is a participant guard uniqueness dimension. Reconciliation must reject missing, extra, partial, or conflicting projections rather than treating one root row as sufficient, even if: +- For the complete expected concrete participant-projection set for each logical mutation, including each namespace-complete `(effect_id, root_effect_id, typed_operation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, region_epoch, tickId, effectKey, targetAggregateType, targetAggregateId)` projection keyed by its persisted mutation `EffectId`—the root `EffectId` for a root mutation or the child `EffectId` for a generated child—with any enclosing root retained separately as lineage and reconciliation context, every expected projection must eventually have exactly one **terminal** outcome in PostgreSQL (`APPLIED` or `ABANDONED`) when the existing evidence policy permits terminalization. `playableStateScope` is exact-validated evidence, and `region_epoch`/`tickId` are ordering metadata; neither is a participant guard uniqueness dimension. Reconciliation must reject missing, extra, partial, or conflicting projections rather than treating one mutation row or root row as sufficient, even if: - Coordination writes near the measured exposure window are dropped, delayed, or replayed, or - Executors crash and re-acquire leases under the same `region_epoch`. - Any work that cannot be safely replayed after Redis loss or tick re-execution must be: - Guarded with idempotency checks that detect and short-circuit replays, or - - Intentionally marked `ABANDONED` in the tick effect ledger with a precise reason only when durable evidence proves it was not applied and the existing policy permits terminalization (for example, reset scopes as described in the failures and operations doc). Inconclusive old-epoch work remains non-terminal reconciliation-required under its original root `EffectId`; reset scope alone does not authorize bulk terminalization. + - Intentionally marked `ABANDONED` in the tick effect ledger with a precise reason only when durable evidence proves it was not applied and the existing policy permits terminalization (for example, reset scopes as described in the failures and operations doc). Inconclusive old-epoch work remains non-terminal reconciliation-required under its original persisted mutation `EffectId`, with any enclosing `rootEffectId` retained separately as lineage and reconciliation context; reset scope alone does not authorize bulk terminalization. Players may observe brief rollbacks or duplicated feedback around failover boundaries, but they must never experience permanent double-application of critical effects or silent corruption of authoritative state. @@ -125,13 +125,14 @@ The registry and focused proof must reject scripts declaring or receiving more t ## Timers and Time Scaling (Conceptual) -Tick timers (cooldowns, regeneration, delayed effects) are: +Timer sources (including cooldowns, regeneration, and delayed effects) carry exactly one explicit due-domain tag and one corresponding due value: -- Stored in per-region sorted sets such as `timer:{tenantRegionTag}`, where the score is an absolute millisecond timestamp and each member encodes the target entity/effect. -- Evaluated using a single, consistent application time source (NTP-synchronized wall clock); Redis server time is not used for timer comparisons. -- Treated as absolute wall-clock due times: changing `tick_interval_ms` does not rescale existing timer scores, and any time-scaling logic must be applied when scheduling (producing a new `due_ms`), not by rewriting past timers. +- Tick/game timers use committed tick identifiers (`dueTickId`, or `due_tick_id` in storage fields) for eligibility and cadence. Wall-clock timers use one immutable absolute `dueAt` in epoch milliseconds; changing `tick_interval_ms` does not rescale it. +- When a wall-clock timer is admitted to a gameplay tick, the scheduler assigns a separate `due_tick_id` admission-order coordinate. That coordinate does not replace, mutate, or become an alias for the timer's `dueAt` due domain. +- Per-region projections such as `timer:{tenantRegionTag}` must preserve the tag and value for each member; a sorted-set score or other index representation must not imply a shared numeric domain. Tick IDs and epoch-millisecond values are never compared or aliased. +- Wall-clock eligibility uses one consistent application time source (NTP-synchronized wall clock); tick eligibility uses the committed region heartbeat/timeline. Redis server time is not used for either comparison. - Drained with bounded work per tick (for example, up to `game.tick-max-timers` timers per region per tick) so delayed or bursty timers do not turn a single tick into unbounded work. -- Implemented using deterministic, idempotent Lua scripts that accept `now_ms` as a caller-supplied `ARGV` value; scripts must not call Redis `TIME`, and AOF replay reuses the same `ARGV` values. +- Implemented using deterministic, idempotent Lua scripts that accept explicit caller-supplied `currentTickId` and, when evaluating a wall-clock source, `now_ms` values as `ARGV`; scripts must not call Redis `TIME`, and AOF replay reuses the same arguments. All writes to timer keys (`timer:{tenantRegionTag}`) are performed under the same region lease and Lua scripts as tick processing; domain services must not modify timer keys via ad-hoc Redis commands. This keeps timers and command queues in the same concurrency domain. @@ -145,7 +146,7 @@ Durations may be scaled dynamically: ## Bounded Effect Chaining -Generated effects are bounded by a shared bootstrap depth ceiling (`8`), deterministic root-chain count and cost budgets, and a deterministic per-target cap. Platform hard ceilings bound every setting; operators and authored features may lower them but may not raise them. Each child records immutable parent/root identity, `depth = parent.depth + 1`, and a digest-covered deterministic child ordinal. +Generated effects are bounded by a shared bootstrap depth ceiling (`8`), deterministic root-chain count and cost budgets, and a deterministic per-target cap. Platform hard ceilings bound every setting; operators and authored features may lower them but may not raise them. Each child records immutable parent/root identity, `depth = parent.depth + 1`, and a digest-covered deterministic child ordinal. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not current target state. Admission evaluates all limits deterministically. Only the child that would exceed a limit is suppressed; committed parents and earlier children are not rolled back. Every authored child is classified as required or optional so suppression derives truthful `SUCCESS`, `PARTIAL`, or `FAILED` outcomes. Durable suppression evidence records root/parent identity, feature/script/version, child ordinal, limit reason and actual/configured values, classification, and resulting player outcome. Metrics use bounded reason/depth/cost/classification dimensions; raw identities remain audit data. See [ADR 0075](./decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). @@ -172,14 +173,14 @@ These mode-aware metric families and formulas are target-only and currently unav Changing tick cadence is also constrained by replay determinism: - `tick_interval_ms` is fixed within a live `region_epoch`. -- Any cadence change that would alter timer ordering or due normalization requires an explicit `regionEpoch` bump and timer re-derivation/reconciliation for the affected region. +- Any cadence change that would alter tick-domain timer ordering or due normalization requires an explicit `regionEpoch` bump and timer re-derivation/reconciliation for the affected region; it does not rewrite an existing wall-clock `dueAt`. Worked cadence-change example: 1. Region `R7` is running at `tick_interval_ms = 100` in `regionEpoch = 13`. 2. Operators decide to move `R7` to `tick_interval_ms = 200`. 3. Game Session pauses the region and bumps `regionEpoch` to `14` rather than changing cadence in place. -4. Timer ordering state is re-derived for the new epoch, including canonical `due_tick_id` values for any timers that must survive the change. +4. Tick-domain timer ordering state is re-derived for the new epoch, including canonical `due_tick_id` values for tick timers that must survive the change. A wall-clock timer retains its immutable `dueAt` and receives a separate admission `due_tick_id` only when it is admitted to a tick. 5. The new epoch resumes at `lastCommittedTickId = -1`, so the first committable tick under the new cadence is `tickId = 0`. At runtime, once the target-only mode-aware metric capability is advertised and proven with fresh required series, observed tick durations are compared against lock TTLs using Prometheus-facing metric-family signatures (non-executable notation) such as `tick_execution_time_ms_p95{scope_class,tick_mode}` and `tick_execution_time_ms_p99{scope_class,tick_mode}` (derived from `tick_execution_time_ms_bucket{scope_class,tick_mode,le}` recording rules). Normal ticks use `tick_execution_time_ms_p99{scope_class,tick_mode="normal"} / on (scope_class,tick_mode) label_replace(tick_lock_ttl_ms{scope_class},"tick_mode","normal","scope_class",".*")` for detection and escalation; an admitted solo-budget tick uses `tick_execution_time_ms_p99{scope_class,tick_mode="solo"} / on (scope_class,tick_mode) label_replace(solo_lock_ttl_ms{scope_class},"tick_mode","solo","scope_class",".*")` instead. If the capability or any required series is absent or stale, these metrics and ratios are unknown/unavailable and cannot drive a decision. The `scope_class` value is the controlled aggregation class (`region`, `game_instance`, `tenant`, or `cluster`), never an individual region or other raw runtime identity; `tick_mode` is exactly `normal` or `solo`; the exact `` tuple and its health remain authoritative control-plane/runtime-health evidence. A class-level rollup cannot identify or set the health of any individual region. diff --git a/design/architecture/system-architecture-tick-execution-flows.md b/design/architecture/system-architecture-tick-execution-flows.md index 4dc1a55a1a..e1570ecf26 100644 --- a/design/architecture/system-architecture-tick-execution-flows.md +++ b/design/architecture/system-architecture-tick-execution-flows.md @@ -12,8 +12,8 @@ This document describes the target execution model. The current live runtime is - the durable owner/status surface is currently `{tenantId, gameInstanceId}`-scoped rather than true region-scoped; - `GetGameplayCommandStatus` is the canonical command-status API, but its live fields and state vocabulary are narrower than the accepted lifecycle described below; -- the live batch/effect substrate exists with the current gameplay-command selected-work manifest on `tick_batch`, but timer/retry/remote-follow-up source-claim manifests, the target-state empty-cadence watermark path, cross-region result-return plumbing, and some richer command-status fields are still target-state follow-through. The current-live runtime has no dedicated target-state empty-cadence status transition or `StreamTickHeartbeats` path. -- the live gameplay-command staging path requires a nonblank durable `commandId` before Redis enqueue and durable batch staging; malformed pre-existing queue entries fail closed before staging and require owner reconciliation. The target path is fail-closed: Game Session assigns the stable root `EffectId` before acknowledgement and rejects before acknowledgement when assignment fails. Target tick execution also rejects any missing or blank root `EffectId` before staging, ledger, or domain writes; a no-ID bypass is permitted only for an explicitly non-tick/control-plane path. The following `ACCEPTED_VOLATILE` clause is exceptional recovery for an acknowledgement that was already issued; it never authorizes late `EffectId` assignment. If assignment failure is discovered after that acknowledgement, `LOST_BEFORE_STAGING` is limited to an eligible unbound `RECEIVED`/`ENQUEUED` command with no surviving batch; batch-bound or inconclusive work remains non-terminal/reconciliation-required and cannot become evidence-free `ABANDONED`. +- the live batch/effect substrate exists with the current gameplay-command selected-work manifest on `tick_batch`, but timer/retry/remote-follow-up source-claim manifests, the target-state empty-cadence watermark path, cross-region result-return plumbing, and some richer command-status fields are still target-state follow-through. The current-live `ScheduleRequest`, `RemoteCommandCoordinator`, `RemoteFollowup`, and `RemoteFollowupResult` models/migrations omit `targetPlayableStateNamespaceId`, so the complete target-scope and request-digest equality contract below is not live or proven. The current-live runtime has no dedicated target-state empty-cadence status transition or `StreamTickHeartbeats` path. +- the live gameplay-command staging path still uses its current `commandId`/deterministic text-and-slot fallback when a complete authored handoff identity is unavailable. The target path is fail-closed: Game Session assigns the stable root `EffectId` before acknowledgement and rejects before acknowledgement when assignment fails. Target tick execution also rejects any missing or blank root `EffectId` before staging, ledger, or domain writes; a no-ID bypass is permitted only for an explicitly non-tick/control-plane path. If assignment fails after an `ACCEPTED_VOLATILE` acknowledgement, `LOST_BEFORE_STAGING` is limited to an eligible unbound `RECEIVED`/`ENQUEUED` command with no surviving batch; batch-bound or inconclusive work remains non-terminal/reconciliation-required and cannot become evidence-free `ABANDONED`. The target wording below is not a claim that the live fallback has already been removed from code. Naming convention: API, workflow, and EffectId prose uses `regionEpoch`. Snake-case forms such as `region_epoch`, `target_region_epoch`, and `due_tick_id` are reserved for explicitly identified SQL/storage fields, Redis payloads/keys, or schema examples. @@ -43,16 +43,18 @@ Within a region’s tick, root actor commands and their effects proceed through 1. **Enqueue** - Game Session accepts commands from Telnet and WebSocket clients, AI, or automation. - - Commands are enqueued into per-entity (or occasionally per-region) queues such as `tick:{tenantRegionTag}:queue:`. + - Work-bearing commands are enqueued into per-entity (or occasionally per-region) queues such as `tick:{tenantRegionTag}:queue:`. + - If admission resolves a zero-effect plan, the same durable command-status transaction records the canonical terminal outcome (`ingressStatus=TERMINAL`, `executionOutcome=APPLIED`, and `gameplayResult=SUCCESS` under [ADR 0053](./decisions/adr-0053-command-atomicity-by-invariant-class.md) and [ADR 0016](./decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md)). This status-only write allocates or persists no `planOrdinal` or root `EffectId`, creates no effect ledger row or `tick_batch`, advances no tick-domain state, and does not enqueue the command; an accepted zero-effect command therefore cannot remain `ENQUEUED`, and retries return its stored terminal outcome. 2. **Target Resolution (read-only)** - During the tick, the executor resolves targets from the pinned snapshot for that ``: - Single-target actions select a specific entity or room. - Multi-target actions derive a bounded set of entity IDs from local region state (room occupants, threat lists, groups). - This phase is read-only with respect to durable state; it decides *what* to touch without mutating Redis or PostgreSQL. 3. **Region-Local Mutations** - - Before target tick staging or any tick-domain ledger or domain write, Game Session requires a present, nonblank root `EffectId`; a missing or blank identity is a non-mutating rejection. No-ID bypasses are limited to explicitly non-tick/control-plane paths. The current live command/text fallback remains an implementation gap and is not target behavior. + - Before target tick staging or any tick-domain ledger or domain write, Game Session materializes and persists the command plan and root allocation under the canonical [Transaction Strategies](./system-architecture-transactions.md#command-atomicity-and-outcome-aggregation) contract. The execution flow consumes that frozen plan in its supplied semantic order and reuses the stored binding across retry, replay, and reconciliation; it does not infer or reallocate roots from tick selection. + - A conserved multi-participant operation normally shares one root with participant guards beneath it, but the command still uses ADR 0053's required/optional classification and co-location or reservation/escrow semantics. A root is not a global transaction or participant-set identity. For each root in a non-empty materialized plan, Game Session requires a present, nonblank root `EffectId` before target tick staging or any tick-domain ledger or domain write; a missing or blank identity is a non-mutating rejection. A zero-effect plan allocates no root, is not rejected for lacking one, and stages or writes no tick-domain state. No-ID bypasses are limited to explicitly non-tick/control-plane paths. The current live command/text fallback remains an implementation gap and is not target behavior. - For purely local effects, each Lua invocation acquires at most one entity lock under `tick:{tenantRegionTag}:lock:`; piecemeal multi-lock acquisition is prohibited. Multi-entity invariants use the owning transaction, durable effect workflow, or reservation/saga boundary described by [ADR 0074](./decisions/adr-0074-one-entity-lock-per-redis-script.md). - - Domain services apply changes under local transactions and the root-`EffectId` participant-guard contract owned by Transaction Strategies. + - Domain services apply changes under local transactions and the persisted-mutation-`EffectId` participant-guard contract owned by Transaction Strategies: a root mutation uses its root `EffectId`, while a generated child uses its persisted child `EffectId`; any enclosing `rootEffectId` is retained separately as lineage and reconciliation context. 4. **Cross-Region Effects (if any)** - For cross-region commands, the origin region: - Applies local-only effects first (for example, text feedback, animations). @@ -61,17 +63,18 @@ Within a region’s tick, root actor commands and their effects proceed through - Writers must persist `target_region_epoch` and `due_tick_id` from the same status read so retries and failover cannot shift eligibility non-deterministically. - Optionally writes a best-effort Redis hint marker such as `remote:{tenantInstanceTag}:` (for the target entity, with the tag derived from the target ``) to reduce latency when the target region drains follow-ups. - If the command needs to wait for remote completion, the origin region creates or updates a separate durable cross-region coordinator record. This waiting state is **not** kept as a non-terminal row inside the origin tick batch. - - Minimum coordinator fields include durable `coordinatorId`, `tenantId`, `originCommandId`, `originGameInstanceId`, `originRegionId`, `originRegionEpoch`, `originTickId`, target scope (`targetGameInstanceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`, `dueTickId`), exact target aggregate (`targetAggregateType`, `targetAggregateId`), the originating `originEffectId` and distinct target-leg `targetEffectId`, target-leg `typedOperation`, immutable `requestDigest`, and the sealed required-participant manifest (or immutable manifest reference plus digest). These identity/binding fields are compared on replay and a missing or conflicting value fails closed. The lifecycle is (`PENDING_REMOTE`, `REMOTE_APPLIED`, `REMOTE_ABANDONED`, `REMOTE_TIMEOUT_ABANDONED`, `LATE_RESULT_IGNORED`, `LATE_RESULT_RECONCILED`), with origin-timeline deadline (`originDeadlineRegionEpoch`, `originDeadlineTickId`; storage may use names such as `remote_deadline_region_epoch` / `remote_deadline_tick_id`), final player-facing/result-facing projection fields when applicable (`executionOutcome`, `gameplayResult`), and `updatedAt`. + - The target `ScheduleRequest`, coordinator, follow-up, and origin-addressed result projections share the complete target scope `(targetGameInstanceId, targetPlayableStateNamespaceId, targetPlayableStateScope, targetRegionId, targetRegionEpoch, dueTickId)` and the immutable request digest covering that scope, exact target identity, operation, and sealed manifest binding. Each projection preserves these fields for exact replay/result equality checks; a missing, conflicting, or mismatched namespace, scope, target, or digest fails closed. + - Minimum coordinator fields include durable `coordinatorId`, `tenantId`, `originCommandId`, `originGameInstanceId`, `originRegionId`, `originRegionEpoch`, `originTickId`, target scope (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`, `dueTickId`), exact target aggregate (`targetAggregateType`, `targetAggregateId`), the originating `originEffectId` and distinct target-leg `targetEffectId`, target-leg `typedOperation`, immutable `requestDigest`, and the sealed required-participant manifest (or immutable manifest reference plus digest). These identity/binding fields are compared on replay and a missing or conflicting value fails closed. The lifecycle is (`PENDING_REMOTE`, `REMOTE_APPLIED`, `REMOTE_ABANDONED`, `REMOTE_TIMEOUT_ABANDONED`, `LATE_RESULT_IGNORED`, `LATE_RESULT_RECONCILED`), with origin-timeline deadline (`originDeadlineRegionEpoch`, `originDeadlineTickId`; storage may use names such as `remote_deadline_region_epoch` / `remote_deadline_tick_id`), final player-facing/result-facing projection fields when applicable (`executionOutcome`, `gameplayResult`), and `updatedAt`. - Target completion is returned through one durable origin-owned result path, not an unspecified transient message: - - the target leg writes an origin-addressed result or inbox row keyed to `coordinatorId` and repeats `originCommandId`, `originGameInstanceId`, origin region/epoch/tick, target game instance, `targetPlayableStateScope`, target region/epoch and `dueTickId`, the distinct target `targetEffectId`, typed operation, exact target aggregate, and one immutable follow-up binding/digest reference that binds the request digest and sealed-manifest context, + - the target leg writes an origin-addressed result or inbox row keyed to `coordinatorId` and repeats `originCommandId`, `originGameInstanceId`, origin region/epoch/tick, target game instance, `targetPlayableStateNamespaceId`, `targetPlayableStateScope`, target region/epoch and `dueTickId`, the distinct target `targetEffectId`, typed operation, exact target aggregate, and one immutable follow-up binding/digest reference that binds the request digest and sealed-manifest context, - the row records the target terminal outcome and any command-specific result payload needed by origin reconciliation; it is not correlated only by the target `gameInstanceId` or a transient message ID, - - origin-side processing claims and applies that result idempotently when advancing the coordinator lifecycle. Acceptance of a result that has a dependent child effect is crash-safe: the durable acceptance transition cannot commit without a deterministic child-effect intent. The result acceptance and child intent commit in one durable transaction where they share an owner, or a resumable durable acceptance intent records both before either is treated as accepted. Replays reuse the child identity and the exact accepted-result digest; missing, extra, partial, or conflicting intent/projection evidence fails closed. This is an acceptance/intent durability invariant, not another coordinator outcome. + - origin-side processing claims and applies that result idempotently when advancing the coordinator lifecycle. Acceptance of a result that has a dependent child effect is crash-safe: the durable acceptance transition cannot commit without a deterministic child-effect intent. The result acceptance and child intent commit in one durable transaction where they share an owner, or a resumable durable acceptance intent records both before either is treated as accepted. Replays reuse the child identity and the exact accepted-result digest; missing, extra, partial, or conflicting intent/projection evidence fails closed. This is an acceptance/intent durability invariant, not another coordinator outcome. Exact opaque allocation remains non-authoritative in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). - The target region later drains these follow-ups into its own tick pipeline and applies them under its lease and locks. 5. **Completion / Finalization (optional)** - Many commands do not need global awareness of “all regions finished”; origin and target regions can operate independently with eventual consistency. - For flows that truly require end-to-end completion (for example, complex cross-region trades), the origin region tracks participating-region outcomes in that separate coordinator record and later applies a final status in a subsequent origin-region tick only under the command family’s ADR 0053 declaration. `PARTIAL` is a permitted terminal subset only when declared before execution; unresolved required work, inconclusive evidence, or a timeout that does not prove a permitted terminal combination remains `PENDING`/reconciliation-required. -Every phase must use its phase-specific durable identity so replays after failure do not double-apply logical work. Command ingress uses `(tenantId, gameInstanceId, commandId)`; source claims and selection use the durable source identity (such as a timer member ID, retry member ID, or follow-up row ID) together with its bound target/timeline; tick effects retain their root `EffectId` and participant guards; and cross-region completion uses the coordinator identity plus the target ledger/result identity. Ordinary retry/replay preserves each identity, including the root `EffectId` and original participant ledger/guard projection. Retry eligibility/attempt metadata is separate and must not rewrite the original `regionEpoch`, `tickId`, `effectKey`, or root/typed-operation/target projection; a future linked-attempt or supersession model requires an explicit contract. A fresh root is reserved for a **post-abandon re-drive**, which requires a conclusively terminal `ABANDONED` effect and terminalized source claim, a later coordinate, a fresh root and participant projections, and durable lineage to the original identities. A command or source item may cross tick boundaries without changing its ingress or source identity. +Every phase must use its phase-specific durable identity so replays after failure do not double-apply logical work. Command ingress uses `(tenantId, gameInstanceId, commandId)`; source claims use their durable owner identity and bound target/timeline; command-root effects use the persisted plan/root binding and participant guards owned by Transaction Strategies; inbound/remote, timer, retry, and generated work retain their owner/source roots unless materialized as admitted commands; and cross-region completion uses the coordinator plus target ledger/result identity. Ordinary retry/replay preserves those identities. Retry metadata never rewrites the original timeline or root/operation/target projection. A post-abandon command re-drive uses a new linked `commandId`; reusing the old id returns its terminal result. A command or source item may cross tick boundaries without changing its ingress or source identity. ### Command Ingress Acknowledgement Contract (Required) @@ -107,7 +110,7 @@ Ingress deduplication is not sufficient on its own: every accepted command must - `RETRY_QUEUED` means the command has already reached `BOUND_TO_BATCH` and its current retry source is enqueued. The prior batch binding remains part of the command lifecycle; retry source state does not make it a new ingress command. - These legacy values are non-terminal. They must not be exposed as new canonical terminal outcomes, and purge/recovery must classify the current attempt by the durable batch binding rather than by the legacy label alone. - Required recovery behavior: - - Region/tenant/cluster resets and coordination-loss reconciliation may assign `LOST_BEFORE_STAGING` only to an `ACCEPTED_VOLATILE` record whose `ingressStatus` is `RECEIVED` or `ENQUEUED` and which has no surviving `tickBatchId`. `BOUND_TO_BATCH` and `TERMINAL` records are never eligible for this ingress-only loss outcome. The decision must use one owner-defined CAS/version-fenced transition so a concurrent bind wins; this rule does not authorize terminalizing batch-bound effects whose old-epoch evidence is inconclusive, which remain non-terminal reconciliation work under the original root `EffectId`. + - Region/tenant/cluster resets and coordination-loss reconciliation may assign `LOST_BEFORE_STAGING` only to an `ACCEPTED_VOLATILE` record whose `ingressStatus` is `RECEIVED` or `ENQUEUED` and which has no surviving `tickBatchId`. `BOUND_TO_BATCH` and `TERMINAL` records are never eligible for this ingress-only loss outcome. The decision must use one owner-defined CAS/version-fenced transition so a concurrent bind wins; this rule does not authorize terminalizing batch-bound effects whose old-epoch evidence is inconclusive, which remain non-terminal reconciliation work under their original persisted mutation `EffectId`, with any enclosing `rootEffectId` retained separately as lineage and reconciliation context. - For eligible `ACCEPTED_VOLATILE` records, `LOST_BEFORE_STAGING` is an expected terminal outcome and must be returned by command-status APIs/events rather than leaving the command indefinitely deduplicated with no execution result. `ACCEPTED_DURABLE` records, including those still before batch binding, follow their feature-specific durable intake replay/re-drive contract and are never classified as `LOST_BEFORE_STAGING` by this reset rule. - Re-sends with the same `(tenantId, gameInstanceId, commandId)` after a terminal outcome return that prior terminal outcome and must not enqueue a new logical command. - Re-sends with a new `commandId` remain new commands. @@ -225,7 +228,7 @@ At each tick for a ``, the executor: - Phase 2 selects at most one root intentional actor action per eligible entity under the actor-action lane’s ordering and budget; a completed start-of-tick passive effect may make an entity ineligible, but selected-yet-uncompleted or deferred passive work does not, and passive work never consumes its actor-action slot. - Phase 3 admits only effects generated by the phase-2 selected actor actions under the passive/effect budget. Generated effects cannot recursively grant another root actor action in the same tick. - Passive or inbound work becoming due after start selection, or deferred because of lane, per-entity, cost, or region budget overflow, affects a later tick without changing its persisted ordering inputs or stable identity. - - Within one entity's eligible queue, orders work by the persisted tuple `(priority, due_tick_id, entity_enqueue_seq, source_kind, commandId_or_effectKey)`. `entity_enqueue_seq` is monotonic within the entity's current region epoch and assigned by the owning Game Session admission/scheduling path. Same-tick derived children use the persisted parent order plus deterministic child ordinals rather than completion timing. + - Within one entity's eligible queue, orders work by the persisted tuple `(priority, due_tick_id, entity_enqueue_seq, source_kind, commandId_or_effectKey)`. `entity_enqueue_seq` is monotonic within the entity's current `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch)` scope and assigned by the owning Game Session admission/scheduling path. Same-tick derived children use the persisted parent order plus deterministic child ordinals rather than completion timing. - Across eligible entities, persisted rotating/deficit scheduling accounts for declared work cost and advances only with the durable selected batch. Permanently eligible non-best-effort work receives capacity within a healthy epoch; bounded aging or `maxDeferralTicks` applies where declared. Source quotas may bound intake inside a lane but cannot bypass lane fairness or create a competing scheduler. - Each work item type (queued command, timer, retry, remote follow-up) must expose its declared phase, lane, cost class, and stable persisted ordering inputs so selection can be reproduced across retries and failover. New work sources must not introduce undocumented scheduler precedence. - After ordering, the executor locks or reserves the selected source entries with their source-specific ownership checks while they remain discoverable. These locks prevent competing executors from selecting the same candidates but are not a substitute for durable source claims. @@ -234,7 +237,7 @@ At each tick for a ``, the executor: - A fenced owner transaction compare-and-sets the expected `regionEpoch`, `executorFence`, and current `lastCommittedTickId`, then advances exactly one canonical `lastCommittedTickId` without creating a `tick_batch`, selected-work manifest, effect ledger row, Redis `pending` entry, entity lock, or domain RPC. A newly due source racing this check is serialized by the same owner transaction: either it is included in a normal batch or the empty CAS loses and the source remains due for the next attempt. - After the durable status transition commits, Game Session emits the target-state `StreamTickHeartbeats` heartbeat for that `(regionEpoch, tickId)`; heartbeat emission is post-commit and never the authority. Canonical `PAUSED` and `STALLED` states freeze the empty path and do not advance the timeline. This target-state branch is not implemented in the current-live instance-scoped owner/progress adapter. 3. Atomically binds selected work: - - While the candidate locks are held, Game Session atomically creates the durable PostgreSQL `tick_batch`, its selected-work manifest, `SCHEDULED` ledger rows, and source claims in one transaction for the complete `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)` scope. Any selected command also moves to `BOUND_TO_BATCH` in that transaction. + - While the candidate locks are held, Game Session atomically creates the durable PostgreSQL `tick_batch`, its selected-work manifest, `SCHEDULED` ledger rows, and source claims in one transaction for the complete `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)` runtime coordinate. The selected-work manifest exact-binds the active `playableStateNamespaceId` and separately persisted `playableStateScope` as immutable execution evidence; missing, stale, mixed, or mismatched namespace/scope evidence fails before batch admission rather than creating a second scheduler partition. Neither namespace nor scope changes tick-batch uniqueness or scheduler partitioning. Any selected command also moves to `BOUND_TO_BATCH` in that transaction. - For remote follow-ups, only that transaction may set the batch claim or remove the row from the due set. A rollback releases the candidate lock and leaves the follow-up discoverable for a later selection. 4. Stages effects: - This step is allowed only after the durable PostgreSQL `tick_batch`, ledger rows, and source claims have committed. Redis `pending` is staging/acceleration coordination only; it is never the authoritative record or a prerequisite that can precede durable batch creation. @@ -259,7 +262,7 @@ The lane is explicit metadata, not an inferred property of the source kind: acto - A wall-clock timer remains eligible from its immutable `dueAt` (`now >= dueAt`). Once eligible, one durable firing-claim/admission transaction reads the authoritative target timeline and assigns/persists exactly one target `regionEpoch` and `due_tick_id` ordering coordinate (normally the next committable tick), together with the source claim. Retries and replays reuse those persisted values and never recompute them from cadence or wall time. An epoch change follows old-epoch reconciliation and new admission; it never rebinds the old firing. - The within-entity tuple uses the persisted admission `due_tick_id` for wall-clock timers and the persisted `dueTickId` for tick timers. Wall-clock timestamps and tick IDs are different domains and must not be compared numerically. - `entity_enqueue_seq`: - - Strictly increasing across all candidate work sources for one entity within its current `` scope. The owning Game Session admission/scheduling path assigns and persists it; it is not a region-global, tenant-only, game-instance-only, or cross-region counter. + - Strictly increasing across all candidate work sources for one entity within its current `` scope. The owning Game Session admission/scheduling path assigns and persists it; it is not a region-global, tenant-only, game-instance-only, or cross-region counter. - A reset bumps `regionEpoch` and restarts `tickId` at `0`, creating a new entity-local sequence domain for new-epoch work. Old-epoch ordering identities remain immutable and are not rebound even if a sequence value is reused in the new epoch. - `source_kind`: - Fixed, low-cardinality source classification (`command`, `retry`, `timer`, `remote_followup`, `generated_effect`) and the fourth tuple component. @@ -293,10 +296,10 @@ Conceptually, tick commit proceeds through these phases: - Target-state winner rule: - The target-state winner is the transaction that successfully creates the tuple-unique `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)` row while holding a revalidated Redis lease and the authoritative current `regionEpoch`/`executorFence` pair. - If a competing executor finds that the existing row carries the authoritative current epoch and an `executorFence` exactly equal to the current status, it must reuse that row as authoritative state for replay/continuation. If the batch carries a different fence, it is prior-fence work; the current owner must pause and reconcile or abandon it before staging a new tick. Unequal opaque fence bytes establish no ordering and are not evidence that either fence is newer. - - If the current owner encounters prior-fence work, it must not continue that batch on the hot path or transfer it based on inferred fence recency. It pauses the affected region and uses the fence-guarded recovery path while preserving the unique tick coordinate, manifest, effect identities, and command bindings where proof permits; inconclusive old-epoch work remains non-terminal reconciliation work under its original root `EffectId`. + - If the current owner encounters prior-fence work, it must not continue that batch on the hot path or transfer it based on inferred fence recency. It pauses the affected region and uses the fence-guarded recovery path while preserving the unique tick coordinate, manifest, effect identities, and command bindings where proof permits; inconclusive old-epoch work remains non-terminal reconciliation work under its original persisted mutation `EffectId`, with any enclosing `rootEffectId` retained separately as lineage and reconciliation context. - If recovery or transfer preconditions fail or any effect might have started, reconciliation must not bulk-abandon the batch. It determines each effect from durable domain state and authoritative effect guards: an effect becomes `APPLIED` only when that evidence proves it is reflected, becomes `ABANDONED` only when that evidence proves it was not applied, and otherwise remains `SCHEDULED`. `reconciliation_required`, its reason, the observed epochs/fences, and the last proof attempt are recovery metadata outside the closed effect status enum; they are not another effect state. - After obtaining the domain evidence, one fence-guarded Game Session PostgreSQL transaction must atomically persist all conclusive effect outcomes together with the corresponding command statuses and source-claim disposition. If any effect is inconclusive, the transaction records reconciliation-required metadata, leaves its effect and dependent command/source claim non-terminal, and keeps the region paused. Unresolved work is ineligible for ordinary effect retry, Redis retry insertion, source requeue, source-claim release, batch transfer, or commit-watermark advancement. - - Independently retryable work becomes eligible for a **post-abandon re-drive** only after the original effect is conclusively `ABANDONED` and its command/source claim is terminalized in that same transaction. The recovery controller must then eventually assign that work a later `(regionEpoch, tickId)` coordinate and new `tick_batch_id`, a fresh root `EffectId` with its ledger/participant-guard projections, and a new retry/source-claim identity before the region resumes; it records lineage to the original identities and never reuses or requeues into the old coordinate. Ordinary retry/replay keeps the original root `EffectId`. Until that fresh-root allocation succeeds, the work remains durable recovery work and cannot return to an ordinary queue. + - Independently retryable work becomes eligible for a **post-abandon re-drive** only after the original effect is conclusively `ABANDONED` and its command/source claim is terminalized in that same transaction. The recovery controller must then eventually assign that work a later `(regionEpoch, tickId)` coordinate and new `tick_batch_id`, a fresh root identity under the applicable owner contract with its ledger/participant-guard projections, and a new retry/source-claim identity before the region resumes; if it is re-admitted as a command, Game Session allocates a fresh command plan/root binding under the same contract. It records lineage to the original identities and never reuses or requeues into the old coordinate. Ordinary retry/replay keeps the original root `EffectId`. Until that fresh-root allocation succeeds, the work remains durable recovery work and cannot return to an ordinary queue. - If the caller's expected epoch or fence is not current in authoritative status, the caller is stale. It must stop without modifying the batch, replaying effects, or requeueing source work. It must never infer recency from `executorFence`, create a second batch for the same unique coordinate, or requeue work into that same coordinate. - The target-state tick-batch record stores at minimum: - `tick_batch_id` @@ -307,9 +310,9 @@ Conceptually, tick commit proceeds through these phases: - `status` (`CREATED`, `REDIS_STAGED`, `COMMITTED`, `ABANDONED`) - `tick_batch.status` is batch lifecycle state, not tick-effect-ledger state; effect-ledger `status` remains closed to `SCHEDULED`, `APPLIED`, and `ABANDONED`. Reconciliation-required flags, reasons, ownership observations, and proof attempts are recovery metadata and never extend that enum. - the selected-work manifest for this batch - - an immutable collision-safe pending envelope for each staged member carrying the exact `tick_batch_id` plus the complete root `EffectId`/participant projection, or an equivalent exact ledger-row identity; `effect_key` remains descriptor metadata only and is not sufficient correlation by itself + - an immutable collision-safe pending envelope for each staged member carrying the exact `tick_batch_id` plus the complete mutation `effect_id`/participant projection (with `root_effect_id` retained for lineage), or an equivalent exact ledger-row identity; `effect_key` remains descriptor metadata only and is not sufficient correlation or replay identity by itself - The selected-work manifest is the authoritative record of which source items were chosen for the tick before Redis staging. At minimum, each selected item records: - - the batch scope `(tenantId, gameInstanceId, regionId, regionEpoch)`; `entity_enqueue_seq` values are allocated monotonically per entity within that complete scope. A `regionEpoch` reset starts a new entity-local sequence domain; old-epoch ordering identities remain immutable and are never rebound. + - the batch runtime scope `(tenantId, gameInstanceId, regionId, regionEpoch)` plus exact bound `playableStateNamespaceId` and separately persisted `playableStateScope` execution evidence; both values are immutable and exact-compared on replay/readback. Missing, stale, mixed, or mismatched namespace/scope evidence fails closed. `entity_enqueue_seq` values are allocated monotonically per entity within that complete runtime-and-namespace context. Namespace and scope evidence do not extend tick-batch uniqueness or the scheduler timeline. A `regionEpoch` reset starts a new entity-local sequence domain; old-epoch ordering identities remain immutable and are never rebound. - `lane` (`actor_action` or `passive_effect`) declared by the work source - explicit semantic `phase`; ordering and comparisons are phase-local or phase-aware - bounded `cost_class` declared by the work source and consumed by the applicable lane budget @@ -363,16 +366,16 @@ Conceptually, tick commit proceeds through these phases: 4. Under the current `regionEpoch` and exact `executorFence`, the executor creates the `tick_batch` and `SCHEDULED` ledger rows, then stages the sealed manifest. Every durable write compares the current epoch and fence. 5. Immediately before authoritative effect dispatch, executor revalidates the same Redis lease token and expected epoch; commit watermark advancement succeeds only under the current exact `executorFence`. Prior-fence work is reconciled or abandoned and does not advance commit state. 2. **Redis staging complete** - - After the durable batch exists, the executor stages the selected effects into `tick:{tenantRegionTag}:pending`, carrying an immutable collision-safe envelope for each staged member: the exact `tick_batch_id` plus the complete root `EffectId`/participant projection or an equivalent exact ledger-row identity. `effect_key` remains descriptor metadata, not the correlation identity. Stage, commit, rollback, and cleanup preserve the envelope unchanged; recovery accepts or clears pending state only after exact set equality with the durable batch/ledger expected set, so a count or digest alone is insufficient. + - After the durable batch exists, the executor stages the selected effects into `tick:{tenantRegionTag}:pending`, carrying an immutable collision-safe envelope for each staged member: the exact `tick_batch_id` plus the complete persisted mutation `EffectId`/participant projection (root ID for a root mutation, child ID for a generated child, with `rootEffectId` retained separately as lineage) or an equivalent exact ledger-row identity. `effect_key` remains descriptor metadata, not the correlation identity. Stage, commit, rollback, and cleanup preserve the envelope unchanged; recovery accepts or clears pending state only after exact set equality with the durable batch/ledger expected set, so a count or digest alone is insufficient. - `tick:{tenantRegionTag}:pending` is an acceleration/coordination structure. The durable tick-batch plus ledger rows are the authoritative record of what the tick intended to stage. 3. **Domain application** - - Domain services process staged effects under idempotent root-`EffectId` participant guards and update authoritative PostgreSQL state in their own databases. - - Game Session records the outcome of each effect in its tick effect ledger (`SCHEDULED` → `APPLIED` or `ABANDONED`) only when the durable domain evidence and existing recovery policy permit that transition; inconclusive old-epoch work remains non-terminal reconciliation work under its original root `EffectId`. Domain services do not write to the Game Session ledger directly. + - Domain services process staged effects under participant guards keyed by the persisted mutation `EffectId` (root ID for a root mutation, child ID for a generated child), with `rootEffectId` retained separately as lineage, and update authoritative PostgreSQL state in their own databases. + - Game Session records the outcome of each effect in its tick effect ledger (`SCHEDULED` → `APPLIED` or `ABANDONED`) only when the durable domain evidence and existing recovery policy permit that transition; inconclusive old-epoch work remains non-terminal reconciliation work under its original mutation `EffectId`, with enclosing `rootEffectId` retained as lineage and reconciliation context. Domain services do not write to the Game Session ledger directly. 4. **Commit visibility** - - For a non-empty batch, once all ledger rows that belong to that tick batch are terminal (`APPLIED` or `ABANDONED`) under the existing evidence policy, the target-state deployment advances the commit authority `RegionStatus.lastCommittedTickId` for the current `regionEpoch` under the same `executorFence`, and only then emits the target-state tick heartbeat for that `(regionEpoch, tickId)`. An inconclusive old-epoch row remains non-terminal and blocks this advancement. A truly empty boundary uses the separate fenced one-tick status transition and post-commit heartbeat branch above, with no batch ledger. The current-live deployment instead advances the committed tick fields on `RuntimeOwnershipStatus` under the current-live opaque fence; `ObserveRuntimeTickProgress` reports that progress, and neither `RegionStatus` nor `StreamTickHeartbeats` is implied to be live. + - For a non-empty batch, once all ledger rows that belong to that tick batch are terminal (`APPLIED` or `ABANDONED`) under the existing evidence policy, one fenced durable commit boundary transitions `tick_batch.status` to `COMMITTED` and advances the commit authority `RegionStatus.lastCommittedTickId` for the complete current scope under the same `executorFence`; only then may the target-state tick heartbeat be emitted. An inconclusive old-epoch row remains non-terminal and blocks this advancement. A truly empty boundary uses the separate fenced one-tick status transition and post-commit heartbeat branch above, with no batch ledger. The current-live deployment instead advances the committed tick fields on `RuntimeOwnershipStatus` under the current-live opaque fence; `ObserveRuntimeTickProgress` reports that progress, and neither `RegionStatus` nor `StreamTickHeartbeats` is implied to be live. - Cross-region coordinator rows such as `PENDING_REMOTE` are not part of this terminal set; they are durable workflow state outside the committing tick batch. 5. **Coordination cleanup** - - A final commit/cleanup script clears the `pending` entry for the tick and releases any entity locks for that region. + - A final commit/cleanup script clears the `pending` entry for the tick and releases any entity locks for that region only after exact equality between the pending envelope set and the durable batch/ledger expected set has been established. `expected_effect_count` and any digest are diagnostic hints and cannot authorize cleanup on their own. - Cleanup is a required part of “tick is no longer in flight”; if an executor crashes after commit visibility but before cleanup, crash recovery must clear/abandon the `pending` entry before any subsequent tick stages new work. From the perspective of the `(regionEpoch, tickId)` timeline: @@ -387,7 +390,7 @@ From the perspective of the `(regionEpoch, tickId)` timeline: - AOF replay or measured coordination loss may cause staging scripts to be re-run; domain idempotency guards and the ledger ensure that replays converge to the same terminal outcome. - Recovery treats PostgreSQL as the source of truth for staging intent: - `tick_batch` exists, Redis `pending` missing: - - Recovery replays directly from the durable batch manifest and `SCHEDULED` ledger rows to drive effects to terminal `APPLIED` or `ABANDONED` outcomes only when durable evidence permits; inconclusive old-epoch work remains non-terminal reconciliation work under its original root `EffectId`. Missing Redis state is not treated as “no work existed”. + - Recovery replays directly from the durable batch manifest and `SCHEDULED` ledger rows to drive effects to terminal `APPLIED` or `ABANDONED` outcomes only when durable evidence permits; inconclusive old-epoch work remains non-terminal reconciliation work under its original mutation `EffectId`, with enclosing `rootEffectId` retained as lineage and reconciliation context. Missing Redis state is not treated as “no work existed”. - Before changing any `SCHEDULED` row, one Game Session durable transaction uses the applicable recovery CAS: target-state reads and locks `RegionStatus` for the complete region scope, requires exact current `regionEpoch`/`executorFence` equality and a matching `contextDigest` against the batch’s sealed execution-context digest or referenced sealed context; current-live instead reads and locks the current instance-scoped `RuntimeOwnershipStatus`, requires exact `regionEpoch`/opaque `executorFence` equality, and verifies the complete selected-work manifest plus `manifest_digest` against durable source, ledger, and participant evidence without requiring sealed execution context. The batch’s captured fence alone is not authority; a mismatch or incomplete set affects zero rows and fails closed. Domain-service evidence and guards remain in their own service-local transactions, so this CAS does not imply a cross-service database transaction. - First implementation does **not** re-stage old ticks through the normal hot-path `pending` scripts once Redis state is missing. The durable batch manifest is authoritative for what was selected, and replay proceeds without requiring the old tick to be materialized back into Redis. - If source entries were intentionally left in place until `REDIS_STAGED`, recovery may reconcile those source structures against the durable batch manifest to clean up or reclassify them, but it must not re-select different work for the same `tick_batch_id`. @@ -397,10 +400,10 @@ From the perspective of the `(regionEpoch, tickId)` timeline: - Recovery pauses the region, marks the batch inconsistent, and requires reconcile tooling before ticks resume. Silent “best effort” continuation is not allowed. - If a crash occurs after `durable_committed` but before `coordination_cleared`, recovery must finish cleanup before the next tick stages new work; this window does not regress the durable commit watermark. -The **TickScheduler** in Game Session enforces a **single in-flight tick per region** invariant and derives tick positions from durable state: +The **TickScheduler** in Game Session enforces a **single in-flight tick per runtime region** invariant and derives tick positions from durable state: - A region is considered busy while prior durable or coordination state has not reached `coordination_cleared`: this includes an existing non-terminal `tick_batch`, any `SCHEDULED` ledger rows, or `tick:{tenantRegionTag}:pending` for an in-flight `tickId`. Missing Redis `pending` does not make unfinished durable work idle. -- The scheduler does not start a new tick for that `` until the previous tick is `coordination_cleared` as part of normal cleanup or explicitly handled during crash recovery. +- The scheduler does not start a new tick for that `` until the previous tick is `coordination_cleared` as part of normal cleanup or explicitly handled during crash recovery. Every admitted work item must exact-match that active instance's bound `playableStateNamespaceId`; namespace is sealed execution evidence, not a second tick timeline or scheduler partition. - The target-state scheduler obtains the current `(regionEpoch, tickId)` baseline and commit authority from `RegionStatus` through `GetRegionTickStatus`. The current-live scheduler obtains owner, fence, and committed tick fields from `RuntimeOwnershipStatus` through `GetRuntimeOwnershipStatus`, and uses `ObserveRuntimeTickProgress` as the live region progress feed; neither deployment treats `tick:{tenantRegionTag}:meta.current_tick_id` as the authority. - Target-state scheduler and recovery tooling determine recency only from authoritative status/CAS of the current `regionEpoch`/`executorFence` pair. A caller whose expected pair is not current is stale; a batch carrying a different fence is prior-fence work that must be reconciled or abandoned before a new tick is staged. Opaque fence bytes are never ordered. - Current-live tooling compares the current `regionEpoch` and opaque `executorFence` for exact equality only; a mismatch fails closed and never supports an older/newer ordering claim. The complete target install/revalidate and takeover proof remains unshipped. @@ -449,9 +452,9 @@ Best-effort hint markers (`remote:{tenantInstanceTag}:`) are only allo Cross-region flows participate in the same coordination timeline and reset rules as purely local ticks: -- Each leg of a cross-region command has a stable root `EffectId`; its origin/target ledger and follow-up storage projections retain the specific scope/timeline on that region plus the distinct target-leg `targetEffectId`, typed operation, immutable request digest, sealed manifest binding, and exact target aggregate. `effectKey` remains descriptor/correlation metadata only, never uniqueness or guard authority. The payload also carries exact target identity plus required ownership, location, and aggregate-version preconditions; a matching target epoch alone is insufficient, and any identity, operation, digest, manifest, or target conflict fails closed. +- Each cross-region mutation leg has its own persisted mutation `EffectId`: `originEffectId` for the origin leg and `targetEffectId` for the target leg; an enclosing command/root `EffectId`, when present, remains lineage and reconciliation context rather than collapsing the legs into one participant identity. The origin/target ledger and follow-up storage projections retain the specific scope/timeline on that region plus the applicable leg identity, typed operation, immutable request digest, sealed manifest binding, exact target `playableStateNamespaceId`, separately persisted and exact-validated target `playableStateScope` fence evidence, and exact target aggregate. The target leg is inbound/remote follow-up work: its deterministic `targetEffectId` is bound to the durable coordinator/follow-up identity under the remote-flow owner contract and is not a command-plan `planOrdinal` allocation unless the target explicitly materializes a new admitted command. `effectKey` remains descriptor/correlation metadata only, never uniqueness or guard authority. The payload also carries exact target identity plus required ownership, location, and aggregate-version preconditions; a matching target epoch alone is insufficient, and any identity, scope, operation, digest, manifest, or target conflict fails closed. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not current target state; its proposed child-manifest schema/serializer/digest binding is not an accepted requirement. - Any origin-side waiting or aggregation state for those legs lives in a separate durable coordinator record. It must not keep the origin tick batch open or prevent `lastCommittedTickId` from advancing. -- When a region/tenant/cluster reset bumps `regionEpoch` for a region, any surviving `SCHEDULED` ledger rows or follow-ups from the old epoch are reconciled under the existing evidence policy: only conclusively unapplied work may converge to `ABANDONED`, while inconclusive work remains non-terminal under its original root `EffectId`; none is silently retried on the new epoch. +- When a region/tenant/cluster reset bumps `regionEpoch` for a region, any surviving `SCHEDULED` ledger rows or follow-ups from the old epoch are reconciled under the existing evidence policy: only conclusively unapplied work may converge to `ABANDONED`, while inconclusive work remains non-terminal under its original mutation `EffectId`, with any enclosing root retained as lineage; none is silently retried on the new epoch. - Origin regions must treat: - Explicit, evidence-backed `ABANDONED` outcomes from target-region effects as a failed remote leg and, where relevant, surface that status to players (for example, “the remote portion of your action failed”). - Timeouts waiting for remote results as a failed remote leg only when the existing policy proves no required mutation succeeded and the command family permits that terminal combination; a timeout or multi-leg failure alone does not authorize `PARTIAL`, and unresolved or inconclusive required work remains `PENDING`/reconciliation-required. @@ -499,7 +502,7 @@ Worked reset example: ## Tick Chaining and Reentrant Effect Control -Some effects (for example, explosions, chained spells, scripted traps) spawn follow-up actions. Each root chain is bounded by the shared bootstrap depth ceiling (`8`), deterministic total count and cost budgets, and a deterministic per-target cap. A generated child records immutable parent/root identity, `depth = parent.depth + 1`, and a digest-covered deterministic child ordinal. Admission suppresses only the child that would exceed a limit; committed parents and earlier children remain authoritative. Required/optional authored classification derives truthful `SUCCESS`, `PARTIAL`, or `FAILED` outcomes, and every suppression records durable evidence with bounded metric labels. Generated effects remain passive/effect work and cannot grant another root actor action in the same tick. See [ADR 0075](./decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). +Some effects (for example, explosions, chained spells, scripted traps) spawn follow-up actions. Each root chain is bounded by the shared bootstrap depth ceiling (`8`), deterministic total count and cost budgets, and a deterministic per-target cap. A generated child records immutable parent/root identity, `depth = parent.depth + 1`, and an owner-defined deterministic child ordinal allocated and persisted by the owning contract for replay-stable reuse. Script-generated command children additionally retain the applicable `automationDispatchId` and `commandOrdinal`; the generic generated-child ordinal replaces neither script-handoff field, and exact retries reuse the same complete binding. When the chain is under an admitted command, it remains beneath that command's root; otherwise it retains its owner/source-specific root identity and does not synthesize a command plan. Admission suppresses only the child that would exceed a limit; committed parents and earlier children remain authoritative. Required/optional authored classification derives truthful `SUCCESS`, `PARTIAL`, or `FAILED` outcomes, and every suppression records durable evidence with bounded metric labels. Generated effects remain passive/effect work and cannot grant another root actor action in the same tick. See [ADR 0075](./decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative. ## Worked Example: Cross-Region Lifesteal Command @@ -518,10 +521,10 @@ To illustrate how cross-region flows compose from the phases above, consider a * - It may also write a best-effort hint marker such as `remote:{tenantInstanceTag}:` (for the target entity under the target ``) to reduce latency, but correctness does not depend on that marker. - In the next tick for ``, the target region’s executor: - Computes the damage amount as a percentage of the target’s authoritative current HP. - - Acquires the target’s lock (`tick:{tenantRegionTag}:lock:`) and applies damage via Entity Management under the stable target-leg root `EffectId` and its derived guard. + - Acquires the target’s lock (`tick:{tenantRegionTag}:lock:`) and applies damage via Entity Management under the target leg’s persisted mutation `EffectId` and its operation/target guard; any enclosing root remains lineage and reconciliation context. - Writes a durable origin-addressed result row for region A containing `coordinatorId`, `originGameInstanceId`, `originRegionId`, `originRegionEpoch`, the target leg identity, `casterEntityId`, the actual `damageApplied`, the exact accepted-result digest, and the target terminal outcome. Origin reconciliation verifies those fields against its durable coordinator row before accepting the result. Acceptance cannot become durable without the deterministic child-heal intent: the accepted result and child intent commit together when co-located, or a resumable durable acceptance intent records both before acceptance is acknowledged. 4. **Heal Leg (origin region)** - - Only after existing coordinator reconciliation accepts the target result does region A record the actor-generated “apply lifesteal heal” effect for the caster. A rejected or abandoned result creates no heal effect; an accepted heal has a deterministic, stable idempotent child `EffectId` derived from the accepted result and is not a new root actor command. Acceptance replay reuses that child identity and the exact accepted-result digest; it cannot create a second heal intent or silently accept a conflicting result. + - Only after existing coordinator reconciliation accepts the target result does region A record the actor-generated “apply lifesteal heal” effect for the caster. A rejected or abandoned result creates no heal effect; an accepted heal has a deterministic, stable idempotent child `EffectId` derived from the accepted result and is not a new root actor command. Acceptance replay reuses that child identity and the exact accepted-result digest; it cannot create a second heal intent or silently accept a conflicting result. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative. - In a subsequent tick for ``, the executor: - Acquires the caster’s lock. - Applies a heal up to `damageApplied` (subject to HP rules) using Entity Management and tick idempotency. @@ -533,6 +536,6 @@ To illustrate how cross-region flows compose from the phases above, consider a * Throughout this sequence: -- Each leg is idempotent through its stable root `EffectId` and derived operation/target guard in the domain service. The heal child is idempotent through the accepted-result digest and child identity; its acceptance/replay rule is a local durability consequence, not a new outcome state. +- Each leg is idempotent through its persisted mutation `EffectId` and operation/target guard in the domain service; the enclosing root remains lineage and reconciliation context. The heal child is idempotent through the accepted-result digest and child identity; its acceptance/replay rule is a local durability consequence, not a new outcome state. - Region executors never hold cross-region locks; they coordinate via queued commands, durable follow-up records, and durable origin-addressed result rows. - Retries due to lock contention or transient failures are handled by the standard retry queues and idempotent handlers in each region without breaking the overall experience. diff --git a/design/architecture/system-architecture-tick-failures-and-operations.md b/design/architecture/system-architecture-tick-failures-and-operations.md index 29adb9890f..dd6e86ade3 100644 --- a/design/architecture/system-architecture-tick-failures-and-operations.md +++ b/design/architecture/system-architecture-tick-failures-and-operations.md @@ -15,6 +15,8 @@ This document describes the full target-state recovery and operator model. Curre - the live fence token is opaque and compare-and-match based; - the live `tick_batch` / `tick_effect` ledger is real and now carries the current gameplay-command selected-work manifest on `tick_batch`, including current-boundary `enqueueSeq`, source metadata, and digest-checked replay reuse for surviving staged batches; live selected-work manifests do not yet preserve the required declared `phase`, `lane`, and `cost_class` metadata. The live `enqueueSeq` is allocated by one database-wide sequence; the region-scoped, cross-source allocator defined below is target-state. Timer/retry/remote-follow-up source-claim manifests, region-scoped replay controller breadth, and cross-region result-return semantics also remain target-state follow-through. - the live gameplay-command staging path does not yet provide the complete target automation handoff identity: it derives `effectKey` from `commandId` and uses a deterministic text/slot fallback when no command ID is available. The target fail-closed contract below assigns the stable root `EffectId` before acknowledgement when possible and rejects before acknowledgement when assignment fails. If an already acknowledged `ACCEPTED_VOLATILE` command cannot receive that identity, `LOST_BEFORE_STAGING` remains limited to eligible `RECEIVED`/`ENQUEUED` work with no surviving batch; batch-bound or inconclusive work remains non-terminal/reconciliation-required and is never evidence-free `ABANDONED`. This document does not claim that target behavior is already live. +- The live rollback purge path is weaker than that target boundary: `TickQueueControlService.purgeCandidate` checks only `GameplayCommandRepository.hasDurableTickEffect(commandId)` before selecting `ABANDONED` versus `LOST_BEFORE_STAGING`. That non-atomic existence check does not prove the absence of a surviving batch, effect, or source claim, and it can race concurrent staging, drain, or effect ownership. The target atomic owner-defined CAS/no-batch proof remains unimplemented and unproved; this is a current implementation/proof gap, not a relaxation of the target `ACCEPTED_VOLATILE`/`RECEIVED`/`ENQUEUED` eligibility contract. +- The target deterministic command-plan root contract is also not live: the owning command/action contract for the frozen typed command or `ResolvedEffectPlan` must supply semantic root order, with built-ins declaring equivalent stable order and ambiguous or duplicate order rejected before admission. Before allocation, the durable gameplay command row must freeze/bind its request fingerprint and resolved runtime scope. Game Session must persist the ordered plan manifest/digest and allocate an opaque root `EffectId` row unique on `(tenantId, gameInstanceId, commandId, planOrdinal)`; the row binds the manifest digest and validates the frozen command/runtime binding, and reuse requires all of those values to match or fails closed. For Automation, the complete applicable Command-Handoff Identity is the admission/deduplication identity and must exact-map to one durable target `commandId`; allocation then uses the target command row's canonical key. The current `tickBatchId`/`effectKey` fallback does not prove that contract, and no global allocator is implied. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not current target state. - The accepted lane and fencing consequences are target-state requirements in this recovery model: selected-work manifests and replay records must preserve each item's declared `phase`, `lane`, and `cost_class`, while takeover reconciliation remains subject to the Redis lease plus durable executor-fence handshake owned by [Tick System and Runtime Design](./system-architecture-ticks.md). This document does not duplicate that owner protocol. Naming convention: API, workflow, and EffectId prose uses `regionEpoch`. Snake-case forms such as `region_epoch`, `last_region_epoch`, and `target_region_epoch` are reserved for explicitly identified SQL/storage fields, Redis payloads/keys, or schema examples. @@ -22,7 +24,7 @@ Naming convention: API, workflow, and EffectId prose uses `regionEpoch`. Snake-c ## What This Covers - Crash recovery and replay behavior. -- Idempotency rules tied to the region-scoped tick timeline `(regionEpoch, tickId)`. +- Root/participant idempotency guards, with a narrow last-tick watermark exception only for explicitly proven at-most-once aggregates; the region-scoped tick timeline `(regionEpoch, tickId)` remains ordering and fencing context. - Handling stuck or partial tick entries. - Design checklist for new tick-driven commands. @@ -31,29 +33,32 @@ Naming convention: API, workflow, and EffectId prose uses `regionEpoch`. Snake-c The following sections in `system-architecture-ticks.md` contain the main failure-handling and operational rules: - **Crash Recovery and Replay** – how executors recover from failure and resume processing safely. -- **Domain Idempotency Rules (Timeline Context + Owner Guards)** – how `(regionEpoch, tickId)` provide ordering/fence context while owner guards enforce logical effect idempotency. +- **Domain Idempotency Rules (Timeline Context + Owner Guards)** – how mutation-identity/participant guards enforce logical effect idempotency while `(regionEpoch, tickId)` provides ordering and fencing context. - **Design Checklist for New Tick-Driven Commands** – review checklist for new commands to ensure they follow tick invariants. - **Tick Execution and Redis Integration** – failure scenarios and invariants around the canonical commit pattern. - **Cross-Region Command Execution and Result Relay** – constraints for cross-region retries and replay. When implementing new failure-handling flows or adding operational procedures, ensure the detailed behavior is captured in `system-architecture-ticks.md` and reflected in the appropriate runbooks (for example, Redis incident runbooks). +Under ADR 0085, each coordination-maintenance recovery, takeover, replay, reset, cleanup, or topology-changing operation is admitted and serialized by one external durable maintenance operation/fence and the evidence-derived `replay_first`/`reset_first` classifier owned by [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md). Before any mutation or reconciliation, the durable handoff must validate, persist, and pass the exact external maintenance `operationId`, fence/lock binding, classifier decision, durable-evidence digest, and complete affected scope (keys, durable work, producers, and consumers). A missing, mismatched, or incomplete handoff or scope fails closed and escalates; Redis-local leases and executor fences remain separate execution aids, not substitutes for that maintenance fence. An ordinary idempotent crash replay may run outside this maintenance operation only when the owner contract explicitly classifies it as non-conflicting routine replay and records that classification and evidence; no path may infer that exemption from Redis residue alone. + ## Crash Recovery and Replay Tick recovery is driven by durable PostgreSQL tick state plus domain-level idempotency rules, with Redis acting only as a volatile coordination layer. Game Session creates the durable PostgreSQL `tick_batch` and `SCHEDULED` ledger rows first; only then may it stage the batch in Redis `pending`. Redis `pending` is staging/acceleration coordination only and is never authoritative for tick intent or recovery. - On executor crash or failover, a new worker acquires the region lease, re-establishes the authoritative recovery baseline from the durable tick-batch, tick effect ledger, follow-up tables, and the active status/progress surface: current live uses `GetRuntimeOwnershipStatus` plus `ObserveRuntimeTickProgress` for the owner, opaque `executorFence`, and committed `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)` progress; target-state uses `RegionStatus`/`GetRegionTickStatus`. It then inspects any surviving `tick:{tenantRegionTag}:pending`, `retry:{tenantRegionTag}`, and timer keys only as optional coordination hints while replay converges from durable state. -- Before replay, cleanup, or takeover adoption, the successor revalidates the same in-memory Redis lease token it acquired and the expected `regionEpoch`, then separately verifies the current durable executor fence under the owner contract before any recovery mutation; a missing or mismatched token, epoch, or fence pauses and enters fenced reconciliation, affects no state, and never persists the raw token. Lane identity is immutable during recovery: actor-action retries remain actor actions, passive/effect retries remain passive effects, and replay cannot mint a new root actor action for the same tick. +- Before replay, cleanup, or takeover adoption, the successor revalidates the same in-memory Redis lease token it acquired and the expected `regionEpoch`, then separately verifies the current durable executor fence under the owner contract. When the owner classifies the path as coordination maintenance under ADR 0085, it also validates the exact external maintenance handoff (`operationId`, fence/lock binding, classifier decision, evidence digest, and complete affected scope) and persists/passes that handoff unchanged with recovery evidence before any mutation; an ordinary crash replay may omit that maintenance operation only under the explicit owner classification described above. A missing or mismatched token, epoch, fence, handoff field, or scope pauses and enters fenced reconciliation, affects no state, and never persists the raw token. Lane identity is immutable during recovery: actor-action retries remain actor actions, passive/effect retries remain passive effects, and replay cannot mint a new root actor action for the same tick. +- A recovery skip after the ADR 0085 handoff is permitted only for an explicitly disposable ADR 0058 hint, or after ADR 0058 reconciliation durably proves an empty cadence with no unresolved authoritative work. A missing Redis entry, empty hint scan, timeout, or maintenance handoff alone never proves that a tick or authoritative work item may be skipped; otherwise recovery must replay or reconcile the durable work and retain any inconclusive item as non-terminal/reconciliation-required. - Redis is treated as a volatile coordination layer with **at-least-once** semantics; network retries, executor failover, and AOF replay can all cause the same logical effect to be attempted more than once. -- Domain services rely on `(regionEpoch, tickId)` and effect guards to ensure that replays do not double-apply logical effects even when Redis state is partially lost. +- Domain services use the mutation-identity/participant-guard boundary to ensure that replays do not double-apply logical effects; `(regionEpoch, tickId)` remains ordering and fencing context even when Redis state is partially lost. ### Durable Commit vs Coordination-Cleared Boundaries Failure handling assumes the same two-boundary model defined in the main tick design: - `durable_committed`: - - Ledger rows for `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId)` are terminal (`APPLIED` or `ABANDONED`) where the existing evidence policy permits terminalization; any inconclusive row remains non-terminal reconciliation work under its original root `EffectId`, and - - The current-live `GetRuntimeOwnershipStatus` reports the same opaque `executorFence` recorded by the batch, the live `regionEpoch` matches, and the live commit boundary has advanced under that same fenced write. `RegionStatus` is a target-state durable projection in examples where the live ownership/status surface is not available. + - **Target-state only:** For a work-bearing (non-empty) tick, the complete [canonical tick commit definition](./system-architecture-ticks.md#tick-commit-definition-heartbeat-watermark) requires every eligible ledger row for `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId)` to be terminal (`APPLIED` or `ABANDONED`) under the evidence policy, `tick_batch.status = COMMITTED`, and the target durable watermark to advance in that same fenced visibility boundary. Any inconclusive row remains non-terminal reconciliation work under its original mutation `EffectId`, with its enclosing root retained as lineage, and blocks this boundary. + - In the current-live deployment, `GetRuntimeOwnershipStatus` reports the same opaque `executorFence` recorded by the batch, the live `regionEpoch` matches, and the committed tick fields advance under that same fenced write. Target-state `RegionStatus.lastCommittedTickId` is the corresponding durable projection; `ObserveRuntimeTickProgress` is only the current-live progress feed and does not replace either durable authority. - `coordination_cleared`: - Redis `pending`/lock coordination for that tick is no longer in flight. @@ -72,21 +77,25 @@ To make replays observable and bounded, Game Session maintains a **tick effect l - Every tick effect that has been durably claimed or staged for execution (for example, rows associated with a tick batch, replay-eligible retry work, or durable follow-up records) is mirrored into a Game Session–owned ledger table (for example `tick_effects`) with columns such as: - `tenant_id`, `game_instance_id`, `playable_state_namespace_id`, `playable_state_scope`, `region_id`, `region_epoch`, `tick_id` - `tick_batch_id` - - `root_effect_id` (stable logical root identity retained on every ledger projection) - - `typed_operation` (canonical operation identity retained alongside the root on every participant projection) + - `effect_id` (persisted mutation identity used by the participant guard: the root `EffectId` for a root mutation or the deterministic child `EffectId` for a generated child) + - `root_effect_id` (enclosing stable logical root identity retained on every ledger projection for lineage and reconciliation; equal to `effect_id` for a root mutation) + - `plan_ordinal` (stable zero-based root position in the command's deterministic plan; absent for a zero-effect command because no effect row exists) + - `typed_operation` (canonical operation identity retained alongside the mutation `effect_id` and enclosing root on every participant projection) - `effect_key` (stable, human-readable descriptor passed through from staging) - declared `phase`, `lane` ∈ {`actor_action`, `passive_effect`}, and bounded `cost_class`; recovery and replay preserve all three values - `target_aggregate_type`, `target_aggregate_id` (required target aggregate identity) + - `request_digest` (immutable request digest bound to the mutation guard and compared on replay; not part of uniqueness) - `automation_dispatch_id`, `command_ordinal` (both required for script-generated effects; nullable for non-scripting commands) - `command_id` - `status` ∈ {`SCHEDULED`, `APPLIED`, `ABANDONED`} - `reason` / `outcome` - replay-verification audit metadata when a replay proves that the effect was already applied (for example verifier, timestamp, and evidence digest/reference) - `created_at`, `updated_at` +- The ledger retains the enclosing root's `plan_ordinal`/`root_effect_id` binding as command-plan identity and reconciliation metadata. A root mutation uses that root as its participant-guard `effect_id`; a generated child uses its persisted deterministic child `EffectId` as `effect_id` while retaining the enclosing root for lineage and reconciliation. A shared root for a conserved multi-participant operation does not replace ADR 0053 atomicity, co-location, or reservation semantics. For command-root work, the root is allocated by Game Session's local durable plan/staging transaction from the opaque binding unique on `(tenantId, gameInstanceId, commandId, planOrdinal)`; the durable command row's frozen request/runtime binding, applicable `playableStateNamespaceId`, and ordered plan manifest digest are validated on reuse, and a mismatch fails closed. Passive, inbound/remote, timer, retry, and already-generated effects retain their owner/source-specific root identities unless they materialize as an admitted command. Random batch, mutable command, effect-key, source-ordering, participant, trigger, and generated-child identities cannot substitute for that durable command row identity or allocation binding; child-ID persistence uses its owning deterministic child contract and does not create another command-root allocator. - Target-state requires one durable tick-batch record per `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)`, owned by Game Session, and stores at minimum: - `tick_batch_id` - `executor_fence` (or equivalent opaque durable fence captured at batch allocation time); this is the canonical durable fence used for compare-and-match protection. - - exactly one immutable sealed execution-context binding: `sealed_execution_context_digest`, or a durable `sealed_execution_context_ref` whose referenced record contains that digest. The binding covers the batch coordinates, executor fence, selected-work manifest/digest, effect identities, and pinned execution inputs/version/script patch; replay must use the sealed context rather than reconstructing mutable context. + - exactly one immutable sealed execution-context binding: `sealed_execution_context_digest`, or a durable `sealed_execution_context_ref` whose referenced record contains that digest. The binding covers the batch coordinates, executor fence, applicable `playableStateNamespaceId`, selected-work manifest/digest, effect identities, and pinned execution inputs/version/script patch; replay must use the sealed context rather than reconstructing mutable context. - `lease_token_correlation` may be retained as optional non-secret lease-acquisition trace/audit metadata; raw Redis lease tokens are never persisted, and this correlation is not an authoritative durable fence and must not authorize batch allocation, commit, cleanup, or recovery writes. - `expected_effect_count` - `status` @@ -94,7 +103,7 @@ To make replays observable and bounded, Game Session maintains a **tick effect l - optional `pending_digest` or equivalent Redis-pending integrity field; it is not a substitute for the required immutable exact pending envelope or the sealed execution-context binding above - `created_at`, `updated_at` - The selected-work manifest is required for deterministic replay and source cleanup. At minimum it records, per selected source item: - - the batch scope `(tenantId, gameInstanceId, regionId, regionEpoch)`; its `enqueue_seq` is allocated from the complete `` scope and is not reset or reused when a reset bumps `regionEpoch` and restarts `tickId` at `0` + - the tick-batch identity `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)`; separately, its entity-local `entity_enqueue_seq` is allocated monotonically within the complete allocation scope `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch)`. `playableStateScope` is not part of either identity. A reset that bumps `regionEpoch` and restarts `tickId` at `0` starts a new entity-local sequence domain, while old-epoch ordering identities remain immutable and are never rebound even if a numeric sequence value is reused. - `source_kind` - declared `phase`, `lane`, and `cost_class` - source item identity @@ -117,7 +126,7 @@ To make replays observable and bounded, Game Session maintains a **tick effect l - Recovery that observes multiple durable rows for the same coordinates treats the region as inconsistent, pauses it, and requires reconcile tooling before normal ticks resume. - Current live boundary note: gameplay commands do not yet use the fuller target-state `BOUND_TO_BATCH` vocabulary. Instead, the command ledger exposes `enqueueSeq`, `STAGED`, `DRAINED`, and later terminal/requeue outcomes, while the sealed batch manifest digest is used to ensure replay reuses only matching staged batches instead of silently mutating an older batch contract. - **Target-state authority:** The durable `tick_batch` record, `tick_effects` ledger, and immutable sealed execution context are authoritative for selected work, execution identity, and replay. The sealed context includes the complete batch coordinates, executor fence, selected-work manifest/digest (including each item's declared phase/lane/cost-class and persisted ordering inputs), effect identities, and pinned execution inputs/version/script patch. Redis `pending`/event streams plus external metrics, logs, traces, and audit streams are projections or diagnostics; they cannot prove a commit or justify replay on their own. -- For the complete expected concrete participant-projection set linked to a root `EffectId` and participant guard contract, every expected `(root_effect_id, typed_operation, tenant_id, game_instance_id, playable_state_namespace_id, playable_state_scope, region_id, region_epoch, tick_id, target_aggregate_type, target_aggregate_id)` projection must eventually have **exactly one evidence-qualified terminal state**, and only when authoritative evidence permits terminalization. `typed_operation` is part of the participant projection alongside the root and exact target aggregate; `effect_key` remains descriptor metadata for correlation and lookup, not a substitute for that identity. Replay/recovery must reconcile the whole expected set and fail closed for missing, extra, partial, or conflicting projections; inconclusive or ambiguous projections remain non-terminal/reconciliation-required and cannot be recorded as `APPLIED` or `ABANDONED`; one root-effect or one ledger-row result is insufficient: +- For the complete expected concrete participant-projection set linked to an enclosing root `EffectId` and participant guard contract, every expected `(effect_id, root_effect_id, typed_operation, tenant_id, game_instance_id, playable_state_namespace_id, playable_state_scope, region_id, region_epoch, tick_id, target_aggregate_type, target_aggregate_id)` projection must eventually have **exactly one evidence-qualified terminal state**, and only when the applicable recovery/evidence policy permits terminalization. Explicitly inconclusive or ambiguous projections remain non-terminal/reconciliation-required (for example, `SCHEDULED`) and continue to block convergence; they cannot be recorded as `APPLIED` or `ABANDONED`. `effect_id` is the mutation's persisted root-or-child `EffectId`; `root_effect_id` remains enclosing lineage and reconciliation context. `typed_operation` is part of the participant projection alongside the mutation ID and exact target aggregate; guard uniqueness uses the owner-declared runtime-family partition: `playable_state_namespace_id` participates for S1/S2, while only explicit S3 uses `game_instance_id`; for S1/S2, `game_instance_id` is separately exact-validated active-runtime authorization/fence evidence. `playable_state_scope` and the remaining timeline/evidence fields are immutable bound evidence, and `effect_key` remains descriptor metadata for correlation and lookup, not a substitute for that identity. Replay/recovery must reconcile the whole expected set and fail closed for missing, extra, partial, or conflicting projections; one root-effect or one ledger-row result is insufficient: - `status = APPLIED` – effect successfully committed to domain state, or durable replay evidence proves that it was already committed under the existing fenced verification policy. - `status = ABANDONED` – effect intentionally skipped or judged unrecoverable only when durable evidence proves it was unapplied and the existing recovery policy permits terminalization; inconclusive work remains non-terminal reconciliation work. - A duplicate handler attempt may return a replay/no-op outcome such as `replay_ok`, but that outcome is recorded in service metrics/audit and never as a third ledger status; when the effect is already reflected in durable state, its ledger row is `APPLIED`. @@ -158,12 +167,12 @@ Tick-related durable structures are intentionally split between a central ledger - **Game Session Service** - Owns the global tick effect ledger tables (for example `tick_effects`) and any cross-region follow-up tables that encode scheduled work between regions. - - Defines the concrete ledger projection of the root `EffectId` and its typed participant-guard contract, and is responsible for converging `(rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, targetAggregateType, targetAggregateId)`—with `effectKey` retained as descriptor metadata and linked to that root, operation, and guard evidence—to `APPLIED` or `ABANDONED` when the recovery policy permits terminalization. + - Defines the concrete ledger projection of the mutation's persisted root-or-child `EffectId` and its typed participant-guard contract, while retaining the enclosing root `EffectId` as lineage and reconciliation context. It is responsible for converging `(effectId, rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, targetAggregateType, targetAggregateId)`—with `effectKey` retained as descriptor metadata and linked to that mutation, root, operation, and guard evidence—to `APPLIED` or `ABANDONED` when the recovery policy permits terminalization. - **Domain services (Entity Management, World Management, etc.)** - Own their own idempotency guard tables (for example `entity_tick_state`, `tick_effect_guard`) in their respective schemas. - - Use those guards to implement per-aggregate `last_tick_id` and operation-level idempotency patterns, but do not introduce additional “mini-ledgers” for tick effects. + - Use operation-level guards by default; a per-aggregate `last_tick_id` watermark is allowed only with an explicit proof of at-most-one logical mutation per tick timeline. Do not introduce additional “mini-ledgers” for tick effects. -New designs must not create ad-hoc ledger tables for tick effects in other services; they should either extend the Game Session–owned ledger/follow-up schema or add domain-local guard tables that project the existing `EffectId`. +New designs must not create ad-hoc ledger tables for tick effects in other services; they should either extend the Game Session–owned ledger/follow-up schema or add domain-local guard tables that project the existing mutation `EffectId` and retain its enclosing root lineage. Cross-region follow-ups extend the same concrete identity rather than treating a region or scope label as sufficient. Each durable coordinator, target follow-up, and origin-addressed result must carry both the origin and target runtime tuples `(tenant_id, game_instance_id, playable_state_namespace_id, playable_state_scope, region_id, region_epoch)` (with the origin/target role made explicit). `playable_state_namespace_id` participates in target-leg uniqueness/claim identity, exact replay comparison, old-epoch recovery, and coordinator-to-result correlation; `playable_state_scope` is separately persisted and exact-validated evidence, not a replacement key. A target result is admissible only when its origin and target namespace/timeline tuples, stable follow-up/coordinator identity, target effect/aggregate identity, and immutable request/result digest agree with the durable rows. Recovery retains the original namespace-complete projection and must not rebind an old follow-up to a new namespace or epoch. The current cross-region storage/wire substrate remains narrower than this target contract. @@ -171,7 +180,7 @@ Replay of a tick is driven from ledger state: - When reprocessing a tick, the executor loads ledger rows for that `` with `status = SCHEDULED` and: - A `SCHEDULED` effect may be re-queued/re-run only after durable authoritative domain evidence proves that it was unapplied and that replay is safe under the existing evidence policy. Absence of `APPLIED` evidence, a missing response, or an unreadable/ambiguous guard is inconclusive: retain `SCHEDULED`/reconciliation-required, escalate, and do not re-queue. After a permitted replay, mark the row `APPLIED` only when durable domain evidence and the fenced replay policy prove application. - - Marks effects `ABANDONED` with a precise reason only when replay proves no required mutation succeeded and the effect is no longer valid (expired session, entity gone, descheduled tick, and so on). Inconclusive work remains non-terminal reconciliation work under its original root `EffectId` and is escalated for reconciliation. + - Marks effects `ABANDONED` with a precise reason only when replay proves no required mutation succeeded and the effect is no longer valid (expired session, entity gone, descheduled tick, and so on). Inconclusive work remains non-terminal reconciliation work under its original mutation `EffectId`, with the enclosing root retained as lineage, and is escalated for reconciliation. - When idempotency evidence may prove that an effect was already applied, replay verification reconciles the complete expected concrete participant-projection set and binds the evidence to the `SCHEDULED -> APPLIED` transitions in fenced/CAS transactions (conceptual shape): ```sql @@ -208,7 +217,8 @@ Replay of a tick is driven from ledger state: -- field or this resolved digest as sealed_context_digest; never rebuild -- context from mutable state. -- expected is the sealed set of concrete participant projections for this - -- effect: root EffectId + typed operation + exact target aggregate, + -- effect: mutation EffectId (root or persisted child) + typed operation + -- + exact target aggregate; enclosing root is lineage/reconciliation context, -- including every required participant and its immutable request-digest -- binding. Read all expected guard rows and durable domain evidence under -- the current fence/context. Require set equality: every expected @@ -263,13 +273,13 @@ Replay of a tick is driven from ledger state: ``` The complete-set evidence check, target authority epoch/fence check, sealed context-digest check, all required Game Session ledger CAS operations, and replay-verification metadata commit together within this one Game Session durable transaction. A stale authority or batch fence/context, missing/extra/partial/conflicting projection, or concurrent winner affects an incomplete set and must roll back and fail closed/reject or retry; an audit/log write without this CAS is not proof and must not be used to skip the domain call. Domain-service guards and evidence remain in their own service-local transactions; this flow does not imply a cross-service database transaction. Current-live uses a separate CAS over the current `RuntimeOwnershipStatus` authority, exact `regionEpoch`/opaque `executorFence`, and the complete selected-work manifest plus `manifest_digest` against durable source, ledger, and participant evidence; sealed execution context is not required at that current-live boundary. Both branches fail closed on mismatches and leave durable state unchanged. -- Every staging script must carry an immutable collision-safe pending envelope for each staged member. `effect_key` remains descriptor metadata only. The envelope must carry the exact `tick_batch_id` plus either the complete root `EffectId`/participant projection (`root_effect_id`, canonical `typed_operation`, exact `target_aggregate_type`/`target_aggregate_id`, and the exact scope, epoch, and tick) or an equivalent immutable exact ledger-row identity that resolves to that complete projection. Stage, commit, rollback, and cleanup preserve the envelope unchanged; recovery exact-set-compares pending envelopes with the durable batch/ledger expected set and fails closed for missing, extra, duplicate, or conflicting envelopes. An `effect_key`-only, count-only, or digest-only correlation is insufficient, and malformed or orphan pending state cannot be committed. +- Every staging script must carry an immutable collision-safe pending envelope for each staged member. `effect_key` remains descriptor metadata only. The envelope must carry the exact `tick_batch_id` plus either the complete mutation `EffectId`/enclosing-root lineage/participant projection (`effect_id`, `root_effect_id`, canonical `typed_operation`, exact `target_aggregate_type`/`target_aggregate_id`, and the exact scope, epoch, and tick) or an equivalent immutable exact ledger-row identity that resolves to that complete projection. Stage, commit, rollback, and cleanup preserve the envelope unchanged; recovery exact-set-compares pending envelopes with the durable batch/ledger expected set and fails closed for missing, extra, duplicate, or conflicting envelopes. An `effect_key`-only, count-only, or digest-only correlation is insufficient, and malformed or orphan pending state cannot be committed. - Recovery rules for Redis/SQL mismatch are explicit: - durable tick-batch + `SCHEDULED` ledger rows exist, Redis `pending` missing: - replay proceeds from PostgreSQL using the durable batch manifest and `SCHEDULED` ledger rows; it does not rely on re-materializing the old tick through the normal hot-path staging scripts. - - First implementation treats normal tick Lua scripts as hot-path guards only. Recovery drives effects directly to `APPLIED`/`ABANDONED` only where the evidence policy permits, leaves any inconclusive work non-terminal under its original root `EffectId`, escalates it for reconciliation, reconciles any surviving source claims/entries against the manifest, and then clears stale coordination residue. + - First implementation treats normal tick Lua scripts as hot-path guards only. Recovery drives effects directly to `APPLIED`/`ABANDONED` only where the evidence policy permits, leaves any inconclusive work non-terminal under its original mutation `EffectId` and enclosing-root lineage, escalates it for reconciliation, reconciles any surviving source claims/entries against the manifest, and then clears stale coordination residue. - Redis `pending` exists without a durable tick-batch: - - treat the Redis entry as orphaned coordination state, clear it, alert, and do not commit work from it. + - treat the Redis entry as orphaned coordination state; clear it only after the exact ADR 0085 handoff has been validated and durably persisted, then passed unchanged to the cleanup operation (`operationId`, fence/lock binding, classifier decision, evidence digest, and complete affected scope), or after the owner has durably recorded this specific non-conflicting routine replay/cleanup classification and evidence. The cleanup must validate a nonblank operation identity, the current fence/lock, classifier, evidence digest, and complete scope immediately before deletion; it must not manufacture or reuse an operation record from Redis residue. Missing, stale, mismatched, or incomplete handoff/classification fails closed and escalates; alert and do not commit work from the orphaned entry. - durable tick-batch and Redis `pending` do not produce exact set equality for the immutable pending envelopes and durable batch/ledger expected set (including missing, extra, duplicate, malformed, or conflicting members; count/digest disagreement is only a diagnostic signal): - mark the batch inconsistent, pause the region, and require reconcile tooling before resuming normal ticks. @@ -288,7 +298,7 @@ Recovery-specific behavior is: ### EffectId, Ledger Rows, and Guard Keys -The canonical root `EffectId` described in the identifier glossary and `system-architecture-transactions.md` ties together the logical effect, Game Session participant status, and replay lineage. Participant guard uniqueness is deterministically derived from exactly that root effect, typed operation, and target aggregate; the immutable request digest is bound to the guard identity, while durable outcome/evidence state is mutable guard-row state protected by CAS. The root identity, original participant ledger projection, and collision-safe guard identity are preserved for every ordinary retry or uncertain replay. Retry eligibility/attempt metadata (such as retry count, next eligible tick, and source-claim state) is separate and must not rewrite the original `regionEpoch`, `tickId`, `effectKey`, or root/typed-operation/target projection. A future linked-attempt or supersession model requires an explicit contract; only a **post-abandon re-drive**—after the original effect is conclusively terminal `ABANDONED` and its source claim is terminalized—may receive a fresh logical `EffectId`, a later tick coordinate, a new retry/source identity, and durable lineage to the original identities. +The canonical root and plan allocation are owned by [Transaction Strategies](./system-architecture-transactions.md#command-atomicity-and-outcome-aggregation). This operations document owns their failure consequences: the ledger retains the persisted mutation `EffectId`, enclosing root lineage, `plan_ordinal`, timeline, typed operation, exact target, digest, participant projection, and replay lineage; ordinary retry and uncertain replay preserve them. A root mutation uses its root `EffectId`; a generated child uses its persisted deterministic child `EffectId` while retaining the enclosing root as lineage and reconciliation context. Retry eligibility is mutable operational metadata and never rewrites that binding. A post-abandon command re-drive requires conclusive terminal evidence, a new durable `commandId`, and explicit lineage to the abandoned command/effect; reusing the old command id returns its terminal result. Non-command sources follow their owner-specific linked re-drive identity. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not current target state. - Tick coordination in Redis. - Tick effect ledger rows in PostgreSQL. @@ -296,12 +306,14 @@ The canonical root `EffectId` described in the identifier glossary and `system-a In schema terms: -- The tick effect ledger persists a concrete, namespace-complete projection of the root `EffectId` and its tick coordinates for scope, ordering, evidence, and target lookup: - - The storage projection includes at minimum `(root_effect_id, typed_operation, tenant_id, game_instance_id, playable_state_namespace_id, playable_state_scope, region_id, region_epoch, tick_id, target_aggregate_type, target_aggregate_id)`. `playable_state_scope` and the tick/region coordinates are persisted and exact-validated evidence or ordering metadata, not uniqueness dimensions. The ledger's logical uniqueness key is exactly `(root_effect_id, typed_operation, target_aggregate_type, target_aggregate_id)`; an owner-local physical partition, if used, is storage placement only and cannot alter logical uniqueness or deduplication. The physical schema must enforce or project that exact logical identity without promoting `playable_state_scope` or tick coordinates into guard uniqueness. `effect_key` may be stored in the projection for stable descriptor/correlation metadata, but it is not the root identity or sole collision protection. Mutable `status`, `reason`, `outcome`, evidence/reconciliation fields, and timestamps remain outside the uniqueness key. The physical schema may encode target identity separately, but it must retain an explicit collision-safe projection containing `root_effect_id`, `typed_operation`, and the exact target aggregate. - - Additional columns such as `command_id`, `automation_dispatch_id`, or `command_ordinal` may exist for queryability and scripting correlation, but they do not replace the root `EffectId` or participant guard identity. +- The tick effect ledger persists a concrete, namespace-complete projection of the persisted mutation `EffectId`, enclosing root lineage, and tick coordinates for scope, ordering, evidence, and target lookup: + - The storage projection includes at minimum `(effect_id, root_effect_id, typed_operation, tenant_id, game_instance_id, playable_state_namespace_id, playable_state_scope, region_id, region_epoch, tick_id, target_aggregate_type, target_aggregate_id)`. `playable_state_scope` and the tick/region coordinates are persisted and exact-validated evidence or ordering metadata, not uniqueness dimensions. The ledger's logical uniqueness key is exactly `(effect_id, typed_operation, target_aggregate_type, target_aggregate_id)`, where `effect_id` is the root `EffectId` for a root mutation and the persisted child `EffectId` for a generated child; `root_effect_id` is retained as enclosing-root lineage and reconciliation context, not as a substitute for `effect_id`. An owner-local physical partition, if used, is storage placement only and cannot alter logical uniqueness or deduplication. The physical schema must enforce or project that exact logical identity without promoting `playable_state_scope` or tick coordinates into guard uniqueness. `effect_key` may be stored in the projection for stable descriptor/correlation metadata, but it is not the mutation identity or sole collision protection. Mutable `status`, `reason`, `outcome`, evidence/reconciliation fields, and timestamps remain outside the uniqueness key. The physical schema may encode target identity separately, but it must retain an explicit collision-safe projection containing `effect_id`, `root_effect_id`, `typed_operation`, and the exact target aggregate. + - Additional columns such as `command_id`, `automation_dispatch_id`, or `command_ordinal` may exist for queryability and scripting correlation, but they do not replace the persisted mutation `EffectId` or participant guard identity. + - On reuse of the persisted mutation identity, the writer exact-compares all immutable scope, lineage, timeline, descriptor, namespace, and request-digest bindings, including the stored projection fields, and fails closed on any conflict; it must not insert another row for a conflicting reuse. For a root mutation, `effect_id` is the root `EffectId`; for a generated child, the persisted child `EffectId` remains the distinct mutation identity while `root_effect_id` retains the enclosing-root lineage used for reconciliation. +- For the Game Session command-root and tick-ledger contract in this document, the command-root allocation identity remains the opaque `(tenantId, gameInstanceId, commandId, planOrdinal)` binding and its collision-safe runtime allocation partition remains `(tenantId, gameInstanceId)`; that command allocation scope is distinct from owner-local participant-guard uniqueness. Every ledger row retains the namespace-complete tick/recovery projection above even when the owner-declared mutation identity or allocation partition uses a narrower uniqueness key. `effect_key` remains descriptor metadata, and mutable status, reason, outcome, evidence, and timestamps remain outside identity protection. - Guard tables such as `tick_effect_guard` implement the deterministic participant projection for multi-effect operations: - - Their uniqueness identity binds root `EffectId`, typed operation, and target aggregate. The immutable request digest is bound and compared on every replay; durable outcome/evidence/reconciliation fields are mutable row state protected by CAS and are not uniqueness inputs. - - The concrete tick/ledger projection columns remain storage scope/order/lookup metadata, not an alternative guard identity. Handlers must not invent alternative idempotency keys for tick-driven effects. + - Their uniqueness identity follows the owner-declared runtime family: S1/S2 uses the `(tenantId, playableStateNamespaceId)` partition plus the mutation's persisted root-or-child `EffectId`, typed operation, and exact target aggregate; only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)` plus those identity fields. For S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence. The immutable request digest and applicable namespace binding are exact-compared on every replay; `playableStateScope`, active-instance evidence, timeline, and lineage remain immutable evidence, while durable outcome/reconciliation fields are mutable row state protected by CAS and are not uniqueness inputs. Unknown or unclassified families fail closed before guard admission and are never inferred to be S3. + - The concrete tick/ledger projection columns remain storage scope/order/lookup metadata, not an alternative guard identity. Handlers must not invent alternative idempotency keys for tick-driven effects or use enclosing-root lineage, child ordinal, `effect_key`, outcome, or evidence state as guard identity. Work explicitly outside playable-state scope must use an accepted owner-specific idempotency/partition contract; it cannot omit namespace/scope and proceed under this gameplay participant-guard contract. The ledger makes replay visible operationally via metrics such as: @@ -345,13 +357,13 @@ Responsibility for driving ledger rows to a terminal outcome lies with the Game - A background “ledger replay controller” in Game Session: - Periodically scans for `SCHEDULED` rows that have exceeded the emitted replay-convergence budget for a given `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId)`. - Replays eligible effects using the same idempotent handlers the tick pipeline uses, marking rows `APPLIED` only when durable domain evidence confirms success. - - Marks rows `ABANDONED` with a precise reason only when replay evidence proves the effect was not applied and is no longer safe or meaningful (for example, entities removed, sessions expired, or region/tenant/cluster resets that bumped `regionEpoch`); inconclusive work remains non-terminal under the original root `EffectId`, is escalated for reconciliation, and follows the applicable evidence policy. + - Marks rows `ABANDONED` with a precise reason only when authoritative owner/domain evidence proves the effect was not applied and an applicable feature rule makes it no longer safe or meaningful (for example, an entity was removed or a session expired, or a reset/epoch change invalidated the effect after that evidence); a reset or epoch change alone never proves non-application. Inconclusive work remains non-terminal under the original mutation `EffectId`, with the enclosing root retained as lineage, is escalated for reconciliation, and follows the applicable evidence policy. - Enforces bounded fairness across active complete recovery scopes so replay does not starve a smaller scope behind one hot backlog: - Scans and replays in bounded batches per complete recovery scope `` (with `tickId` and work identity retained within that scope). - Uses round-robin (or weighted-fair) scheduling across complete recovery scopes rather than draining one scope completely before touching others; fairness cursors and deficit/cost accounting are keyed by the complete recovery scope, while `scope_class` remains metrics-only selection metadata. - Emits `tick_effects_replay_scan_lag_ms{scope_class}` and `tick_effects_replay_batches_total{scope_class}` so starvation is visible without reintroducing raw tenant/game-instance/region labels to Prometheus. -- The controller also runs on service startup for each complete recovery scope to converge any lingering `SCHEDULED` rows before normal tick processing resumes; any inconclusive row instead remains reconciliation-required, is escalated, and cannot be hidden by normal startup replay. -- For incident handling, the same replay logic is exposed via coordination tooling (for example, an admin CLI or maintenance API) so operators can explicitly drive convergence for a selected complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch)` after authoritative enumeration and exact validation. Incomplete or caller-supplied namespace/scope evidence must fail closed before any replay or maintenance mutation when guided by runbooks in the Redis operations docs. +- The controller also runs on service startup for each complete recovery scope to converge any lingering `SCHEDULED` rows before normal tick processing resumes; any inconclusive row instead remains reconciliation-required, is escalated, and cannot be hidden by normal startup replay. Before startup replay mutates or reconciles a row, the owner must explicitly classify the path as non-conflicting routine idempotent replay and record that classification/evidence, or pass the exact ADR 0085 maintenance handoff; an absent or incomplete classification/handoff fails closed. +- For incident handling, the same replay logic is exposed via coordination tooling (for example, an admin CLI or maintenance API) so operators can explicitly drive convergence for a selected complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch)` after authoritative enumeration and exact validation. Incomplete or caller-supplied namespace/scope evidence must fail closed before any replay or maintenance mutation when guided by runbooks in the Redis operations docs. The incident path is a coordination-maintenance operation and must pass the exact ADR 0085 handoff before replay, reconciliation, or cleanup mutation; Redis leases and executor fences do not substitute for it. - Convergence SLO contract (required): - `SCHEDULED` rows should converge to terminal `APPLIED`/`ABANDONED` within the emitted `tick_effects_replay_convergence_budget_seconds` window when evidence permits; explicitly marked inconclusive/reconciliation-required work—including current-epoch timeout or retry-exhaustion cases—remains non-terminal and is escalated under the applicable reconciliation policy. - If oldest `SCHEDULED` age exceeds the emitted budget for a bounded scope-class rollup, incident runbooks require exact-scope enumeration and authoritative runtime-health lookup. The rollup does not itself classify or authorize a region as `DEGRADED`/`STALLED`. @@ -362,16 +374,16 @@ Before an affected region, tenant, or cluster scope reopens, recovery completely Across every epoch, an effect whose application status is inconclusive—including a current-epoch timeout or retry-exhaustion case—remains `SCHEDULED`/reconciliation-required and is escalated. Absence of a response, a deadline, control-plane health, or exhausted retry budget never proves `ABANDONED`; only durable evidence proving that no required mutation succeeded may authorize that terminal outcome. The policy below adds the authority-fenced attestation required for old-epoch reset work. -The same policy applies whenever a region-, tenant-, or cluster-scoped reset or epoch fence leaves an old-epoch effect in `SCHEDULED` and normal domain inspection cannot yet prove whether the effect was applied. Recovery must use a bounded, out-of-band attestation under the original `EffectId`; reset scope alone is never evidence for terminalization. The attestation: +The same policy applies whenever a region-, tenant-, or cluster-scoped reset or epoch fence leaves an old-epoch effect in `SCHEDULED` and normal domain inspection cannot yet prove whether the effect was applied. Recovery must use a bounded, out-of-band attestation under the original mutation `EffectId`, retaining its enclosing root as lineage and reconciliation context; reset scope alone is never evidence for terminalization. The attestation: -- retains the original concrete ledger/guard projection `(rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)`, with `typedOperation` part of the collision-safe participant identity, and exact-compares that projection against both the durable ledger row and the authoritative domain guard/state; any missing, extra, partial, or conflicting field fails closed. It also retains the maintenance/recovery fence that authorized the reset; +- retains the original concrete ledger/guard projection `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectId, rootEffectId, typedOperation, requestDigest, effectKey, targetAggregateType, targetAggregateId)`, with the persisted mutation `effectId` as the root-or-child collision identity and `rootEffectId` retained only as enclosing lineage/reconciliation context; the owner-declared runtime-family partition plus `effectId`, `typedOperation`, and exact target aggregate form the collision-safe participant identity (S1/S2 uses `tenantId + playableStateNamespaceId`; only explicit S3 uses `tenantId + gameInstanceId`). The attestation independently exact-compares the partition, typed operation, exact target aggregate, immutable request digest, and every other projection field against both the durable ledger row and authoritative domain guard/state; any missing, extra, partial, or conflicting field fails closed. It also retains the exact external maintenance `operationId`, fence/lock binding, classifier decision, evidence digest, and complete affected scope that authorized the reset; `playableStateScope` and active-instance evidence remain immutable bound evidence; - reads the authoritative domain guard/state and any existing `APPLIED` reflection without invoking current-epoch staging or replay; - records an auditable attestation outcome and retries only within the emitted replay-convergence budget; and -- permits exactly these outcomes: `APPLIED` when durable domain state or the authoritative guard proves the effect occurred; `ABANDONED` with an explicit reset/reconciliation reason only when durable state proves it was unapplied and cannot be safely re-driven; or an explicit reconciliation-required non-terminal state while the evidence remains inconclusive. +- permits exactly these outcomes: ledger `status=APPLIED` when durable domain state or the authoritative guard proves the effect occurred; ledger `status=ABANDONED` with an explicit reset/reconciliation reason only when durable state proves it was unapplied and cannot be safely re-driven; or retained ledger `status=SCHEDULED` with explicit `reconciliation_required` metadata/reason while the evidence remains inconclusive. If the bounded attestation remains inconclusive, the original effect remains non-terminal under an explicit reconciliation-required marker. It is not an `ABANDONED` outcome, is never sent through normal current-epoch replay, and blocks the affected reset scope from declaring convergence until an authority-fenced worker records a terminal decision supported by authoritative evidence. A later epoch must not reuse the old row as though it were a new current-epoch effect. -Current-epoch executors must never re-drive the old `EffectId`. Any feature that needs to carry work across the epoch boundary requires separately designed maintenance or saga/outbox tooling. A new current-epoch identity is a **post-abandon re-drive** only: the old effect and source claim must first be terminal `ABANDONED`, then the tooling allocates a later coordinate, fresh root and retry/source identity, and durable lineage. Ordinary retry/replay preserves the old root, and inconclusive work cannot be re-driven. +Current-epoch executors must never re-drive the old mutation `EffectId`. Any feature that needs to carry work across the epoch boundary requires separately designed maintenance or saga/outbox tooling. A new current-epoch identity is a **post-abandon re-drive** only: the old effect and source claim must first be terminal `ABANDONED`, then the tooling allocates a later coordinate, fresh root and retry/source identity, and durable lineage. Ordinary retry/replay preserves the old mutation identity and its enclosing root lineage, and inconclusive work cannot be re-driven. Common scenarios and invariants: @@ -379,7 +391,7 @@ Common scenarios and invariants: - Redis: `pending`, locks, timers, and retry metadata preserved for recent ticks. - PostgreSQL: all committed effects durably stored. - Invariants: no double-apply; at-most-one executor per region after lease re-acquisition. - - Action: new executor replays any surviving `pending` entries; ticks complete or are retried automatically. + - Action: new executor replays any surviving `pending` entries; ticks complete or are retried automatically. This ordinary replay may omit a maintenance operation only when the owner explicitly classifies it as non-conflicting routine idempotent replay and records the classification/evidence; a recovery skip remains limited to an explicitly disposable ADR 0058 hint or an ADR 0058 reconciliation that durably proves an empty cadence with no unresolved authoritative work. Otherwise the exact ADR 0085 handoff must be validated and persisted before replay or reconciliation, and inconclusive work remains non-terminal. - **Crash during the measured Redis unreplicated-write window** - Redis: some recent `pending`/lock/queue keys for the last ticks may be missing. - PostgreSQL: effects applied before the crash remain; very recent, in-flight effects may or may not have been applied. @@ -387,11 +399,11 @@ Common scenarios and invariants: - Action: - Metrics and dashboards surface gaps or stuck regions. - Operators treat a breached unreplicated-write SLO as a trigger to run the **ledger replay controller** (and, where appropriate, the scoped reset/reconcile flows) for affected `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch)` combinations. - - The controller applies ADR 0058 class-specific outcomes: it drives eligible durable effects and correctness-bearing timers through evidence-backed replay or terminalization, while session/lease/cache/wake-up loss remains a latency or reconnect consequence. Any inconclusive effect remains reconciliation-required and escalated; old-epoch effects additionally follow the [Inconclusive Old-Epoch Reconciliation Policy](#inconclusive-old-epoch-reconciliation-policy). The controller does **not** re-stage older ticks through normal tick-staging Lua scripts; cross-epoch reconstruction uses the explicit fresh-identity lineage path. + - The controller applies ADR 0058 class-specific outcomes: it drives eligible durable effects and correctness-bearing timers through evidence-backed replay or terminalization, while session/lease/cache/wake-up loss remains a latency or reconnect consequence. Any inconclusive effect remains reconciliation-required and escalated; old-epoch effects additionally follow the [Inconclusive Old-Epoch Reconciliation Policy](#inconclusive-old-epoch-reconciliation-policy). The controller does **not** re-stage older ticks through normal tick-staging Lua scripts; cross-epoch reconstruction uses the explicit fresh-identity lineage path. The outage-triggered replay path must carry the exact ADR 0085 handoff, unless its owner explicitly records the non-conflicting routine-replay classification/evidence; any scoped reset/reconcile flow always requires the maintenance handoff before mutation. - The same reconcile scope also converges accepted-but-unbound `ACCEPTED_VOLATILE` command records according to the [canonical command outcome contract](./system-architecture-tick-execution-flows.md#command-outcome-status-surface-required), so ingress dedupe state does not strand commands indefinitely after coordination loss. `ACCEPTED_DURABLE` records delegate to their feature-specific durable intake and safe-replay recovery contract. - **GC pause > `lock_ttl_ms` but < `lease_ttl_ms`** - Redis: locks may expire and be reacquired; `pending` remains; lease still held by original executor. - - PostgreSQL: any effects applied before the pause remain consistent; replays of the same concrete ledger/guard projection `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` retain the original root `EffectId` and are treated as no-ops by idempotent handlers. + - PostgreSQL: any effects applied before the pause remain consistent; replays of the same concrete ledger/guard projection `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectId, rootEffectId, typedOperation, requestDigest, effectKey, targetAggregateType, targetAggregateId)` retain the original mutation `EffectId` and enclosing root lineage and are treated as no-ops by idempotent handlers. Guard uniqueness follows the owner-declared runtime family (`tenantId + playableStateNamespaceId` for S1/S2, `tenantId + gameInstanceId` only for explicit S3, plus the mutation identity/operation/exact target); `playableStateScope`, active-instance evidence, and `requestDigest` are immutable bound evidence. - Invariants: no double-apply; lease ownership unchanged; at-most-one executor per region. - Action: late work that fails token checks is retried; regions with persistent over-TTL behavior may be marked degraded until configuration or workload is adjusted. - **GC pause > `lease_ttl_ms` (lease lost)** @@ -403,7 +415,7 @@ Common scenarios and invariants: - Redis: coordination keys temporarily unavailable; a tail window of recent `pending`/lock/queue state may be lost depending on failure and AOF configuration. - PostgreSQL: remains authoritative; effects committed before the outage are not rolled back. - Invariants: apply the ADR 0058 class-specific outcome. Durable commands/effects/correctness-bearing timers are replayed, reconstructed, reconciled, or evidence-terminalized from their durable records; only class-declared lossy hints may be dropped, while already-applied effects are not undone. - - Action: Game Session halts ticks/commands for affected regions, following the Redis outage policy; after Redis recovers, the recovery subsystem and operators decide whether to skip, retry, or repair missing ticks. + - Action: Game Session halts ticks/commands for affected regions, following the Redis outage policy; after Redis recovers, the owner recovery subsystem or operators may choose retry or repair for missing ticks after validating, persisting, and passing the exact ADR 0085 handoff (`operationId`, fence/lock binding, classifier decision, evidence digest, and complete affected scope) unchanged. A skip is permitted only for an explicitly disposable ADR 0058 hint or after ADR 0058 reconciliation durably proves an empty cadence with no unresolved authoritative work; otherwise recovery replays or reconciles durable work, retaining inconclusive items as non-terminal. A non-conflicting routine replay may omit that maintenance operation only when the owner explicitly records the specific classification and evidence; missing or incomplete handoff/classification fails closed and escalates. These scenarios assume the Redis persistence/profile contract described in `system-architecture-redis.md`. If AOF or replication settings differ, the same ADR 0058 class-specific outcomes and ledger replay rules still apply, but the measured coordination-exposure evidence and affected recovery scope may change. @@ -427,9 +439,9 @@ In rare cases, a `tick:{tenantRegionTag}:pending` entry may remain present even - Regions where `tick:{tenantRegionTag}:pending` has not advanced despite repeated recovery attempts. - Candidate stuck ticks are enqueued into a `tick_recovery` queue or table with metadata such as ``. The namespace identifier must be carried by the candidate or resolved from an authoritative, namespace-bound runtime record before any shadow-state lookup, cleanup, replay, or mutation; an unbound or ambiguous resolution fails closed. Metrics and Redis contents identify candidates only; they do not establish the authoritative region, namespace, epoch, or owner. - An automated recovery worker: - - Re-reads the current control-plane/runtime-health authority for the complete candidate scope and, before any recovery or cleanup mutation, revalidates the same in-memory Redis lease token it acquired and the expected candidate `regionEpoch`, then separately verifies the current durable `executorFence`. A missing, stale, or mismatched token, epoch, or authority record fails closed; the worker must not persist the raw token, clear pending state, or stage/commit work under a different owner or epoch. - - Uses the same idempotent handlers and ledger/guard patterns as normal ticks to drive any effects associated with the stuck tick to terminal `APPLIED` or `ABANDONED` outcomes only when the existing evidence policy permits; inconclusive effects remain non-terminal reconciliation work and are escalated. It reconciles any higher-level tick or command status (for example `FAILED`/`SKIPPED`) from that effect evidence into the durable authoritative status record, using its monotonic status version/CAS and preserving `failureCode`/`failureMessage`; the status record is not merely a derived view, and events/metrics remain projections of it. - - Clears `tick:{tenantRegionTag}:pending` and associated retry metadata via a dedicated, idempotent helper path. + - Re-reads the current control-plane/runtime-health authority for the complete candidate scope and, before any recovery or cleanup mutation, revalidates the same in-memory Redis lease token it acquired and the expected candidate `regionEpoch`, then separately verifies the current durable `executorFence`. It must also pass the exact ADR 0085 maintenance handoff, or have the owner explicitly classify and record this specific path as non-conflicting routine idempotent replay; that classification cannot be inferred from Redis residue. A missing, stale, or mismatched token, epoch, authority record, handoff, or classification fails closed; the worker must not persist the raw token, clear pending state, or stage/commit work under a different owner or epoch. + - Uses the same idempotent handlers and ledger/guard patterns as normal ticks to drive any effects associated with the stuck tick to terminal `APPLIED` or `ABANDONED` outcomes only when the existing evidence policy permits; inconclusive effects remain non-terminal reconciliation work and are escalated. It reconciles a higher-level command status only through the canonical command-outcome contract and supported durable `executionOutcome` values, using its monotonic status version/CAS and preserving `failureCode`/`failureMessage`. Tick-local labels such as `FAILED` or `SKIPPED` are not additional canonical `GetGameplayCommandStatus` values: they must be mapped to a supported command outcome only when the complete effect evidence and command-family policy justify that mapping; otherwise the command remains pending/reconciliation-required. The status record is authoritative, while events/metrics remain projections. + - Immediately before clearing, revalidates the selected branch: the exact ADR 0085 handoff (`operationId`, external maintenance fence/lock binding, evidence-derived classifier decision, durable-evidence digest, and complete affected scope), or the owner-recorded non-conflicting routine-replay classification/evidence with its applicable fence, epoch, and scope proof. For a maintenance handoff, every operation/fence/classifier/digest/scope field must exact-match; for routine replay, missing or mismatched classification, non-conflict evidence, fence, epoch, or scope fails closed. Any stale or regressed evidence leaves `pending` and retry metadata untouched and escalates for fenced reconciliation; only then does a dedicated idempotent helper clear `tick:{tenantRegionTag}:pending` and associated retry metadata. - Emits detailed logs and metrics for audit and dashboards. - Operator tooling allows manual override for complex cases (for example, suspected data corruption), with two typical modes: - **Recommendation mode** – the system proposes recoveries; operators approve or override. @@ -445,9 +457,9 @@ Entity Management provides the reference example for per-aggregate tick idempote ## Domain Idempotency Rules (Timeline Context + Owner Guards) -Domain services use the **region-scoped tick timeline** `(regionEpoch, tickId)` as ordering and fence context, not as the canonical idempotency token for tick-driven effects. The canonical participant guard logical uniqueness is exactly `(rootEffectId, typedOperation, exact target aggregate)`; the immutable request digest is bound to that identity. If an owner-local physical partition is used, it is storage placement only and cannot alter logical uniqueness or deduplication. A guard must not substitute the timeline tuple for that root/operation/aggregate identity. +Domain services use the **region-scoped tick timeline** `(regionEpoch, tickId)` as ordering and fence context, not as the canonical idempotency token for tick-driven effects. The canonical participant guard logical uniqueness is the owner-declared runtime-family partition plus `(effectId, typedOperation, exact target aggregate)`, where `effectId` is the persisted root `EffectId` for a root operation and the persisted child `EffectId` for a generated child; S1/S2 uses `(tenantId, playableStateNamespaceId)`, while only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)`, and unknown or unclassified families fail closed. `rootEffectId` is retained only as enclosing-root lineage and reconciliation context. The immutable request digest is bound to that identity. Additional physical partitioning used only for storage placement cannot alter this logical identity or deduplication. A narrow last-tick watermark is permitted only for an explicitly documented aggregate proven to receive at most one logical mutation per tick timeline; it must not replace the effect/participant guard for general command effects. Any applicable namespace binding is validated separately from timeline ordering and fence evidence, and a guard must not substitute the timeline tuple for the root/operation/aggregate identity. Exact allocator details remain pending and non-authoritative under the conditional [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); they do not change this accepted guard contract. -`tickId` is monotonic only **within a given `regionEpoch`** and may restart at `0` after a region-scoped or tenant-scoped reset that bumps `regionEpoch`. Any idempotency scheme that keys only on `tickId` (without `regionEpoch`) is therefore unsafe across resets. +`tickId` is monotonic only **within a given `regionEpoch`** and may restart at `0` after a region-scoped or tenant-scoped reset that bumps `regionEpoch`. Any ordering or watermark scheme that keys only on `tickId` (without `regionEpoch`) is therefore unsafe across resets; the timeline pair still does not replace the effect/participant guard. Two patterns are used: @@ -468,8 +480,9 @@ Two patterns are used: - **Operation-level effect guard** - This is the default pattern for gameplay-visible mutations. - Operations that may touch multiple aggregates or legitimately apply multiple distinct effects to the same aggregate in a single tick (for example trades, combat damage, healing, AoE damage, room occupancy changes, drops/pickups, or multi-target buffs) use a small guard table such as `tick_effect_guard` with a concrete participant projection storing: - - The uniqueness identity is the root `EffectId`, typed operation, and exact target aggregate. The immutable request digest is bound to that identity and checked on replay; the durable outcome is mutable guard-row state advanced by CAS. The concrete fields below are retained as the participant projection for scope, ordering, and target lookup and must not be mistaken for an alternative uniqueness identity. - - `root_effect_id` + - The uniqueness identity follows the owner-declared runtime family: S1/S2 uses the `(tenantId, playableStateNamespaceId)` partition, while only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)`; each partition also includes the mutation's persisted root-or-child `EffectId`, typed operation, and exact target aggregate. A root mutation uses the root `EffectId`; a generated child uses its persisted child `EffectId` while retaining the enclosing root as lineage and reconciliation context. For S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence. The immutable request digest and applicable namespace binding are bound evidence exact-compared on replay; `playableStateScope`, active-instance evidence, timeline, and lineage remain immutable projection evidence, and durable outcome/evidence is mutable guard-row state advanced by CAS. The concrete fields below are retained as the participant projection for scope, ordering, and target lookup and must not be mistaken for an alternative uniqueness identity. Unknown or unclassified families fail closed before guard admission and are never inferred to be S3. + - `effect_id` (the persisted mutation `EffectId` used by guard uniqueness) + - `root_effect_id` (enclosing root lineage and reconciliation context) - `typed_operation` - `tenant_id` - `game_instance_id` @@ -479,46 +492,47 @@ Two patterns are used: - `region_epoch` - `tick_id` - `effect_key` – a deterministic identifier describing the logical effect (for example `entity::award:achievement:` or `room::drop:item:`). + - `request_digest` – immutable request digest bound to the participant guard and compared on replay, not a uniqueness input. - `target_aggregate_type` - `target_aggregate_id` - - Inside the same transaction as the domain update, the handler attempts to insert a participant guard whose uniqueness identity is exactly `(root EffectId, typed operation, target aggregate type, target aggregate ID)`, binding the immutable request digest and storing the namespace-complete concrete projection `(root_effect_id, typed_operation, tenant_id, game_instance_id, playable_state_namespace_id, playable_state_scope, region_id, region_epoch, tick_id, effect_key, target_aggregate_type, target_aggregate_id)` as scope/order/ledger metadata. Replay and exact-set comparisons must compare the namespace as well as the scope; an implementation may omit a separate projection column only when the root/target guard is an authoritative, exact namespace-bound proof that is enforced by the owner transaction: + - Inside the same transaction as the domain update, the handler attempts to insert a participant guard whose collision-safe uniqueness identity follows the owner-declared runtime family: `(tenantId, playableStateNamespaceId, mutation EffectId, typed operation, target aggregate type, target aggregate ID)` for S1/S2, or `(tenantId, gameInstanceId, mutation EffectId, typed operation, target aggregate type, target aggregate ID)` only for explicit S3. `tenantId` and `playableStateNamespaceId` partition namespace-backed S1/S2 guards, while `tenantId` and `gameInstanceId` partition explicitly disposable S3 guards; for S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence. `playableStateScope`, timeline, digest, and lineage fields are immutable bound evidence, not additional uniqueness inputs. The guard binds the immutable request digest and stores the namespace-complete concrete projection `(effect_id, root_effect_id, typed_operation, tenant_id, game_instance_id, playable_state_namespace_id, playable_state_scope, region_id, region_epoch, tick_id, effect_key, target_aggregate_type, target_aggregate_id)` as scope/order/ledger metadata. For a generated child, `root_effect_id` is retained as enclosing lineage/reconciliation context and is not substituted for `effect_id`. Unknown or unclassified families, or work explicitly outside playable-state scope without an accepted owner-specific partition, are rejected before this insert. - If the insert succeeds, the effect is new for this participant identity and the handler applies all associated state changes, advancing mutable outcome state by CAS as required. - - If the uniqueness identity conflicts, the handler compares the stored namespace, typed operation, exact target aggregate, and immutable request digest. An exact existing guard replay returns its stored outcome without reapplying domain state; any changed namespace, operation, target, or digest fails closed. It must also verify the complete expected participant-guard set and corresponding authoritative state. Only a complete, consistent set is a replay/no-op; a partial conflict is incomplete and must reconcile the original root `EffectId` or fail closed. - - A replay at a later coordinate that retains the same root `EffectId`, typed operation, namespace, and target aggregate therefore reuses/conflicts with the same guard; `region_epoch`, `tick_id`, and `effect_key` metadata cannot create a second participant guard. + - If the uniqueness identity conflicts, the handler compares the stored owner-declared runtime-family partition, typed operation, exact target aggregate, immutable request digest, applicable `playableStateNamespaceId` binding, separately bound `playableStateScope` evidence, and separately validated active-instance authorization/fence evidence. An exact existing guard replay returns its stored outcome without reapplying domain state; any changed family/partition, operation, target, digest, namespace, scope, or active-instance evidence fails closed. It must also verify the complete expected participant-guard set and corresponding authoritative state. Only a complete, consistent set is a replay/no-op; a partial conflict is incomplete and must reconcile the original mutation `EffectId` and enclosing root lineage or fail closed. + - A replay attempted later in physical time with the same mutation `EffectId`, typed operation, and target aggregate reuses the same guard only when it carries and exactly matches the original sealed runtime-family partition and namespace-complete timeline projection, including the bound namespace where applicable, separately bound `playableStateScope`, active-instance authorization/fence evidence, `region_epoch`, and `tick_id`. A request with changed coordinates or a changed active-instance fence is conflicting reuse and fails closed; neither changed coordinates nor `effect_key`, enclosing-root lineage, or mutable outcome/evidence state can create a second participant guard or overwrite the original projection. Examples: - **Once-per-tick aggregate watermark (per-aggregate last-tick state)** - `AdvanceRegionAuraWatermark` receives `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, targetAggregateType, targetAggregateId)`. - The design guarantees this aggregate is advanced at most once per tick. - - It reads the shadow tick state for the complete `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, targetAggregateType, targetAggregateId)` key, exact-validating separately persisted `playableStateScope` evidence, and applies the update only when `(last_region_epoch, last_tick_id) < (regionEpoch, tickId)`. + - It reads the shadow tick state for `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, targetAggregateType, targetAggregateId)`, exact-validating separately persisted `playableStateScope` evidence, and applies the update only when `(last_region_epoch, last_tick_id) < (regionEpoch, tickId)`. - If `(last_region_epoch, last_tick_id) >= (regionEpoch, tickId)`, the handler treats the request as a replay/out-of-order and returns without changing state. - **Trade between two entities (operation-level effect guard)** - - The `TradeItem` endpoint explicitly receives `rootEffectId` and immutable `requestDigest` in addition to `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, fromEntityId, toEntityId, itemId)`. It creates one participant guard/ledger projection linked to that root effect per affected inventory aggregate. + - The `TradeItem` endpoint explicitly receives `rootEffectId` (the mutation `EffectId` for this root operation) and immutable `requestDigest` in addition to `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, fromEntityId, toEntityId, itemId)`. It creates one participant guard/ledger projection linked to that mutation/root effect per affected inventory aggregate. - The typed operation is `TradeItem`; it computes `effectKey = "trade:" + fromEntityId + ":" + toEntityId + ":" + itemId` only as stored projection/ledger metadata, not as guard uniqueness identity. - In one transaction it: - - Attempts to insert one guard per affected inventory aggregate with uniqueness identity `(rootEffectId, typed operation=TradeItem, targetAggregateType=INVENTORY, targetAggregateId)`, binding and comparing `requestDigest` and retaining `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey)` as namespace-complete projection/ledger metadata. - - If any uniqueness identity conflicts, it re-reads the complete expected guard set and the authoritative state of both source and target inventories. Only a complete guard set whose root effect, typed operation, target aggregates, immutable `requestDigest`, and inventory state all match the committed transfer is a replay/no-op; a partial conflict, missing guard, or mismatch must reconcile the original root effect or fail closed. `effectKey` is never used to admit a replay. + - Attempts to insert one guard per affected inventory aggregate with the namespace-backed S1/S2 inventory uniqueness identity `(tenantId, playableStateNamespaceId, mutation EffectId=rootEffectId, typed operation=TradeItem, targetAggregateType=INVENTORY, targetAggregateId)`. Inventory is durable player value and therefore remains namespace-stable, with any S2 version mapping validated and applied by its owner; it is not an S3 disposable family. The guard binds and exact-compares `requestDigest`, separately validates active `gameInstanceId` authorization/fence evidence, and retains `playableStateScope`, `regionId`, `regionEpoch`, `tickId`, and `effectKey` as exact-bound projection/ledger evidence, not additional uniqueness dimensions. + - If any uniqueness identity conflicts, it re-reads the complete expected guard set and the authoritative state of both source and target inventories. Only a complete guard set whose mutation/root effect, typed operation, target aggregates, immutable `requestDigest`, and inventory state all match the committed transfer is a replay/no-op; a partial conflict, missing guard, or mismatch must reconcile the original mutation/root effect or fail closed. `effectKey` is never used to admit a replay. - If the insert succeeds, it debits the item from `fromEntityId`, credits it to `toEntityId`, and commits both inventory changes and the guard-row insert together. Operationally: -- Every tick-driven write path must use either the per-aggregate `last_tick_id` pattern or the operation-level guard pattern. -- The default review assumption is that a gameplay-visible mutation requires an effect guard unless the design explicitly proves “at most one logical effect per aggregate per tick”. +- Every tick-driven write path must use the operation-level guard pattern by default; the per-aggregate `last_tick_id` pattern is allowed only with an explicit proof of at-most-one logical mutation per tick timeline. +- The default review assumption is that a gameplay-visible mutation requires an effect guard unless the design explicitly proves “at most one logical effect per aggregate per tick”; that proof must not be inferred from `(regionEpoch, tickId)` alone. - Domain handlers treat Redis locks and leases as opaque; they never read `tick:{tenantRegionTag}:lock:` or `tick-executor-lease:{tenantRegionTag}` directly. - Operations that cannot be made idempotent or compensatable at the domain layer—for example payments, emails, or webhooks into third-party systems—must not be executed directly inside tick-driven handlers. Those flows must use the saga/outbox patterns in `system-architecture-transactions.md` so they can tolerate retries and partial failures independently of tick replay. ### Effect Identity, Endpoint Semantics, and Outcome Metrics -Tick-driven domain calls use the stable root `EffectId` plus a shared participant guard contract for retries: +Tick-driven domain calls use the mutation's persisted root-or-child `EffectId` plus a shared participant guard contract for retries: -- Game Session assigns the stable root `EffectId` for the logical effect. A concrete ledger/guard/storage projection must carry the namespace-complete identity and tick context `(rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` for scope, ordering, and exact target lookup, unless the owner transaction enforces an equivalent namespace-bound root/target proof. It remains linked to the root identity. Each participant derives its guard uniqueness identity from the root `EffectId`, typed operation, and exact target aggregate, binding the immutable request digest; durable outcome/evidence state is mutable guard-row state protected by CAS. Additional operation-specific distinctions belong in that typed operation/target/request-digest contract; they must not create a competing root identity. -- Game Session passes the same opaque root `EffectId` plus the structured operation, target, request digest, and any concrete ledger projection fields to each tick-invoked handler. Handlers validate and project that contract into their own guards; they must not generate fresh random IDs, re-derive from mutable payload, or silently drop required scope or target fields. +- For command-root work, Game Session assigns the opaque root `EffectId` from the durable command row's `(tenantId, gameInstanceId, commandId, planOrdinal)` allocation binding, which also validates the frozen request fingerprint/runtime scope, applicable `playableStateNamespaceId`, and ordered plan manifest digest. Passive, inbound/remote, timer, retry, and already-generated work retain their owner/source-specific root identity unless they materialize as an admitted command. A generated child uses its persisted deterministic child `EffectId` under the owning child contract and does not create another command-plan root or allocator. A concrete ledger/guard/storage projection must carry the namespace-complete applicable mutation identity and tick context `(effectId, rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` for scope, ordering, and exact target lookup; generated children retain `rootEffectId` as lineage and reconciliation context. The command-root/tick-ledger allocation binding remains distinct from participant-guard uniqueness: each participant derives its guard identity from the owner-declared runtime-family partition—`(tenantId, playableStateNamespaceId)` for S1/S2 or `(tenantId, gameInstanceId)` only for explicit S3—plus the mutation's persisted root-or-child `EffectId`, typed operation, and exact target aggregate, binding the immutable request digest and applicable namespace evidence. For S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence; durable outcome/evidence state is mutable guard-row state protected by CAS. Unknown or unclassified families, and work explicitly outside playable-state scope without an accepted owner-specific partition, fail closed before guard admission. Additional operation-specific distinctions belong in that typed operation/target/request-digest contract; they must not create a competing root identity. The exact allocator and versioned fan-out binding remain conditional on the non-authoritative [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +- Game Session passes the mutation's persisted root-or-child `EffectId` plus the structured operation, target, immutable request digest, and any concrete ledger projection fields to each tick-invoked handler. Generated children also carry their enclosing root/parent lineage binding. Handlers validate and project that contract into their own guards; they must not generate fresh random IDs, re-derive from mutable payload, or silently drop required scope or target fields. Every gRPC endpoint that can be invoked from tick execution must document and implement: - **Duplicate handling** – repeated calls with the same effect identity must return OK / “already applied” semantics (for example, no new HP or inventory changes) instead of logical errors that drive infinite retries. -- **Already-in-desired-state handling** – if the target state already reflects the intended outcome, the endpoint first resolves the participant guard in the owner transaction. An exact existing guard with the same root `EffectId`, typed operation, exact target aggregate, and immutable `requestDigest` returns its stored outcome; when no matching guard exists, the owner records a new durable guarded no-op under the current root `EffectId`, typed operation, exact target, and `requestDigest` before returning OK. Mutable state already matching the requested value is not replay evidence by itself, and a conflicting or ambiguous guard fails closed. + - **Already-in-desired-state handling** – if the target state already reflects the intended outcome, the endpoint first resolves the participant guard in the owner transaction. An exact existing guard with the same owner-declared runtime-family partition (S1/S2 `(tenantId, playableStateNamespaceId)` or explicit S3 `(tenantId, gameInstanceId)`), mutation `EffectId` (root or persisted child), typed operation, exact target aggregate, immutable `requestDigest`, separately persisted `playableStateScope`, and separately exact-validated active-instance fence evidence returns its stored outcome; unknown or unclassified families, or work explicitly outside playable-state scope without an accepted owner-specific partition, are rejected before guard admission. When no matching guard exists, the owner records a new durable guarded no-op under the same conditional partition and exact evidence before returning OK. A generated child also retains its enclosing root as lineage and reconciliation context. Mutable state already matching the requested value is not replay evidence by itself, and a conflicting or ambiguous guard fails closed. - **Retry classification** – errors must be classified as retryable (transient infrastructure issues) vs terminal (invalid inputs, missing aggregates). Terminal errors may move the corresponding ledger/guard entry into a terminal state (for example `ABANDONED`) only when the error and durable evidence prove that no required mutation succeeded; inconclusive work remains reconciliation-required rather than entering a retry loop or being bulk-terminalized. Endpoints participating in tick-driven effects should also emit a small, standardized metric: @@ -571,7 +585,7 @@ Coordination resets are expressed in terms of Redis scopes (region, tenant, clus - Timeline impact: - A tenant reset is an orchestration over every running or recoverable `gameInstanceId` belonging to the tenant, not a single tenant-only key scan or epoch. The reset first snapshots the authoritative game-instance inventory and mapping generation under the reset lease, then enumerates every `` pair and reads each region's current `regionEpoch` and executor fence. - For every enumerated game instance and every one of its regions, the region-scoped coordination keys are cleared and that instance-region's `regionEpoch` is bumped independently. A changed mapping generation, missing instance/region, lost lease, or fence mismatch fails closed before the next mutation; it must not reset only the regions visible in Redis. - - Cross-region flows (for example follow-ups) resume only under the new epochs; stale follow-ups from previous epochs are ignored or reconciled. + - Cross-region flows (for example follow-ups) resume only under the new epochs; stale follow-ups from previous epochs are reconciled under the [Inconclusive Old-Epoch Reconciliation Policy](#inconclusive-old-epoch-reconciliation-policy), never ignored, and remain `APPLIED`, evidence-qualified `ABANDONED`, or fenced non-terminal `SCHEDULED` according to that policy. - Gameplay session records follow the canonical reset-policy matrix in [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md), while `sessionctx:*` pre-auth context is always invalidated or rebuilt and is never preserved. A tenant reset does not perform account-wide token invalidation. Preserved gameplay sessions must rebind after auth validation. - Ledger behavior: - Tick effect ledger rows for each enumerated instance-region scope with `status = SCHEDULED` follow the [Inconclusive Old-Epoch Reconciliation Policy](#inconclusive-old-epoch-reconciliation-policy): inspect durable domain state and any existing `APPLIED` reflection first, mark confirmed reflections `APPLIED`, and mark `ABANDONED` with a tenant-scoped reset reason such as `RESET_TENANT_SCOPED` only when domain state confirms the effect was unapplied and cannot be safely re-driven across the reset. @@ -596,8 +610,8 @@ Coordination resets are expressed in terms of Redis scopes (region, tenant, clus In all three cases, the **goal is convergence**: -- For each complete expected concrete participant-projection set linked to a root `EffectId`, every expected `(rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, targetAggregateType, targetAggregateId)` projection must eventually have exactly one terminal ledger state (`APPLIED` or `ABANDONED`) when the evidence policy permits terminalization. `typedOperation` is part of the expected set alongside the root and exact target aggregate; `effectKey` remains descriptor metadata for correlation and lookup. Reconciliation rejects missing, extra, partial, or conflicting projections; any inconclusive row remains reconciliation-required and non-terminal, with old-epoch rows additionally following the [Inconclusive Old-Epoch Reconciliation Policy](#inconclusive-old-epoch-reconciliation-policy), including across resets. -- Reset tooling and Game Session control flows must ensure that no tick remains forever “half-applied” in the ledger (for example, perpetually `SCHEDULED` with no chance of replay), by running a per-effect tick-effect-ledger reconcile for the relevant `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch)` combinations as part of the reset flow. The reconcile must inspect durable domain state before terminalizing each row and may abandon only effects confirmed unapplied. +- For each complete expected concrete participant-projection set linked to an enclosing root `EffectId`, every expected `(effectId, rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, targetAggregateType, targetAggregateId)` projection must eventually have exactly one terminal ledger state (`APPLIED` or `ABANDONED`) when the evidence policy permits terminalization. `effectId` is the mutation's persisted root-or-child `EffectId`; `rootEffectId` remains enclosing lineage and reconciliation context. `typedOperation` is part of the expected set alongside the mutation ID and exact target aggregate; guard uniqueness follows the owner-declared runtime-family partition (`tenantId + playableStateNamespaceId` for S1/S2, `tenantId + gameInstanceId` only for explicit S3), while `playableStateScope`, active-instance evidence, and `effectKey` remain immutable projection/descriptor evidence rather than additional uniqueness dimensions. Reconciliation rejects missing, extra, partial, or conflicting projections; any inconclusive row remains reconciliation-required and non-terminal, with old-epoch rows additionally following the [Inconclusive Old-Epoch Reconciliation Policy](#inconclusive-old-epoch-reconciliation-policy), including across resets. +- Reset tooling and Game Session control flows must ensure that no tick remains forever “half-applied” in the ledger (for example, perpetually `SCHEDULED` with no chance of replay), by running a per-effect tick-effect-ledger reconcile for the relevant `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch)` combinations as part of the reset flow. The reconcile must inspect durable domain state before terminalizing each row and may abandon only effects confirmed unapplied; inconclusive effects remain `SCHEDULED`/reconciliation-required, and reset reconciliation must neither force nor require their terminalization without that evidence. These expectations should be reflected in the coordination reset tooling described in `system-architecture-redis-operations.md` and the reset policy matrix in `system-architecture-redis-reset-and-recovery.md`. @@ -605,11 +619,11 @@ These expectations should be reflected in the coordination reset tooling describ Cross-region tick-driven flows (such as combat actions that affect entities in multiple regions) are designed to be **best-effort and eventually consistent** by default rather than globally atomic across regions: -- Each leg of a cross-region flow (origin-region effects, target-region effects, and any results relayed back) uses its own `EffectId` and converges independently to `APPLIED` or `ABANDONED` in the tick effect ledger only when the existing evidence policy permits terminalization; inconclusive work remains non-terminal reconciliation work under its original root `EffectId` and is escalated, with old-epoch work additionally following the applicable reset policy. +- Each leg of a cross-region flow (origin-region effects, target-region effects, and any results relayed back) uses its own persisted mutation `EffectId` and converges independently to `APPLIED` or `ABANDONED` in the tick effect ledger only when the existing evidence policy permits terminalization; inconclusive work remains non-terminal reconciliation work under its original mutation `EffectId`, with its enclosing root retained as lineage, and is escalated, with old-epoch work additionally following the applicable reset policy. - Origin regions derive a high-level **command outcome** (for example `SUCCESS`, `PARTIAL`, `FAILED`) from the combination of leg outcomes and timeouts only under the command family’s ADR 0053 declaration. `PARTIAL` is valid only for a permitted terminal subset declared before execution; unresolved required work remains `PENDING`, and a timeout or multi-leg failure does not silently become an undeclared `PARTIAL`. - Features that truly require “all-or-nothing across regions” semantics must build that coordination explicitly on top of the tick primitives (for example using saga/outbox patterns outside the tick loop as described in `system-architecture-transactions.md`); it is not provided implicitly by the tick engine. -When origin reconciliation accepts a target result that drives a dependent child effect (for example, remote lifesteal damage driving a local heal), the acceptance transition is crash-safe: it cannot become durable without a deterministic child-effect intent. The accepted result and child intent commit in one owner-local transaction when possible, or a resumable durable acceptance intent records both before acceptance is acknowledged. Acceptance replay reuses the child identity and exact accepted-result digest; missing, extra, partial, or conflicting result/intent projections fail closed. This is a durability consequence of the existing coordinator lifecycle, not a new outcome. +When origin reconciliation accepts a target result that drives a dependent child effect (for example, remote lifesteal damage driving a local heal), the acceptance transition is crash-safe: it cannot become durable without a deterministic child-effect intent. The accepted result and child intent commit in one owner-local transaction when possible, or a resumable durable acceptance intent records both before acceptance is acknowledged. Acceptance replay reuses the child identity and exact accepted-result digest; missing, extra, partial, or conflicting result/intent projections fail closed. This is a durability consequence of the existing coordinator lifecycle, not a new outcome. Any future opaque allocation shape remains conditional on the non-authoritative [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Operationally: @@ -628,7 +642,7 @@ Region resets and epoch bumps intentionally sever the old coordination timeline - When a target region’s `regionEpoch` is bumped (via region/tenant/cluster reset): - Recovery first completely enumerates every undrained follow-up and `SCHEDULED` ledger row for the old epoch from durable storage. Conclusive rows terminalize as `APPLIED` or `ABANDONED` with a reset/topology reason under the authority-fenced policy; an inconclusive row keeps the scope fenced and cannot be hidden by Redis loss or omitted from the enumeration. - The ledger replay controller applies the [Inconclusive Old-Epoch Reconciliation Policy](#inconclusive-old-epoch-reconciliation-policy): it marks confirmed reflections `APPLIED`, converges only effects confirmed unapplied to `ABANDONED` with a reset-specific reason (for example `RESET_REGION_SCOPED` or `RESET_TENANT_SCOPED`), and keeps inconclusive effects non-terminal under their original EffectId for authority-fenced reconciliation rather than attempting to “replay them into the new epoch”. Normal current-epoch replay is forbidden. - - Target-region tick executors ignore old-epoch work based on epoch/tick guards in their coordination scripts; they only stage and apply effects for the current epoch. + - Target-region tick executors reject old-epoch work as non-executable based on epoch/tick guards in their coordination scripts; they only stage and apply effects for the current epoch. That rejection is not a terminal outcome or a disposable “ignored” observation: the durable follow-up/ledger identity remains enumerated and must reconcile to ledger `status=APPLIED`, evidence-qualified ledger `status=ABANDONED`, or retained ledger `status=SCHEDULED` with explicit `reconciliation_required` metadata/reason and its scope fenced. An ambiguous or missing execution response therefore cannot strand the follow-up behind an `ignored` label or make it eligible in the new epoch. - Origin regions: - Observe evidence-backed `ABANDONED` outcomes for remote legs and compute the appropriate high-level command outcome only when the command family declared that terminal combination before execution; unresolved required work, including timeouts without authoritative non-application evidence, remains `PENDING`/reconciliation-required rather than becoming `PARTIAL`. - Surface player-facing feedback consistent with that outcome (for example “your cross-region trade failed due to region reset; your currency has been refunded”). @@ -645,7 +659,7 @@ Cross-region follow-ups are durable PostgreSQL records owned by Game Session (or - `tenant_id`, `target_game_instance_id`, `target_playable_state_namespace_id`, resolved `target_playable_state_scope`, `target_region_id`, `target_region_epoch` - `due_tick_id` in the target region timeline (preferred; do not use wall-clock due-time fields for cross-region follow-up eligibility) - `origin_effect_id` for the originating leg and a distinct `target_effect_id` for the target leg, plus the target-leg `typed_operation`, `effect_key` (stable descriptor/correlation metadata only), `target_aggregate_type`, and `target_aggregate_id`. - - An immutable `request_digest` and sealed required-participant manifest (or immutable manifest reference plus digest) are persisted as binding/comparison evidence. Target admission and replay compare the exact operation, target, digest, and manifest binding; any missing, conflicting, or mismatched value fails closed. + - An immutable `request_digest` and sealed required-participant manifest (or immutable manifest reference plus digest) are persisted as binding/comparison evidence. Target admission and replay compare the exact operation, target, namespace, separately persisted `playable_state_scope`, digest, and manifest binding; any missing, conflicting, or mismatched value fails closed. - exact target identity plus required feature preconditions for ownership, location, and aggregate version. Target execution requires those preconditions to remain valid under current authoritative state and executor fence; matching `target_region_epoch` and `due_tick_id` alone are insufficient. - `due_tick_id` is computed from the authoritative region status read, not from Redis hint keys. Current live uses `GetRuntimeOwnershipStatus` and its committed region/epoch/tick fields; target state uses `GetRegionTickStatus` / `RegionStatus.lastCommittedTickId`. The target owner compare-and-set persists and exact-compares this coordinate with the target epoch when admitting/claiming the follow-up; retries and replays reuse it, but it is not part of stable follow-up uniqueness: - Canonical baseline: `due_tick_id = target_last_committed_tick_id + delta_ticks` (for immediate eligibility, `delta_ticks = 1`). @@ -662,11 +676,11 @@ Cross-region follow-ups are durable PostgreSQL records owned by Game Session (or - Origin-side reconciliation claims that row idempotently and advances the coordinator only after the correlation matches the durable coordinator record. A transient message, target-only `gameInstanceId`, or mutable command payload is not sufficient correlation. - **Topology changes** - Mapping-changing split/merge operations must bump `regionEpoch` for affected source/target regions before follow-up draining resumes (see required topology protocol in `system-architecture-ticks.md`). - - **Target-state rollover invariant:** If a topology change needs a new target leg, the old follow-up identity and the new identity must be handled atomically: one durable transaction creates and links the new target record, then marks the old identity `ABANDONED` only after that new record is durable and the existing per-effect evidence policy permits terminalization. If the records cannot share a transaction, persist a fenced durable rollover intent containing both identities, the desired mapping, and the sealed follow-up context; recovery retries that intent until the new record and link are durable before terminalizing the old identity, while inconclusive old-epoch work remains non-terminal under its original root `EffectId`. + - **Target-state rollover invariant:** If a topology change needs a new target leg, the old follow-up identity and the new identity must be handled atomically: one durable transaction creates and links the new target record, then marks the old identity `ABANDONED` only after that new record is durable and the existing per-effect evidence policy permits terminalization. If the records cannot share a transaction, persist a fenced durable rollover intent containing both identities, the desired mapping, and the sealed follow-up context; recovery retries that intent until the new record and link are durable before terminalizing the old identity, while inconclusive old-epoch work remains non-terminal under its original mutation `EffectId`, with its enclosing root retained as lineage and reconciliation context. - **Current drift:** The current cross-region follow-up path has durable rows and epoch/mapping checks but does not yet claim this atomic or recoverable rollover boundary. Until it is implemented and proven, topology tooling must remain paused/fenced and must not mark an old identity `ABANDONED` merely because its mapping changed. - If region split/merge changes which region owns the target entity, topology-change tooling must either: - Complete the atomic or durable-intent rollover above, creating a new target-leg/follow-up identity for the new `(target_game_instance_id, target_region_id, target_region_epoch)` before marking the old identity `ABANDONED` with a topology-change reason only where the existing per-effect evidence policy permits. The new record must carry a fresh `target_effect_id`, the typed operation, its sealed manifest and immutable request digest, and a new `due_tick_id`, linked to the old identity by durable correlation; updating only the target instance, region, or epoch on the old record is forbidden. - - Mark it `ABANDONED` with a topology-change reason only when the existing evidence policy proves replaying it under the new mapping is not valid and no required mutation succeeded; otherwise retain the old identity as non-terminal reconciliation work under its original root `EffectId`. + - Mark it `ABANDONED` with a topology-change reason only when the existing evidence policy proves replaying it under the new mapping is not valid and no required mutation succeeded; otherwise retain the old identity as non-terminal reconciliation work under its original mutation `EffectId`, with its enclosing root retained as lineage and reconciliation context. ## Remote Hint Markers and Resets @@ -690,10 +704,13 @@ When debugging cross-region issues, operators should rely on PostgreSQL follow-u Because crash recovery relies on idempotent handlers, each service with tick-driven logic should include integration tests that simulate Redis-style replays: -- Invoke the same handler multiple times with the same root `EffectId`, typed operation, target, immutable request digest, concrete ledger/guard projection `(rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)`, and payload, and assert that: +Select validation commands and assign evidence ownership according to [Validation and Runtime Proof](../developer-workflows/validation-and-runtime-proof.md); this checklist does not add validation results or a validation ledger. + +- Invoke the same handler multiple times with the same mutation `EffectId` (root or persisted child), typed operation, target, immutable request digest, enclosing root lineage where applicable, concrete ledger/guard projection `(effectId, rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)`, and payload, and assert that: - The first call mutates state as expected. - Subsequent calls are treated as replays and do not apply additional logical effects (HP changes, inventory moves, etc.). -- Repeat the same `effectKey` against a different `targetAggregateType` or `targetAggregateId` and assert that the distinct target is not incorrectly deduplicated. For script-generated fan-out effects, vary `automationDispatchId` and, as applicable, the root `EffectId`, typed operation, and target aggregate to create distinct logical identities; `effectKey` is projection/storage metadata, never guard uniqueness. A request-digest mismatch for the same guard identity must fail closed. +- Repeat the same `effectKey` against a different `targetAggregateType` or `targetAggregateId` and assert that the distinct target is not incorrectly deduplicated. For script-generated fan-out effects, vary `commandOrdinal` under one `automationDispatchId` and assert distinct logical identities, then replay the same dispatch/ordinal pair and assert stable deduplication; also vary, as applicable, the persisted root-or-child `EffectId`, enclosing root lineage, typed operation, and target aggregate. `effectKey` is projection/storage metadata, never guard uniqueness, and a request-digest mismatch for the same guard or dispatch/ordinal identity must fail closed. +- Exercise deterministic command-plan admission with zero, one, and multiple roots: assert that semantic order comes from the frozen typed command/action contract or `ResolvedEffectPlan`, built-ins declare equivalent stable order, ambiguous/duplicate order fails before admission, and the ordered plan manifest/digest plus opaque `(tenantId, gameInstanceId, commandId, planOrdinal)` allocation binding persist in the local plan/staging transaction and reuse only when the command row identity, frozen request/runtime/namespace binding, ordinal, and manifest digest match. Assert no root allocation for zero effects, and that random batch IDs, mutable text, effect keys, source ordering, participant tuples, Trigger Identity/`scriptEventId`, and generated child ordinals cannot substitute for the durable command row identity. Exercise Automation handoff admission exact-mapping to one durable target `commandId`, and exercise passive, inbound/remote, timer, retry, and already-generated work through their existing owner/source-specific root identities rather than synthesizing a command plan unless materialized as an admitted command. - Exercise both idempotency strategies: - Per-aggregate `last_tick_id` tables (for single-entity updates). - Operation-level `tick_effect_guard` tables (for multi-entity effects). @@ -715,8 +732,9 @@ When introducing a new command type that will run under tick control, design doc - Does it run because an entry is dequeued from `tick:{tenantRegionTag}:queue:` or because a tick timer/retry fired? - If not, it may follow different idempotency rules and does not belong in this section. - **What is the idempotency key?** - - For single-aggregate updates: which complete `(tenant_id, game_instance_id, playable_state_namespace_id, region_id, target_aggregate_type, aggregate_id)` key, separately validated `playable_state_scope` evidence, and `(last_region_epoch, last_tick_id)` (or equivalent) fields and table enforce “at most one update per tick timeline” for that aggregate? - - For multi-aggregate or multi-effect operations: what participant guard identity combines the root `EffectId`, typed operation, and target aggregate, and how is the immutable request digest bound and checked? `effect_key` is a concrete storage projection/descriptor, not a replacement for that guard identity. + - Which frozen typed command/action contract or `ResolvedEffectPlan` supplies semantic order for the command's logical root effects, and how does it reject ambiguous/duplicate order before admission, persist the ordered manifest/digest, and allocate an opaque binding unique on `(tenantId, gameInstanceId, commandId, planOrdinal)` only after the durable command row freezes/binds its request fingerprint, resolved runtime scope, and applicable `playableStateNamespaceId`? Reuse must validate the same command row identity, frozen binding, ordinal, and manifest digest; any mismatch fails closed. A zero-effect command must allocate neither. Source ordering remains separate, and non-command-root work retains its owner/source-specific identity. + - For single-aggregate updates: which `(tenant_id, game_instance_id, playable_state_namespace_id, region_id, target_aggregate_type, aggregate_id)` key plus separately exact-validated `playable_state_scope` evidence and `(last_region_epoch, last_tick_id)` (or equivalent) fields and table enforce “at most one update per tick timeline” for that aggregate? + - For multi-aggregate or multi-effect operations: what participant guard identity combines the mutation's persisted root-or-child `EffectId`, typed operation, and exact target aggregate, and how is the immutable request digest bound and checked? A generated child retains its enclosing root as lineage and reconciliation context; `effect_key` is a concrete storage projection/descriptor, not a replacement for that guard identity. - **Where is the guard persisted?** - Which schema/table holds the per-aggregate “last applied tick” state or `tick_effect_guard` entries? - Is there a primary key or unique index that enforces the idempotency key at the database level? diff --git a/design/architecture/system-architecture-tick-incident-runbook.md b/design/architecture/system-architecture-tick-incident-runbook.md index fd476de8a1..456c6e38a6 100644 --- a/design/architecture/system-architecture-tick-incident-runbook.md +++ b/design/architecture/system-architecture-tick-incident-runbook.md @@ -8,6 +8,8 @@ For the detailed tick design, see: - `design/architecture/system-architecture-tick-concepts-and-invariants.md` - `design/architecture/system-architecture-tick-failures-and-operations.md` +Validation and runtime-proof selection for changes to this runbook follows the shared [Validation and Runtime Proof workflow](../developer-workflows/validation-and-runtime-proof.md); record execution results in PR/CI evidence or the owning implementation tracker. + Redis coordination behavior and reset flows are defined in: - `design/architecture/system-architecture-redis.md` @@ -53,7 +55,7 @@ Normal incident escalation groups by `` as described in `system-architecture-redis-reset-and-recovery.md`. - - In shared rulesets, sustained `tick_status{scope_class=~"^(region|game_instance|tenant|cluster)$",status="STALLED"} == 1`, a prolonged `DEGRADED` rollup, or continued queue/ratio pressure starts exact-scope enumeration and authoritative status lookup; none of these class-level signals alone identifies a region, sets its status, or authorizes intervention. +- If the stall is brief and authoritative runtime-health evidence shows recovery to `RUNNING` (with queues draining and class-level execution-time ratios returning to healthy ranges), continue to monitor without intervention. +- **Target state only, once implemented and proven:** If the authoritative runtime-health/control-plane record reports the exact region as `STALLED` or `DEGRADED` long enough to require action, use the class-level tick-health paging conditions as supporting detection/escalation evidence and plan a **region-scoped** coordination reset for the affected `` as described in `system-architecture-redis-reset-and-recovery.md`. + - **Current deployments:** These thresholds classify the incident and escalation severity only; they do not authorize a reset. Use read-only inspection, preserve AOF and incident evidence, keep the affected scope fenced or stopped, and escalate through the fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). + - In shared rulesets, sustained `tick_status{scope_class,status="STALLED"} == 1`, a prolonged `DEGRADED` rollup, or continued queue/ratio pressure starts exact-scope enumeration and authoritative status lookup; none of these class-level signals alone identifies a region, sets its status, or authorizes intervention. - Treat the control-plane/runtime-health status and its forward-progress evidence as the intervention threshold. The current live authority is `GetRuntimeOwnershipStatus` with `ObserveRuntimeTickProgress`; target state is `RegionStatus` through `GetRegionTickStatus`. -- Only escalate to a **tenant-scoped** or **cluster-wide** reset if multiple regions for the same `` group show similar symptoms or if Redis incident runbooks indicate broader coordination corruption, and only after enumerating every affected game instance, namespace/scope pair, and region and passing the explicit blast-radius approval/gate required above. + - **Target state only, once implemented and proven:** Treat `tick_status{scope_class,status="STALLED"} == 1` sustained through the environment’s alert hold time as a class-level trigger for exact-scope enumeration and authoritative status lookup, not as an intervention threshold by itself. Sustained `DEGRADED` plus over-threshold execution-time ratios or queue growth may raise escalation priority, but region action still requires the exact authoritative region tuple/status above; current deployments treat these class-level signals as diagnostic/escalation evidence only. +- **Target state only, once implemented and proven:** Only escalate to a **tenant-scoped** or **cluster-wide** reset if multiple regions for the same `` group show similar symptoms or if Redis incident runbooks indicate broader coordination corruption, and only after enumerating every affected game instance, namespace/scope pair, and region and passing the explicit blast-radius approval/gate required above. +- **Current deployments:** A broader tenant/cluster blast-radius determination is evidence and escalation only; it does not authorize a reset or broader pause. Enumerate the affected scope from authoritative mapping evidence, preserve evidence, keep affected scopes fenced, and use the fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). ### Act (Stalled tick region) @@ -88,7 +93,7 @@ Normal incident escalation groups by `` using the Game Session controls described in the tick architecture and Redis reset docs; missing or mismatched namespace/scope/epoch evidence fails closed. - - **Executor fencing/drain gate:** The current owner-authoritative read is `GetRuntimeOwnershipStatus`, including its opaque `executorFence`; it does not itself pause or drain an executor. The live service has no exact regional executor-disable or drain API, so do not claim that the instance-wide pause or `ObserveRuntimeTickProgress` provides that control. Keep available admission/containment controls active, and before any reset or recovery mutation verify from owner status plus the deployed control-plane/log readback that the current executor has stopped claiming work and relinquished the applicable lease/fence. If no current-live control can establish or maintain that pause/fence, preserve any active broader containment, block further mutations, mark exact containment unverified, and escalate. In the target region model, require the Game Session owner’s exact region `executorFence` and an owner-supported drain acknowledgement before reset; do not synthesize either from Redis keys or metrics. + - **Executor fencing/drain gate:** The current owner-authoritative read is `GetRuntimeOwnershipStatus`, including its opaque `executorFence`; it does not itself pause or drain an executor. The live service has no exact regional executor-disable or drain API, so do not claim that the instance-wide pause or `ObserveRuntimeTickProgress` provides that control. Keep available admission/containment controls active, ensure no new executor instances attempt to acquire the region lease while inspecting metrics, and before any reset or recovery mutation verify from owner status plus the deployed control-plane/log readback that the current executor has stopped claiming work and relinquished the applicable lease/fence. If no current-live control can establish or maintain that pause/fence, preserve any active broader containment, block further mutations, mark exact containment unverified, and escalate. In the target region model, require the Game Session owner’s exact region `executorFence` and an owner-supported drain acknowledgement before reset; do not synthesize either from Redis keys or metrics. 2. **Inspect metrics and optional workflow traces** - Use the Tick Health dashboard to confirm: - The authoritative runtime-health/control-plane record identifies the exact region as stalled or degraded. @@ -107,7 +112,7 @@ Normal incident escalation groups by `` @@ -116,17 +121,17 @@ Normal incident escalation groups by `` keys as reset-tolerant observer hints; consumers reacquire leases and re-establish baselines from the active status/progress adapter and durable domain state. - - Do not delete domain data or non-coordination prefixes. + - **Target state only, once implemented and proven:** Do not delete domain data or non-coordination prefixes. 4. **Resume ticks and verify recovery** - - Resume tick scheduling for the region only after Game Session coordination cleanup and, **once the target Automation projections exist**, executable owner-reconciled Automation cleanup/rebuild and exact readback have completed, followed by the canonical post-reset smoke gate. In the current-live branch, the instance/deployment remains paused and non-accepting while that Automation recovery is unavailable; the current operator fallback has no executable Automation cleanup/rebuild and must not claim this target gate is complete. Resume additionally requires Automation admission-mode readback to show the intended post-incident mode and a verified executor start/drain gate; Game Session resume is not sufficient evidence that Automation has resumed safely. + - **Target state only, once implemented and proven:** Resume tick scheduling for the region only after Game Session coordination cleanup and, **once the target Automation projections exist**, executable owner-reconciled Automation cleanup/rebuild, exact readback, the canonical post-reset smoke gate, and all applicable recovery release gates have completed. Target-state resume additionally requires Automation admission-mode readback to show the intended post-incident mode and a verified executor start/drain gate; Game Session resume is not sufficient evidence that Automation has resumed safely. The current-live instance/deployment remains paused and non-accepting while that Automation recovery is unavailable; the current operator fallback has no executable Automation cleanup/rebuild and must not claim this target gate is complete. - Confirm via dashboards that: - The authoritative runtime-health/control-plane record reports the exact region as `RUNNING`. - When the target-only mode-aware metric capability and fresh required series are present, `tick_status{scope_class,status="RUNNING"}` and `tick_execution_time_ms_*` ratios fall back into healthy class-level envelopes. Otherwise, use authoritative forward-progress/runtime-health readback, available queue evidence, and structured logs; unavailable ratios remain unknown and do not block current-live verification. - Command and retry queue depths stabilize. - - When the replay-ledger capability is advertised and proved, the required `tick_effects_*` metric families and bounded-label proof are current, and every required series is present and fresh, review `tick_effects_pending_total{scope_class}` for the approved bounded scope bucket to ensure the ledger is draining and not accumulating new stuck rows. If that capability or any metric/freshness proof is absent, stale, invalid, or unproved, treat the metric as `unknown` and use exact complete-scope durable tick-ledger/batch state, `GetRuntimeOwnershipStatus` with `ObserveRuntimeTickProgress`, and structured Game Session logs instead. Replay-batch/controller-progress evidence is target-only and may be used only after its controller is implemented and proved. + - **Current deployments:** Do not resume or reopen the affected scope after this reset path. Use the fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback): keep the scope fenced or stopped, use only the shipped pause/status surface and read-only inspection, preserve evidence, and escalate. ## Tick Scheduler Pressure @@ -248,7 +253,7 @@ When this section uses target-only `tick_effects_*` replay-ledger metrics, requi - If lag persists: - Treat as a coordination cleanup incident first (not a domain correctness incident) unless ledger/backlog signals also indicate stuck effects. - Prefer region-scoped remediation before tenant- or cluster-scoped actions. -- If cleanup lag is coupled with growing ledger backlog (`tick_effects_pending_total{scope_class}`) and stale `SCHEDULED` age, run replay-controller and ledger remediation flow in parallel. +- **Target state only, once implemented and proven:** If cleanup lag is coupled with growing ledger backlog (`tick_effects_pending_total{scope_class}`) and stale `SCHEDULED` age, the recovery controller may run replay-controller and ledger remediation flows in parallel. Current operators must use the fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) instead. ### Act (durable commit/coordination cleanup divergence) @@ -260,9 +265,9 @@ When this section uses target-only `tick_effects_*` replay-ledger metrics, requi - Validate Redis health (latency, memory pressure, and unreplicated-write exposure) using Redis coordination dashboards. 3. **Apply scoped remediation** - Resolve each affected scope from authoritative runtime/control-plane records and carry the complete tuple `` plus the current executor fence; the bounded metrics bucket is not sufficient evidence. - - **Current-live branch:** because any deployed containment boundary is at most instance-scoped, enumerate and record every affected region and namespace/scope under the ``, obtain the broader-scope approval gate, and apply only a deployed containment/fencing control that provides authoritative scope evidence. If none is available, preserve any active broader containment, block further mutations, mark exact containment unverified, and escalate. Use `GetRuntimeOwnershipStatus` plus `ObserveRuntimeTickProgress` only as evidence-only status and forward-progress reads. Require authoritative readback of that full enumeration and fence before any cleanup action; do not describe this as an exact regional pause or reset. - - **Target-state branch:** use the exact namespace/region-qualified pause and cleanup controls, with CAS/readback proving the carried tuple and executor fence at each mutating step. If a region remains stuck, execute the region-scoped coordination reset flow in `system-architecture-redis-reset-and-recovery.md`; missing or mismatched evidence fails closed. - - Where deployed controls establish containment, keep current-live instances/deployments paused and non-accepting while Automation projection recovery is unavailable. If no current-live control can establish or maintain that state, preserve any active broader containment, block further mutations, mark exact containment unverified, and escalate. Resume only after executable owner-reconciled recovery, authoritative full-scope readback, and the canonical smoke gate. If the authoritative durable ledger shows backlog also accumulating, trigger ledger replay-controller remediation for the same fully resolved scope. + - **Current-live branch:** because any deployed containment boundary is at most instance-scoped, enumerate and record every affected region and namespace/scope under the ``, obtain the broader-scope approval gate, and apply only a deployed containment/fencing control that provides authoritative scope evidence; if none is available, keep the affected scope fenced or stopped, mark exact containment unverified, and escalate. Use `GetRuntimeOwnershipStatus` plus `ObserveRuntimeTickProgress` only as evidence-only status and forward-progress reads. Require authoritative readback of that full enumeration and fence before any cleanup action; do not describe this as an exact regional pause or reset. + - **Target state only, once implemented and proven:** use the exact namespace/region-qualified pause and cleanup controls, with CAS/readback proving the carried tuple and executor fence at each mutating step. If a region remains stuck, execute the region-scoped coordination reset flow in `system-architecture-redis-reset-and-recovery.md`; missing or mismatched evidence fails closed. + - Keep current-live instances/deployments paused and non-accepting while Automation projection recovery is unavailable. Resume only after executable owner-reconciled recovery, authoritative full-scope readback, and the canonical smoke gate. If ledger backlog also accumulates, trigger ledger replay-controller remediation for the same fully resolved scope. 4. **Verify convergence** - Confirm `tick_cleanup_lag_ms{scope_class}` returns to normal envelope. - Confirm `tick_coordination_cleared_total{scope_class}` catches up with durable commits for affected approved bounded scope buckets. @@ -302,9 +307,9 @@ Before **Detect**, **Decide**, or **Act** interprets any target-only `tick_effec Normal replay and re-enqueue in this section apply only to effects from the current authoritative `regionEpoch`. An old-epoch effect is never replayed through the current-epoch handlers merely because it remains `SCHEDULED`. 1. **Inspect ledger and domain state** - - Use SQL or service-level admin APIs to query `tick_effects` (or the equivalent ledger table) for the exact affected `` scope; resolve `playableStateNamespaceId` authoritatively and fail closed on missing, ambiguous, or mismatched namespace evidence; do not mix rows from another `playableStateNamespaceId`, `playableStateScope`, or `regionEpoch`: - - Identify the oldest `SCHEDULED` entries and carry each complete `tick_effects` ledger projection: ``. This storage projection remains linked to the stable root `EffectId` and any participant guard identity; `effectKey` is a ledger/lookup field, not a replacement for the other tuple fields. - - The complete ledger projection, together with its linked root `EffectId` and participant-guard evidence, is authoritative for effect-level replay and reconciliation only. Phase-specific execution identities remain authoritative in their owning phase records; do not use an `EffectId` to replace admission, staging, commit, or follow-up-leg identity. + - For target-state S1/S2, use SQL or service-level admin APIs to query `tick_effects` (or the equivalent ledger table) for the exact affected `` scope; do not mix rows from another `playableStateNamespaceId`, `playableStateScope`, or `regionEpoch`. The current-live schema may expose only the documented narrower `` scope; that limitation must remain explicit rather than being treated as namespace-complete S1/S2 evidence: + - Identify the oldest `SCHEDULED` entries and, for target-state S1/S2, carry and exact-validate each complete `tick_effects` ledger projection: ``. This storage projection is keyed by the persisted mutation `EffectId` and retains any enclosing root `EffectId` as lineage/reconciliation context; `playableStateNamespaceId` is a required exact-bound S1/S2 field, and `effectKey` is a ledger/lookup field, not a replacement for the other tuple fields. Current-live may lack that namespace field at its boundary and therefore cannot claim the target-state projection is complete. + - The complete ledger projection, together with its linked mutation `EffectId`, enclosing-root lineage, and participant-guard evidence, is authoritative for effect-level replay and reconciliation only. Phase-specific execution identities remain authoritative in their owning phase records; do not use an `EffectId` to replace admission, staging, commit, or follow-up-leg identity. - When the replay-ledger capability is advertised and proven and all required series are fresh, compare `tick_effects_pending_oldest_age_seconds{scope_class}` with `tick_effects_replay_convergence_budget_seconds{scope_class}` to distinguish “brief replay delay” from “budget breach that requires active remediation”. Otherwise, treat that comparison as `unknown` and use the exact durable ledger age/status, runtime-health, and structured-log evidence; do not infer a budget breach from missing or stale metrics. - For a small sample, inspect domain state (for example entity HP, inventory, room state) to determine whether the effects have already been applied. 2. **Classify outcomes** @@ -321,9 +326,9 @@ Normal replay and re-enqueue in this section apply only to effects from the curr - For “applied but not marked” rows: - Do not update ledger rows directly to `APPLIED` from ad hoc SQL, a generic admin endpoint, or a one-off script. - Select the verifier/reconcile branch from the deployment mode; do not require target-state fields from the current-live schema or weaken the target-state gate: - - **Current-live:** Run the service-owned verifier for the exact ledger projection and linked root `EffectId`, including `effectKey` and target aggregate identity, within the exact `` scope. Resolve `playableStateNamespaceId` from authoritative namespace-bound runtime evidence and fail closed on missing, ambiguous, or mismatched namespace evidence. Read `GetRuntimeOwnershipStatus` (the current instance-scoped ownership boundary) and require the current `regionEpoch` and opaque `executorFence` to match the batch/ledger ownership snapshot. Verify that the current selected-work manifest and its `manifest_digest` match the durable source and ledger projections and the expected participant evidence. This branch may be processed without `sealed_execution_context_digest` or `sealed_execution_context_ref`, which are not present at the current-live boundary. The service-owned verifier must atomically CAS the current owner/epoch/fence, require complete manifest and participant-evidence set equality, transition the matching `SCHEDULED` row(s) to `APPLIED`, and record replay-verification evidence (including the evidence digest/reference and `replay_ok` audit) in one durable transaction. Missing, extra, or conflicting evidence, or any owner/epoch/fence mismatch, affects zero rows and fails closed with no ledger mutation. The owning domain must prove the effect is already reflected in authoritative state or in its durable participant guard; a replay no-op is not a third ledger status. - - **Target-state:** Read the current region authority from `RegionStatus`/`GetRegionTickStatus` and require exact current `regionEpoch`/`executorFence` equality. Require exactly one immutable sealed execution-context binding: either `sealed_execution_context_digest` or `sealed_execution_context_ref` resolved to its immutable digest, with the referenced context and digest matching the batch and replay request. The complete participant-projection set, sealed context, current authority/fence, and every `SCHEDULED` ledger transition must pass the same evidence-qualified CAS; a missing, stale, mismatched, incomplete, extra, or conflicting value affects zero rows and fails closed with no ledger mutation. Target-only replay-ledger metrics are optional supporting evidence only when advertised and proved with fresh required series; absent, stale, or unproved series are `unknown` and do not replace this durable evidence. - - In either branch, replay no-op is an attempt outcome, not a third ledger status, and the verifier must not reconcile the same root effect identity across region epochs. + - **Current-live:** Run the service-owned verifier for the exact current-live ledger projection and its persisted mutation `EffectId` (retaining any enclosing root as lineage), including `effectKey` and target aggregate identity, within the narrower `` scope. Because `playableStateNamespaceId` is not persisted at this current-live boundary, this branch cannot establish namespace-complete S1/S2 binding and must not infer the namespace from `gameInstanceId`. Read `GetRuntimeOwnershipStatus` (the current instance-scoped ownership boundary) and require the current `regionEpoch` and opaque `executorFence` to match the batch/ledger ownership snapshot. Verify that the current selected-work manifest and its `manifest_digest` match the durable source and ledger projections and the expected participant evidence. This branch may be processed without `sealed_execution_context_digest` or `sealed_execution_context_ref`, which are not present at the current-live boundary. The service-owned verifier must atomically CAS the current owner/epoch/fence, require complete manifest and participant-evidence set equality, transition the matching `SCHEDULED` row(s) to `APPLIED`, and record replay-verification evidence (including the evidence digest/reference and `replay_ok` audit) in one durable transaction. Missing, extra, or conflicting evidence, or any owner/epoch/fence mismatch, affects zero rows and fails closed with no ledger mutation. The owning domain must prove the effect is already reflected in authoritative state or in its durable participant guard; a replay no-op is not a third ledger status. + - **Target-state:** Read the current region authority from `RegionStatus`/`GetRegionTickStatus` and require exact current `regionEpoch`/`executorFence` equality. For S1/S2, require the complete namespace-bound projection `` and exact-compare `playableStateNamespaceId` (as well as every other immutable scope, identity, timeline, and target field) across the ledger, manifest, sealed context, and participant set. Require exactly one immutable sealed execution-context binding: either `sealed_execution_context_digest` or `sealed_execution_context_ref` resolved to its immutable digest, with the referenced context and digest matching the batch and replay request. The complete participant-projection set, sealed context, current authority/fence, and every `SCHEDULED` ledger transition must pass the same evidence-qualified CAS; a missing, stale, mismatched, incomplete, extra, or conflicting value affects zero rows and fails closed with no ledger mutation. + - In either branch, replay no-op is an attempt outcome, not a third ledger status, and the verifier must not reconcile a mutation under a different persisted `EffectId` across region epochs; any enclosing `rootEffectId` remains lineage and reconciliation context rather than the effect-level identity. - If no verifier exists for that effect family, treat the row as not safely proven: retain it non-terminal as `SCHEDULED`/reconciliation-required and escalate to the owning service for positive evidence. Do not re-run or mark `ABANDONED` merely because a verifier is absent. - For current-epoch rows with positive durable evidence that the effect is unapplied and an evidence-qualified service-owned replay path: - If replay is safe, enqueue follow-up commands or trigger replay using the same idempotent handlers that tick execution uses. @@ -332,7 +337,7 @@ Normal replay and re-enqueue in this section apply only to effects from the curr - For old-epoch rows, first enumerate every durable old-epoch effect and follow-up independently of Redis hints. Use the authority-fenced attestation under the original `EffectId` described in [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy); the affected scope cannot reopen while any row remains unresolved. A new epoch lineage may be created only after both the original effect and its source claim are authority-fenced terminal `ABANDONED`; an explicitly approved maintenance or saga/outbox flow may then create a fresh current-epoch identity with durable lineage and revalidated scope. No normal replay may create or drive that new lineage, and the original effect identity must not be re-driven across the epoch boundary. - For replay-controller starvation: - Reduce per-region replay batch monopolization or other hot-region pressure first. - - If the region remains starved, run scoped replay-controller remediation for the affected complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch)` after authoritative enumeration and exact validation; incomplete or caller-supplied namespace/scope evidence must fail closed before any replay or maintenance mutation. Escalate to broader reset actions only after that exact scope evidence is qualified. + - **Target state only, once implemented and proven:** If the region remains starved, run scoped replay-controller remediation for the affected complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch)` after authoritative enumeration and exact validation; incomplete or caller-supplied namespace/scope evidence must fail closed before any replay or maintenance mutation. Escalate to broader reset actions only after that exact scope evidence is qualified. Current operators must use the fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) instead. 4. **Prevent recurrence** - Review Game Session and domain handlers to ensure: - Ledger status transitions happen atomically with domain commits where required. @@ -344,14 +349,14 @@ Normal replay and re-enqueue in this section apply only to effects from the curr Correlation is a lookup aid, not proof of application. Always establish the exact deployment mode before selecting an identity, and verify the candidate against the complete durable ledger projection, current ownership boundary, and participant/domain evidence. -- **Current-live correlation:** Live admission requires a present durable `commandId` in the command ledger and selected-work manifest. The current `TickStagingService` may still expose a command-text hash/slot value for legacy reconciliation only; use it only as an explicitly legacy, non-authorizing lookup aid and verify any such candidate against the exact scope and epoch, the batch `manifest_digest`, the ledger row, its linked root `EffectId` and participant guards, and authoritative domain state before invoking the service-owned verifier. It is mutable implementation metadata, never a current-live admission or fallback identity, replacement for a missing root `EffectId`, or authority to transition a row to `APPLIED`. -- **Target-state correlation:** Use only the stable root `EffectId` and its complete concrete ledger/participant projection (including the typed participant-guard identity and target aggregate). `commandId`, `effectKey`, command text, and trace attributes may narrow a search but cannot establish identity, authorize reconciliation, or permit an `APPLIED` transition. +- **Current-live correlation:** Prefer the durable `commandId` when it is present in the command ledger and selected-work manifest. When no command ID is available, the current implementation may use the documented `command-text::slot:` fallback to locate a candidate in the selected-work manifest. That text-and-slot value is only non-authorizing correlation: verify it against the exact scope and epoch, the batch `manifest_digest`, the ledger row, its linked root `EffectId` and participant guards, and authoritative domain state before invoking the service-owned verifier. The fallback is mutable implementation metadata, never a canonical identity, replacement for a missing root `EffectId`, or authority to transition a row to `APPLIED`. +- **Target-state correlation:** Use only the persisted mutation `EffectId` and its complete concrete ledger/participant projection, retaining any enclosing root `EffectId` as lineage/reconciliation context (including the typed participant-guard identity and target aggregate). `commandId`, `effectKey`, command text, and trace attributes may narrow a search but cannot establish identity, authorize reconciliation, or permit an `APPLIED` transition. ## Using Proved Workflow Traces During Tick Incidents For all of the scenarios above, workflow traces are optional diagnostics rather than the operational baseline: -For effect-level replay and reconciliation, the exact correlation input is the complete durable ledger projection linked to the stable root `EffectId`: ``. `playableStateNamespaceId` must be authoritatively resolved and exact-validated with the rest of the scope tuple; missing, ambiguous, or mismatched namespace evidence fails closed. `effectKey`, `targetAggregateType`, and the exact `targetAggregateId` remain required ledger/lookup fields; `effect_type` and other trace attributes are exploratory filters only and cannot establish an exact effect match, authorize reconciliation, or justify a ledger transition. Command, source-claim, coordinator, and completion identities remain authoritative for their own execution phases and must not be replaced by `EffectId`. +For target-state S1/S2 effect-level replay and reconciliation, the exact correlation input is the complete namespace-bound durable ledger projection keyed by the persisted mutation `EffectId` and retaining any enclosing root lineage: ``. Exact comparison must include `playableStateNamespaceId` and every other projection field before correlation or reconciliation. Current-live may use only its narrower documented projection without `playableStateNamespaceId`; that implementation limitation is not target-state S1/S2 proof and must not be silently filled by `gameInstanceId`. `effectKey`, `targetAggregateType`, and the exact `targetAggregateId` remain required ledger/lookup fields; `effect_type` and other trace attributes are exploratory filters only and cannot establish an exact effect match, authorize reconciliation, or justify a ledger transition. Command, source-claim, coordinator, and completion identities remain authoritative for their own execution phases and must not be replaced by `EffectId`. - Only when the environment advertises and proves the named workflow-tracing capability, use Jaeger to search for spans representing tick scheduling and execution (for example `tick_schedule`, `tick_execute`) filtered by `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, `regionEpoch`, and, where available, `tickId`; trace filters are diagnostic and never replace authoritative exact-scope validation. - When that capability is proved, inspect stalled regions for long-running or repeated spans for the same tick IDs and cross-reference domain service spans to identify downstream bottlenecks. diff --git a/design/architecture/system-architecture-ticks.md b/design/architecture/system-architecture-ticks.md index 9299ae8b06..7ef44d518a 100644 --- a/design/architecture/system-architecture-ticks.md +++ b/design/architecture/system-architecture-ticks.md @@ -36,6 +36,8 @@ Current live substrate to keep in mind while reading: - the live `executorFence` is an opaque generation token used for compare-and-match stale-fence protection, not yet the richer numeric ordering model used in some target-state examples; - the live `tick_batch` / `tick_effect` substrate is real, and the current gameplay-command manifest now carries current-boundary `enqueueSeq`, `sourceType`, `dueTickId`, and explicit claimed-source state plus digest-checked replay reuse. The live `enqueueSeq` comes from one database-wide sequence; the region-scoped, cross-source allocator that remains monotonic across epoch resets is target-state. Timer/retry/remote-follow-up source-claim breadth and the cross-region result-return contract described below are also target-state follow-through rather than fully shipped behavior. - the live Game Session automation handoff carries `scriptPatchVersion`, positive `scriptPinEpoch`, and `scriptPinControlPlaneRequestId` on `EnqueueAutomationCommandIfAbsentRequest`; Game Session compares the tuple with authoritative owner state and rejects incomplete or stale evidence before staging or duplicate replay. Exact tuple checks also remain at the live instance-bound Automation ingress, timer, and work-item admission boundaries. The handoff still lacks `commandOrdinal` and the full Trigger Identity required for target-state per-command diagnostics. Live gameplay staging requires a present, nonblank durable `commandId` before Redis enqueue or durable batch staging, and `TickStagingService` derives `effectKey` as `command:`; complete source/target binding and remote final-effect fence proof remain implementation gaps. +- Any future region-scoped/cross-source ordering allocator, including its scope and reset sequence behavior, remains conditional and non-authoritative pending [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); it cannot change the accepted current `enqueueSeq` or replay/effect identity rules. Timer/retry/remote-follow-up source-claim breadth and the cross-region result-return contract described below are also target-state follow-through rather than fully shipped behavior. +- the target deterministic command-plan root contract is not fully live: the owning command/action contract for the frozen typed command or `ResolvedEffectPlan` must supply semantic root order, with built-ins declaring equivalent stable order; ambiguous or duplicate order fails before admission. Before allocation, the durable gameplay command row must freeze/bind its request fingerprint, resolved runtime scope, and applicable `playableStateNamespaceId`. Game Session must persist the ordered plan manifest/digest and an opaque root allocation row unique on `(tenantId, gameInstanceId, commandId, planOrdinal)`; the row binds the manifest digest and validates the frozen command/runtime/namespace binding, and retries reuse it only when all of those values match, otherwise failing closed. For Automation, the complete applicable Command-Handoff Identity must exact-map at admission to one durable target `commandId`; allocation then uses that target command row's canonical key. The current `tickBatchId`/`effectKey` derivation is not evidence of that contract. --- @@ -52,6 +54,8 @@ Conceptually, FireMUD treats time as **localized pulses** rather than a single g - Per-service database transactions guarded by effect identity and idempotency, and - Replayable coordination via Redis and the tick effect ledger rather than a single cross-service ACID boundary. +Before staging, each admitted command is materialized as a deterministic plan: the ordered set of logical root effects for that command in the frozen typed command or `ResolvedEffectPlan` semantic order supplied by its owning command/action contract. Built-in commands declare an equivalent stable order; ambiguous or duplicate order fails before admission. The durable gameplay command row freezes/binds its request fingerprint and resolved runtime scope before Game Session persists the ordered plan manifest/digest and owns an opaque local durable allocation row unique on `(tenantId, gameInstanceId, commandId, planOrdinal)`. The row binds the manifest digest and validates that frozen command/runtime binding; retries reuse it only when the command row identity, frozen binding, ordinal, and digest match, otherwise failing closed. One logical operation has one root `EffectId` with participant guards beneath it. A single-root plan uses `planOrdinal=0`, a multi-root plan uses stable zero-based ordinals, and a zero-effect plan allocates no ordinal or root. For Automation, the complete applicable Command-Handoff Identity exact-maps at admission to one durable target `commandId`, after which allocation uses that target command row's canonical key. This command-root contract does not synthesize plans for passive, inbound/remote, timer, retry, or already-generated effects that retain owner/source-specific identities unless they materialize as an admitted command. A shared root for a conserved multi-participant operation does not replace ADR 0053 atomicity, co-location, or reservation semantics. + For the precise cross-service transaction model and when sagas are required, see `system-architecture-transactions.md`. See `system-architecture-tick-concepts-and-invariants.md` for the full description of fairness guarantees and queueing rules. @@ -65,7 +69,7 @@ The canonical scheduler has two independently bounded lanes: The phases are ordered as follows: (1) due start-of-tick passive effects, (2) one selected actor action for each still-eligible entity, and (3) effects generated by those selected actor actions. Only phase-1 effects completed before phase-2 eligibility evaluation may change same-tick eligibility; work selected but not completed, or deferred by lane, per-entity, cost, or region budget overflow, affects a later tick. Passive or inbound work that becomes due after start selection is also deferred to a later tick; phase 3 does not drain it. A completed start-of-tick effect may make an entity ineligible to act. An actor-generated effect does not retrospectively remove an action that already executed, and neither lane may recursively grant another root actor action in the same tick. -Every work source declares its phase, lane, and cost class before admission. Within one entity's eligible queue, the persisted manifest orders work by `(priority, due_tick_id, entity_enqueue_seq, source_kind, commandId_or_effectKey)`, with due points normalized before selection. Across eligible entities, persisted rotating/deficit scheduling accounts for declared cost and advances only with the durable selected batch; bounded aging or `maxDeferralTicks` applies where declared. Each lane has separate per-entity count and cost caps, region-wide work budgets, bounded carry-over/backoff, and pressure metrics. Overflow is deferred without changing its persisted ordering inputs or retry/action/effect identity; a new source cannot silently introduce a custom scheduler. See [ADR 0065](./decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md). +Every work source declares its phase, lane, and cost class before admission. Within one entity's eligible queue, the persisted manifest orders work by `(priority, due_tick_id, entity_enqueue_seq, source_kind, commandId_or_effectKey)`, with due points normalized before selection. `entity_enqueue_seq` is allocated within the complete entity scope `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch)`; it is not a region-global or instance-only sequence. Across eligible entities, persisted rotating/deficit scheduling accounts for declared cost and advances only with the durable selected batch; bounded aging or `maxDeferralTicks` applies where declared. Each lane has separate per-entity count and cost caps, region-wide work budgets, bounded carry-over/backoff, and pressure metrics. Overflow is deferred without changing its persisted ordering inputs or retry/action/effect identity; a new source cannot silently introduce a custom scheduler. See [ADR 0065](./decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md). --- @@ -87,7 +91,7 @@ The tick heartbeat is the **canonical timeline** for each ` `region_epoch` mapping rather than treating the two names as competing fields. -Consumers that persist offsets must key stable consumer identity by `(tenantId, gameInstanceId, regionId, consumerId)` and store `regionEpoch` and `latestTickId` as mutable timeline state. Durable schedule identity is the scheduler-owned `scheduleInstanceId`; it excludes mutable runtime-region metadata (`runtimeRegionId`, `runtimeRegionEpoch`), due point, and exact pin/provenance. Trigger-instance de-duplication and candidate-audit identity use the complete event-scope due-candidate/firing identity owned by [Scripting Scheduler and Timers](./system-architecture-scripting-scheduler-and-timers.md#target-state-design) and [Normative Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields), including applicable runtime region/epoch, event/schema, exact patch/pin, dry-run, trigger mode, target selector, tagged due point, catch-up `resumeWindowId`, and schedule-owned script/plugin fields. This document does not redefine that schema or mutate the schedule itself. Any observed epoch jump is a reset boundary: state derived from the old epoch is discarded or reconciled from PostgreSQL before resuming. +Consumers that persist offsets must key stable consumer identity by `(tenantId, gameInstanceId, regionId, consumerId)` and store `regionEpoch` and `latestTickId` as mutable timeline state. For durable schedules, `scheduleInstanceId` is the immutable physical row-generation identity allocated under the materializing operation; it is not the stable logical continuity identity and is not sufficient for trigger uniqueness. The scheduler-owned stable continuity key is `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}` for each `isDryRun` mode; compatible transitions may retain the same row generation, while reset or incompatible replacement can allocate a fresh `scheduleInstanceId` under that continuity model. Mutable runtime-region metadata (`runtimeRegionId`, `runtimeRegionEpoch`), due point, and exact pin/provenance remain schedule state or evidence rather than continuity identity. Trigger-instance de-duplication and candidate-audit identity instead use the complete event-scope due-candidate/firing identity owned by [Scripting Scheduler and Timers](./system-architecture-scripting-scheduler-and-timers.md#target-state-design) and [Normative Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields), including applicable runtime region/epoch, event/schema, exact patch/pin, dry-run, trigger mode, target selector, exactly one tagged due point (`dueTickId` or `dueAt`), catch-up `resumeWindowId`, and schedule-owned script/plugin fields. A wall-clock source may carry a separately assigned admission `due_tick_id` for tick ordering, but it does not become or alias the source `dueAt`; tick IDs and epoch-millisecond values are never compared. This document does not redefine that schema or mutate the schedule itself. Any observed epoch jump is a reset boundary: state derived from the old epoch is discarded or reconciled from PostgreSQL before resuming. ### Tick Commit Definition (Heartbeat Watermark) @@ -95,7 +99,8 @@ FireMUD uses two explicit tick boundaries for `:tier:`). Redis quota counters are reset-tolerant and a reset may temporarily relax fairness; it does not change durable schedule or work truth. The target `tick-events:{tenantRegionTag}` stream and its offsets are separate best-effort coordination hints only; once implemented, losing or resetting those hints may delay next discovery but must not change which automation jobs are eventually executed or create duplicate durable claims. The current live path has no such stream or offsets and uses `ObserveRuntimeTickProgress`. The `script-scheduler:{tenantRegionTag}:lastTickId` projection is target-only and unimplemented, with no current reset operation; once delivered, it will be a similarly reset-tolerant discovery hint rather than an authority for automation work. +Durable automation schedules and trigger-instance de-duplication remain PostgreSQL/domain-owned. In the target state, Account owns plan-driven quota values through tenant entitlement and plan-limit authority; the current Automation implementation instead uses service configuration for its limits. Live per-script and tenant-tier quota reservations/counters are Redis-backed enforcement state (for example, `automation:tenant-budget::tier:`). Redis quota counters are reset-tolerant and a reset may temporarily relax fairness; it does not change durable schedule or work truth. The current `tick-events:{tenantRegionTag}` stream and its offsets are separate best-effort coordination hints only; losing or resetting those hints must not silently drop correctness-bearing one-shot intent or eligible durable work or create duplicate durable claims, but may affect discovery timing and policy-governed missed recurring/advisory firings, including declared `SKIP_MISSED`, cap-excluded, or terminal capacity-denial outcomes. The `script-scheduler:{tenantRegionTag}:lastTickId` projection is target-only and unimplemented, with no current reset operation; once delivered, it will be a similarly reset-tolerant discovery hint rather than an authority for automation work. Automation & Scripting Service instances typically: - In target-state deployments, establish long-lived gRPC subscriptions to `StreamTickHeartbeats` with `tenantId`, `gameInstanceId`, and `regionId`; every message must repeat that complete scope so consumers cannot rely on an implicit stream binding to disambiguate instances. - In the current live deployment, consume `ObserveRuntimeTickProgress` with the same complete runtime scope instead of assuming `StreamTickHeartbeats` is available. - In target-state deployments, once implemented, maintain per-region scheduler state in Redis as a derived discovery hint (for example `script-scheduler:{tenantRegionTag}:lastTickId`). Its value stores `{regionEpoch, latestTickId}` and never owns or persists `streamOffset`; the canonical per-consumer event-offset record remains `tick-events-offset:{tenantRegionTag}:{consumerId}`. The target scheduler must reject the hint when its epoch differs from the authoritative current epoch, discard it on reset, and rebuild it from the current canonical status/progress observation. This Redis projection is currently unimplemented and has no current reset operation; current live Automation instances must use `ObserveRuntimeTickProgress` and durable PostgreSQL schedules without reading or writing it. If the event stream is truncated, only each affected consumer's canonical event-offset record is invalidated for resumption; a target scheduler still validates or rebuilds its separate hint from canonical progress rather than using the hint as a stream offset. The event-offset identity is `(tenantId, gameInstanceId, regionId, consumerId)`, while `regionEpoch`, `tickId`, and the stream event offset are never key dimensions. -- After a due candidate passes the applicable schedule-admission checks, claim or insert a durable PostgreSQL trigger-instance/outbox row keyed by an **instance-aware** uniqueness projection before enqueueing any `onInterval` or other tick-derived trigger so duplicate heartbeat consumers or failover cannot create duplicate logical gameplay actions. Discovery of a due candidate alone does not create a firing claim or `scriptEventId`; a terminal/permanent or declared pre-admission skip is recorded as an immutable event-scope candidate audit under a deterministic `scheduleCandidateId` derived from the complete canonical event-scope due-candidate fields, while only owner-defined transient retryable reload, reconciliation, or authority-fence failures retain the original exact-tuple due candidate as fenced, retry-eligible nonterminal state with no firing claim or `scriptEventId` until settlement. The schedule's canonical natural-key fields participate as defined by the scheduler owner; a surrogate `scheduleInstanceId` is not an identity input or substitute. - - The complete trigger-instance due-candidate/firing/candidate-audit identity and its field-presence rules are owned by [Scripting Scheduler and Timers](./system-architecture-scripting-scheduler-and-timers.md#target-state-design) and [Normative Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields): applicable runtime region/epoch, event/schema, exact patch/pin, dry-run, trigger mode, target selector, tagged due point, catch-up `resumeWindowId`, and schedule-owned script/plugin fields. `automationDispatchId` plus `commandOrdinal` remains the per-command child identity and is not a replacement for the parent Trigger Identity. +- After a due candidate passes the applicable schedule-admission checks, claim or insert a durable PostgreSQL trigger-instance/outbox row keyed by an **instance-aware** uniqueness projection before enqueueing any `onInterval` or other tick-derived trigger so duplicate heartbeat consumers or failover cannot create duplicate logical gameplay actions. Discovery of a due candidate alone does not create a firing claim or `scriptEventId`; a terminal/permanent or declared pre-admission skip is recorded as an immutable event-scope candidate audit under a deterministic `scheduleCandidateId` derived from the complete canonical event-scope due-candidate fields, while only owner-defined transient retryable reload, reconciliation, or authority-fence failures retain the original exact-tuple due candidate as fenced, retry-eligible nonterminal state with no firing claim or `scriptEventId` until settlement. The schedule's canonical natural-key fields participate as defined by the scheduler owner; a surrogate `scheduleInstanceId` is only physical row-generation metadata and is not an identity input or substitute. + - The complete trigger-instance due-candidate/firing/candidate-audit identity and its field-presence rules are owned by [Scripting Scheduler and Timers](./system-architecture-scripting-scheduler-and-timers.md#target-state-design) and [Normative Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields): applicable runtime region/epoch, event/schema, exact patch/pin, dry-run, trigger mode, target selector, exactly one tagged due point (`dueTickId` or `dueAt`), catch-up `resumeWindowId`, and schedule-owned script/plugin fields. `automationDispatchId` plus `commandOrdinal` remains the per-command child identity and is not a replacement for the parent Trigger Identity. Target-state only: Before schedule admission resumes under a new `scriptPinEpoch`, an atomic durable or resumable-idempotent reconciliation must fence pending occurrences/claims from the old `scriptPinEpoch` and make old-epoch enqueue attempts fail. Reconciliation separates scheduler candidate-audit state from linked durable tick/effect/source-claim state: when durable evidence proves the linked effect was applied, its original durable identity remains terminal `APPLIED`; when evidence proves no firing/effect was accepted or applied, the linked effect/source claim may terminalize `ABANDONED` with its owner-defined explicit reset/reconciliation reason, while an applicable scheduler candidate is recorded only with its owner-defined canceled/permanent-skip outcome and bounded reason, never `APPLIED` or `ABANDONED`. An ambiguous or unreadable claim remains nonterminal/reconciliation-required under its original identity until reconciled. The new epoch cannot enqueue the same schedule occurrence unless it is explicitly represented by a distinct durable logical occurrence/due identity; candidate-audit identity and outcome remain immutable. Detailed transition and recovery semantics remain with [Scripting Scheduler and Timers](./system-architecture-scripting-scheduler-and-timers.md), [Transaction Strategies](./system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory), and the [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy). See [current scripting runtime status](./system-architecture-scripting-runtime-execution.md#current-implementation-status) and the [Game Session implementation status](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#script-pin-epoch-and-rollout-history-reconciliation). @@ -314,16 +319,17 @@ Normal lease handoff/rebalancing does **not** bump `regionEpoch`: `regionEpoch` For most deployments, region topology changes (splits, merges, or reassignments between executors) are applied between game instances or during maintenance windows so active sessions are not disrupted. -World Management owns region topology (layout and `` assignments scoped by `{tenantId, gameInstanceId}`) and may, over time, support “drain and split” or “merge” flows: +World Management owns region topology (layout and `` assignments scoped by `{tenantId, gameInstanceId}`) and may, over time, support “drain and split” or “merge” flows. These flows and the protocol below are target-state tooling, not current operator capabilities: the live durable ownership boundary remains instance-scoped, and no shipped split/merge cutover or region-scoped reset/rebuild controller currently exists. -- Split flows mark a region for split, freeze scheduling and new command intake, reconcile each in-flight and durable effect under authoritative evidence, bump `regionEpoch` when the ownership mapping changes, move entities to new `` assignments, and reset/rebuild coordination state from durable state before ticks resume. They do not move live Redis queues by renaming them under new prefixes. +- Split flows establish an admission barrier covering player front ends, supported Logging & Admin operator effect admission/forwarding, automation, timers, and remote-follow-up producers before freezing scheduling and new command intake; they then reconcile each in-flight and durable effect under authoritative evidence, bump `regionEpoch` when the ownership mapping changes, move entities to new `` assignments, and reset/rebuild coordination state from durable state before ticks resume. They do not move live Redis queues by renaming them under new prefixes. - Merge flows consolidate lightly used regions into a single region to reduce overhead. -### Topology Changes (Split/Merge) Protocol (Required Invariants) +### Topology Changes (Split/Merge) Protocol (Target-State Required Invariants) -Region split/merge operations interact directly with tick idempotency, Redis key ownership, and cross-region follow-ups. To keep these operations safe and deterministic, topology changes must follow a single, explicit protocol: +Region split/merge operations interact directly with tick idempotency, Redis key ownership, and cross-region follow-ups. Once the target topology cutover and recovery tooling is implemented and proven, topology changes must follow a single, explicit protocol: -1. **Freeze and fence** +1. **Admission barrier, freeze, and fence** + - Establish an admission barrier covering player front ends, supported Logging & Admin operator effect admission/forwarding, automation, timers, and remote-follow-up producers. Effects admitted before the barrier drain or reconcile under their owning lifecycle; no post-barrier effect is admitted until the cutover reopens. - Pause tick scheduling and new command intake for the affected region(s). - Wait for any in-flight `tick:{tenantRegionTag}:pending` work to commit or be recovered effect-by-effect to an evidence-qualified terminal state; inconclusive effects remain nonterminal/reconciliation-required. 2. **Converge durable outcomes** @@ -334,7 +340,7 @@ Region split/merge operations interact directly with tick idempotency, Redis key - If the operation changes region boundaries or re-homes entities to a different region mapping, bump `regionEpoch` for all affected `` pairs as part of the topology change (the same epoch-severing mechanism used by scoped coordination resets). - Only topology operations that preserve entity-to-region ownership exactly may skip an epoch bump, and those exceptions must be explicitly documented and audited in the maintenance record. 4. **Reset or migrate coordination state using shared key builders** - - First implementation resets/rebuilds coordination state from durable PostgreSQL state after the epoch bump instead of moving live Redis keys. + - Target-state first implementation resets/rebuilds coordination state from durable PostgreSQL state after the epoch bump instead of moving live Redis keys; this is unavailable until the reset/rebuild controller and its focused proof exist. - Future in-place migration may move only reset-tolerant, purely coordination structures (queues, timers, retry metadata) using versioned tooling that uses the shared key builders and Lua Script Registry descriptors. - Queue entries, timers, and retry records that are purely coordination state are not reconstructed from old Redis keys unless dedicated migration tooling re-derives them from durable intent under the new mapping. The default fate for accepted-but-unbound queued commands is the explicit command outcome above, not silent replay on the new epoch. - Do not hand-edit `tick:*`, `timer:*`, `retry:*`, or lease/lock keys. @@ -344,11 +350,15 @@ Region split/merge operations interact directly with tick idempotency, Redis key - **Target-state fallback:** If one transaction cannot cover the records, persist a fenced durable rollover intent containing the old/new identities, desired mapping, and sealed follow-up context; recovery retries/reconciles that intent until the new identity and link are durable and effect-by-effect evidence proves the old identity unapplied before marking it `ABANDONED`. Inconclusive work remains nonterminal/reconciliation-required. - Mark the old identity `ABANDONED` with a topology-change reason only when authoritative evidence proves it unapplied, replaying it under the new mapping is invalid, and no new target identity is required; otherwise preserve `APPLIED` or nonterminal/reconciliation-required state. - **Current drift:** The current follow-up path does not yet claim the complete atomic or recoverable rollover boundary. Until it is proven, a mapping-changing operation remains paused/fenced and must not mark an old follow-up `ABANDONED` solely because the mapping changed. -6. **Resume** - - Re-enable tick scheduling and command intake once the new mapping is in place and the region(s) are healthy. +6. **Resume (target-state release)** + - Re-enable tick scheduling and command intake only after the target mapping, durable reconciliation, coordination reset/rebuild, and owner-defined health/release evidence are complete. See `system-architecture-tick-concepts-and-invariants.md` and the World Management service docs for detailed topology guidance and operational runbooks. +### Current Topology Cutover Fallback + +The current runtime has no supported split/merge operation, region-partitioned durable ownership boundary, or topology reset/rebuild/resume controller. Do not move or rename live Redis queues, hand-edit coordination keys, flush/rebuild a topology scope, or invoke the target protocol. For an actual topology or reset incident, use only the shipped instance-scoped `PauseTicksForScope` / `GetRuntimeOwnershipStatus` boundary and read-only inspection, keep the affected instance paused/fenced or stopped, and escalate through [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). The current instance-scoped resume endpoint is an ordinary pause control, not evidence that a mapping-changing cutover or reset/rebuild completed; it must not be used to release this fallback. + --- ## Per-Command Execution Phases @@ -382,7 +392,7 @@ See `system-architecture-tick-execution-flows.md` for the detailed algorithm, in Tick execution uses a **staging/commit pattern**: - Stage: compute intended effects and write them into Redis (`tick:{tenantRegionTag}:pending`) via Lua under the region lease. -- Commit: call into domain services, which apply changes using the region-scoped tick timeline `(regionEpoch, tickId)` and effect guards to ensure idempotency across replays and resets. +- Commit: call into domain services, which apply changes under the root/participant guard contract; the region-scoped tick timeline `(regionEpoch, tickId)` supplies ordering and fencing context across replays and resets. Full commit-pattern details are in `system-architecture-tick-execution-flows.md` and the Redis docs. @@ -414,21 +424,17 @@ Isolation and replay guarantees rely on: - Per-region leases and locks in Redis. - A shared coordination timeline `(regionEpoch, tickId)` per `` as described in the Redis architecture docs. -- Domain-level idempotency rules use `(regionEpoch, tickId)` as timeline ordering/fence context and use namespace-complete effect projections plus owner-local effect guards for logical identity. +- Domain-level idempotency rules use root/participant guards and namespace-complete effect projections for logical identity; `(regionEpoch, tickId)` remains ordering and fencing context rather than a universal mutation token. -Crash recovery replays staged ticks safely by re-invoking domain handlers; replays must not double-apply logical effects. Redis loss is evaluated against the measured `redis_unreplicated_write_window_slo_ms`; `ticks_exposed` is diagnostic only. The namespace-complete storage projection tuple `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` identifies the ledger/storage view. `playableStateScope` is separately persisted and exact-validated evidence, while `regionEpoch` and `tickId` provide ordering/timeline context rather than guard uniqueness. Participant guard logical uniqueness is exactly `(rootEffectId, typedOperation, targetAggregateType, targetAggregateId)`. If an owner-local physical partition is used, it is storage placement only and cannot alter logical uniqueness or deduplication. The immutable request digest is bound to and compared by that participant guard. The combination of the coordination timeline, tick effect ledger, and per-service idempotency guards applies the ADR 0058 class-specific outcomes: each projection converges to a single terminal outcome (`APPLIED` or `ABANDONED`) only when the evidence policy permits terminalization; an inconclusive old-epoch projection remains reconciliation-required and non-terminal under its original root `EffectId`. See [ADR 0058](./decisions/adr-0058-class-specific-redis-loss-outcomes.md) and [Tick Failure and Operations](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy). +Crash recovery re-invokes a domain handler for a staged effect only when durable evidence proves that the `SCHEDULED` effect was unapplied and replay is safe under its owner contract; a missing response or ambiguous guard leaves the effect `SCHEDULED` and reconciliation-required. Replays must not double-apply logical effects. Redis loss is evaluated against the measured `redis_unreplicated_write_window_slo_ms`; `ticks_exposed` is diagnostic only. The namespace-complete storage projection tuple `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` identifies the ledger/storage view; durable projections also retain the persisted root-or-child `EffectId`, enclosing `rootEffectId` lineage, typed operation, immutable request digest, and required command/source bindings where allocated. `playableStateScope` is separately persisted and exact-validated evidence, while `regionEpoch` and `tickId` provide ordering/timeline context rather than guard uniqueness. Participant-guard logical uniqueness is the owner-declared runtime-family partition plus the persisted root-or-child `EffectId`, typed operation, and exact target aggregate: root operations use the root `EffectId`, while generated children use their persisted child `EffectId` and retain `rootEffectId` only as enclosing lineage and reconciliation context. S1/S2 uses `(tenantId, playableStateNamespaceId)` and only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)`; the partition must be sealed and exact-validated and cannot create a second guard or fork the same logical mutation. For S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence; for all families, `playableStateScope`, timeline, digest, and lineage remain immutable bound projection evidence rather than additional uniqueness dimensions. Game Session command-root allocation remains the opaque durable command-row identity `(tenantId, gameInstanceId, commandId, planOrdinal)`; passive, inbound/remote, timer, retry, and already-generated effects retain owner/source-specific identities. The combination of the coordination timeline, tick effect ledger, and per-service idempotency guards applies the ADR 0058 class-specific outcomes: each projection converges to a single terminal outcome (`APPLIED` or `ABANDONED`) only when the evidence policy permits terminalization; an inconclusive old-epoch projection remains reconciliation-required and non-terminal under its original mutation `EffectId`, with enclosing `rootEffectId` retained as lineage and reconciliation context. See [ADR 0058](./decisions/adr-0058-class-specific-redis-loss-outcomes.md) and [Tick Failure and Operations](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy). --- ## Timers and Time Scaling -Tick timers (cooldowns, regeneration, delayed effects) are: +Every scheduler/timer source carries exactly one tagged, persisted source due point: `dueTickId` for tick-based scheduling or immutable `dueAt` for wall-clock scheduling; it carries neither both nor neither as its source due point. Tick-based queued commands, retries, remote follow-ups, and tick timers use their persisted `dueTickId` directly. A wall-clock timer remains eligible from its immutable `dueAt` (`now >= dueAt`). Once eligible, one durable firing-claim/admission transaction reads the authoritative target timeline and assigns/persists exactly one target `regionEpoch` and `due_tick_id` ordering coordinate (normally the next committable tick), together with the source claim. Retries and replays reuse those persisted values and never recompute them from cadence or wall time. An epoch change follows old-epoch reconciliation and new admission; it never rebinds the old firing. The within-entity tuple uses the persisted admission `due_tick_id` for wall-clock timers and the persisted `dueTickId` for tick timers. Wall-clock timestamps and tick IDs are different domains and must not be compared numerically or aliased. -- Stored and scheduled via Redis timer keys. -- Aligned with the tick heartbeat and tick cadence. -- Subject to time-scaling rules that speed up or slow down perceived time while preserving ordering. -- Evaluated against absolute wall-clock `due_ms` values using caller-supplied `now_ms` in Lua (never Redis `TIME`); changing `tick_interval_ms` does not rescale already-scheduled timers. -- When a timer also has durable ordering/replay metadata, `due_ms` is the wall-clock firing input while the persisted `due_tick_id` is the canonical ordering and replay key. +Timer projections are stored and scheduled via Redis timer keys and remain aligned with the tick heartbeat and tick cadence. Time-scaling rules may speed up or slow down perceived time while preserving ordering, but a later cadence or time-scale change never rewrites an existing due point. Wall-clock eligibility uses caller-supplied `now_ms` in Lua (never Redis `TIME`); tick eligibility uses the committed region timeline. Tick-region timers and retry queues are **volatile coordination structures**, not durable schedules. After coordination resets or data loss, only timers/schedules that are also represented durably elsewhere (for example PostgreSQL-backed automation schedules or other explicit domain state) are expected to be recovered or re-derived. Gameplay features that require timers to survive resets must store the underlying intent durably and treat Redis timer entries as derived coordination indexes rather than as the only record of the timer. @@ -459,19 +465,19 @@ See `system-architecture-tick-failures-and-operations.md` for the full crash-rec ## Domain Idempotency Rules (Timeline Context + Owner Guards) -Domain services use the region-scoped tick timeline `(regionEpoch, tickId)` for ordering and fencing, not as the canonical idempotency token for a logical effect: +Domain services use the region-scoped tick timeline `(regionEpoch, tickId)` for ordering and fencing, not as the canonical idempotency token for a logical effect. The default mutation boundary is the mutation's stable persisted `EffectId` plus a participant guard containing the typed operation, exact target aggregate, and immutable request digest. Root effects use the root `EffectId`; generated child mutations use their deterministic persisted child `EffectId` and retain the enclosing root as lineage. A narrow last-tick watermark is permitted only for an explicitly documented aggregate proven to receive at most one logical mutation per tick timeline; it must not replace the effect/participant guard for general command effects. Exact allocator format and allocation-boundary details remain pending and non-authoritative in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). - Single-aggregate updates may use an epoch-aware “last applied tick” pattern (for example storing and comparing `(last_region_epoch, last_tick_id)` for the aggregate) only when the owning contract proves that at most one logical update for that aggregate can occur in each tick. Without that one-update-per-aggregate-per-tick invariant, each logical effect requires a participant guard derived from the stable root `EffectId`, typed operation, and target aggregate; a root-only ledger or guard is insufficient. The timeline tuple is ordering/fence context and is not sufficient idempotency identity. -- Multi-aggregate operations use explicit `tick_effect_guard` storage projections that retain the namespace-complete fields (for example `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)`) and link each row to the stable root `EffectId` plus its derived typed operation/target guard identity. `playableStateScope` is separately exact-validated evidence, and `regionEpoch`/`tickId` are ordering metadata; neither replaces the namespace nor creates guard uniqueness. +- Multi-aggregate operations use explicit `tick_effect_guard` storage projections that retain the namespace-complete fields (for example `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)`) and link each row to the enclosing root lineage plus the mutation's persisted root-or-child `EffectId` and derived typed operation/target guard identity. The guard uniqueness identity follows the owner-declared runtime family: S1/S2 uses the `(tenantId, playableStateNamespaceId)` partition plus `EffectId`, typed operation, and exact target aggregate, while only an explicit S3 family uses `(tenantId, gameInstanceId)` plus those identity fields. For S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence; `playableStateScope`, timeline, digest, and lineage remain immutable evidence, not uniqueness dimensions. Unknown or unclassified families fail closed and are never inferred to be S3. ### Tick Effect Identity and Idempotency Contract Effect identity and idempotency rules are defined jointly by: -- The `(regionEpoch, tickId)` carried on tick-driven calls as timeline ordering/fence context, not as the standalone logical identity of an effect. -- **Target-state effect identity:** Game Session assigns a stable root `EffectId` for each logical effect from admitted identity and tick context. Participant guard identities derive from that root effect, typed operation, and target aggregate; they bind the immutable request digest. Script-generated commands include `(automationDispatchId, commandOrdinal)` in their admitted operation identity; `scriptEventId` alone cannot distinguish fan-out commands. The current live path is documented above and remains a tracked implementation gap. +- The `(regionEpoch, tickId)` carried on tick-driven calls as ordering/fencing context. +- **Target-state plan-root identity:** Game Session supplies tick execution with the persisted deterministic command-plan root binding owned by [Transaction Strategies](./system-architecture-transactions.md#command-atomicity-and-outcome-aggregation). That frozen binding includes the applicable `playableStateNamespaceId` as exact runtime evidence and provides the stable root `EffectId`; participant guards derive from that root or a deterministic persisted child, typed operation, exact target aggregate, and immutable request digest. Tick scheduling and `(regionEpoch, tickId)` fence that work but never allocate, replace, or reinterpret its `EffectId`/`planOrdinal`; owner/source-specific non-command roots remain distinct. Script-generated commands retain `(automationDispatchId, commandOrdinal)` in their admitted operation identity, so `scriptEventId` alone cannot distinguish fan-out commands. The current live path is documented above and remains a tracked implementation gap. -The root identity is the canonical `EffectId` described in `system-architecture-transactions.md`; ledger records retain it and participant guards use its deterministic operation/target projection rather than ad-hoc keys. +The root identity and generated-child identity distinction is canonical in `system-architecture-transactions.md`; ledger records retain the enclosing root lineage, while participant guards use the mutation's persisted root-or-child `EffectId` with its deterministic operation/target projection rather than ad-hoc keys. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative. For the complete contract, ledger schema, and endpoint semantics, see `system-architecture-tick-failures-and-operations.md` and `system-architecture-transactions.md`. diff --git a/design/architecture/system-architecture-transactions.md b/design/architecture/system-architecture-transactions.md index 8f312b17bc..a97799d5f5 100644 --- a/design/architecture/system-architecture-transactions.md +++ b/design/architecture/system-architecture-transactions.md @@ -6,7 +6,7 @@ Script evaluation and pin transitions are not a new transaction substrate. The s ## Implementation Status -The structured participant-guard request, shared `IdempotentEffectExecutor`, standardized tick-effect outcome metric, and replay-verification helper described below are target-state contracts. The current replay tables and helpers remain narrower and domain-local; complete propagation and validation of the root `EffectId`, typed operation, target aggregate, immutable request digest, complete participant set, and shared helper/metric behavior are not yet fully implemented or proven. The current scripting handoff also does not carry, persist, or enforce `scriptPinEpoch` end to end, so it cannot yet reject same-version work from an older epoch; this is an implementation gap rather than a weakened target invariant. The target contract remains authoritative: matching requests may replay safely, while an operation, target, or digest mismatch fails closed. +The structured participant-guard request, deterministic command-plan root identity, shared `IdempotentEffectExecutor`, standardized tick-effect outcome metric, and replay-verification helper described below are target-state contracts. The current replay tables and helpers remain narrower and domain-local; complete propagation and validation of the plan's persisted `planOrdinal`/root-or-child `EffectId`, typed operation, target aggregate, owner-resolved S1/S2-versus-explicit-S3 guard partition, applicable `playableStateNamespaceId` and separately persisted `playableStateScope` evidence, separately validated active-instance fence, immutable request digest, complete participant set, and shared helper/metric behavior are not yet fully implemented or proven. Unknown or unclassified guard families must be rejected before any participant-guard allocation or admission; no implicit third partition exists. The current local instance-bound scripting handoff now carries, persists, and enforces the exact `scriptPinEpoch` tuple with its owner request evidence, including same-version old-epoch rejection; complete source/target remote tuple binding and full command identity remain implementation gaps rather than weakened target invariants. The target contract remains authoritative: matching requests may replay safely, while an operation, target, namespace, scope, active-instance evidence, or digest mismatch fails closed. Lifecycle and authoring workflows follow the same local-transaction boundary. World Management commits its lifecycle row/epoch with database compare-and-set; Temporal coordinates retries and waits but is not a transaction or authority. Replacement cutover follows the canonical [PREPARING-to-ACTIVE proof sequence](./system-architecture-versioning-runtime.md#realm-routing-contract-for-player-addressable-realms) and [Game Session cutover boundary](./microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary): World owns the lifecycle CAS and one-shot cutover hold, while the Game Session owner-local cutover transaction validates the hold id/fence, expected pointer version, and exact source and target `ACTIVE` proofs before its pointer CAS. World finalizes the hold only after authoritative Game Session readback proves the local pointer/audit/prepared-execution/source-cleanup/drain-fence transaction; no global transaction spans the services. A multi-owner Draft commit carries the complete [ADR 0129](./decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) binding, including target `tenantId`/`versionId`, request or proposal identity, exact `baseCommitId`, canonical revision order, proposed input/digest, and the complete affected `(owner, aggregateId, scopeId, epoch)` set. It performs compare-and-set in each owner database, records durable per-owner outcomes, and publishes through a synchronized read fence; it never uses a global epoch, silent merge, or distributed transaction. These are control-plane workflows and do not add a global ACID path to ordinary gameplay. @@ -32,6 +32,8 @@ Lifecycle and authoring workflows follow the same local-transaction boundary. Wo Commands whose temporary partial state could violate unique ownership, value conservation/non-negative balance, conditional exchange, irreversible consumption, premium entitlement, or external commitment do not use independent tick effects. They use one co-located authoritative transaction where possible, otherwise a durable reservation/escrow workflow with idempotent steps and transactional outbox delivery. Routine distributed two-phase commit is not a gameplay pattern. +Before tick staging, Game Session materializes the command's deterministic effect plan as the ordered set of logical root effects admitted for that command. The owning command/action contract for the frozen typed command or `ResolvedEffectPlan` supplies semantic order; built-in commands declare an equivalent stable order, and ambiguous or duplicate order fails before admission. Game Session persists the ordered plan manifest and digest. Each logical operation has one root `EffectId` and any number of participant guards beneath it. Single-root plans use `planOrdinal=0`, multi-root plans use stable zero-based `0..n-1`, and zero-effect plans allocate neither an ordinal nor a root. The durable gameplay command row freezes/binds its request fingerprint and resolved runtime scope before allocation. Game Session owns an opaque allocation row unique on `(tenantId, gameInstanceId, commandId, planOrdinal)`; it also binds the ordered plan manifest digest and validates that frozen command/runtime binding in the same local durable plan/staging transaction. Reuse requires the same command row identity, frozen command/runtime binding, `planOrdinal`, and manifest digest; any mismatch fails closed. For Automation, the complete applicable Command-Handoff Identity, including optional distinct target runtime fields when present, is the admission/deduplication identity and must exact-map to one durable target `commandId`; after that mapping, allocation uses the target command row's same canonical key. Trigger Identity and `scriptEventId` remain handler/correlation identities, not allocation inputs. A conserved multi-participant operation normally shares one root, but its atomicity still comes from the applicable ADR 0053 co-location or reservation/escrow boundary; the shared root is not global transaction authority. `tickBatchId`, mutable command text, `effectKey`, source ordering, participant tuples, and generated child ordinals cannot substitute for the durable command row identity or allocation binding; no global allocator is introduced. Exact allocator details remain pending and non-authoritative in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). + All real-time gameplay logic — movement, combat, item use, AI — is executed inside **ticks**. Each command is: - Pulled from the command queue @@ -80,23 +82,23 @@ If a proposed gameplay feature truly requires stronger semantics than this model ### Tick Effects Are At-Least-Once: Idempotency Is Mandatory -Tick execution is replayable: retries, failover, and Redis AOF replay can cause the same logical effect to be attempted more than once. For gameplay commands this is expected and safe only because tick-invoked domain mutations are required to be idempotent with respect to the stable root `EffectId` defined by the identifier glossary. - -- **Target-state identity contract:** Game Session assigns one stable root `EffectId` for the admitted logical effect. It preserves the intended pre/post state, required participant set, and status. A participant guard's uniqueness identity has exactly these inputs: the root `EffectId`, typed operation, and target aggregate. The guard row binds the immutable request digest and stores the outcome; outcome/status, evidence, and reconciliation fields are mutable guard-row state protected by compare-and-set (CAS), not uniqueness-identity inputs. A matching identity with a changed operation, target, or request digest fails closed. Ordinary retries and replay keep the root `EffectId`; deterministic child effects are used for derived reactions. -- **Post-abandon re-drive:** A fresh root is not an ordinary retry or replay. It is permitted only after the original effect is conclusively terminal `ABANDONED` and its source claim is terminalized, and only when recovery allocates a later `(regionEpoch, tickId)` coordinate, a fresh root `EffectId` and participant projections, and a new retry/source identity with durable lineage to the original identities. Until that allocation commits, the work remains recovery work and is not returned to an ordinary queue. -- **Command/effect boundary:** An accepted command lost before durable staging terminalizes only at command scope as `executionOutcome = LOST_BEFORE_STAGING` and `gameplayResult = NOT_APPLIED`; no effect ledger row is invented. Once an effect is durably claimed or staged, physical execution is at least once and its immutable identity/digest guard permits at most one logical mutation. Staged effects terminalize as `APPLIED` or `ABANDONED` only when authoritative evidence permits; inconclusive work remains `SCHEDULED`/reconciliation-required, explicitly including timeout, retry exhaustion, or missing coordination. `REPLAY_NOOP` is an `APPLIED` reason, never a third status. Command `SUCCESS`, `PARTIAL`, `FAILED`, `TIMEOUT`, and `NOT_APPLIED` remain derived player-result vocabulary under ADR 0053. See [ADR 0069](./decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md). -- **Single propagation contract:** The coordinator sends the root `EffectId`, typed operation, target, immutable request digest, and required-participant context. Participants validate them and atomically commit their guard with effect-visible rows before acknowledging. They do not generate a fresh identity or bind a guard to mutable payload. -- **Current live implementation gap:** The live Game Session proto does not yet carry `commandOrdinal` or the full Trigger Identity for this handoff. `TickStagingService` currently derives `effectKey` from `commandId`, falling back to a hash of command text plus the staging slot when no command id is available. That current fallback is not the target-state automation fan-out identity and must not be documented as though `(automationDispatchId, commandOrdinal)` were already enforced live. -- The canonical `effectKey` serialization is versioned, deterministic, and shared by all participants: before encoding, validate every identity-bearing and typed field against its declared type and domain, then serialize only canonical representations of the stable identity, per-effect discriminator or operation identity, and other fields in a fixed order with canonical UTF-8 length-prefixed values. Numeric values use canonical base-10 decimal representations where their type permits them; a participant must not independently stringify, normalize differently, or reorder the fields. The exact serialized bytes are reused unchanged on retry. -- Owning services implement durable idempotency guards (unique constraints, monotonic updates, transactional outbox) under the derived participant guard identity. Duplicate matching attempts become prior-result/no-op outcomes; a guard conflict fails closed. Each service persists its guard outcome and any outbox/reconciliation reference, while Game Session aggregates required participant outcomes under the root `EffectId`. -- **Generated effect chains:** Generated children carry immutable parent/root identity, `depth = parent.depth + 1`, a digest-covered deterministic child ordinal, and deterministic root-chain count/cost/per-target accounting. Only a child exceeding a bound is suppressed; committed parents and earlier children remain authoritative. Required/optional authored classification derives truthful `SUCCESS`, `PARTIAL`, or `FAILED` outcomes, and suppression evidence uses bounded metric dimensions with raw identities retained for audit. See [ADR 0075](./decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). -- For gameplay-visible mutations, derived participant-guard rows backed by the stable root `EffectId` are the default idempotency boundary. Simpler `last_tick_id` watermark patterns are allowed only for aggregates explicitly documented as receiving at most one logical mutation per tick. +Tick execution is replayable: retries, failover, and Redis AOF replay can cause the same logical effect to be attempted more than once. For gameplay commands this is expected and safe only because tick-invoked domain mutations are required to be idempotent with respect to the stable persisted mutation `EffectId`—the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child mutation—with any enclosing `rootEffectId` retained only as lineage and reconciliation context, as defined by the identifier glossary. + +- **Target-state identity and guard contract:** The deterministic command-plan allocation above is the canonical command-root contract. Participant-guard durability follows the owning runtime-family classification: S1/S2 owner families use `(tenantId, playableStateNamespaceId)` plus the owning identity/effect (`EffectId`, typed operation, and target aggregate), while only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)` as its durable partition. For S1/S2, the active `gameInstanceId` remains separately exact-validated authorization/fence evidence and does not create a second guard identity; unknown or unclassified families are rejected before any participant-guard allocation or admission and are never inferred to be S3. Root effects use the root `EffectId`, while generated child mutations use their deterministic persisted child `EffectId` and retain the enclosing root as lineage and reconciliation context. The guard row binds the immutable request digest and stores mutable outcome/evidence state under CAS. Matching replay returns the stored result, while a tenant, namespace, owning effect, operation, target, scope, active-instance evidence, or digest mismatch fails closed. Work explicitly outside playable-state scope must use an accepted owner-specific idempotency/partition contract; it cannot omit namespace/scope and proceed under this gameplay participant-guard contract. Exact child allocation remains outside this accepted guard decision and is described only by non-authoritative [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +- **Post-abandon re-drive:** A fresh root is not an ordinary retry or replay. After conclusive `ABANDONED` evidence and source terminalization, a command re-drive creates a new durable `commandId` linked to the prior command/effect lineage before allocating its later-coordinate plan root; reusing the old `commandId` returns its terminal result. Non-command sources use their owner-specific linked re-drive identity. Until the new allocation commits, the work remains recovery work and is not returned to an ordinary queue. +- **Command/effect boundary:** An `ACCEPTED_VOLATILE` command lost before durable staging may terminalize only at command scope as `executionOutcome = LOST_BEFORE_STAGING` and `gameplayResult = NOT_APPLIED` while its ingress status is `RECEIVED` or `ENQUEUED` and no `tickBatchId` survives; an `ACCEPTED_DURABLE` command follows its feature-specific durable replay/re-drive contract instead. No effect ledger row is invented for either command unless an effect was durably claimed or staged. A durable pre-staging source/effect claim establishes recoverability but does not itself make physical execution at least once; only a staged or otherwise dispatchable effect enters physical execution, after which its immutable identity/digest guard permits at most one logical mutation. Staged effects terminalize as `APPLIED` or `ABANDONED` only when authoritative evidence permits; inconclusive work remains `SCHEDULED`/reconciliation-required, explicitly including timeout, retry exhaustion, or missing coordination. `REPLAY_NOOP` is an `APPLIED` reason, never a third status. Command `SUCCESS`, `PARTIAL`, `FAILED`, `TIMEOUT`, and `NOT_APPLIED` remain derived player-result vocabulary under ADR 0053. See [ADR 0069](./decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md). +- **Single propagation contract:** The coordinator sends the mutation's persisted root-or-child `EffectId`, typed operation, target, immutable request digest, conditional owner-family partition, separately validated active-instance authorization/fence evidence, and required-participant context; generated children also carry their enclosing root/parent lineage binding. Game Session retains the command root's associated `planOrdinal` in its plan/ledger binding. Participants validate the complete binding and atomically commit their guard with effect-visible rows before acknowledging. They do not generate a fresh identity or bind a guard to mutable payload. +- **Current live implementation gap:** The live Game Session proto does not yet carry `commandOrdinal`, the complete applicable Command-Handoff Identity, or the deterministic plan manifest/opaque root allocation binding for this handoff. `TickStagingService` derives the live `effectKey` from `commandId`; it retains a deterministic command-text-plus-slot fallback helper for selection metadata, but durable tick batching rejects any queued entry without a `commandId` before staging or effect persistence. That fallback is therefore not a live staging, replay, or recovery identity, and it is not the target-state automation handoff or command-plan identity; the complete Command-Handoff Identity and root allocation binding are not yet enforced live. +- **Effect-key boundary:** `effectKey` remains a source-specific descriptor, ordering, or correlation field under its owning contract; it is not the root allocation identity. Existing source-specific validation or serialization may remain where already defined. Root allocation uses the opaque Game Session binding on the durable command row's `(tenantId, gameInstanceId, commandId, planOrdinal)` key plus its frozen command/runtime binding and ordered plan manifest digest; retries reuse the stored binding, and any mismatch fails closed. +- Owning services implement durable idempotency guards (unique constraints, monotonic updates, transactional outbox) under the derived participant guard identity. Duplicate matching attempts become prior-result/no-op outcomes; a guard conflict fails closed. Each service persists its guard outcome and any outbox/reconciliation reference, while Game Session aggregates required participant outcomes under the enclosing root `EffectId`. +- **Generated effect chains:** Generated children carry immutable parent/root identity, `depth = parent.depth + 1`, a stable child ordinal allocated and persisted by the owning contract for replay-stable reuse, and deterministic root-chain count/cost/per-target accounting. When generated work is under an admitted command, it remains beneath that command's root; otherwise it retains its owner/source-specific identity and does not synthesize a command plan. Only a child exceeding a bound is suppressed; committed parents and earlier children remain authoritative. Required/optional authored classification derives truthful `SUCCESS`, `PARTIAL`, or `FAILED` outcomes, and suppression evidence uses bounded metric dimensions with raw identities retained for audit. The owning contract's child-admission transaction must durably map its complete owner scope, enclosing root identity, immutable parent identity, and deterministic child ordinal to exactly one child `EffectId` using CAS, insert-if-absent, or an equivalent atomic boundary. The mapping is persisted before enqueue/apply; exact retries/replays read and reuse the persisted child identity, lineage, and accounting, while any scope, identity, lineage, ordinal, or immutable-request-digest conflict fails closed before enqueue/apply. This source-specific mapping does not replace participant-guard uniqueness (child `EffectId`, typed operation, exact target) or the separate Automation Command-Handoff/global-fanout identity contracts. See [ADR 0075](./decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). Exact scalar/allocation details remain non-authoritative in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +- For gameplay-visible mutations, derived participant-guard rows backed by the mutation's stable persisted root-or-child `EffectId` are the default idempotency boundary. Simpler `last_tick_id` watermark patterns are allowed only for aggregates explicitly documented as receiving at most one logical mutation per tick. - **Target-state shared idempotency helper contract (not yet fully implemented or proven):** To keep this contract consistent across services, tick-driven handlers use a shared idempotency helper from `common-data-runtime` (for example an `IdempotentEffectExecutor`) instead of ad-hoc “check or insert” patterns. The helper: - - **Target-state request shape:** Accepts a structured `ParticipantGuardRequest` containing the root `EffectId` (`rootEffectId`), typed operation, target aggregate type, target aggregate ID, and immutable request digest (`requestDigest`), plus callbacks for “apply-if-first” and “handle-replay”. - - **Target-state full-field replay validation:** Treats an existing guard as a valid replay only when all of those request fields match the persisted guard identity and digest; a changed operation, target aggregate, or digest fails closed and must not invoke the replay callback. + - **Target-state request shape:** Accepts a structured `ParticipantGuardRequest` containing the owner-resolved runtime-family classification and conditional durable partition—S1/S2 uses `(tenantId, playableStateNamespaceId)` plus the owning identity/effect, while only an explicitly owner-classified S3 uses `(tenantId, gameInstanceId)`—and separately carries the active `gameInstanceId` authorization/fence evidence for S1/S2. The request also contains mutation guard `EffectId` (`effectId`), typed operation, target aggregate type, target aggregate ID, applicable `playableStateNamespaceId` evidence, separately persisted server-derived `playableStateScope` evidence, and immutable request digest (`requestDigest`), plus callbacks for “apply-if-first” and “handle-replay”. A generated child request also carries its enclosing `rootEffectId` and parent/child lineage binding; for S1/S2, namespace is the uniqueness partition while scope and active-instance evidence are exact-validated sealed-context fences, and lineage fields do not replace the conditional partition, `effectId`, operation, and exact target in guard uniqueness. Unknown or unclassified families, or a request with no accepted owner-specific partition, are rejected before any participant-guard allocation or admission; they are never inferred to be S3. + - **Target-state full-field replay validation:** Treats an existing guard as a valid replay only when all of those request fields match the persisted guard identity, conditional allocation partition, namespace evidence, separately persisted scope evidence, separately validated active-instance authorization/fence evidence, and digest. A changed tenant, namespace, owning effect, operation, target aggregate, scope, active-instance evidence, or digest fails closed and must not invoke the replay callback; an S3 family additionally exact-compares its durable `gameInstanceId` partition. A work item explicitly outside playable-state scope must use an accepted owner-specific idempotency/partition contract; it cannot omit namespace/scope and proceed under this gameplay participant-guard contract. No family may omit its declared partition. - **Target-state guard behavior:** Encapsulates the canonical guard pattern (insert-if-absent, treat conflicts as replay) and throws well-defined exceptions on guard violations. - **Target-state standardized metric:** Emits a simple, standardized counter such as `tick_effect_outcome_total{service, effect_type, outcome}` so operators can distinguish first-apply vs replay behavior across services without per-tenant configuration. -- **Replay verification transaction (target state):** Replay evidence is not an audit-only side effect and is not proved by a root effect or one ledger row in isolation. The verifier reconstructs the complete expected concrete participant-projection set from the sealed required-participant and manifest context. It validates every expected participant guard and corresponding durable domain evidence, rejects missing, extra, partial, or conflicting projections, and CASes all required rows transactionally within their owning durable boundaries before the fenced Game Session reconciliation transaction records the result. A stale status, fence/context, missing evidence, incomplete set, set mismatch, or concurrent winner fails closed and rolls back/rejects or retries; external logs and audit streams are projections and cannot authorize a replay transition. +- **Replay verification transaction (target state):** Replay evidence is not an audit-only side effect and is not proved by a root effect or one ledger row in isolation. The verifier reconstructs the complete expected concrete participant-projection set from the sealed required-participant and manifest context. It validates every expected participant guard and corresponding durable domain evidence against the declared S1/S2 or explicit S3 partition, namespace/owning identity, and separately validated active-instance fence, rejects missing, extra, partial, or conflicting projections, and CASes all required rows transactionally within their owning durable boundaries before the fenced Game Session reconciliation transaction records the result. A stale status, fence/context, missing evidence, incomplete set, set mismatch, or concurrent winner fails closed and rolls back/rejects or retries; external logs and audit streams are projections and cannot authorize a replay transition. > 🔗 The canonical `EffectId` contract and per-side-effect patterns are defined in [Tick Effect Identity and Idempotency Contract](./system-architecture-ticks.md#tick-effect-identity-and-idempotency-contract). @@ -119,11 +121,13 @@ To prevent cross-instance collisions and make retries safe, spatial tick effects #### DROP/PICKUP targeting and actor-fence critical section -`DROP` and `PICKUP` keep the holder mutation in Entity Management, but their World fact read and Entity commit form one Game Session-controlled critical section. Game Session acquires an actor lock keyed by the complete gameplay scope, including `regionId`, and `actorEntityId`, captures the lock's opaque Redis token separately from the current `(regionId, regionEpoch, executorFence)` durable-authority tuple, and, before World validation, durably records one in-flight spatial critical-section barrier keyed by the existing scoped root identity `(tenantId, gameInstanceId, EffectId)` and bound to `actorEntityId`, `regionId`, `RoomInstanceRef`, `regionEpoch`, `executorFence`, and the canonical immutable `requestDigest`. The barrier is coordination/evidence state, not a second effect identity. `regionId` comes from Game Session's durable region authority and is propagated unchanged through World validation and any Game Logic re-resolution under the same root `EffectId` and unchanged `requestDigest`. Game Session retains the actor-lock token/lease and durable fence through the Entity-local transaction while asking World to validate the `TargetingFactSnapshot` location/version evidence. World returns an attestation bound to that same root `EffectId`, actor, `regionId`, `RoomInstanceRef`, `regionEpoch`, `executorFence`, and exact unchanged `requestDigest`. +`DROP` and `PICKUP` keep the holder mutation in Entity Management, but their World fact read and Entity commit form one Game Session-controlled critical section. Game Session acquires an actor lock keyed by the complete gameplay scope, including `regionId`, and `actorEntityId`, captures the lock's opaque Redis token separately from the current `(regionId, regionEpoch, executorFence)` durable-authority tuple, and, before World validation, durably records one in-flight spatial critical-section barrier keyed by the existing scoped root identity `(tenantId, gameInstanceId, EffectId)` and bound to `actorEntityId`, `regionId`, the exact `playableStateNamespaceId`, the separately exact-bound `playableStateScope`, `RoomInstanceRef`, `regionEpoch`, `executorFence`, and the canonical immutable `requestDigest`. The namespace and scope are barrier evidence, not additional uniqueness dimensions; barrier uniqueness remains `(tenantId, gameInstanceId, EffectId)`. The barrier is coordination/evidence state, not a second effect identity. `regionId` comes from Game Session's durable region authority and is propagated unchanged through World validation and any Game Logic re-resolution under the same root `EffectId` and unchanged `requestDigest`. Game Session retains the actor-lock token/lease and durable fence through the Entity-local transaction while asking World to validate the `TargetingFactSnapshot` location/version evidence. World returns an attestation bound to that same root `EffectId`, actor, `regionId`, exact `playableStateNamespaceId`, exact `playableStateScope`, `RoomInstanceRef`, `regionEpoch`, `executorFence`, and exact unchanged `requestDigest`. + +Game Session renews the actor-lock lease with that same opaque Redis lock token through Entity's commit acknowledgement and passes the attestation unchanged to Entity; the durable `executorFence` is validated separately at the barrier and Entity commit gates. Entity verifies the attestation's exact binding, including `regionId`, exact `playableStateNamespaceId`, and exact `playableStateScope`, against the request, participant guard, and canonical unchanged `requestDigest` for the same root `EffectId` in its local transaction before changing the holder. A missing, mismatched, or stale attestation (including a changed region, namespace, scope, epoch, or fence) commits no Entity mutation; the Game Session orchestrator invokes Game Logic to re-resolve the targeting facts under that same root `EffectId`, preserving the unchanged `requestDigest`, namespace, scope, and `regionId`. A changed request is rejected under the participant guard rather than reusing the root. Barrier creation, renewal, replay, terminalization, and reconciliation are durable, fence-checked transitions; each preserves and exact-compares the namespace and scope evidence, and Redis lock expiry cannot clear or terminalize the barrier. A lock-renewal failure or fence change fences the old orchestrator and leaves the durable barrier `RECONCILIATION_REQUIRED`. Handoff/recovery must drain or reconcile that barrier from durable guard/holder evidence, including the exact namespace and scope; a new owner may reconcile the exact root `EffectId`, but MOVE admission cannot authorize a conflicting actor move merely because the Redis lock expired, and must wait for terminal barrier evidence. Every `MOVE` for the actor must acquire the same actor lock and pass the barrier gate, so it cannot interleave between World validation and Entity commit. After Entity commits, the acknowledgement is recorded, and the barrier and lock are released, a later valid `MOVE` is permitted. This is serialization, durable barrier evidence, and fencing across local transactions, not a distributed World/Entity transaction. -Game Session renews the actor-lock lease with that same opaque Redis lock token through Entity's commit acknowledgement and passes the attestation unchanged to Entity; the durable `executorFence` is validated separately at the barrier and Entity commit gates. Entity verifies the attestation's exact binding, including `regionId`, against the request, participant guard, and canonical unchanged `requestDigest` for the same root `EffectId` in its local transaction before changing the holder. A missing, mismatched, or stale attestation (including a changed region, epoch, or fence) commits no Entity mutation; the Game Session orchestrator invokes Game Logic to re-resolve the targeting facts under that same root `EffectId`, preserving the unchanged `requestDigest` and `regionId`. A changed request is rejected under the participant guard rather than reusing the root. Barrier creation, renewal, and terminalization are durable, fence-checked transitions; Redis lock expiry cannot clear or terminalize the barrier. A lock-renewal failure or fence change fences the old orchestrator and leaves the durable barrier `RECONCILIATION_REQUIRED`. Handoff/recovery must drain or reconcile that barrier from durable guard/holder evidence; a new owner may reconcile the exact root `EffectId`, but MOVE admission cannot authorize a conflicting actor move merely because the Redis lock expired, and must wait for terminal barrier evidence. Every `MOVE` for the actor must acquire the same actor lock and pass the barrier gate, so it cannot interleave between World validation and Entity commit. After Entity commits, the acknowledgement is recorded, and the barrier and lock are released, a later valid `MOVE` is permitted. This is serialization, durable barrier evidence, and fencing across local transactions, not a distributed World/Entity transaction. +Any handoff or recovery path that performs maintenance mutation on this barrier must first carry the unchanged ADR-0085 external maintenance handoff: exact `operationId`, external maintenance fence/lock binding, classifier, immutable evidence digest, and complete affected scope. The only alternative is an explicitly owner-recorded non-conflicting routine-replay or reconciliation exemption with its classification and evidence. The actor Redis lock and durable `executorFence` remain separate execution aids and never substitute for either authorization; a missing or mismatched handoff or exemption leaves the barrier `RECONCILIATION_REQUIRED` and fails closed. These controls do not alter the accepted `(tenantId, gameInstanceId, EffectId)` identity or its exact request/namespace/scope evidence. -Focused proof must exercise stale location/version evidence, root/actor/room/epoch/fence or request-digest mismatches, Entity rejection before holder mutation, actor-lock lease expiry while the barrier is in flight, an owner crash after World validation and before Entity acknowledgement, lock-renewal failure, executor-fence change fencing the old orchestrator, handoff/recovery reconciliation of the exact root, an old Entity commit racing a new MOVE, and a valid `MOVE` after terminal barrier evidence. For `PICKUP`, a previously moved item is replay only when the stored participant guard matches the same root `EffectId`, immutable request digest, and exact destination container for that actor; another holder or a different destination is a conflict/stale/reconciliation outcome, never a generic replay. +Focused proof must exercise stale location/version evidence, root/actor/room/namespace/scope/epoch/fence or request-digest mismatches, Entity rejection before holder mutation, actor-lock lease expiry while the barrier is in flight, an owner crash after World validation and before Entity acknowledgement, lock-renewal failure, executor-fence change fencing the old orchestrator, handoff/recovery reconciliation of the exact root, an old Entity commit racing a new MOVE, and a valid `MOVE` after terminal barrier evidence. For `PICKUP`, a previously moved item is replay only when the stored participant guard matches the same root `EffectId`, immutable request digest, and exact destination container for that actor; another holder or a different destination is a conflict/stale/reconciliation outcome, never a generic replay. Ambient world mutations (doors, hazards, weather) are treated as spatial effects for replay and idempotency purposes: @@ -142,41 +146,59 @@ Cross-service effect convergence has a single owner of record: - **Game Session Service** owns reconciliation orchestration and backlog durability for spatial/ambient effects. - World Management and Entity Management remain owners of their domain writes and idempotency guards, but they do not own cross-service retry scheduling. +**Current implementation status:** this reconciliation backlog, its typed `EffectReconciliationAuthority`, its durable backlog/authority schema, and the list/retry/acknowledgement control-plane interfaces below are target-only and unimplemented. Current Game Session persists `tick_batch` and `tick_effect` rows, but it has no implemented `effect_reconciliation_backlog` schema or API. Existing domain participant guards and remote-follow-up reconciliation do not establish this cross-service backlog surface. This paragraph records current status only; the owner and contract below remain normative target state. + Durable backlog contract: - Game Session persists one row per logical effect in a durable backlog table (for example `effect_reconciliation_backlog`) keyed by `(tenantId, gameInstanceId, effectId)`. - Minimum persisted fields: - - `effectType` - - `targetScope` (`RoomInstanceRef` or region scope) + - `effectType` (the typed operation/effect identity, not only a display category) + - `targetAggregateId` (the exact target aggregate identity) + - `targetScope` (the complete target scope, including the applicable namespace, region/epoch, and other scope-fence evidence; `RoomInstanceRef` or region scope is not sufficient by itself) + - `requestDigest` (the immutable digest of the normalized request and operation inputs) + - `sealedManifestRef` and `sealedManifestDigest` for the immutable participant/operation manifest, or an equivalent immutable reference whose read is mandatory before action + - `ownerFence`, `executorFence`, and applicable pin/version and namespace/scope evidence, when those guards apply to the effect - `expectedParticipants` (for example `WORLD`, `ENTITY`) - `participantAckState` (per participant applied/pending/final-failure) - `firstObservedAt`, `lastAttemptAt`, `attemptCount`, `nextAttemptAt` + - `backlogRevision` (a monotonic compare-and-set revision for control-plane actions) - `status` (`PENDING`, `CONVERGED`, `DEAD_LETTER`) - `lastErrorCode` / `lastErrorMessage` +- Every immutable guard field is binding evidence written with the initial backlog row; it is not an additional backlog uniqueness or partition dimension, and retries and acknowledgements must not rewrite it. A compact reference to the sealed effect ledger is acceptable only when every retry and acknowledgement atomically resolves that reference and exact-compares the complete guard before action. A missing, unreadable, stale, or mismatched guard is an identity conflict/reconciliation-required outcome and fails closed; it is never treated as a fresh effect or a permissive wildcard. - The reconciliation ledger's `status` is a closed enum of `PENDING`, `CONVERGED`, and `DEAD_LETTER`; it remains separate from the player-visible command result and is not expanded with `PARTIAL` or other command-result values. -- Inserts and status transitions must be idempotent on `(tenantId, gameInstanceId, effectId)` so duplicate scheduling does not create duplicate backlog rows. +- Inserts and status transitions must remain idempotent on `(tenantId, gameInstanceId, effectId)` so duplicate scheduling does not create duplicate backlog rows; guard fields such as namespace, scope, operation, target, and fence are exact-compared conflict/reconciliation evidence rather than new uniqueness dimensions. Every control-plane mutation also compares `backlogRevision` and the expected status and advances the revision atomically with its result. - Backlog rows must be indexed at minimum by `(status, nextAttemptAt)` and `(tenantId, status, firstObservedAt)` for retry scans and operator triage. - For participant ack semantics, `applied` means the owning service can serve the effect through its documented durable read surface for the corresponding fence token. It does not mean `accepted for later batch flush`. +- `EffectParticipantAcknowledgement/v1` is the typed target acknowledgement exchanged by each mutation owner and Game Session. It carries the participant key and owner, a stable acknowledgement identity, the complete immutable effect guard (or mandatory `sealedManifestRef` plus `sealedManifestDigest`), exact effect request digest, target aggregate, complete target scope, applicable owner/executor/pin/version fence, owner revision, durable `applied` or `no-op` result/read reference, acknowledgement status, and evidence digest. An exact identity/guard retry replays the stored acknowledgement; changed identity, guard, target, scope, digest, fence, or owner revision fails closed. Only exact durable `applied`/`no-op` acknowledgements for every member of the sealed participant manifest may advance the backlog to `CONVERGED`; pending, final-failure, stale, missing, or ambiguous evidence cannot do so. World and Entity expose this participant contract from their owner boundaries; Game Session remains the cross-service backlog authority. Retry and dead-letter policy: - Default retry strategy is bounded exponential backoff with jitter and no mutation of `EffectId`. -- Effects remain `PENDING` until all required participants acknowledge applied/no-op for the same `EffectId`. -- Effects move to `DEAD_LETTER` only after retry exhaustion or explicit operator action; no destructive compensation is issued from this path. -- Dead-letter rows remain replayable via explicit operator/API actions; replay must preserve original `EffectId`. +- A backlog row remains `PENDING` until either all required participants acknowledge applied/no-op for the same `EffectId`, allowing reconciliation to transition it to `CONVERGED`, or retry exhaustion or explicit audited operator action transitions the backlog row to `DEAD_LETTER` without terminalizing the underlying effect. +- `DEAD_LETTER` is a backlog retry-control status, not an effect-ledger outcome; no destructive compensation is issued from this path. The underlying effect ledger remains governed by the `APPLIED`/evidence-qualified `ABANDONED` contract and remains nonterminal when execution is inconclusive. +- Dead-letter backlog rows remain replayable via explicit operator/API actions; an authorized replay transitions the backlog row back to `PENDING` under the existing audit/recovery contract and preserves the original `EffectId`. Acknowledgement is separate attention/audit evidence: it leaves retry-control status `DEAD_LETTER`, never terminalizes or compensates the underlying effect, and records immutable acknowledgement time, actor, reason, action identity, and result. A later authorized retry CASes `DEAD_LETTER` to `PENDING` while preserving that acknowledgement history. Retention and lifecycle policy: -- `CONVERGED` rows are retained for 24 hours, then deleted by background GC. -- `DEAD_LETTER` rows are retained for 30 days minimum (or longer by policy) for incident analysis. -- GC jobs must be idempotent and rate-limited per tenant to avoid write spikes. +- The owning Game Session family must declare its ADR 0163 retention class, terminal/reference/blocker predicate, minimum configured horizon, safe watermark, hold behavior, and bounded GC cadence/batch. Cleanup is eligible only after that predicate and watermark prove that no producer retry, replay, restore, or downstream compatibility path can reference or resurrect the logical effect; nonterminal, inconclusive, and held rows remain blockers. +- Exact retention values are configuration-backed operational policy owned by the [Scaling Runbook](./system-architecture-scaling-runbook.md#data-retention-and-high-churn-tables), not universal durations in this transaction contract. GC remains owner-local, idempotent, and rate-limited per tenant to avoid write spikes. Required control-plane interfaces: - `ListEffectReconciliationBacklog(tenantId, status, olderThan, page)` for diagnostics. -- `RetryEffectReconciliation(tenantId, gameInstanceId, effectId)` for explicit replay from `DEAD_LETTER` or stuck `PENDING`. -- `AcknowledgeEffectDeadLetter(tenantId, gameInstanceId, effectId, reason)` for audited operator decisions. +- `RetryEffectReconciliation(tenantId, gameInstanceId, effectId, actionRequestId, actionDigest, expectedBacklogRevision, expectedStatus, authority: EffectReconciliationAuthority)` for explicit replay from `DEAD_LETTER` or stuck `PENDING`. +- `AcknowledgeEffectDeadLetter(tenantId, gameInstanceId, effectId, reason, actionRequestId, actionDigest, expectedBacklogRevision, expectedStatus, authority: EffectReconciliationAuthority)` for audited operator decisions. It records the immutable acknowledgement evidence while leaving the row in `DEAD_LETTER` and the underlying effect outcome unchanged. - Logging & Admin dashboards should consume these APIs; operators should not mutate backlog tables directly. +- `actionRequestId` is stable for one requested control-plane action. Before any effect execution or external/authority call, the owner must persist a unique, digest-bound action-intent row keyed by the stable action-family request identity `(tenantId, gameInstanceId, effectId, actionRequestId)` with status `IN_PROGRESS`; `actionType` is an immutable tuple member, not a deduplication partition, and the existing identity must be loaded and compared before selecting the retry or acknowledgement branch. No action may execute without that intent. Reuse of the same request identity with a different action type or any other complete-tuple/digest difference fails closed as an identity conflict; it must not create a second intent row. `actionDigest` remains the API field name where useful and is the `mutationDigest/v1` value for the `effect-reconciliation-action/v1` action-family schema pair; it is not a competing `actionDigest/v1` digest owner. This family uses ADR 0047's exact seven top-level fields only: `scope` is the exact affected tenant/game/runtime scope; `target` is the effect identity plus exact target aggregate; `expectedVersion` is the expected backlog status and revision; `mutation` is the closed retry-or-ack action and its typed action inputs; and `auditReason` is the typed reason with explicit presence/value. `actionRequestId`, the opaque Account authorization reference, `EffectReconciliationAuthority` branch/reference/evidence, handoff/member evidence, actor/workload evidence, and reservation/fence fields remain excluded from the digest exactly as ADR 0047 requires and are separately exact-compared in the complete post-authorization/execution tuple. Absent and explicit `null` are distinct canonical values. The action-family mapping requires shared cross-language golden vectors, including absent/null cases, and explicit schema-version migration rules before any version change. +- Every `IN_PROGRESS` intent also records the current recovery owner/claim identity, a monotonic attempt fence, lease/deadline evidence, and the durable action identity used downstream. A successor may take over only through an owner-local CAS after lease expiry; stale owners and stale attempt fences are rejected before any backlog mutation or external call. The downstream owner or external operation must receive the stable action identity plus the current attempt fence, or an equivalent durable idempotency binding. For an owner-local backlog mutation, the action-intent row, backlog status/revision CAS, and final action result/outcome commit atomically in one owner-local transaction, so a successful local CAS cannot exist without the result persistence. Each intent has at most one terminal action result; a response is only a readback of that durable result. For an external or cross-service consequence, the action remains `IN_PROGRESS` until readback reconciliation against the exact effect guard, handoff and sealed member-manifest evidence, current backlog status/revision, and current attempt fence determines whether the consequence is applied, already applied, or still inconclusive. An ambiguous action must not be blindly reissued or assigned a new identity; the same `actionRequestId`/digest resumes reconciliation, while a changed digest fails closed as an identity conflict. Concurrent retry and acknowledgement actions serialize through the backlog CAS, rather than last-writer-wins behavior. +- The durable action ledger/result stores the digest, actor/time, expected state, CAS result, recovery claim/attempt fence, and returned outcome. Owner-local proof covers crash before the intent or before the atomic transaction commits, plus response loss after the committed result (which replays that result). Separately, external or cross-service proof covers a successful downstream CAS/consequence before local result persistence or a lost external response; recovery must reconcile the still-`IN_PROGRESS` intent from exact evidence. Lease expiry, takeover, stale-owner rejection, and all ambiguous cases must preserve the same action identity and either replay the committed result, reconcile the consequence, or remain safely inconclusive without a second action identity. + +`EffectReconciliationAuthority` is a typed union/reference carried by both mutating requests: + +- `ExternalMaintenanceHandoff` is the unchanged ADR-0085 handoff: exact `operationId`, external maintenance fence/lock binding, classifier, immutable evidence digest, and complete affected scope. The handoff also contains either a sealed exact-effect manifest or an immutable selection predicate plus a frozen owner-resolved member manifest and digest. For each action, the owner atomically resolves the handoff and compares its operation/fence/classifier/evidence digest/affected scope and member membership with the selected effect's immutable guard and current backlog revision/status. A handoff authorizes only its bounded sealed member set; it is not globally single-use, and each member action is independently idempotent through `actionRequestId`/`actionDigest`. Scope widening, stale revision or fence, absent membership, or any mismatch fails closed. The handoff evidence digest does not replace the effect's request digest. +- `OwnerRoutineReplayExemption` is an owner-issued, durably recorded non-conflicting exemption. It carries the stable owner-recorded `exemptionId` (and the existing owner authorization/audit record link where applicable), the exact effect identity, exact target, complete affected scope, classification, and immutable evidence digest. The owner persists this record before the request and atomically reads it back and exact-compares those fields with `(tenantId, gameInstanceId, effectId)`, the target, and the requested scope before allowing replay or reconciliation. A caller cannot self-label a request as routine or supply an unverified exemption. + +For spatial or ambient maintenance, recovery, or reset mutations invoked through either API, exactly one authority branch must resolve and match before mutation. The selected authority must also pass the common atomic effect-guard and backlog revision/status comparison; an authority that is valid for another effect, target, scope, or revision cannot authorize this action. Ordinary owner-local replay/reconciliation that satisfies the owner exemption may preserve the original `EffectId`; missing, ambiguous, or contradictory handoff/exemption evidence fails closed. Existing operator authorization issuance and redemption policy remains owned by its canonical Account/Logging & Admin contract; this carrier links to that owner evidence rather than redefining it here. Operational SLOs and alerts: @@ -311,15 +333,16 @@ FireMUD uses a **shared short synchronous saga orchestration library**, not a se - Supports compensation. - Explicitly classified adopters apply the bundled migrations as part of their own startup; non-adopter startup must not create Saga tables. - `SagaRunner` emits a `sagas.active` metric and attaches a `correlationId` to logs for each orchestration using MDC. - - The current Saga Dashboard (`/sagas` and `/sagas/{id}/steps`) provided by the [Logging & Admin Service](./microservices/logging-admin-service/README.md) reads only Logging & Admin's own local Saga rows. It does not aggregate adopter-local Saga state; target cross-owner visibility requires owner read APIs plus a bounded aggregation/read model, and must distinguish an unknown/unavailable adopter from an empty result. + - The current Saga Dashboard (`/sagas` and `/sagas/{id}/steps`) provided by the [Logging & Admin Service](./microservices/logging-admin-service/README.md) reads only Logging & Admin's own local Saga rows. It does not aggregate adopter-local Saga state; target cross-owner visibility requires read-only owner status APIs plus a bounded aggregation/read model or fan-out, must distinguish an unknown/unavailable adopter from an empty result, and must not read foreign databases or acquire execution authority. This library is intentionally not FireMUD's durable workflow engine. World lifecycle, publish, and script-patch readiness now use Temporal because they need restart-safe continuation, stable workflow identity, and operator-visible runtime state independent of one service process. - **Execution Model**: - Steps are gRPC calls to owning services - Helper `GrpcSagaSteps.callWithRetry` wraps gRPC calls with basic retry logic - - All steps are **idempotent** - - Every retryable workflow has one durable workflow/request identity derived from stable business identity and workflow scope. Every logical step has a durable guard identity `(workflow/request identity, stable step name, deterministic occurrence key, execution role)` bound to an immutable request digest. Same identity plus same digest deduplicates/replays its recorded outcome; same identity plus a different digest fails closed. Run, process, retry-attempt, and message/delivery IDs are trace metadata only, never authoritative deduplication keys. See [ADR 0078](./decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md). + - The retry helper does not make every step **idempotent**; idempotency remains an owner-local implementation and proof obligation. + - **Target-state workflow and step guards:** Every retryable workflow has one durable workflow/request identity derived from stable business identity and workflow scope. Every logical step has a durable guard identity `(workflow/request identity, stable step name, deterministic occurrence key, execution role)` bound to an immutable request digest. Same identity plus same digest deduplicates/replays its recorded outcome; same identity plus a different digest fails closed. Run, process, retry-attempt, and message/delivery IDs are trace metadata only, never authoritative deduplication keys. See [ADR 0078](./decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md) and its [current Automation adopter mapping](./decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md#current-automation-adopter-mapping). + - **Current implementation status:** Durable guard storage, conflict enforcement, adopter migration, and focused retry/replay proof remain incomplete; the current `common-saga` persistence and Temporal helper do not establish this target contract universally. See [ADR 0078 implementation status](./decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md#implementation-status). - Each step runs inside a local `@Transactional` method for atomicity - Compensation logic is registered via hooks - Retried automatically or flagged for manual review @@ -397,9 +420,7 @@ This is a target-state branch illustration, not current implementation or proof. This design centralizes logic, improves visibility, and avoids coupling orchestration directly into gameplay services. The `common-saga` module provides a `SagaBuilder` class implementing this pattern. See [Shared Libraries Overview](./system-architecture-shared-libraries.md) for additional details. -A concrete adopter must satisfy [Mandatory Workflow Adopter Classification](#mandatory-workflow-adopter-classification) in its canonical owning-service architecture document or an accepted ADR before it exposes the library's accompanying Flyway migrations at `classpath:db/migration/saga`; module or convention inclusion alone does not establish Saga adoption. See [ADR 0080](./decisions/adr-0080-service-owned-schemas-with-adopter-local-shared-migrations.md). -Example saga flows are documented in [World Creation Workflow](./microservices/world-management-service/world-creation-workflow.md) -and in the Logging & Admin Service README. +A concrete adopter must satisfy [Mandatory Workflow Adopter Classification](#mandatory-workflow-adopter-classification) in its canonical owning-service architecture document or an accepted ADR before it exposes the library's accompanying Flyway migrations at `classpath:db/migration/saga`; module or convention inclusion alone does not establish Saga adoption. See [ADR 0080](./decisions/adr-0080-service-owned-schemas-with-adopter-local-shared-migrations.md). The migrations persist `saga_instance` and `saga_step` in each adopter's own schema. Short-saga examples and consequences are documented in the [Game Session Service runtime and data](./microservices/game-session-service/runtime-and-data.md) and the Logging & Admin Service README; the [World Creation Workflow](./microservices/world-management-service/world-creation-workflow.md) is the Temporal `world-lifecycle` adopter, not a Saga. ### Saga vs Temporal Boundary diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 491a711f63..9cb93ca1e3 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -4,7 +4,7 @@ This workstream establishes a complete, reviewable chain from FireMUD product ca ## Status -Completed phases: capability allocation, implementation/proof reconciliation, cross-domain convergence, structural enforcement, independent validation of prior parcel states, human-led adversarial review of all `183` historical queue/navigation rows in the remotely backed review archive, selective import of all `182` historical decision keys, and integration of four direct post-archive human decisions with family-local contract consolidation. Packets 3-4 apply ADRs 0051-0130 plus the no-ADR TICK-05 outcome. Packet 5 applies all `21` reviewed outcomes through ADRs 0131-0150, including the superseded `SOCIAL-01` provenance. Packet 6 and Packet 7 complete the historical imports through ADRs 0151-0178. Direct decisions `COMMERCE-02`, `HOSTED-TERMS-01`, `HOSTED-TERMS-02`, and `OPS-07` apply through ADRs 0179-0182 without changing Packet 1-7 totals. The separately tracked service-scan `MS-AA-TOKEN-REVOCATION` row remains the only excluded navigation alias. The canonical registry contains `180` ADR records; `172` carry completed review metadata and `11` are pre-formal, with overlap where accepted legacy pre-formal records now carry exact provenance. Source-archive identifiers remain archive-local evidence and may collide numerically with canonical ADRs, so each integration preserves canonical repository numbering rather than importing source numbers. +Completed phases: capability allocation, implementation/proof reconciliation, cross-domain convergence, structural enforcement, independent validation of prior parcel states, human-led adversarial review of all `183` historical queue/navigation rows in the remotely backed review archive, selective import of all `182` historical decision keys, and integration of four direct post-archive human decisions with family-local contract consolidation. Packets 3-4 apply ADRs 0051-0130 plus the no-ADR TICK-05 outcome. Packet 5 applies all `21` reviewed outcomes through ADRs 0131-0150, including the superseded `SOCIAL-01` provenance. Packet 6 and Packet 7 complete the historical imports through ADRs 0151-0178. Direct decisions `COMMERCE-02`, `HOSTED-TERMS-01`, `HOSTED-TERMS-02`, and `OPS-07` apply through ADRs 0179-0182 without changing Packet 1-7 totals. The separately tracked service-scan `MS-AA-TOKEN-REVOCATION` row remains the only excluded navigation alias. The canonical registry contains `181` ADR records; `172` carry completed review metadata and `11` are pre-formal, with overlap where accepted legacy pre-formal records now carry exact provenance. ADR 0183 is a separately preserved pending proposal and is not counted as a reviewed or applied decision. Source-archive identifiers remain archive-local evidence and may collide numerically with canonical ADRs, so each integration preserves canonical repository numbering rather than importing source numbers. | Phase | Status | Output | | --- | --- | --- | @@ -24,7 +24,7 @@ This is the sole live corpus section-status index for a fresh whole-corpus revie The preserved 5B implementation work has been rebuilt into #2826 Schema, the dependent #2827 Automation lifecycle/fence successor, #2828 Publication, and #2829 Retention. The superseded #2808, #2678, #2804, and #2679 PRs were closed only after hunk-level no-loss verification; their branches and private ledgers remain historical evidence rather than live section ownership. The replacement stack is based on the independently reviewed non-5B prerequisites #2824 and #2818. Overall 5B is complete only after all three semantic subunits taper and a cross-subunit synthesis is recorded; there is no separate overall 5B status row. -5B synthesis: Active at the three-cycle report boundary; paired whole-5B closure Cycle 1 was dry, Cycle 2 was productive, and corrected-state Cycle 3 was dry. Cycle 2's two independent reviewers produced three accepted obligation families after deduplication. The corrected stack now enforces coordinated `Recreate`, roll-forward-only deployment for the incompatible Automation V3 and Game Design V26 migration boundaries; quarantines only V13-marked unattested legacy full versions while preserving bundled and script-only rows; and explicitly classifies the two Automation plugin-history retention families without inventing a cleanup TTL. Cycle 3's two independent reviewers returned 18 and 19 raw observations with zero new accepted obligations, but this is only the first dry cycle after the Cycle 2 corrections. The required two consecutive corrected-state dry cycles have therefore not established whole-5B closure taper. +5B synthesis: Corpus discovery accepted closed by Overseer at final cumulative #2829 head `dce1d8246e3ff2bf9c3bfcb9649ae0e5c4181e6b`; no fourth closure cycle is required. Paired whole-5B closure Cycle 1 was dry, Cycle 2 was productive, and corrected-state Cycle 3 was dry. Cycle 2's two independent reviewers produced three accepted obligation families after deduplication. The corrected stack enforces coordinated `Recreate`, roll-forward-only deployment for the incompatible Automation V3 and Game Design V26 migration boundaries; quarantines only V13-marked unattested legacy full versions while preserving bundled and script-only rows; and explicitly classifies the two Automation plugin-history retention families without inventing a cleanup TTL. Cycle 3's two independent reviewers returned 18 and 19 raw observations with zero new accepted obligations. Remaining implementation and proof gaps stay with their named owners; discovery closure does not claim those capabilities implemented or merged. | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | @@ -41,11 +41,11 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | 4A | Script ingress, sandbox, and runtime execution | Queued | — | — | | 4B | Scheduling, quotas, reload, and operational fairness | Queued | — | — | | 5A | API, message, identifier, tenant, time, and authorization primitives | Complete (corpus review; implementation gaps remain) | [#2813](https://github.com/benhook1013/FireMUD/pull/2813) | Three fresh whole-section passes each covered 17/17 substantive allocated sources: 8, 15, and 12 raw observations. The corrected-state third pass confirmed 12 useful already-owned handoffs, no new unowned root, and taper. The shared-library Redis status claim and conflicting operator incident/revocation guidance were corrected. gRPC outcomes, Account runtime-read exposure, numeric IDs, gameplay attestation, JWT/workload identity, Gateway connect-carrier and route inventory, and script-fence gaps remain with their service/shared-runtime owners; Redis role clients and descriptor foundation belong to 5C, and operator binding enforcement/readback plus terminal-reissuance design belong to 6D. This status does not claim those capabilities are implemented. | -| 5B-Schema | SQL/Flyway/jOOQ, schema and identifier migration | Broad review tapered; merge proof pending | [#2826](https://github.com/benhook1013/FireMUD/pull/2826) | Six fresh whole-unit cycles reached two corrected-state dry cycles after the accepted Schema fixes. Retained-row adjudication, mixed-binary deployment evidence, and Docker-backed PostgreSQL proof remain explicit limits. Dependent #2827 carries the separately reviewed Automation lifecycle/fence successor and is not additional Schema scope. | -| 5B-Publication | Durable version/publication/readiness state | Broad review tapered; closure correction published; merge proof pending | [#2828](https://github.com/benhook1013/FireMUD/pull/2828) | Cycles 1–4 were productive and corrected the accepted findings through V27; corrected-state Cycles 5 and 6 were dry. Whole-5B closure Cycle 2 subsequently added the V28 legacy full-version quarantine and made V26's incompatible participant-scope migration operationally stop-before-start and roll-forward-only. PostgreSQL retained-row execution, live mounted-certificate/Temporal owner calls, version-scoped Automation content, exact Game Design template/asset mapping, readiness notification, and dedicated ability-schema attestation remain open. | -| 5B-Retention | Retention classes, cleanup, horizons, contraction | Broad review tapered; closure correction published; merge proof pending | [#2829](https://github.com/benhook1013/FireMUD/pull/2829) | Cycle 1 fixed incomplete handoff-child cleanup; corrected-state Cycles 2 and 3 were dry. Whole-5B closure Cycle 2 then classified `plugin_runtime_request_history` as retry/idempotency receipt evidence and `plugin_runtime_events` as recovery/reconciliation plus lifecycle-audit evidence. Both remain ineligible for automatic deletion until measured horizons, holds, safe watermarks, bounded sweeps, and metrics exist. Recovery-aware dead-letter cleanup, cross-owner inequalities, and Docker-backed PostgreSQL proof remain open. | -| 5C | Redis roles and cache/rate-limit semantics | Queued | — | — | -| 5D | Idempotency, outbox, replay, saga, and workflow patterns | Queued | — | — | +| 5B-Schema | SQL/Flyway/jOOQ, schema and identifier migration | Corpus discovery accepted closed; merge proof pending | [#2826](https://github.com/benhook1013/FireMUD/pull/2826) | Six fresh whole-unit cycles reached two corrected-state dry cycles after the accepted Schema fixes. Retained-row adjudication, mixed-binary deployment evidence, and Docker-backed PostgreSQL proof remain explicit limits. Dependent #2827 carries the separately reviewed Automation lifecycle/fence successor and is not additional Schema scope. | +| 5B-Publication | Durable version/publication/readiness state | Corpus discovery accepted closed; merge proof pending | [#2828](https://github.com/benhook1013/FireMUD/pull/2828) | Cycles 1–4 were productive and corrected the accepted findings through V27; corrected-state Cycles 5 and 6 were dry. Whole-5B closure Cycle 2 subsequently added the V28 legacy full-version quarantine and made V26's incompatible participant-scope migration operationally stop-before-start and roll-forward-only. PostgreSQL retained-row execution, live mounted-certificate/Temporal owner calls, version-scoped Automation content, exact Game Design template/asset mapping, readiness notification, and dedicated ability-schema attestation remain open. | +| 5B-Retention | Retention classes, cleanup, horizons, contraction | Corpus discovery accepted closed; merge proof pending | [#2829](https://github.com/benhook1013/FireMUD/pull/2829) | Cycle 1 fixed incomplete handoff-child cleanup; corrected-state Cycles 2 and 3 were dry. Whole-5B closure Cycle 2 then classified `plugin_runtime_request_history` as retry/idempotency receipt evidence and `plugin_runtime_events` as recovery/reconciliation plus lifecycle-audit evidence. Both remain ineligible for automatic deletion until measured horizons, holds, safe watermarks, bounded sweeps, and metrics exist. Recovery-aware dead-letter cleanup, cross-owner inequalities, and Docker-backed PostgreSQL proof remain open. | +| 5C | Redis roles and cache/rate-limit semantics | Active in combined 5C/5D successor | Pending publication | The successor consumes the preserved #2661 Redis role, authority, reset, recovery, keyspace, and operational content on exact final #2829. Fresh whole-unit corrected-state review follows baseline publication. | +| 5D | Idempotency, outbox, replay, saga, and workflow patterns | Active in combined 5C/5D successor | Pending publication | The same successor consumes #2661's replay, effect identity, scheduler, tick, saga, workflow, and recovery content. Pending ADR 0183 is preserved without acceptance or proposal-dependent implementation. | | 6A | Gateway routes, traffic planes, sharding, and close taxonomy | Queued | — | — | | 6B | WebSocket, Telnet, protocol bridge, and session transport | Queued | — | — | | 6C | Logging & Admin/operator ingress and action authorization | Queued | — | — | diff --git a/design/project-management/design-alignment/consequential-decision-inventory.md b/design/project-management/design-alignment/consequential-decision-inventory.md index 6dd32a914d..1b743c7f3d 100644 --- a/design/project-management/design-alignment/consequential-decision-inventory.md +++ b/design/project-management/design-alignment/consequential-decision-inventory.md @@ -51,16 +51,16 @@ The inventory is split into this control ledger and exhaustive source-scoped led - [Specialized runtime decisions](./decision-inventory-specialized-runtime.md) contains 54 decisions and stronger evidence for 20 cross-cutting decisions from 38 Redis, scripting, tick, identity, token, migration, shared-library, spatial, authorization, and tracing documents. - [Product and operations decisions](./decision-inventory-product-operations.md) contains 41 decisions and stronger evidence for 11 existing keys from the remaining 38 product, frontend, authoring, protocol, infrastructure, deployment, recovery, observability, and generated-settings sources. -The merged Packet 6 P1-P3 baseline covered `340` discovered sources (`337` allocated, `3` explicit exemptions), including `165` allocated ADR records through ADR 0167. Packet 7 added 11 ADR records through ADR 0178, and the four post-archive direct decisions add ADRs 0179-0182. The canonical allocation therefore covers all 355 discovered product and architecture sources: 352 allocated decision-bearing sources and 3 explicit exemptions (the ADR registry/index plus two microservice governance/template documents). The four disjoint source-scoped partitions account for all 174 non-ADR paths (`22 + 76 + 38 + 38`); 172 are allocated (`22 + 74 + 38 + 38`) and two microservice governance/template paths are explicit exemptions. The 181-path ADR partition contributes 180 allocated ADR records plus the exempt ADR registry/index, yielding `174 + 181 = 355` discovered, `172 + 180 = 352` allocated, and 3 exemptions. The decision evidence set is 353 sources: the 352 allocated sources plus the exempt ADR registry/index; the two exempt microservice governance/template documents are discovered but excluded from decision evidence. A source may provide evidence without producing a distinct decision row. The source-scoped ledgers preserve unique primary ownership for the 186 current decision keys; cross-cutting evidence/reference rows may repeat existing keys across ledgers and do not add distinct keys. The microservice service-source ledger has 23 rows: 22 distinct non-alias service-source decisions (21 active plus the formal superseded `MS-GR-EQUIPMENT-BODY-LAYOUT`) plus the navigation-only historical service-scan alias `MS-AA-TOKEN-REVOCATION`. The removed `MS-PO-OWNER-REMEDIATION` key remains historical review evidence below and is not a service-source row. The completed historical human-review archive still has one row for each of its 182 decision keys plus the historical alias; the four direct decisions increase the current universe to 186 distinct keys and 187 key/navigation rows without changing that archive. Collectively, the inventories reference all 79 leaf capabilities in the taxonomy. +The merged Packet 6 P1-P3 baseline covered `340` discovered sources (`337` allocated, `3` explicit exemptions), including `165` allocated ADR records through ADR 0167. Packet 7 added 11 ADR records through ADR 0178, and the four post-archive direct decisions add ADRs 0179-0182. The separately preserved ADR 0183 proposal is allocated but remains `Proposed - Pending Human Review`; it does not add a reviewed or applied decision key. The canonical allocation therefore covers all 356 discovered product and architecture sources: 353 allocated decision-bearing sources and 3 explicit exemptions (the ADR registry/index plus two microservice governance/template documents). The four disjoint source-scoped partitions account for all 174 non-ADR paths (`22 + 76 + 38 + 38`); 172 are allocated (`22 + 74 + 38 + 38`) and two microservice governance/template paths are explicit exemptions. The 182-path ADR partition contributes 181 allocated ADR records plus the exempt ADR registry/index, yielding `174 + 182 = 356` discovered, `172 + 181 = 353` allocated, and 3 exemptions. The decision evidence set is 354 sources: the 353 allocated sources plus the exempt ADR registry/index; the two exempt microservice governance/template documents are discovered but excluded from decision evidence. A source may provide evidence without producing a distinct decision row. The source-scoped ledgers preserve unique primary ownership for the 186 current reviewed decision keys; cross-cutting evidence/reference rows may repeat existing keys across ledgers and do not add distinct keys. The microservice service-source ledger has 23 rows: 22 distinct non-alias service-source decisions (21 active plus the formal superseded `MS-GR-EQUIPMENT-BODY-LAYOUT`) plus the navigation-only historical service-scan alias `MS-AA-TOKEN-REVOCATION`. The removed `MS-PO-OWNER-REMEDIATION` key remains historical review evidence below and is not a service-source row. The completed historical human-review archive still has one row for each of its 182 decision keys plus the historical alias; the four direct decisions increase the current reviewed universe to 186 distinct keys and 187 key/navigation rows without changing that archive. Collectively, the inventories reference all 79 leaf capabilities in the taxonomy. | Capability | Sources reviewed | Decisions inventoried | Human-review candidates | Coverage state | | --- | ---: | ---: | ---: | --- | -| Existing ADR set | 180 ADR records (172 with completed review metadata; 11 pre-formal records, with overlap where accepted legacy records now carry exact review provenance) plus the architecture decision registry/index | 9 original aliases within the 68 cross-cutting decisions; later reviewed records are allocated directly | Complete in the historical source archive; ADRs 0179-0182 are direct post-archive decisions | Complete and allocated through ADR 0182 | +| Existing ADR set | 181 ADR records (172 with completed review metadata; 11 pre-formal records, with overlap where accepted legacy records now carry exact review provenance; ADR 0183 remains pending) plus the architecture decision registry/index | 9 original aliases within the 68 cross-cutting decisions; later reviewed records are allocated directly; ADR 0183 adds no accepted key | Complete in the historical source archive; ADRs 0179-0182 are direct post-archive decisions; ADR 0183 is pending human review | Complete and allocated through ADR 0182; pending proposal preserved as ADR 0183 | | Cross-cutting system architecture | 22 canonical sources plus ADRs | 68 | Complete in the source archive | Complete and independently audited | | Microservice architecture | 76 covered paths (74 allocated evidence paths; 2 explicit governance/template exemptions) | 23 service-source rows = 22 distinct decisions (21 active + formal superseded `MS-GR-EQUIPMENT-BODY-LAYOUT`) + excluded historical `MS-AA-TOKEN-REVOCATION` alias; `MS-PO-OWNER-REMEDIATION` remains historical review evidence; stronger evidence for 41 existing keys | Complete in the historical source archive plus direct `HOSTED-TERMS-01` provenance | Complete and independently audited | | Specialized runtime architecture | 38 sources | 54 new; stronger evidence for 20 existing keys | Complete in the source archive | Complete and independently audited | | Product and operations architecture | 38 sources | 41 new; stronger evidence for 11 existing keys | Complete in the historical source archive plus four direct post-archive decisions | Complete and independently audited | -| **Decision keys / navigation rows** | **All 355 design sources: 352 allocated decision-bearing sources (172 allocated non-ADR documents and 180 ADR records), 1 exempt architecture decision registry/index, and 2 excluded governance/template exemptions; 352 allocated and 3 total exemptions** | **186 current decision keys; 187 navigation/key rows including one historical service-scan alias** | **All 183 historical queue/navigation rows reviewed in the source archive plus four direct human decisions** | **All 186 current decision keys have reviewed outcomes applied; Packet 1-7 remains complete through ADR 0178 and direct post-archive decisions are applied through ADR 0182** | +| **Decision keys / navigation rows** | **All 356 design sources: 353 allocated decision-bearing sources (172 allocated non-ADR documents and 181 ADR records), 1 exempt architecture decision registry/index, and 2 excluded governance/template exemptions; 353 allocated and 3 total exemptions** | **186 current reviewed decision keys; 187 navigation/key rows including one historical service-scan alias; pending ADR 0183 adds no accepted key** | **All 183 historical queue/navigation rows reviewed in the source archive plus four direct human decisions; ADR 0183 remains pending** | **All 186 current reviewed decision keys have outcomes applied; Packet 1-7 remains complete through ADR 0178 and direct post-archive decisions are applied through ADR 0182; ADR 0183 is not applied** | ## Legacy ADR Alias Navigation diff --git a/design/project-management/design-alignment/decision-inventory-cross-cutting.md b/design/project-management/design-alignment/decision-inventory-cross-cutting.md index 4228cedbe3..4886445561 100644 --- a/design/project-management/design-alignment/decision-inventory-cross-cutting.md +++ b/design/project-management/design-alignment/decision-inventory-cross-cutting.md @@ -131,7 +131,7 @@ The first 22 source-index entries are the counted cross-cutting partition. `WE`, | `TICK-01` | `GR-1.2` | `GR-1.3`, `GR-1.1`, `GR-4.1`, `AS-1.4` | What is the gameplay clock and fairness unit? Independently advancing regional hybrid ticks use separate deterministic actor-action and passive/inbound-effect lanes. The actor-action lane selects at most one root intentional actor action originated by an eligible entity per tick; passive/inbound effects are separately bounded and do not consume the target entity's actor-action slot. | `accepted-explicit` | H/hard | [ADR 0051](../../architecture/decisions/adr-0051-separate-actor-action-and-effect-lanes.md); `TK § Hybrid Tick Model`; `TK § Per-Command Execution Phases`; `OV § Game Loop / Tick Model` | One universal entity work slot, a real-time event loop, global ticks, or unrestricted per-entity concurrency. | Human review revised the universal work slot into actor-action and effect lanes; implementation and focused proof remain. | | `TICK-02` | `GR-1.3` | `GR-1.2`, `GR-1.4`, `SF-2.2`, `SF-2.3`, `PO-4.2` | How is tick authority fenced? An opaque Redis liveness token proves ephemeral lease possession; PostgreSQL independently installs a fresh never-reused durable `executorFence` by expected-epoch/prior-state CAS and persists only a non-secret token correlation; the same Redis token is revalidated before staging; Redis mutations compare token/epoch and durable writes compare fence/epoch. Renewal preserves the fence, reset advances epoch before Redis clear, and either authority outage stops new progress. | `accepted-explicit` | H/hard | [ADR 0052](../../architecture/decisions/adr-0052-redis-liveness-lease-with-durable-executor-fence.md); `TK § Region Authority and Tick Executor`; `TK § Tick Commit Definition (Heartbeat Watermark)`; `RD § Redis Coordination Invariants` | PostgreSQL-only expiring leases, Redis-only leases, a consensus service, or global coordinator. | Human review revised and accepted the dual-store install-and-revalidate protocol; true region partitioning and failure proof remain. | | `TICK-03` | `SF-2.4` | `GR-1.2`, `SF-2.3`, `GR-4.1`, `GR-2.2`, `GR-3.2` | Are gameplay commands globally atomic? Local transactions plus stable `EffectId`-guarded at-least-once effects remain the default, but every command declares required/optional effects, permitted terminal combinations, and whether `PARTIAL` is intentional before execution; `SUCCESS` requires every required effect to be durably applied or have durable, evidence-qualified stored replay/no-op proof; unresolved or merely replayable required work remains `PENDING`/reconciliation-required. Invariant-sensitive commands use one authoritative local transaction or durable reservation/escrow; recovery records `APPLIED`/`ABANDONED` only where the existing durable evidence policy permits, never by bulk terminalization. | `accepted-explicit` | H/hard | [ADR 0053](../../architecture/decisions/adr-0053-command-atomicity-by-invariant-class.md); `TX § In-Game Command Transactions (No Sagas Needed)`; `TX § When Gameplay Commands Must Not Depend on Global Atomicity` | Distributed transaction, synchronous two-phase commit, or compensating rollback. | Human review revised and accepted invariant-class atomicity; command-family classification and proof remain. | -| `TICK-04` | `SF-2.3` | `GR-2.2`, `GR-3.2`, `GR-4.1`, `GR-1.4`, `SF-1.2` | How are effects deduplicated and spatial ownership divided? World owns topology/location/occupancy/ambient state; Entity owns inventory/equipment/containment/ground; participant guard uniqueness is the root `EffectId` plus typed operation plus target aggregate. The immutable `requestDigest` is persisted and validated separately as guard metadata—changed metadata fails closed—but it is never part of uniqueness. Under ADR 0059, Game Logic propagates the Game Session-allocated causal floor and composes returned same-scope/epoch served-through proofs with opaque component versions. | `accepted-explicit` | H/hard | [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md); [ADR 0059](../../architecture/decisions/adr-0059-causal-floor-cross-service-presentation-reads.md); [ADR 0060](../../architecture/decisions/adr-0060-world-owned-ambient-facts-and-logic-owned-consequences.md); [identifier glossary](../../architecture/system-architecture-identifier-glossary.md) § `Cross-Service Causal-Read Fence Identity`; `TX § Tick Effects Are At-Least-Once: Idempotency Is Mandatory`; `TX § Spatial Effects: Location vs Containment (World ↔ Entity)`; `OV § Canonical Room Runtime Contract`; `TK § Tick Effect Identity and Idempotency Contract` | Shared room transaction or authoritative monolithic gameplay state. | Human review revised and accepted split spatial authority under ADR 0054 and causal-floor composition under ADR 0059; operation-bound guards, mutation preconditions, and proof remain. | +| `TICK-04` | `SF-2.3` | `GR-2.2`, `GR-3.2`, `GR-4.1`, `GR-1.4`, `SF-1.2` | How are effects deduplicated and spatial ownership divided? World owns topology/location/occupancy/ambient state; Entity owns inventory/equipment/containment/ground; participant guard uniqueness is the persisted mutation `EffectId` (root for a command-root mutation or one-time allocated opaque child for a generated/derived mutation) plus typed operation plus target aggregate, with the enclosing root retained as lineage where applicable. This is scoped shorthand for the owner-declared runtime-family partition: S1/S2 use `(tenantId, playableStateNamespaceId)`, explicit S3 uses `(tenantId, gameInstanceId)`, and an unknown or unclassified family fails closed. The immutable `requestDigest` is persisted and validated separately as guard metadata—changed metadata fails closed—but it is never part of uniqueness. The accepted TICK-04 decision does not select a generated-child allocator; any future allocator and replay binding remain non-authoritative pending the [ADR 0183 proposal](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Under ADR 0059, Game Logic propagates the Game Session-allocated causal floor and composes returned same-scope/epoch served-through proofs with opaque component versions. | `accepted-explicit` | H/hard | [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md); [ADR 0059](../../architecture/decisions/adr-0059-causal-floor-cross-service-presentation-reads.md); [ADR 0060](../../architecture/decisions/adr-0060-world-owned-ambient-facts-and-logic-owned-consequences.md); [identifier glossary](../../architecture/system-architecture-identifier-glossary.md) § `Cross-Service Causal-Read Fence Identity`; `TX § Tick Effects Are At-Least-Once: Idempotency Is Mandatory`; `TX § Spatial Effects: Location vs Containment (World ↔ Entity)`; `OV § Canonical Room Runtime Contract`; `TK § Tick Effect Identity and Idempotency Contract` | Shared room transaction or authoritative monolithic gameplay state. | Human review revised and accepted split spatial authority under ADR 0054 and causal-floor composition under ADR 0059; operation-bound guards, mutation preconditions, and proof remain. | | `TICK-05` | `SF-2.4` | `SF-2.3`, `GR-1.2`, `AS-1.5`, `PO-1.1` | Where do side effects and workflows run? Gameplay uses tick reconciliation; simple asynchronous delivery uses an outbox; bounded caller/worker-owned orchestration may use a local saga; restart-independent continuation, durable waits/signals, and operator-managed in-flight lifecycle use Temporal. | `accepted-explicit` | H/med | `TX § Tick-Adjacent Workflows (Outbox Boundary)`; `TX § Saga vs Temporal Boundary`; `TW § Canonical Usage Boundary` | Put every durable operation in Temporal or rebuild durable continuation from local sagas and outbox workers. | Human review accepted the three-way substrate boundary with a mandatory adopter test; implementation/proof remain adopter-specific and no new ADR is required while gameplay remains outside Temporal. | | `TICK-06` | `GR-2.1` | `GR-1.3`, `GR-1.4`, `SF-2.3`, `AA-3.3`, `PO-4.2` | How do cross-region effects and topology changes work? Durable asynchronous follow-ups use static live topology; maintenance split/merge freezes producers, drains and reconciles, bumps epochs, rebuilds coordination, and reopens only after explicit terminalization and health validation. | `accepted-explicit` | H/hard | [ADR 0055](../../architecture/decisions/adr-0055-durable-cross-region-effects-with-static-live-topology.md); `TK § Tick Regions and Parallel Execution`; `TK § Topology Changes (Split/Merge) Protocol (Required Invariants)`; `TX § Reconciliation Owner of Record (Spatial/Ambient Effects)` | Global locks, synchronous cross-region ticks, or automatic live topology migration. | Human review revised and accepted the static-topology/maintenance-cutover boundary; remote follow-up and migration proof remain. | | `TICK-07` | `AS-1.4` | `GR-1.2`, `GR-2.3`, `AS-1.5`, `SF-1.4` | How are timers recovered? Each timer declares its clock and recovery class; durable correctness work preserves identity, recurring schedules choose `SKIP_MISSED` or one bounded `COALESCE_ONE`, and advisory work may drop under its declared budget. | `accepted-explicit` | H/med | [ADR 0072](../../architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md); `TK § Timers and Time Scaling`; `TK § Scheduler Recovery Semantics`; `SC § Validation & Admission Pipeline` | Replay every missed timer or treat all timers as durable commands. | Human review revised and accepted class-specific timer durability/recovery; scheduler implementation and proof remain partial. | @@ -172,7 +172,7 @@ The first 22 source-index entries are the counted cross-cutting partition. `WE`, | `SEC-02` | `SF-1.3` | `PO-3.2`, `PO-4.2`, `AA-1.3`, `PO-1.3` | How do Account JWT keys rotate and when is the boundary player-facing ready? Planned rotation prepublishes, proves validator visibility, promotes, overlaps through retiring-token expiry, and prunes; compromise/restore quarantines and hard-cuts the environment-wide issuer. Current shared HMAC is implementation debt and fails the readiness gate. | `accepted-explicit` | H/hard | `SE § JWT Key & JWKS Rotation Workflow`; [ADR-0014](../../architecture/decisions/adr-0014-phased-jwt-signing-key-rotation-and-readiness.md) | Use a maintenance-window hard cutover for every rotation, or adopt a non-exportable external signer while preserving the lifecycle protocol. | ADR-0014 records the revised human decision; issuance, validation, automation, convergence, and gate enforcement remain incomplete. | | `SEC-03` | `PO-2.2` | `SF-1.3`, `AA-1.3`, `PO-2.1`, `AA-2.1`, `EA-3.1` | Is plaintext Telnet accepted in production and is TOTP enforced? Public player-facing Telnet requires TLS; raw Telnet is local/test/private-only, and no TOTP transport gate is added. | `accepted-explicit` | H/hard | [ADR 0033](../../architecture/decisions/adr-0033-public-player-facing-telnet-requires-tls.md); `SE § Plaintext Telnet policy`; `AU § Implemented Status` | Preserve public plaintext with warnings/hardening, require TOTP, or add a secure-side-channel single-use ticket. | Revised and accepted by human decision; TLS protects the actual channel without imposing a factor that leaves the session exposed. | | `SEC-04` | `PO-1.1` | `PO-1.2`, `PO-1.3`, `PO-1.4`, `PO-2.1`, `GR-1.1`, `AR-3.3` | Where do administrative and session-lifecycle writes enter? The target external operator boundary sends moderation, runtime flags, quota overrides, admission control, tick/coordination remediation, and session-lifecycle operations through Gateway to Logging/Admin; domain services retain mutation authority. Current Game Session `/sessions*` routes remain owner-local/internal and are not evidence that target Logging/Admin forwarding is live. The moderation policy-input/audit mutation is currently unavailable/gated pending its action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account-owned authorization-reference issuance, and Logging & Admin receiving-boundary validation/redemption; `EvaluateModerationPolicy` remains a separate live read consumed at the owner enforcement boundaries, and no domain-owner redemption or enforcement is part of that persistence path. Quota overrides, broader remediation, and other owner mutations without a complete route/proof remain gated or target-only. | `accepted-explicit` | H/med | `OV § Admin Entry Points and Traffic Surfaces`; `OV § Core Operator Action Backing Contracts (Canonical)`; `RM § Notes on Movement and Moderation Contracts`; [ADR-0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md) (human review completed 2026-07-19; revised); [ADR-0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) (human review completed 2026-07-19; revised) | Direct domain admin endpoints or a separate operator write plane. | ADR-0047 and ADR-0048 are accepted, revised, and human-reviewed; action-family implementation and proof remain partial where the route or owner contract is gated. | -| `ADMIN-01` | `PO-1.1` | `PO-1.3`, `PO-1.4`, `SF-2.3`, `GR-1.1`, `PO-4.1` | What backs operator writes and forwarding? Logging & Admin durably records one logical mutation under one `controlPlaneRequestId`; only ADR 0048-permitted transport retries reuse the exact authority-bound tuple, and the domain owner deduplicates them while atomically persisting the mutation and idempotent result. Lost responses and final-audit failures use read-only reconciliation under that identifier rather than redelivering an ambiguous mutation. Observability is not a write dependency, and region-scoped Game Session mutations execute at the current lease owner under the current gameplay fence. | `accepted-explicit` | H/hard | [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md); `OV § Core Operator Action Backing Contracts (Canonical)`; `OV § Admin Entry Points and Traffic Surfaces`; `RM § Notes on Movement and Moderation Contracts` | Let operators write domain stores directly, use best-effort forwarding or distributed transactions, let dashboards determine write success, or let a session front-end mutate region-owned coordination without lease-owner forwarding. | Human review revised and accepted durable intent, owner-local idempotency, explicit uncertain outcomes, and fenced lease-owner forwarding; implementation and focused proof remain. | +| `ADMIN-01` | `PO-1.1` | `PO-1.3`, `PO-1.4`, `SF-2.3`, `GR-1.1`, `PO-4.1` | What backs operator writes and forwarding? Logging & Admin durably records one logical mutation under the applicable action-family request identity: `controlPlaneRequestId` for non-moderation mutations, `policyIntentRequestId` for local moderation policy intent, and `ownerEnforcementRequestId` for moderation owner-enforcement commands; moderation may carry `controlPlaneRequestId` only as correlation. Only ADR 0048-permitted transport retries reuse the exact authority-bound tuple, and the domain owner deduplicates them while atomically persisting the mutation and idempotent result. Lost responses and final-audit failures use read-only reconciliation under that applicable identity rather than redelivering an ambiguous mutation. Observability is not a write dependency, and region-scoped Game Session mutations execute at the current lease owner under the current gameplay fence. | `accepted-explicit` | H/hard | [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md); [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md) (`MOD-01`); `OV § Core Operator Action Backing Contracts (Canonical)`; `OV § Admin Entry Points and Traffic Surfaces`; `RM § Notes on Movement and Moderation Contracts` | Let operators write domain stores directly, use best-effort forwarding or distributed transactions, let dashboards determine write success, or let a session front-end mutate region-owned coordination without lease-owner forwarding. | Human review revised and accepted durable intent, owner-local idempotency, explicit uncertain outcomes, and fenced lease-owner forwarding; implementation and focused proof remain. | | `MOD-01` | `PO-1.2` | `EA-2.4`, `AA-1.3`, `PO-1.3`, `PO-4.1` | Logging & Admin owns moderation ingress, policy intent, moderation cases, and audit, then forwards a typed digest-bound idempotent command to the enforcement owner. Appeal cases are a distinct bounded case type governed separately by ADR 0142. Account durably owns `platform_access_ban`, its authentication-generation/account-wide revocation consequence, and Account owner-local restriction/security state; protective `account_security_lock` remains separate Account policy/recovery state. Game Session durably owns `gameplay_ban`; Social durably owns `chat_mute` and `chat_ban`; routine enforcement reads owner-local state without a Logging & Admin RPC. | `accepted-explicit` | H/hard | [ADR 0146](../../architecture/decisions/adr-0146-owner-local-moderation-enforcement.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); `OV § Moderation, Restriction, and Appeal Authority (Canonical)`; [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); `RM § Notes on Movement and Moderation Contracts` | Versioned distributed policy snapshots, synchronous central checks, centralized enforcement, or best-effort notification after audit success. | Human review completed 2026-07-20; `revised`. Current synchronous `PLAY` and chat-send checks are implementation drift; owner commands, monotonic enforcement records, active-binding containment, and lifecycle proof remain incomplete. | | `SEC-05` | `SF-1.3` | `AA-1.3`, `AA-2.1`, `PO-2.4`, `PO-1.2` | Who owns brute-force and abuse controls? Edge services own transport pressure, Account exclusively owns credential abuse without failed-attempt hard locks, and Game Session owns local fast-path post-auth command budgets with optional coarse shared backstops. | `accepted-explicit` | H/hard | [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); `SE § Brute-Force Defense and Abuse Handling`; `GW § Rate Limiting & Abuse Protection` | Let the edge lock accounts, centralize all limits in Account, durably lock after a failure threshold, or retain a distributed Redis operation for every gameplay command. | Revised and accepted by human decision; trusted source propagation, non-enumerating graduated throttles, fail-closed new login, and local command buckets preserve security without an attacker-triggered denial or gameplay datastore dependency. | | `OPS-01` | `PO-3.1` | `AR-1.5`, `PO-3.3`, `PO-4.4`, `SF-1.1` | What artifact is promoted? One canonical build records exact source/build/platform lineage; the staged OCI manifest or index digest and all production-supported child digests promote without rebuild. Tags are aliases, and changed cross-registry copies require mapped destination staging. Platform and game-content attestations remain separate. | `accepted-explicit` | H/med | [ADR 0097](../../architecture/decisions/adr-0097-git-and-ci-validated-single-operator-promotion-evidence.md); `CI § Building and Pushing Images`; `CI § Promotion & Rollback Model`; `VR § Game Version Publishing` | Rebuild separately per environment, promote mutable tags, or treat an unproved platform child/cross-registry copy as the staged artifact. | `accepted` on 2026-07-21 with multi-architecture, copy, and lineage clarification; current builder and fail-open attestation drift remain implementation gaps. | diff --git a/design/project-management/design-alignment/design-capability-allocation.md b/design/project-management/design-alignment/design-capability-allocation.md index 1149c37021..b2815051f6 100644 --- a/design/project-management/design-alignment/design-capability-allocation.md +++ b/design/project-management/design-alignment/design-capability-allocation.md @@ -24,6 +24,7 @@ This file intentionally owns the detailed allocation-validation history; the des - Final combined Packet 5 tail and Packet 6 P0 validation record on 2026-08-25 Pacific/Auckland (2026-08-24 UTC): all active ADRs 0146-0159 are allocated; `linkCheck` checked `6,039` total links (`6,002` OK, `37` excluded, `0` errors); `lintMarkdown` checked `509` files (`0` issues); allocation reported `332` sources (`329` allocated, `3` explicit exemptions); ADR review status was `146` reviewed / `11` pre-formal; architecture doc contracts, allocation regression `28` tests, ADR review regression `141` tests, and authorization-route regression `216` tests passed; the focused preflight, player-experience evidence, player-experience runner, and observability-validator contract tests passed; and Ruff, ShellCheck, Python syntax, and `git diff --check` were clean. No environment-backed runtime proof is required for validating this allocation ledger itself. That ledger-only exemption does not waive runtime-proof requirements for the allocated architecture documents or operational validation tooling; changes requiring canonical fresh-image rebuild-and-boot proof must retain and report that requirement separately. - Packet 6 P1-P3 allocation state: ADRs 0160-0167 add 8 reviewed records, bringing the canonical source set to `340` discovered sources (`337` allocated, `3` explicit exemptions) and the ADR registry to `165` records. The final reviewed import through Packet 7 ADRs 0168-0178 adds 11 more ADR records (19 reviewed records across both parcels), yielding `351` discovered sources (`348` allocated, `3` explicit exemptions) and `176` ADR records. Those review categories overlap where accepted legacy pre-formal records now carry exact review metadata. This structural state does not upgrade implementation or runtime proof for the allocated decisions; final parcel validation is reported by the design-alignment workstream rather than inferred from allocation arithmetic. - The four post-archive direct human decisions `COMMERCE-02`, `HOSTED-TERMS-01`, `HOSTED-TERMS-02`, and `OPS-07` add ADRs 0179-0182 without changing the completed historical Packet 1-7 archive. They bring the canonical source set to `355` discovered sources (`352` allocated, `3` explicit exemptions) and the ADR registry to `180` records. The marketplace, hosted-terms, signer, and billing-lifecycle boundaries remain future or pre-launch target state. This allocation entry records allocation authority and target-state boundaries only; for ADR 0182, only local/static prerequisite evidence exists, while live activation, certificate issuance, and consumer convergence remain unproved. It does not establish broader implementation status, focused proof, or environment-backed runtime proof. +- The pending AI-authored ADR 0183 proposal is an additional allocated ADR source, not a reviewed decision: it brings the current canonical source set to `356` discovered sources (`353` allocated, `3` explicit exemptions), including `181` ADR records plus the registry/index exemption. Its pending status and `AI-AUTHORED-PENDING` provenance remain unchanged until human review; mechanical renumbering from the conflicting source-branch ADR 0182 is preservation only and does not accept the proposal. - Historical baseline allocation-validator run on 2026-08-27 Pacific/Auckland: `python3 dev-tools/validation/check-design-capability-allocation.py` passed with `340` discovered sources (`337` allocated, `3` explicit exemptions). This records the Packet 6 baseline allocation coverage only and does not claim implementation or runtime proof. - Pre-licensing-integration allocation and ADR review-status baseline on 2026-08-28 Pacific/Auckland: allocation validation passed with `351` discovered sources (`348` allocated, `3` explicit exemptions), and ADR review-status validation passed with `168` reviewed ADRs and `11` pre-formal records. ADRs 0002, 0007, and 0008 are overlapping records present in both the reviewed count and the 11 pre-formal records, so the deduplicated registry total is `168 + 11 - 3 = 176` before licensing integration. These are historical baseline/provenance facts, separate from implementation or runtime proof. - Licensing-integration validation on 2026-08-28 Pacific/Auckland: allocation validation passed with `354` discovered sources (`351` allocated, `3` explicit exemptions); ADR review-status validation passed with `171` reviewed ADRs and `11` pre-formal records; implementation tracking passed with `79` leaves across `10` trackers; the authorization-route matrix and full architecture-document contract suite passed; `linkCheck` checked `6,537` links (`6,489` OK, `0` errors, `48` excluded); `lintMarkdown` checked `535` files (`0` issues); and `git diff --check` was clean. ADRs 0002, 0007, and 0008 are overlapping records present in both the reviewed count and the 11 pre-formal records, so the deduplicated registry total is `171 + 11 - 3 = 179` after licensing integration. These checks establish documentation and structural consistency for the integration only; they do not claim commit, PR, CI, or runtime proof. @@ -45,16 +46,16 @@ This file intentionally owns the detailed allocation-validation history; the des | Infrastructure | 6 | 6 | 0 | 100% classified | | Generated references | 2 | 2 | 0 | 100% classified | | Microservice architecture | 76 | 74 | 0; 2 explicit governance/template exemptions | 100% classified | -| Architecture decisions | 181 | 180 | 0; 1 registry exemption | 100% classified | +| Architecture decisions | 182 | 181 | 0; 1 registry exemption | 100% classified | | Product documentation | 7 | 7 | 0 | 100% classified | -| **Total** | **355** | **352** | **0; 3 explicit exemptions** | **100% classified** | +| **Total** | **356** | **353** | **0; 3 explicit exemptions** | **100% classified** | ## Allocation Ledger | Design source | Heading or scope | Primary capability | Secondary handoffs | Source class | Notes or gap | | --- | --- | --- | --- | --- | --- | | [Microservice architecture allocation](./design-capability-allocation-microservices.md) | All 76 files under `design/architecture/microservices/**` | Per-source allocation | Per-source handoffs | Service design, contract, runtime/data, configuration, operations, and reference sources | All 76 files are accounted for as 74 allocated sources plus 2 exempt governance/template files: `service-documentation-structure.md` and `service-template.md`; complete path-set coverage | -| [Architecture decision registry](../../architecture/decisions/README.md) | Registry plus 180 ADRs | Per-record allocation | Per-record affected capabilities | Decision record | The registry is an index; reviewed, accepted, superseded, and withdrawn records remain distinguishable | +| [Architecture decision registry](../../architecture/decisions/README.md) | Registry plus 181 ADRs | Per-record allocation | Per-record affected capabilities | Decision record | The registry is an index; reviewed, accepted, superseded, withdrawn, and pending records remain distinguishable | | [System architecture allocation](./design-capability-allocation-system.md) | All 83 direct architecture, 6 infrastructure, and 2 generated sources | Per-source allocation | Per-source handoffs | Normative design, runbook, reference, index, and generated sources | Complete path-set coverage | | [Product documentation](../../product/README.md#canonical-sources) | All 7 files under `design/product/**` | Per-source allocation | Per-source product behavior scope | Requirements, taxonomy, index, and observable product behavior | Complete path-set coverage | @@ -243,6 +244,7 @@ This file intentionally owns the detailed allocation-validation history; the des | `design/architecture/decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md` | `AA-1` | `AR-1`, `EA-3`, `PO-1`, `SF-2` | Accepted | | `design/architecture/decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md` | `PO-1` | `AA-1`, `AR-1`, `EA-3`, `SF-2` | Accepted | | `design/architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md` | `PO-3` | `PO-1`, `PO-4`, `SF-1` | Accepted | +| `design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md` | `GR-1` | `GR-4`, `AS-1`, `SF-1`, `SF-2`, `PO-4` | Proposed - Pending Human Review | ADR 0121 is superseded by [ADR 0114](../../architecture/decisions/adr-0114-command-plan-preview-dry-run-isolation.md); its historical capability allocation remains recorded above. 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 8c6a2694e4..83879605f0 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -51,7 +51,7 @@ These links add decision provenance only; they do not upgrade Automation impleme ## Final Reviewed-Import Status and Proof Gaps -- `AS-1.6`: [ADR 0166](../../architecture/decisions/adr-0166-attributable-script-breakers-and-tenant-first-fairness.md) is applied as decision provenance. Current quota and tier budgets are partial foundations; breaker authority, audited reset, general priority scheduling, priority-sensitive queue-delay/starvation emission, the ADR 0166 cluster-ceiling capability (distinct from the current dry-run `SCRIPT_TEST_MAX_CLUSTER_CONCURRENCY` capacity), concurrency policy, and focused fairness proof remain gaps. +- `AS-1.6`: [ADR 0166](../../architecture/decisions/adr-0166-attributable-script-breakers-and-tenant-first-fairness.md) is applied as decision provenance. Current quota and tier budgets are partial foundations; breaker authority, audited reset, general priority scheduling, priority-sensitive queue-delay/starvation emission, the ADR 0166 cluster-ceiling capability (distinct from the current dry-run `SCRIPT_TEST_MAX_CLUSTER_CONCURRENCY` capacity), concurrency policy, and focused fairness proof remain gaps. The live dry-run capacity counter uses the separate Cache/Rate-Limit `automation:test:capacity:*` family; its reset/ACL inventory remains part of the incomplete Redis-role convergence. - `AS-1.1`: [ADR 0172](../../architecture/decisions/adr-0172-parent-event-and-frozen-handler-execution-identity.md) supersedes ADR 0001. Current ingress, storage, retry, scheduler, audit, and handoff convergence and focused proof remain incomplete. - `AS-1.5`: Human review retained [ADR 0002](../../architecture/decisions/adr-0002-automation-handoff-reliability-and-success-semantics.md). Current duplicate recovery and child-dispatch/readback proof remain incomplete, so this capability stays partial. - `AS-1.6`: [ADR 0173](../../architecture/decisions/adr-0173-registry-classified-reload-admission-policy.md) supersedes ADR 0003. Current implementation lacks the registry-classified `RELOADING`/`retryAfterMs` behavior, null-safe policy identity and atomic first-claim convergence, and `REJECT_VISIBLE`/`DURABLE_RETRY`/`SKIP_RECONCILE` producer behavior; existing readiness/plugin/admission tests do not prove the transient-denial retry lifecycle. These are implementation and proof gaps; ADR 0173 owns the normative reload policy semantics. @@ -106,6 +106,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` instead follows readiness-owner terminalization and is not supported through generic replay. 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). +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 bounded readiness correction serializes tenant `begin` and refresh mutations, retains an existing readiness identity on retry without restarting `onLoad`, schedule refresh, or Temporal tracking, and installs a partial unique index for one active tenant candidate. Retained duplicate active rows fail V2 migration rather than being rewritten. Focused unit tests pass, but the two new PostgreSQL concurrency/duplicate-migration cases are unexecuted here; empty-notification, manifest, base/request binding, generation-CAS, and recovery gaps remain with 5B-Publication and the named Automation owners. @@ -127,6 +128,8 @@ Game Session advances durable `lastCommittedTickId` after successful tick cycles Runtime-scope changes fence tick and wall-clock due points before work is minted. Stale due points are dropped with `runtime_scope_changed`, the `automation_script_timer_runtime_fence_dropped_total` metric, and old-scope audit identity rather than being re-emitted under a new region epoch. Emitted and skipped rows retain the current routing bundle. Timer audit reads expose due-point identity, plugin provenance, routing, and persisted-versus-skipped outcomes. The ownership model is explicitly best effort and does not imply stronger timer guarantees; richer scheduler dashboards and a later leader-checkpoint substrate are outside this first model. +Current scheduler residuals remain beyond the bounded substrate above: ordinary runtime observation/reconciliation can reseed an existing millisecond `nextDueAt` after a fired one-shot was cleared, and the duplicate-work path then leaves the overdue point stuck or rediscoverable. Timer candidate and work-item uniqueness also omit `targetScopeType`/`targetScopeId`, so distinct non-entity bindings can collide. The current timer metric producer uses raw `eventType`/optional `reason` labels and emits an undefined fired family rather than the bounded catalog; these are implementation drifts from the [scheduler due-state contract](../../architecture/system-architecture-scripting-scheduler-and-timers.md#target-state-design), [scheduler identity contract](../../architecture/system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields), and [Normative Table 4](../../architecture/system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix). Focused proof for re-observation preservation, duplicate/cross-binding exclusion, and canonical metric schemas remains absent. + Tick-aligned materialization derives the next future `nextDueTickId`. Scheduler materialization and plugin activation preflight ignore enabled plugin rows whose persisted observed runtime scope differs from current Game Session ownership, with exact `runtimeRegionId` and `runtimeRegionEpoch` checks; scoped plugin-policy convergence uses the same fence. ### Execution Budgets, Quotas, and Isolation @@ -154,11 +157,13 @@ The queue status below is an implementation description, not a recovery authoriz Automation never writes Game Session tick keys directly. The live queue uses instance-aware `automation:queue:{tenantInstanceTag}:*` pointers containing a documented outbox-pointer envelope (`schemaVersion`, `outboxWorkItemId`, and bounded identity metadata); the retired `automation:tick:*` staging path is not part of the live design. Quota counters use `automation:quota::`. Queue pointers are derived coordination indexes, not work truth: Redis drain deduplicates by `outboxWorkItemId`. The callable `rebuildPendingWorkItemIndex` unconditionally selects both statuses and has no stale, owner, or compare-and-set 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 the safe PENDING-only path. Bounded duplicate-pointer recovery remains the owner-controlled gap defined in the [scripting runtime rebuild contract](../../architecture/system-architecture-scripting-runtime-execution.md#current-queue-rebuild-concurrency-gap). Health inspection reports `automation_queue_orphaned_entries_total` and `automation_queue_oldest_entry_age_seconds`, and the executor drains pointers for discovery before claiming PostgreSQL work, falling back to durable scanning if Redis discovery fails. -Game Session exposes idempotent `EnqueueAutomationCommandIfAbsent`, persists automation dispatch/work-item correlation on the gameplay command ledger before tick staging, and rejects new handoff when runtime ownership is missing, paused, or on another `regionEpoch`; an already-recorded dispatch still returns duplicate/no-op. Numeric gameplay `targetEntityId` is captured as `characterId` so durable execution can resolve an active session without a caller-owned `sessionId`. Automation assigns a per-command `automationDispatchId`, preserves the full routing bundle, and either uses the local admitted command path or creates a durable remote follow-up for a different target runtime scope. Local scripting commands therefore enter the same Game Session actor-action safety and fairness path as player commands; the durable remote-follow-up delivery envelope is passive at the target and does not consume its actor slot, but if its payload enqueues a gameplay/automation command, that resulting command remains an actor action and cannot receive a same-tick extra root action. The live Game Session enqueue proto remains narrower than the target automation handoff contract: it does not yet carry the full Trigger Identity, `commandOrdinal`, immutable `lane`, or `cost_class`; therefore target dispatch-plus-ordinal identity, lane/cost conflict and digest checks, readback, retry, recovery preservation, and enforcement are not implemented or proven. +Current enqueue/rebuild is RPUSH-only (with no target pointer TTL or maximum length), and `tenantInstanceTag` still concatenates raw IDs, so retention, memory-pressure, and collision-safe opaque encoding remain unproved. Canonical queue and Redis mechanics are owned by [Scripting Runtime Execution](../../architecture/system-architecture-scripting-runtime-execution.md) and [Redis](../../architecture/system-architecture-redis.md); this tracker records the current implementation gaps. + +The live Game Session handoff provides idempotent admission for the direct enqueue path and enters the same actor-action safety and fairness path as player commands; remote-follow-up delivery is passive until its payload enqueues a gameplay command. That admission idempotency does not cover the current `scheduleFollowup` terminal-timeout/late-result path, which can reopen an existing terminal coordinator/follow-up pair; this remains the implementation/proof gap recorded in Game Session runtime/data. The current enqueue proto/storage remains narrower than the target: full Trigger Identity, command ordinal, lane/cost binding, complete child deduplication, readback, retry, recovery preservation, and enforcement are not implemented or proven. Canonical handoff mechanics are owned by [ADR 0063](../../architecture/decisions/adr-0063-durable-per-dispatch-script-handoff.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), and [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary); this tracker records the local actor-path consequence and current gap. The target remote-follow-up contract is owned by [Scripting & Automation: Cross-Service Contracts](../../architecture/system-architecture-scripting-contracts.md#3-version-fencing-rollback-safety). Current `ScriptHandoffEvent` persistence and readback now carry the source `scriptPinEpoch`, but they do not yet bind the source tuple to the target tuple or prove downstream target admission against that binding. The legacy target-side `trigger_script_event` path is therefore deterministically disabled until the complete source/target tuple-plus-owner binding exists: missing, malformed, or mismatched tuple evidence is a terminal fail-closed outcome, while unavailable authority remains non-admitted and retryable. Same-instance cross-region work and semantic target `UNPINNED` handling remain subject to that owner contract. -For plugin-originated remote follow-ups, the exact `(pluginId, pluginVersionId, bindingId)` plus captured Automation-owned `(pluginActivationEpoch, lifecycleRevision)` and fresh lifecycle/publication/policy evidence remain independent fences across Automation persistence/handoff and Game Session final execution, separate from Command-Handoff child identity and dedupe. Unavailable, displaced, disabled, revoked, activation-epoch-mismatched, or lifecycle-revision-mismatched evidence fails closed; current plugin-originated follow-up persistence and proof remain partial. +Game Session owns deterministic command-plan root allocation; Automation's current handoff does not yet carry or prove complete command-level mapping, deduplication, or root binding. This remains a target/proof gap under the canonical owners above, not an implementation claim. The bounded evaluator supports command-specific `targetEntityId`, structured `commandAlias` plus templated `arguments`, `when`/`unless` conditions, and multi-target `targetEntityIds[]` fan-out with stable command ordinals. **Target state:** durable handoff history is per command and preserves rendered command text, script/plugin/source/dispatch identity, captured plugin `(pluginActivationEpoch, lifecycleRevision)` when applicable, target scope, remote coordinator/follow-up ids, and later Game Session gameplay execution/outcome plus remote-state tail. Target `ListScriptHandoffEvents` directly filters by remote scope, remote ids, origin identity, command id, target entity, routing bundle, and source/state instead of reconstructing history from payloads; its exhaustive plugin-backed output retains the captured lifecycle revision beside the activation epoch. The current handoff storage/proto remains narrower and does not yet prove this target projection. @@ -182,11 +187,14 @@ Game Session pin reads remain distinct: `GetPinnedScriptPatchVersion` reports pi ## Active Gaps +- `AS-1.4` scheduler ordering is current implementation drift: `ScriptScheduleInstanceServiceImpl` sorts candidates by wall-clock lane, then due point (`dueTickId` or epoch-millisecond `dueAt`), then `priorityTag`, and finally schedule key, with round-robin grouping applied only after that sort. Due-point/lane order can therefore outrank bounded priority, and the due-order comparison spans distinct clock domains; the target remains bounded priority-first ordering with stable schedule-instance identity round-robin fairness. No scheduler algorithm change is claimed by this tracker. +- The live clock-lane key is `wallClock ? 1 : 0` (tick candidates precede wall-clock candidates); the recorded drift is the lane and due-point precedence over priority, not a claim that wall-clock candidates always run first. - The evaluator is intentionally bounded to persisted script definitions, structured command emission, simple conditions, and target fan-out. Richer graph/runtime evaluation, compiled artifacts, and a broader sandbox execution seam are not implemented and require a separate runtime slice. - Script-driven generation and richer procedural population are not established gameplay slices; the current runtime does not provide the broader procedural-population flow described by the target architecture. - The first scheduler ownership model is complete, but richer scheduler dashboards and a later explicit leader-checkpoint substrate are not part of it. TICK-01 lane declaration, actor-versus-passive selection, cost-class enforcement, and focused proof remain unimplemented; any future timer, retry, remote, or script-generated source must declare its lane and cost class and use the existing selected-work, region-fence, routing, quota, and durable-result contracts. - The accepted [ADR 0072](../../architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md) timer classes, durable resume-window identity, and `SKIP_MISSED`/`COALESCE_ONE` outcomes do not promote the current best-effort scheduler to complete recovery; durable correctness-bearing timer intent and focused recovery proof remain gaps. - [ADR 0063](../../architecture/decisions/adr-0063-durable-per-dispatch-script-handoff.md) and [ADR 0064](../../architecture/decisions/adr-0064-stage-qualified-script-outcomes.md) require one durable child dispatch per emitted command and separate ingress, handler, and command outcome authorities. Current handoff paths remain bounded/partial where downstream execution-disposition readback and stage-qualified proof are absent. +- [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) remains an implementation and proof gap for the Automation-to-Game-Session handoff and command-plan/root binding. The [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary) own the canonical handoff details, while the [Game Session tracker](./game-session-runtime-and-tick-coordination.md) records current implementation and proof status. - [ADR 0075](../../architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md), [ADR 0076](../../architecture/decisions/adr-0076-failure-class-specific-durable-tick-retries.md), and [ADR 0078](../../architecture/decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md) are target contracts only: generated-chain budgets, class-specific durable retry owners, and adopter-side digest-conflict guards remain unimplemented or unproved in this runtime. - Additional publish-adjacent or script-patch rollout Temporalization is not implemented by this tracker. It is justified only by a concrete long-lived workflow need; surviving short synchronous saga seams remain explicitly scoped for the later boundary cleanup. - Custom event families and future gameplay lifecycle producers do not yet exist as additional implementation families. They must extend the manifest-backed ingress and payload contract rather than create local semantics. diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 6e3acafb27..f4140a25e7 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -24,6 +24,8 @@ Target rollback requires the scoped Automation admission barrier to pause new sc Distinct-instance remote follow-up has bounded durable coordinator/follow-up persistence and handoff paths live. Current `ScriptHandoffEvent` persistence and the handoff wire retain the source `scriptPinEpoch` and source owner-request evidence, but do not yet retain or enforce the complete source/target pin-tuple binding. The remaining target implementation/proof gap is source revalidation, target admission under a frozen target tuple, complete source/target fencing and retry/replay proof, and plugin `pluginActivationEpoch`/owner `lifecycleRevision` propagation where applicable. The legacy target-side `trigger_script_event` path is deterministically disabled until that durable source/target binding exists; it must not derive a Trigger ingress tuple from mutable target state or generic patch metadata. Game Session's local plugin projection, lexicographic lifecycle-fence CAS, durable lifecycle install acknowledgement, and exact final revision fence are also not implemented or proved. Game Session owns the remote coordinator/follow-up records and its local plugin projection; Automation owns authoritative plugin activation/lifecycle state and the owner `pluginActivationEpoch`/`lifecycleRevision` fence evidence. The tuple, fence, durable install acknowledgement, and exact final revision requirements remain cross-service target obligations; see the [canonical scripting contract](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary), [ADR 0119](../../architecture/decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md), and [normative remote-follow-up tuple-binding contract](../../architecture/system-architecture-scripting-normative-contract-tables.md#remote-follow-up-tuple-binding-normative) for target semantics. +The deterministic command-plan/root boundary remains a Game Session implementation and proof gap. Current command/effect and Automation handoff paths use narrower current identities and do not yet persist or prove the target bindings. See [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), [Transaction Strategies](../../architecture/system-architecture-transactions.md#command-atomicity-and-outcome-aggregation), and [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary) for the canonical command-plan, participant/replay, ordering, and handoff contracts. + ## Packet 4 Status and Proof Gaps - `GR-1.1` / `GR-1.4`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) adds the runtime local consequence that admission and reconnects must use the active playable-state namespace and `playableStateScope`/instance fence. Existing pointer, handoff, drain, and route-swap gaps remain; current Game Session evidence does not prove replacement-state migration or cleanup. Concretely, the `game_instances` schema/entity/repository and `PreparedVersionUpgrade` persistence have no `playableStateNamespaceId` or `playableStateScope`, and prepared cutover records version/remap and target-pointer facts only; this remains a partial implementation gap rather than evidence that current cutover carries stable namespace/scope identity. @@ -38,7 +40,7 @@ These links add decision provenance only; they do not upgrade any Game Session i | `GR-1.1` Session front-end and execution routing | `partial`: WebSocket handshake/session bootstrap, protocol parsing, normalized routing, takeover-safe transport registration, and current local/remote admission are live; lease-owner forwarding for independently partitioned regions is not | `proven`: [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java), [GameSessionWebSocketHandshakeInterceptorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java), [SessionRoutingNormalizationServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java), and [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java) cover the shipped front-door and routing seams | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md) | [WebSocket handler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [handshake interceptor](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [session routing normalization](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [Game Session gRPC](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java) | [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [GameSessionWebSocketHandshakeInterceptorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [SessionRoutingNormalizationServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java) | `GR-1.3` ownership/fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); gateway/TCP edge behavior remains a secondary handoff | The API contract requires front-end-to-lease-owner forwarding to be fenced, with retry/ambiguity handling. The current owner boundary is game-instance scoped and does not implement that forwarding or true region partitioning; no new design decision is recorded. | | `GR-1.2` Tick timelines, action fairness, queues, and scheduling | `partial`: current bounded scheduler, per-entity queue selection, gameplay-command ordering (including timer/automation-origin work only after materialization as gameplay commands with retained provenance/order fields), durable batch/effect staging, pressure signals, and sealed selected-work manifests for gameplay commands are live; directly selected timer/retry/remote-follow-up source-claim manifests remain target-state; it still uses universal work-item selection and does not implement the accepted separate actor-action/passive-effect lane classification, phase budgets, or lane-preserving retry contract; the complete in-place command-status lifecycle accepted by [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) is not | `drift-found`: the shipped scheduler and queue/effect seams have focused proof, but lane/source classification, separate lane budgets, and passive/inbound non-actor-turn behavior are not proved; the accepted command-status lifecycle in [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) remains unimplemented and is not fully proved | [ticks](../../architecture/system-architecture-ticks.md); [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) | [TickScheduler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickScheduler.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [TickServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game-session-service.proto](../../../protos/game-session/v1/game_session_service.proto) | [TickSchedulerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickSchedulerTest.java); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java) | `AS-1.4` timer progress and `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); `GR-1.3` ownership in this tracker | Add the [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) acknowledgement dimensions, authoritative attempt history, bound-tick summary, convergence contract, persistence, and focused proof to `GetGameplayCommandStatus`; separately add TICK-01 source classification, lane/cost metadata, phase budgets, lane-preserving retry identity, and focused actor/passive scheduling proof; adaptive timing and true region-wide scheduling remain separate gaps. | | `GR-1.3` Region leases, fencing, and executor coordination | `partial`: durable runtime ownership, epoch/fence snapshots, pause/resume, stale-owner rejection/requeue, and current runtime-progress publication are live at the game-instance boundary; the TICK-02 Redis lease plus durable executor-fence install/revalidate handshake and true region takeover boundary remain target-state | `proven`: current tests cover fence/scope admission, tick progress, stale execution, and operator reads, but do not prove the TICK-02 lease/fence handshake or takeover reconciliation | [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md) | [RuntimeRegionStatus](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/RuntimeRegionStatus.java); [runtime ownership read](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java); [TickRuntimeProgressService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressService.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java); [TickRuntimeProgressServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressServiceTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java); [GameSessionControlPlaneGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | `GR-1.1` front-end routing in this tracker; `AS-1.1` ingress and `AS-1.4` timers in [Automation runtime tracker](./automation-and-scheduler-runtime.md); Redis lease coordination is the shared infrastructure handoff | The current durable owner row and lease boundary are game-instance scoped. Add proof for Redis lease acquisition/loss before and after durable fence installation, same-token revalidation, stale-fence rejection, and takeover reconciliation; true region-partitioned leases, cluster scheduling, and front-end forwarding remain unimplemented. | -| `GR-1.4` Runtime recovery, replay, and reconciliation | `partial`: durable command/batch/effect recovery, manifest-digest repair, stale-fence requeue, fenced re-drive of accepted-but-unmaterialized commands, remote result reconciliation, and bounded restart/reset paths are live; queue/pending loss before durable batch materialization and recovery of `STAGED` batches/effects after Redis loss remain unimplemented; lane-preserving replay and the complete TICK-02 takeover reconciliation remain target-state follow-through | `unverified`: focused unit recovery tests execute exact accepted-row re-drive, serializer-free identity/payload-idempotent queue/pending behavior, and retryability on Redis/eligibility races; the real-Redis serializer integration test is present but skipped when Docker is unavailable, so production Lua execution and broader proof for lane/cost preservation across recovery, Redis-loss recovery of `STAGED` state, or the Redis lease plus durable-fence takeover handshake remain deferred | [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [reconnection](../../architecture/system-architecture-reconnection.md); [Game Session operations](../../architecture/microservices/game-session-service/operations.md); [ADR 0013](../../architecture/decisions/adr-0013-bounded-invisible-non-edge-restart-recovery.md) | [DatabaseGameplayCommandRecoveryService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java); [GameplayCommandRepository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [TickQueueControlService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickQueueControlService.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [RemoteFollowupRuntimeServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [DatabaseGameplayCommandRecoveryServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java); [TickQueueControlServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java); [TickQueueControlServiceRedisIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceRedisIntegrationTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [RemoteFollowupRuntimeServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java); [RemoteFollowupDrainServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupDrainServiceImplTest.java); [DefaultDurableRemoteFollowupExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableRemoteFollowupExecutionServiceTest.java) | `GR-1.2` queue/replay and `GR-1.3` fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); downstream domain services own effect application/reconciliation | Downstream effect ledgers and replay/idempotency consumers beyond the migrated command families, full non-edge restart recovery, broader payload/work-source recovery, and a durable replay/reconciliation controller for Redis-loss `STAGED` command/batch state remain; add focused proof for lane/cost preservation, current epoch/fence validation, old-fence takeover reconciliation, and broader payload/work-source recovery; ADR 0013 is accepted and owns the bounded invisible non-edge restart target. | +| `GR-1.4` Runtime recovery, replay, and reconciliation | `partial`: durable command/batch/effect recovery, manifest-digest repair, stale-fence requeue, remote result reconciliation, and bounded restart/reset paths are live; current startup handling unsafely terminalizes old accepted-but-unstaged rows as `LOST_BEFORE_STAGING` without materialization evidence, so safe accepted-but-never-staged convergence remains an open gap; queue/pending loss before durable batch materialization and recovery of `STAGED` batches/effects after Redis loss remain unimplemented; lane-preserving replay and the complete TICK-02 takeover reconciliation remain target-state follow-through | `drift-found`: focused unit recovery tests cover accepted-row handling, serializer-free identity/payload-idempotent queue/pending behavior, remote reconciliation, and retryability on Redis/eligibility races, but do not prove safe accepted-but-never-staged convergence, lane/cost preservation, Redis-loss recovery of `STAGED` state, or the Redis lease plus durable-fence takeover handshake; the real-Redis serializer integration test is present but skipped when Docker is unavailable | [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [reconnection](../../architecture/system-architecture-reconnection.md); [Game Session operations](../../architecture/microservices/game-session-service/operations.md); [ADR 0013](../../architecture/decisions/adr-0013-bounded-invisible-non-edge-restart-recovery.md) | [DatabaseGameplayCommandRecoveryService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java); [GameplayCommandRepository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [TickQueueControlService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickQueueControlService.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [RemoteFollowupRuntimeServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [DatabaseGameplayCommandRecoveryServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java); [TickQueueControlServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java); [TickQueueControlServiceRedisIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceRedisIntegrationTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [RemoteFollowupRuntimeServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java); [RemoteFollowupDrainServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupDrainServiceImplTest.java); [DefaultDurableRemoteFollowupExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableRemoteFollowupExecutionServiceTest.java) | `GR-1.2` queue/replay and `GR-1.3` fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); downstream domain services own effect application/reconciliation | Downstream effect ledgers and replay/idempotency consumers beyond the migrated command families, full non-edge restart recovery, broader payload/work-source recovery, and a durable replay/reconciliation controller for Redis-loss `STAGED` command/batch state remain; add focused proof for lane/cost preservation, current epoch/fence validation, old-fence takeover reconciliation, and broader payload/work-source recovery; ADR 0013 is accepted and owns the bounded invisible non-edge restart target. | ### GR-1.2 Command-Status Dimensions @@ -75,9 +77,9 @@ After ingress validation, rate and queue-target resolution, Game Session writes Current pointer-CAS status/proof: routed Automation and remote gameplay-command insertion uses one PostgreSQL `INSERT ... SELECT` guarded by exactly one total current pointer row for the tenant/game-instance target, with that sole row matching the normalized world/realm selectors, pointer version, and required nonblank playable-state scope. Missing, mismatched, or ambiguous authority fails retryably before the insert. Existing pointer updates use expected-version CAS, and pointer creation serializes on the runtime target and fails closed when another route already owns it. Focused unit and compile proof has passed for this path, but live PostgreSQL/Testcontainers concurrency proof is unavailable locally and remains required before claiming full proof. This current pointer-CAS note does not establish target stable-namespace or `realmId` completeness. -The current command lifecycle is explicit: `ACCEPTED` means durable identity exists but staging has not succeeded; `STAGED` means Redis staging succeeded; `DRAINED` means a durable tick batch consumed the staged command; `RETRY_QUEUED` means an abandoned attempt was returned for another attempt; `FAILED` means staging failed before gameplay application; and `LOST_BEFORE_STAGING` is a terminal result only when an explicit recovery or control action determines that accepted work must not be staged. Startup recovery does not assign that terminal result: it re-drives matching `ACCEPTED`/`staged_at IS NULL` rows through the fenced identity/payload-aware queue materializer, while Redis or payload ambiguity leaves the row `ACCEPTED` and retryable. Batch drain and abandonment update command rows, so status is not ingress-only. +The current command lifecycle is explicit: `ACCEPTED` means durable identity exists but staging has not succeeded; `STAGED` means Redis staging succeeded; `DRAINED` means a durable tick batch consumed the staged command; `RETRY_QUEUED` means an abandoned attempt was returned for another attempt; `FAILED` means staging failed before gameplay application; and target `LOST_BEFORE_STAGING` is the terminal recovery state only for explicitly volatile/no-batch accepted work that never reached staging. In the live implementation, startup recovery unsafely applies `LOST_BEFORE_STAGING` to every old `ACCEPTED` row with `stagedAt IS NULL`, without distinguishing durable from volatile/no-batch work. Target durable accepted work remains retryable under its original identity pending materialization evidence. Batch drain and abandonment update command rows, so status is not ingress-only. -`commandId` is carried in enqueue responses, Redis tick payloads, logs/MDC, batch manifests, effect rows, retries, and remote execution. `GetGameplayCommandStatus` is the single canonical Game Session read and currently resolves the command-id identity `(tenantId, gameInstanceId, commandId)`. The automation-handoff identity `(tenantId, gameInstanceId, regionId, regionEpoch, automationDispatchId)` is the accepted target lookup but is not implemented by the live resolver; both identities are defined by [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md), and this tracker records their current and target status below. The read exposes `enqueueSeq`, the latest selected queue-source kind/state/ordinal and due-point tuple, lifecycle and routing data, and remote correlation/result fields. Logging & Admin exposes the implemented command-id read at `GET /gameplay-commands/{tenantId}/{gameInstanceId}/{commandId}` and validates tenant and game-instance identity before trusting the response. +`commandId` is carried in enqueue responses, Redis tick payloads, logs/MDC, batch manifests, effect rows, retries, and remote execution. `GetGameplayCommandStatus` is the single canonical Game Session read and currently resolves the command-id identity `(tenantId, gameInstanceId, commandId)`. The automation status lookup/correlation key `(tenantId, gameInstanceId, regionId, regionEpoch, automationDispatchId)` is the accepted target lookup but is not implemented by the live resolver; it is not the complete Command-Handoff Identity defined by the scripting normative contract table, which additionally carries command ordinal and applicable source/target scope fields. This tracker records the status lookup keys and their current/target status below under [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md). The read exposes `enqueueSeq`, the latest selected queue-source kind/state/ordinal and due-point tuple, lifecycle and routing data, and remote correlation/result fields. Logging & Admin exposes the implemented command-id read at `GET /gameplay-commands/{tenantId}/{gameInstanceId}/{commandId}` and validates tenant and game-instance identity before trusting the response. | Status lookup identity | Implementation status | Proof status | | --- | --- | --- | @@ -86,18 +88,23 @@ The current command lifecycle is explicit: `ACCEPTED` means durable identity exi Rollback queue purge controls cover script-patch and plugin-version scopes. Their ingress `reason` is required and non-blank. Enqueue and purge share renewable queue-mutation and tick leases; purge writes durable terminal state before post-commit Redis queue/pending cleanup, and tick staging discards stale payloads whose durable command is missing or no longer executable. The canonical [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) mapping uses `executionOutcome=LOST_BEFORE_STAGING` before durable batch binding and `executionOutcome=ABANDONED` only for an explicitly retryable command with a prior durable tick-effect binding. Both use `gameplayResult=NOT_APPLIED` and the required structured terminal-reason pair `failureCode=ROLLBACK_PURGED` plus `failureMessage=`, with `completedAt`. `GetGameplayCommandStatus` returns those durable fields. Focused unit proof covers both purge scopes, lock contention, commit-ordered cleanup, durable binding classification, and blank-reason rejection. Batch-bound work outside the explicit retry queue and already-applied work remain outside this purge path. +Current purge implementation/proof is narrower than the target mapping above: `TickQueueControlService.purgeCandidate` checks only `GameplayCommandRepository.hasDurableTickEffect(commandId)` and then classifies the row, rather than performing one atomic owner-defined CAS that proves no surviving batch, effect, or source claim. A concurrent staging, drain, or effect-claim race is therefore not excluded, and the focused purge tests do not establish the target no-batch/no-effect/no-source proof. The target contract remains unchanged; this is an implementation/proof gap and no code fix is claimed here. + ### Scheduler and Queue Pressure -The scheduler has bounded fan-out: one runtime scope can have at most one pending or running tick. Overlapping pulses merge instead of accumulating debt, executor rejection is observable, and gameplay and automation/script ticks use disjoint Redis key namespaces. The scheduler records scheduled, merged, rejected, and paused-cycle counters, queue-depth signals, pressure summaries, and conservative consecutive-cycle thresholds for sustained rejection, elevated merging, and high executor queue depth. Threshold crossings produce alert counters and consecutive-cycle gauges, and canonical alert rules consume the exported gauges. +The live `TickScheduler` provides the bounded pulse-scheduling substrate and its focused proof is summarized in the canonical [Tick System and Runtime Design](../../architecture/system-architecture-ticks.md) and [tick incident runbook](../../architecture/system-architecture-tick-incident-runbook.md). Its current deduplication key is only `(tenantId, gameInstanceId)`; target region partitioning, exact active-namespace evidence, and the accepted lane/budget scheduling contract remain implementation and proof gaps. Scheduler-pressure observability and alert semantics remain owned by those canonical sources rather than duplicated in this tracker. The policy is observability-first. Pressure is an operator alert/input and does not automatically change gameplay timing. The tick incident runbook has a dedicated scheduler-pressure flow. There is no dedicated queue/lease scheduler or broader game-logic action scheduler at this boundary. ### Durable Batches, Effects, and Source Contracts -Redis queue-to-pending staging currently creates one durable `tick_batch` with `tickBatchId`, tenant/game scope, `batchSource`, status, solo-tick requirement, command count, expected effect count, selected-work manifest JSON and digest, ownership snapshot, and timestamps. Each selected gameplay command creates one durable `tick_effect` with stable `effectId`, batch and command links, effect key/type, target aggregate, status, failure code/message, and timestamps. Target aggregates narrow to the known character or entity when the command provides one instead of always using the game instance. This live manifest persistence is gameplay-command-only; timer, retry, and remote-follow-up source-claim manifests remain target-state and are not implied by the current batch fields. +Redis queue-to-pending staging currently creates one durable `tick_batch` with `tickBatchId`, tenant/game scope, `batchSource`, status, solo-tick requirement, command count, expected effect count, selected-work manifest JSON and digest, ownership snapshot, and timestamps. Each selected gameplay command creates one durable `tick_effect` with a stable same-batch `effectKey` (currently derived from `commandId`) and an `effectId` currently derived from `tickBatchId` plus that key, along with batch and command links, effect type, target aggregate, status, failure code/message, and timestamps. Target aggregates narrow to the known character or entity when the command provides one instead of always using the game instance. Current batch/manifest persistence does not yet prove exact active-namespace evidence throughout admission, replay, replacement, and fresh-playtest isolation, but namespace remains evidence rather than a tick-batch uniqueness dimension. This live manifest persistence is gameplay-command-only; timer, retry, and remote-follow-up source-claim manifests remain target-state and are not implied by the current batch fields. Batch states are `STAGED`, `DRAINED`, `APPLIED`, and `ABANDONED`. Effect states are `STAGED`, `DRAINED`, `APPLIED`, `REPLAY_NOOP`, `REJECTED`, and `ABANDONED`. Existing pending work is correlated to an older staged batch or to a bounded `PENDING_REPLAY` batch created during recovery. The current tick boundary requires durable command identity; it does not retain a no-`commandId` recovery path. +The current `REPLAY_NOOP` and `REJECTED` effect statuses are implementation drift from the accepted [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) and [transaction effect contract](../../architecture/system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory): `REPLAY_NOOP` is an `APPLIED` outcome/reason, never a status, and a rejected or fenced effect is not terminally settled merely because execution did not proceed. The live executor persists those statuses and can mark a batch `APPLIED` once no `DRAINED` rows remain, without requiring every effect to be `APPLIED` or evidence-qualified `ABANDONED`. Target convergence must preserve the canonical terminal set, retain replay/rejection reasons separately, leave inconclusive work reconciliation-required, and add focused participant-set and batch-aggregation proof; the ADR and transaction owner remain authoritative for the mapping. + +The stale-fence path is a concrete instance of that drift: for a non-remote gameplay-command batch, `TickBatchExecutionService.executeDurableEffects` routes a stale-ownership `DRAINED` batch to `abandonStaleDrainedBatch`, which marks every remaining `DRAINED` effect `ABANDONED` and requeues its commands without domain evidence. Remote-followup batches instead route to `markRemoteFollowupBatchAbandoned` and do not requeue gameplay commands. The stale-fence handling can therefore terminalize unfinished effects without evidence that they were unapplied; an effect that started before the fence changed can be replayed and applied twice. Target recovery requires the ADR 0069 evidence-qualified `APPLIED`/`ABANDONED` decision, with inconclusive effects retained as non-terminal reconciliation work; focused stale-fence proof remains absent. Legacy `TickStaging` rows with `commandId='-'` remain unresolved: the current parser and Lua path fail closed, and no authoritative drain, migration, or command-correlation proof exists for them. The sealed gameplay-command selected-work manifest is the current replay contract. It records explicit `regionId`, `enqueueSeq`/comparable source ordering, source kind/type and state, due tick/point, target and routing facts, automation dispatch/work-item identity, script/plugin provenance, and source-state metadata. `enqueueSeq` is used as `sourceOrdinal` where available instead of a transient batch slot. Durable command and remote-follow-up rows also persist their latest origin-source and queue-source tuples so status and operator reads do not need to parse manifests or payload JSON. Complete timer/retry/remote-follow-up source-claim manifests remain target-state follow-through; timer/automation-origin work appears in the current sealed manifest only after materialization as a gameplay command with its provenance and ordering fields retained. @@ -111,6 +118,7 @@ After Redis drain commit, Game Session executes `DRAINED` effects from the durab Malformed or orphaned tick queue/pending entries have no token-fenced atomic quarantine and convergent-removal implementation or proof; a separate-check `LREM` is not an authorized cleanup path. Stale drain, fresh-stage rollback, and manifest-mismatch repair requeue actual commands, advance their queue-source state deliberately, and increment `tick_requeued_action_total` by action count and durable source (`player`, `automation`, bounded `remote_followup`, or `unknown`). Requeue preserves sealed source identity, comparable ordinal, due point, and source state; mutable command-row state cannot replace the sealed ordering facts. Only the first current migrated command families consume the post-drain effect seam, while pure views remain direct reads. +The complete target command-plan/root replay and reconciliation bindings are not yet persisted or proved; see [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), [Transaction Strategies](../../architecture/system-architecture-transactions.md#command-atomicity-and-outcome-aggregation), and [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary) for the owning contracts. ### Gameplay Mutation Consumers @@ -122,7 +130,7 @@ The item command handler records `gamesession.command.item.*` invocation and fai ### Ownership, Epochs, and Fencing -`runtime_region_status` is the current durable owner-of-record keyed by the live tenant/game boundary. It stores explicit `regionId`, `regionEpoch`, opaque `executorFence`, owner service and instance identity, paused state, `lastCommittedTickBatchId`, and backlog truth. Tick processing observes this row and refreshes owner identity from the shared runtime identity. Pause, resume, and recovery advance the durable epoch/fence timeline; the fence is an opaque generation token and is compared for equality/freshness rather than treated as a numeric sequence. +`runtime_region_status` is the current durable owner-of-record keyed by the live tenant/game boundary. It stores explicit `regionId`, `regionEpoch`, opaque `executorFence`, owner service and instance identity, paused state, `lastCommittedTickBatchId`, and backlog truth. The current schema also retains the unscoped unique index `idx_runtime_region_status_tenant_region` on `(tenant_id, region_id)` even though canonical region scope includes `gameInstanceId`; ordinary writes therefore collide when two game instances reuse a region id. This collision is implementation drift, not proof of globally unique regions. Separately, `RuntimeRegionStatusRepository.findByTenantIdAndRegionId` omits `gameInstanceId` and can select the wrong instance if legacy or constraint-bypassing data ever contains multiple matching rows. These are distinct implementation/proof gaps; duplicate-row ambiguity is not the normal consequence of the still-active unique index. Active-namespace evidence must still be exact-bound in selected work and replay, but it does not extend region-ownership identity. Tick processing observes this row and refreshes owner identity from the shared runtime identity. Pause, resume, and recovery advance the durable epoch/fence timeline; the fence is an opaque generation token and is compared for equality/freshness rather than treated as a numeric sequence. Batch creation seals the owner `regionEpoch`/`executorFence` and `regionId`. Drain/finalization rejects a changed owner, rolls pending work back to the queue, and abandons the batch with `STALE_EXECUTOR_FENCE`. Before applying `DRAINED` effects, the executor checks the same snapshot again; stale effects are not sent to domain handlers, are abandoned, and their commands are requeued for a fresh fenced batch. `lastCommittedTickBatchId` advances only on durable batch drain. @@ -133,9 +141,12 @@ The canonical `GetRuntimeOwnershipStatus` read returns owner, scope, epoch/fence Cross-region remote runtime remains partial. Current Game Session implementation has durable coordinator/follow-up persistence and handoff, bounded duplicate-window paging and per-entity de-duplication, durable result recording/replay, terminal follow-up replay, late-result handling, and selected reconciliation branches; the focused proof for those slices is recorded in [Validation and Proof](#validation-and-proof). Current storage and wire rows still lack the complete source/target projection and sealed handler-input manifest needed for exact source/target tuple binding, replay, and fencing. The remaining fair-due selection, source-claim ordering/manifests, terminal/result/reconciliation convergence, terminal-failure mirroring, missing-coordinator recovery, origin reconciliation, and plugin lifecycle-fence propagation are not implemented or proved. Origin timeout cannot currently terminalize scheduled or claimed target follow-up work: that requires coordinator-side arbitration/CAS plus authoritative proof that the target work was unapplied; current origin reconciliation lacks that implementation and proof. +The current `remote_followup` uniqueness index on `(tenant_id, target_region_id, target_region_epoch, effect_key)` omits `target_game_instance_id`, while repository reads include it; this is implementation drift, not target behavior. Persisted row fields remain canonical even when the original command row is absent, with payload JSON as optional enrichment. Origin timeout cannot currently terminalize scheduled or claimed target follow-up work: that requires coordinator-side arbitration/CAS plus authoritative proof that the target work was unapplied; current origin reconciliation lacks that implementation and proof. The complete target contract is owned by the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md), [tick failure contract](../../architecture/system-architecture-tick-failures-and-operations.md#cross-region-follow-up-record-contract-required), [scripting contract](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary), [ADR 0055](../../architecture/decisions/adr-0055-durable-cross-region-effects-with-static-live-topology.md), [ADR 0066](../../architecture/decisions/adr-0066-durable-asynchronous-cross-region-result-arbitration.md), [ADR 0071](../../architecture/decisions/adr-0071-durable-tick-commit-before-fenced-coordination-cleanup.md), and [ADR 0119](../../architecture/decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md). This tracker records only current implementation and proof status; target field, identity, outcome, scope, and reconciliation requirements remain in those canonical owners. +Origin reconciliation remains target-state and is not yet fully implemented or proved: the owner must reconcile durable results before timeout, require matching scope/epoch evidence, wait for target-command convergence, and preserve the original timeout or abandonment cause. The live result-inbox path has partial late-result handling, but exact serialized arbitration, immutable terminal/retry proof, and documented compensation ownership remain unproven. Current remote due/backlog gauges use durable owned-region truth; the remaining terminalization and reconciliation proof gaps are tracked by the linked owner contracts. + ### Operator Readback and Facade Boundaries Game Session control-plane reads are canonical and bounded. The runtime-state read for `(tenantId, gameInstanceId)` returns the current runtime version plus the resolved launch descriptor, version/release identifiers, and script-patch pin metadata including the persisted pin `controlPlaneRequestId`; `GetGameSessionPinConvergence` provides the direct pin-convergence read used by rollback/promotion orchestration. The live `GetGameSessionPinConvergenceResponse`/adapter now also exposes `observed_script_pin_epoch` alongside `observed_pinned_script_patch_version`, `last_observed_control_plane_request_id`, `observed_at_ms`, `is_stale`, and publication, providing exact epoch readback on that surface. Pin/rollback writes now carry tagged expected-current-pin CAS input and persist a durable request digest/result ledger with exact replay and deterministic conflict/precondition outcomes; their responses include previous/resulting epochs. The target `GetScriptPinTransitionWorkflowStatus` read is not exposed and remains required for authoritative timeout-consumer workflow state, deadline, generation, and terminal-evidence readback. Its `is_stale` age signal is not the Automation projection tuple (`projection_as_of_ms`, `projection_lag_ms`, `is_projection_stale`), which the target Game Session read does not currently define. These workflow-status, remaining Automation source/target tuple-binding, and exact history/rollout proof gaps remain. `GameSessionControlPlaneGrpcService` is the transport, authorization, and application-error delegation layer; `GameSessionCommandControlPlaneService` owns gameplay-command status projection, staged automation-command admission, alias validation, remote-result/status mapping, and publication lookup helpers. The remaining remote runtime read/delegation collaborators keep the facade from carrying a second domain implementation. Current control-plane handlers preserve normal-response application mappings, while the [gRPC owner contract](../../architecture/system-architecture-grpc.md#outcome-and-transport-classification) governs typed domain results versus canonical non-OK failures. Stable mutation identities remain the reconciliation boundary; exact per-RPC classification and focused proof are implementation gaps. @@ -152,7 +163,11 @@ Game Session owns the implemented runtime feature-flag mutation and persists the ### Validation and Proof -The recorded proof covers durable command identity and sanitized persistence, restart/Redis-loss recovery at the ingress and ownership boundaries, accepted-but-never-staged convergence, single-record retry/replay updates, command correlation, batch/effect creation, manifest-digest replay repair, stale drain and post-drain fence rejection, durable `DRAINED` resumption, source-tuple preservation through timer/retry/remote claim-release transitions, fair selection in the local scheduler/queue path, and operator DTO/request mapping. Focused remote-runtime tests cover payload validation, bounded duplicate-window paging and de-duplication for due follow-up candidates, bounded durable result recording/replay, already-terminal follow-up replay, late-result handling, and selected reconciliation branches; this does not establish the full remote-follow-up fair-due-selection contract. They do not establish complete exact replay, general target-command convergence, complete terminal-failure mirroring, safe missing-coordinator recovery, or full origin reconciliation; those remain the target gaps described above. +The recorded proof covers durable command identity and sanitized persistence, restart/Redis-loss recovery at the ingress and ownership boundaries, single-record retry/replay updates, command correlation, batch/effect creation, manifest-digest replay repair, stale drain and post-drain fence rejection, durable `DRAINED` resumption, source-tuple preservation through timer/retry/remote claim-release transitions, fair selection in the local scheduler/queue path, and operator DTO/request mapping. Focused remote-runtime tests cover payload validation, bounded duplicate-window paging and de-duplication for due follow-up candidates, bounded durable result recording/replay, already-terminal follow-up replay, late-result handling, and selected reconciliation branches; this does not establish the full remote-follow-up fair-due-selection contract. They do not establish complete exact replay, safe accepted-but-never-staged convergence, general target-command convergence, complete terminal-failure mirroring, safe missing-coordinator recovery, or full origin reconciliation; those remain the target gaps described above. + +Current handling proof for accepted-but-never-staged work is limited to the live [recovery helper](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java) and its [focused test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java): they show that old `ACCEPTED` unstaged rows are terminalized as `LOST_BEFORE_STAGING` based on `stagedAt IS NULL`. This is not proof of safe convergence; the helper unsafely terminalizes durable accepted work without materialization evidence. Target durable accepted work remains retryable under its original identity pending materialization evidence; only explicitly volatile/no-batch work may use `LOST_BEFORE_STAGING`. Deterministic remote-result replay, paused-origin/late-result reconciliation, target-command convergence, and tenant/scope/id guards therefore remain proof gaps rather than completed coverage. + +Run-owned Compose mutation and teardown are implemented and proved at their bounded scope, but Game Session implementation and proof do not yet establish persistent/shared restricted-synthetic identity/namespace/fence isolation or independently isolated two-transport mutating parity. Shared/player-facing whole-stack reset is prohibited, and fixture teardown is not Coordination Redis reset authority; see the canonical [player-flow smoke and reset contract](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). The focused validation commands recorded for the live slices are `./gradlew :game-session-service:test --tests 'net.firedevops.firemud.gamesession.service.impl.TickStagingServiceTest' --tests 'net.firedevops.firemud.gamesession.service.impl.TickBatchExecutionServiceTest' --tests 'net.firedevops.firemud.gamesession.service.impl.TickServiceImplTest'`, the corresponding `RemoteFollowupRuntimeServiceImplTest` and `DefaultDurableRemoteFollowupExecutionServiceTest`, `dev-tools/validation/run-locked-gradle.sh :game-session-service:check -PfullCheck`, and `dev-tools/validation/run-locked-gradle.sh :logging-admin-service:check -PfullCheck`. Logging & Admin point/list/status controller and service tests cover successful reads, tenant guards, invalid enums, and fail-closed response mismatches for the listed control-plane routes; `/actuator/settings/effective` is outside that coverage pending route-aware authorization and cross-tenant denial proof. Game Session control-plane contract tests cover the upstream reads and fencing. The scheduler has a real bounded `ThreadPoolTaskExecutor` pressure proof including threshold trip and recovery reset. Lifecycle, feature-authority, and migrated command suites provide the corresponding focused proofs. @@ -161,11 +176,14 @@ The recorded Markdown and contract checks for these slices include `./gradlew li ## Active Gaps - TICK-03 is now the accepted command-level boundary: required versus optional effects, permitted terminal combinations, intentional `PARTIAL`, and stronger atomicity routing must be classified per command family. Current implementation and proof remain partial; no status promotion is implied. -- TICK-04 makes Game Session the durable owner of cross-service effect intent, required-participant status, retry, and reconciliation. The runtime still needs operation/digest-bound participant guards, stable root `EffectId` reuse, and focused crash/retry/dead-letter proof across World and Entity. -- Replacement cutover remains partial at the Game Session boundary: the target requires binding World’s one-shot `cutoverHoldId`/`cutoverHoldFence` and exact source/target `ACTIVE` proofs in the local pointer, audit, prepared-execution, source-cleanup, and drain-fence transaction, then proving post-swap readback before World finalization. The current wire/durable record/reconciler has no complete hold binding or safe-abort/finalization proof; it must not infer success from a pointer write or an in-memory termination request. +- TICK-04 remains partial and proof remains incomplete: deterministic command-plan admission, operation/digest-bound participant guards, stable `planOrdinal`/root `EffectId` persistence and reuse, and focused crash/retry/dead-letter coverage across World and Entity are still gaps. The canonical effect/root and durable-commit contracts are defined by [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) and [ADR 0071](../../architecture/decisions/adr-0071-durable-tick-commit-before-fenced-coordination-cleanup.md); this tracker records only the implementation and proof gaps. +- Replacement cutover remains partial at the Game Session boundary: the current wire/durable record/reconciler has no complete proof of exact cross-service cutover binding, post-swap readback, safe abort, or finalization, and must not infer success from a pointer write or an in-memory termination request. See the canonical [World Management replacement cutover hold contract](../../architecture/microservices/world-management-service/api-contracts.md#replacement-cutover-hold-contract) and [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). - The current Game Session movement seam is a room-binding/projection seam, not World-authoritative location/occupancy mutation. The target World-owned authoritative mutation path remains unimplemented/unproved, and `DROP`/`PICKUP` still lack proof that the World actor-location precondition remains valid through the Entity commit. - Ownership is durable only at the current game-instance queue boundary. True region-partitioned execution, a cluster scheduler, and lease-owner forwarding from session front ends are not implemented. +- The current runtime-status schema/repository still exposes unscoped `(tenant, region)` uniqueness/read behavior, despite the complete region scope including `gameInstanceId`; the remote-followup schema similarly uses `(tenant, target-region, target-epoch, effect_key)` uniqueness while repository reads include target instance scope. These are concrete implementation/proof gaps; no target contract should be inferred from the current indexes, and no migration is claimed here. +- Durable-first commit and fenced coordination cleanup remain partial: current implementation and focused proof do not yet establish the target `durable_committed` boundary. [ADR 0071](../../architecture/decisions/adr-0071-durable-tick-commit-before-fenced-coordination-cleanup.md) owns the canonical commit/cleanup contract; this tracker records only the current implementation and proof status. +- Region split/merge remains an operator-controlled cutover. Current implementation and proof do not establish the [ADR 0055](../../architecture/decisions/adr-0055-durable-cross-region-effects-with-static-live-topology.md) producer-wide admission barrier across player fronts, supported operator forwarding, automation, timers, and remote-follow-up producers; pausing only the current tick/command loop is not sufficient. - The scheduler has no adaptive gameplay-timing feedback loop. Pressure remains observable and operator-driven; changing gameplay timing requires preview or production-like data and a deliberate decision. - Only the current built-in state-changing command families consume the durable effect path. Later authored or game-defined authoritative mutations must use it; read-only views remain direct by design. - Timer, retry, and remote-follow-up work is live only after materialization as gameplay commands with retained provenance and ordering fields; directly selected source-claim manifests for those sources remain target-state. The three current remote payload families are live, but any new work-source or payload family still needs explicit durable source, ordering, ownership, fence, replay, result, and operator-read contracts. No side channel is part of the current implementation. The accepted [ADR 0055](../../architecture/decisions/adr-0055-durable-cross-region-effects-with-static-live-topology.md), [ADR 0066](../../architecture/decisions/adr-0066-durable-asynchronous-cross-region-result-arbitration.md), and [ADR 0077](../../architecture/decisions/adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md) do not claim those broader implementation families are complete. 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 8df39a9ab6..f308558105 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 @@ -79,11 +79,11 @@ The live transfer contract deliberately rejects an already-moved item by default ### Durable Effects and Replay Guards -Game Session persists a stable same-batch `effectKey` and deterministically derives `effectId` from `tickBatchId` plus that key. The current key vocabulary is `command:` when a durable command id exists, or `command-text::slot:` for a queue entry without one. Same-batch duplicate keys are rejected. Durable drained effects resume after restart and, after an ownership-fence check, converge to `APPLIED`, `REPLAY_NOOP`, or `REJECTED`; stale executors abandon and requeue rather than applying under the wrong fence. +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 target command-plan root binding, which remains unimplemented and unproved here. See [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) for the owning target contracts and remaining proof boundary. -Owning domains provide the duplicate-application boundary rather than relying on one global guard table. Movement uses an `effectId`-keyed idempotency service tied to session-context mutation. Entity Management has a mutation replay row per `{tenantId,effectId}` for the bounded item/equipment/container path, and a separate `ApplyActorCondition` replay path that uses the temporary `sourceId` adapter; duplicate delivery returns the stored response on those exercised paths. This is not replay-proof coverage for every Entity mutation ingress: blank-`effectId` compatibility requests bypass the ledger, and the actor-condition adapter does not yet expose a dedicated replay field. 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 duplicate whose first row was already committed; concurrent first-apply replay remains unproved. +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 shared execution helper also keeps Game Session communication, AFK, action-state, and authored-action replay lookup/save/delivery behavior aligned. 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 is a bounded adoption set, not a universal cross-service guard table; future authoritative mutation families must adopt the same durable-identity and owning-domain boundary. +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. @@ -123,10 +123,11 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, ## Active Gaps - Accepted TICK-03 requires command-level required/optional effect classification and invariant-sensitive routing; current gameplay families do not yet provide complete classification or terminal-outcome proof. See [ADR 0053](../../architecture/decisions/adr-0053-command-atomicity-by-invariant-class.md) and its [tick failure/operations owner](../../architecture/system-architecture-tick-failures-and-operations.md). -- Accepted TICK-04 requires one durable root `EffectId` with operation/target/request-digest-bound participant guards and causal read composition. Existing replay proof is domain-bounded and does not prove the cross-service guard, stale-precondition, or mixed-floor cases. See [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) and its [identifier-glossary owner](../../architecture/system-architecture-identifier-glossary.md). +- Accepted TICK-04 remains an implementation and proof gap: current replay paths do not establish cross-service operation/target/request-digest-bound participant guards, causal read composition, stale-precondition handling, or mixed-floor handling. The canonical mutation identity, participant-guard, and root/child lineage rules are owned by [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), and the [identifier glossary](../../architecture/system-architecture-identifier-glossary.md); pending generated-child allocation is recorded only in the non-authoritative [ADR 0183 proposal](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). This tracker records implementation and proof status only. - [ADR 0059](../../architecture/decisions/adr-0059-causal-floor-cross-service-presentation-reads.md) accepts a causal floor plus actual opaque World/Entity component versions; current LOOK composition still has scope-marker compatibility behavior, bounded stale-floor retry, and final read-fence error mapping gaps. This tracker does not claim the accepted presentation identity is implemented. - [ADR 0060](../../architecture/decisions/adr-0060-world-owned-ambient-facts-and-logic-owned-consequences.md) and [ADR 0061](../../architecture/decisions/adr-0061-single-owner-spatial-mutations-across-split-authority.md) keep ambient/location facts in World, item holders in Entity, and root outcomes/reconciliation in Game Session. Current gameplay has no complete cross-owner mutation/targeting proof; the accepted ownership direction does not promote current item or movement seams. -- [ADR 0056](../../architecture/decisions/adr-0056-one-hot-path-fan-out-owner.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), and [ADR 0075](../../architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md) are target contracts only: transitive two-participant proof, one-logical-effect terminal convergence, and deterministic chain count/cost/per-target suppression remain unimplemented or unproved for broader gameplay families. +- The repository still advertises HTTP inventory/equipment mutation controllers that call Entity directly outside Game Session effect, tick, and barrier admission. These routes are not production-safe gameplay paths unless explicitly isolated under a separately approved owner/admin contract; their presence is implementation drift, not a second gameplay ingress. +- Broader gameplay families remain unimplemented or unproved against the target contracts owned by [ADR 0056](../../architecture/decisions/adr-0056-one-hot-path-fan-out-owner.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), [ADR 0075](../../architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md), and the canonical [Transactions generated-effect-chain contract](../../architecture/system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory). - The parent inventory slice remains partially implemented as a domain: manual happy-path verification over both WebSocket and Telnet is still unchecked, and later nested-container UX, crafting/material flows, banking/vendor/mail/trade, loot generation, scripted item behavior, durability, and richer client filtering are not implemented. - Broader holder families must reuse the direct-holder and guarded-handoff model. Cross-domain transfer replay is not implicit; it needs an explicit caller-owned contract. Stronger audit invariant/alert tooling is also future work. @@ -135,7 +136,7 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, - Generic authored stat/condition definitions, release-catalog enforcement as a full authoring system, broader effect kinds, generic resource-cost mutation, cooldown lifecycle, multi-effect action execution, and combat-facing effect consumption remain future work. The intended catalog is versioned DML frozen into a release bundle; Entity Management must reject unknown or stale keys rather than invent defaults, and starter profiles must materialize ordinary editable DML rather than hidden runtime fallback. The current typed payload is still a transitional continuous-source contract. The locked `EffectDeclaration` model distinguishes `CONTINUOUS` read-time sources, which never persist derived resource values, from idempotent `INSTANT` mutations under a resolved plan; future condition application uses authored `REPLACE`, `REFRESH`, `STACK`, or `PARALLEL` and duration policy, while cooldowns remain a sibling timed-state type. - The future actor-state contract keeps capacity-change policy, floor transitions, disposition, conditions/equipment overlays, action-admission tags, command capability policy, costs, and cooldowns as separate concerns. Resource floors have no implicit `health`, death, victory, corpse, loot, respawn, or revival meaning; continuous sources cannot override disposition admission, and durable instant mutations must own explicit lifecycle transitions. - The future action-admission contract uses a release-pinned DML `ActionAdmissionTag` catalog and ordered required `admissionTags`. Command-capability and login/play stage gates run first; disposition and continuous overlays may deny but never grant forbidden behavior, and unknown, stale, or omitted required tags fail closed. -- The broad authored target-resolution and structured-outcome model is not live: cross-actor target sets, canonical candidate/fact snapshots, target-resolution evidence, `ResolvedEffectPlan` application, remote legs, semantic presentation events, and general required/optional outcomes remain design work beyond the self-targeted v1 path. The locked boundary is Game Logic-owned resolution from frozen policies and owner fact snapshots/tokens, followed by idempotent Entity Management application; Game Session must not choose final actor identities. Candidate selection is explicitly bounded and deterministic, observation failures must not disclose hidden facts, same-region required legs commit atomically or reject, and cross-region legs use durable follow-up coordination rather than claimed distributed atomicity. The future `GameplayActionOutcome` separates source `commitState` from `completionState`, carries ordered target-leg outcomes, and drives idempotent semantic presentation events rather than treating free-form text as gameplay truth. +- The broad authored target-resolution and structured-outcome capability remains unimplemented and unproved beyond the self-targeted v1 path: cross-actor target sets, multi-effect composition, cross-region outcomes, and the wider typed primitive catalogue remain gaps. Canonical ownership is defined by [ADR 0112](../../architecture/decisions/adr-0112-typed-bounded-gameplay-effect-extension.md), with target-plan resolution in the [Game Logic API contracts](../../architecture/microservices/game-logic-service/api-contracts.md) and validated actor/effect mutation in the [Entity Management API contracts](../../architecture/microservices/entity-management-service/api-contracts.md); this tracker records the current capability and proof gap only. - Reusable DML observation, targeting, and selection policies define `SOURCE` plus keyed target sets, `EXACTLY_ONE`, bounded `UP_TO_N`, or `ALL_ELIGIBLE` cardinality, and player-selected, canonical-order, ranked, or effect-id-seeded selection. Resolution records candidates, fact snapshots, policy identity, ranking or seed, selected targets, and owner fence/version tokens. Missing or stale facts fail closed; token mismatch re-resolves under the same effect id before mutation. - Resource costs and cooldowns remain future actor-state execution work. Game Design declarations carry typed costs, cooldowns, and `ON_EXECUTION` or `ON_EFFECT_SUCCESS` commit policy; Entity Management must atomically validate and consume resources, create durable cooldown records, and apply same-region effects under one idempotent effect id. Game Session timers are reconstructible wake-up projections, concurrent actions serialize at the authoritative mutation, queue acceptance consumes nothing, and cross-region failure has no implicit refund. Capacity changes use authored preserve/shift/clamp policy, and floor transitions are explicit one-shot lifecycle events rather than implicit death or victory semantics. - No unified persisted actor runtime, NPC runtime actors, generic actor targeting/communication, or actor-state linkage exists. The locked core is an opaque `actorId` with tenant/game-instance context, `actorKind`, display name, presence state, and disposition, linking player actors to account/character and NPC actors to runtime instances; `PLAYER` and `NPC` are first kinds, with later `PET`/`SUMMON`, and gods/admins remain player overlays. 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 d1ae1372b2..5d3716ef28 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -14,6 +14,8 @@ This tracker is the permanent reader-facing implementation record for world runt - `AR-3.1`: [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) records the database lifecycle row/epoch and Temporal coordination boundary. Existing prepare/activate/terminate caveats, including blocking calls and missing stages, remain active gaps. - `GR-2.1` / `SF-2.3`: The synchronous termination seam returns a `TERMINATED` snapshot before checking a supplied `terminationRequestId`; mismatched terminal retries therefore are not fail-closed, and exact identity/conflict proof remains incomplete. See [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). - `GR-2.1` / `SF-2.1`: Versioned topology and spawn schemas carry tenant/version columns but use scalar parent foreign keys, so the database does not enforce child/parent scope equality. Composite ownership enforcement (or an equivalent owner-local guard) and database readback proof remain incomplete; this is separate from sentinel-default and hierarchy/version-graph backfill drift. See [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). +- `GR-2.1` / `AR-1.5`: The WMS design handoff performs only a remote Game Design Draft-state check before its local mutation transaction. Durable owner-freeze acknowledgement and commit-bound `versionStateEpoch`/`publicationFence` evidence are absent, so a pre-check can race publication; the target handoff and race semantics belong to [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff), with local status and proof consequences in [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). +- The current Temporal lifecycle signal implementation keeps one mutable pending slot per operation and can overwrite repeated requests or process activate plus terminate against a stale epoch; this race and its focused proof remain incomplete. The target durable signal/update contract and conflict semantics are owned by [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). These links add decision provenance only; they do not upgrade world runtime, lifecycle, or Draft mutation status. diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index b9c8c7cd91..d84f19aba1 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -8,6 +8,15 @@ import re root = pathlib.Path(".") obsolete_public_resume_signature = "`resume(operationId, expectedPhase, scope, maintenanceLockToken, evidenceRef)`" +obsolete_scope_resume_window_identity = re.compile( + r"<(?=[^<>]*\btenantId\b)" + r"(?=[^<>]*\bgameInstanceId\b)" + r"(?=[^<>]*\bregionId\b)" + r"(?=[^<>]*\bregionEpoch\b)" + r"(?=[^<>]*\bisDryRun\b)" + r"(?=[^<>]*\bplayableStateScope\b)" + r"(?=[^<>]*\bresumeGeneration\b)[^<>]*>" +) obsolete_gameplay_session_selector = "session:game:{tenantInstanceTag}" obsolete_gameplay_character_index = "session:game:index:character:{tenantGameplayTag}::" obsolete_gameplay_character_index_with_scope = "session:game:index:character:{tenantGameplayTag}:::" @@ -1817,7 +1826,7 @@ require_section_contains( "`lastResetValidationEvidence`", "bounded `validationEvidence`", "`resetReason` is absent from lifecycle and trip rows", - "persisted non-identity `playableStateNamespaceId` evidence", + "`playableStateNamespaceId` is the immutable playable-state identity/allocation dimension", "`currentRuntimePlayableStateNamespaceId`", "The normalized exact scope is `(tenantId, gameInstanceId, regionId)`, where an omitted or blank `regionId` selects the exact empty/unscoped row and never a wildcard", "For both this mutation and `GetAutomationDrainStatus`, `tenantId` and `gameInstanceId` are required nonblank after normalization", @@ -1898,40 +1907,86 @@ require_absent( require_contains( "design/architecture/system-architecture-scripting-scheduler-and-timers.md", [ - "resume-window record per ``", - "its `resumeWindowId` is ``", - "retains the authoritative `playableStateNamespaceId` as immutable non-identity scope evidence", + "resume-window record per ``", + "its `resumeWindowId` is ``", + "The server-derived `playableStateScope` is persisted separately as immutable policy/routing/authorization/migration-fence evidence and is exact-validated; it is not part of the window identity.", "missing or mismatched evidence fails closed without changing any canonical identity tuple", ], ) require_contains( - "design/architecture/system-architecture-scripting-dsl-for-designers.md", + "design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md", [ - "`resumeWindowId` identified by ``", - "one-tenant, one-mode ID", + "The authoritative `playableStateNamespaceId` is part of the due and resume-window identity", + "server-derived `playableStateScope` remains immutable policy/routing/authorization/migration-fence evidence", + "is exact-validated alongside that identity, and is not a uniqueness discriminator", + "`resumeWindowId` identity", ], ) -require_absent( +for resume_identity_path in ( + "design/architecture/system-architecture-scripting-scheduler-and-timers.md", + "design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md", + "design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md", + "design/architecture/system-architecture-scripting-normative-contract-tables.md", + "design/architecture/system-architecture-scripting-dsl-for-designers.md", +): + resume_identity_text = (root / resume_identity_path).read_text(encoding="utf-8") + if obsolete_scope_resume_window_identity.search(resume_identity_text): + raise SystemExit( + f"{resume_identity_path}: contains a scope-based resume-window identity tuple" + ) +require_contains( "design/architecture/system-architecture-scripting-dsl-for-designers.md", [ - "`resumeWindowId` identified by ``", + "`resumeWindowId` identified by ``", + "one-tenant, one-mode ID", + "the server-derived `playableStateScope` is retained as immutable policy/routing/authorization/fence evidence and is exact-validated alongside that identity", ], ) require_contains( "design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md", [ - "resume-window record per runtime scope, epoch, and `isDryRun` mode", - "`resumeWindowId` is the exact tuple ``", + "resume-window record per playable-state namespace/runtime scope, epoch, and `isDryRun` mode", + "`resumeWindowId` is the exact tuple ``", + "the server-derived `playableStateScope` is retained and exact-validated as immutable policy/routing/authorization/fence evidence, not as a uniqueness input", "each prior epoch's `OPEN` resume window, independently for each `isDryRun` mode", ], ) require_contains( "design/architecture/system-architecture-scripting-normative-contract-tables.md", [ - "resume window identified by ``", - "Durable compare-and-set creates or reuses one `OPEN` window per runtime scope, epoch, and `isDryRun` mode", + "resume window identified by ``", + "Durable compare-and-set creates or reuses one `OPEN` window per namespace/runtime identity, epoch, and `isDryRun` mode", + "the server-derived `playableStateScope` is retained as immutable exact-validated policy/routing/authorization/migration-fence evidence for that window and is excluded from its identity, with missing or mismatched evidence fencing admission", ], ) +for non_resume_scope_fixture in ( + "", + "", +): + if obsolete_scope_resume_window_identity.fullmatch(non_resume_scope_fixture): + raise SystemExit( + "non-resume-window scope validation tuple was incorrectly rejected: " + f"{non_resume_scope_fixture}" + ) +for obsolete_resume_identity_fixture in ( + "", + "", + ( + "" + ), +): + if obsolete_scope_resume_window_identity.fullmatch(obsolete_resume_identity_fixture) is None: + raise SystemExit( + "scope-based resume-window identity fixture was not rejected: " + f"{obsolete_resume_identity_fixture}" + ) +canonical_resume_identity_fixture = ( + "" +) +if obsolete_scope_resume_window_identity.fullmatch(canonical_resume_identity_fixture): + raise SystemExit("canonical namespace-owned resume-window identity was rejected") require_contains( "design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md", [ @@ -1955,7 +2010,7 @@ if len(preimage_matches) != 1: expected_scheduler_preimage = [ "tenantId", "gameInstanceId", - "playableStateScope", + "playableStateNamespaceId", "stableOwnerKind", "stableOwnerId", "regionId", diff --git a/dev-tools/validation/check-design-capability-allocation.py b/dev-tools/validation/check-design-capability-allocation.py index 8f28078646..bf9e4e4c8e 100644 --- a/dev-tools/validation/check-design-capability-allocation.py +++ b/dev-tools/validation/check-design-capability-allocation.py @@ -684,6 +684,15 @@ def adr_allocation(primary: str, classification: str, *secondary: str) -> tuple[ "design/architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md": adr_allocation( "PO-3", "Accepted", "PO-1", "PO-4", "SF-1" ), + "design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md": adr_allocation( + "GR-1", + "Proposed - Pending Human Review", + "GR-4", + "AS-1", + "SF-1", + "SF-2", + "PO-4", + ), } MICROSERVICE_STANDARD_CLASSIFICATIONS = { "README.md": "Service overview", diff --git a/services/automation-scripting-service/src/main/resources/openapi.yaml b/services/automation-scripting-service/src/main/resources/openapi.yaml index aff8e55a67..afebd50337 100644 --- a/services/automation-scripting-service/src/main/resources/openapi.yaml +++ b/services/automation-scripting-service/src/main/resources/openapi.yaml @@ -1,7 +1,10 @@ openapi: 3.0.3 info: title: Automation Scripting Service API - description: API for NPC automation and script management + description: >- + API for NPC automation and script management. Current REST routes are + unauthenticated and trust caller-supplied tenant/subject selectors; this + is an implementation security gap, not tenant-isolation proof. version: 1.0.0 license: name: PolyForm Noncommercial License 1.0.0 diff --git a/services/game-session-service/src/main/resources/openapi.yaml b/services/game-session-service/src/main/resources/openapi.yaml index b7e7840e60..b1f030b8eb 100644 --- a/services/game-session-service/src/main/resources/openapi.yaml +++ b/services/game-session-service/src/main/resources/openapi.yaml @@ -1,4 +1,4 @@ -openapi: 3.0.3 +openapi: 3.1.0 info: title: Game Session Service API description: API for managing active game sessions @@ -8,7 +8,8 @@ info: url: https://polyformproject.org/licenses/noncommercial/1.0.0 servers: - url: https://api.firemud.com -security: [] +security: + - bearerAuth: [] components: securitySchemes: bearerAuth: @@ -59,11 +60,32 @@ components: type: integer status: type: string + ResultStatus: + type: string + enum: [SUCCESS, ERROR] + ErrorDetail: + type: object + properties: + code: + type: string + message: + type: string + RefreshRolesResponse: + type: object + properties: + status: + $ref: '#/components/schemas/ResultStatus' + data: + type: string + example: refreshed + error: + $ref: '#/components/schemas/ErrorDetail' paths: /ping: get: summary: Health check endpoint operationId: ping + security: [] responses: '200': description: Pong response @@ -99,6 +121,10 @@ paths: $ref: '#/components/schemas/GameInstanceDto' '400': description: Invalid request + '401': + description: Missing or invalid Bearer JWT + '403': + description: Caller lacks a privileged role under the current predicate /sessions/{sessionId}/stop: post: summary: Stop a running session @@ -121,6 +147,10 @@ paths: $ref: '#/components/schemas/GameInstanceDto' '400': description: Invalid session ID + '401': + description: Missing or invalid Bearer JWT + '403': + description: Caller lacks a privileged role under the current predicate /sessions/{sessionId}/restart: post: summary: Restart a stopped session @@ -143,3 +173,38 @@ paths: $ref: '#/components/schemas/GameInstanceDto' '400': description: Invalid session ID + '401': + description: Missing or invalid Bearer JWT + '403': + description: Caller lacks a privileged role under the current predicate + /sessions/{sessionId}/refresh-roles: + post: + summary: Acknowledge a session role refresh request + description: >- + Current behavior requires a privileged Bearer JWT and returns an + acknowledgement (`data: refreshed`); the service currently only logs + the request and does not refresh session roles. Target behavior is an + internal_workload route requiring the exact mTLS workload identity of + the allowlisted Logging & Admin Service, with no end-user token. That + target mTLS authorization and role-refresh mutation are not implemented + yet. + operationId: refreshRoles + parameters: + - in: path + name: sessionId + required: true + schema: + type: integer + responses: + '200': + description: ApiResponse acknowledgement; current implementation is a no-op + content: + application/json: + schema: + $ref: '#/components/schemas/RefreshRolesResponse' + '400': + description: Invalid session ID + '401': + description: Missing or invalid Bearer JWT + '403': + description: Caller lacks a privileged role under the current predicate diff --git a/services/logging-admin-service/src/main/resources/openapi.yaml b/services/logging-admin-service/src/main/resources/openapi.yaml index 9cf5fac9db..301a5cc89e 100644 --- a/services/logging-admin-service/src/main/resources/openapi.yaml +++ b/services/logging-admin-service/src/main/resources/openapi.yaml @@ -1506,9 +1506,15 @@ components: paths: /ping: get: - summary: Health check endpoint + summary: Privileged HTTP health check endpoint + description: >- + Current HTTP behavior requires a privileged Bearer JWT through the + shared interceptor, whose `hasPrivilegedRole()` predicate accepts both + global and tenant-scoped privileged roles, so this is not proof of a + global-role-only boundary. The target Public/infra health + classification uses platform health policy; this route has not + converged to that exact target. operationId: ping - security: [] responses: '200': description: Pong response @@ -1516,6 +1522,10 @@ paths: application/json: schema: $ref: '#/components/schemas/ApiResponseString' + '401': + description: Missing or invalid Bearer JWT + '403': + description: Caller lacks a privileged role under the current predicate /command-registry/built-in-aliases/{alias}: get: summary: Validate one built-in command alias diff --git a/services/spring-cloud-gateway/src/main/resources/openapi.yaml b/services/spring-cloud-gateway/src/main/resources/openapi.yaml index 8132a3332e..32674961a1 100644 --- a/services/spring-cloud-gateway/src/main/resources/openapi.yaml +++ b/services/spring-cloud-gateway/src/main/resources/openapi.yaml @@ -1,15 +1,26 @@ openapi: 3.0.3 info: title: Spring Cloud Gateway API - description: API for dynamic route management + description: >- + Current REST route mutations require a Bearer JWT accepted by the gateway's + privileged-role predicate, which currently accepts global or tenant-scoped + privileged roles; global-role-only enforcement is implementation drift. + The target management contract requires exact operator authentication and + global privileged authorization on an internal dev/test-only surface. version: 1.0.0 license: name: PolyForm Noncommercial License 1.0.0 url: https://polyformproject.org/licenses/noncommercial/1.0.0 servers: - url: https://api.firemud.com -security: [] +security: + - bearerAuth: [] components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + bearerFormat: JWT schemas: GatewayRoute: type: object @@ -31,6 +42,7 @@ paths: get: summary: Health check operationId: ping + security: [] responses: '200': description: Pong response @@ -66,6 +78,10 @@ paths: $ref: '#/components/schemas/GatewayRoute' '400': description: Invalid route configuration + '401': + description: Missing or invalid Bearer JWT + '403': + description: Caller lacks a privileged role under the current predicate /routes/{routeId}: delete: summary: Remove a gateway route @@ -89,3 +105,7 @@ paths: example: removed '400': description: Invalid route ID + '401': + description: Missing or invalid Bearer JWT + '403': + description: Caller lacks a privileged role under the current predicate From e57b184c665b25614f0907deeb56896b1bca9870 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 00:26:21 +1200 Subject: [PATCH 16/68] docs(alignment): link combined 5C and 5D review --- design/project-management/design-alignment/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 9cb93ca1e3..d0bf453cb6 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -44,8 +44,8 @@ The preserved 5B implementation work has been rebuilt into #2826 Schema, the dep | 5B-Schema | SQL/Flyway/jOOQ, schema and identifier migration | Corpus discovery accepted closed; merge proof pending | [#2826](https://github.com/benhook1013/FireMUD/pull/2826) | Six fresh whole-unit cycles reached two corrected-state dry cycles after the accepted Schema fixes. Retained-row adjudication, mixed-binary deployment evidence, and Docker-backed PostgreSQL proof remain explicit limits. Dependent #2827 carries the separately reviewed Automation lifecycle/fence successor and is not additional Schema scope. | | 5B-Publication | Durable version/publication/readiness state | Corpus discovery accepted closed; merge proof pending | [#2828](https://github.com/benhook1013/FireMUD/pull/2828) | Cycles 1–4 were productive and corrected the accepted findings through V27; corrected-state Cycles 5 and 6 were dry. Whole-5B closure Cycle 2 subsequently added the V28 legacy full-version quarantine and made V26's incompatible participant-scope migration operationally stop-before-start and roll-forward-only. PostgreSQL retained-row execution, live mounted-certificate/Temporal owner calls, version-scoped Automation content, exact Game Design template/asset mapping, readiness notification, and dedicated ability-schema attestation remain open. | | 5B-Retention | Retention classes, cleanup, horizons, contraction | Corpus discovery accepted closed; merge proof pending | [#2829](https://github.com/benhook1013/FireMUD/pull/2829) | Cycle 1 fixed incomplete handoff-child cleanup; corrected-state Cycles 2 and 3 were dry. Whole-5B closure Cycle 2 then classified `plugin_runtime_request_history` as retry/idempotency receipt evidence and `plugin_runtime_events` as recovery/reconciliation plus lifecycle-audit evidence. Both remain ineligible for automatic deletion until measured horizons, holds, safe watermarks, bounded sweeps, and metrics exist. Recovery-aware dead-letter cleanup, cross-owner inequalities, and Docker-backed PostgreSQL proof remain open. | -| 5C | Redis roles and cache/rate-limit semantics | Active in combined 5C/5D successor | Pending publication | The successor consumes the preserved #2661 Redis role, authority, reset, recovery, keyspace, and operational content on exact final #2829. Fresh whole-unit corrected-state review follows baseline publication. | -| 5D | Idempotency, outbox, replay, saga, and workflow patterns | Active in combined 5C/5D successor | Pending publication | The same successor consumes #2661's replay, effect identity, scheduler, tick, saga, workflow, and recovery content. Pending ADR 0183 is preserved without acceptance or proposal-dependent implementation. | +| 5C | Redis roles and cache/rate-limit semantics | Active in combined 5C/5D successor | [#2839](https://github.com/benhook1013/FireMUD/pull/2839) | The successor consumes the preserved #2661 Redis role, authority, reset, recovery, keyspace, and operational content on exact final #2829. Fresh whole-unit corrected-state review follows baseline publication. | +| 5D | Idempotency, outbox, replay, saga, and workflow patterns | Active in combined 5C/5D successor | [#2839](https://github.com/benhook1013/FireMUD/pull/2839) | The same successor consumes #2661's replay, effect identity, scheduler, tick, saga, workflow, and recovery content. Pending ADR 0183 is preserved without acceptance or proposal-dependent implementation. | | 6A | Gateway routes, traffic planes, sharding, and close taxonomy | Queued | — | — | | 6B | WebSocket, Telnet, protocol bridge, and session transport | Queued | — | — | | 6C | Logging & Admin/operator ingress and action authorization | Queued | — | — | From c0c494bbba61b8a68db9c315457c03683696b415 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 00:45:46 +1200 Subject: [PATCH 17/68] docs(redis): correct current automation queue behavior --- .../automation-scripting-service/runtime-and-data.md | 6 +++--- .../microservices/entity-management-service/operations.md | 2 +- .../system-architecture-redis-cache-reference.md | 4 ++-- design/architecture/system-architecture-redis-cheatsheet.md | 2 +- .../system-architecture-redis-incident-runbook.md | 4 ++-- design/architecture/system-architecture-redis-operations.md | 2 +- .../system-architecture-redis-reset-and-recovery.md | 2 +- design/architecture/system-architecture-redis.md | 2 +- .../automation-and-scheduler-runtime.md | 2 +- 9 files changed, 13 insertions(+), 13 deletions(-) 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 7a2e02d413..943094b640 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -31,11 +31,11 @@ The live `script_event_audit` and `script_work_items` schema uniqueness constrai The command-plan preview boundary in [ADR 0114](../../decisions/adr-0114-command-plan-preview-dry-run-isolation.md) is non-committing: a preview must not persist live evaluated script work items, populate the live automation queue, hand off commands, or perform external side effects. It may persist isolated audit/result evidence containing the exact input identity, fenced snapshot/fixture reference, and ordered plan. The current materialized dry-run path may use the internal pre-DSL trigger-record/queue shape and persists that current pre-DSL trigger record, but its live implementation records `finalStage=DSL_EVAL`, `finalOutcome=dry_run_completed`, and `finalReason=dry_run_no_handoff`; the shared terminal-success helper marks its internal `script_work_items.status=HANDED_OFF` even though no Game Session handoff or gameplay-work acceptance occurs. It has not converged on target `DRY_RUN_RESULT` terminology; that internal marker is not target live-work persistence or downstream-handoff evidence, and complete plan-result/input proof is still absent. This is an implementation handoff, not a competing contract. -Redis adoption has separate current gaps: the live `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` builders are named in the cache catalog but are not yet all represented in the central reset/ACL ownership inventory, and readiness plus dry-run capacity reservation invokes the shared two-key counter/lease script with untagged keys. The live `automation:queue:{tenantInstanceTag}:*` projection also appends to lists without a pointer TTL or maximum-length bound, so it is not yet proven TTL-only; its current `AutomationRedisKeys` builder accepts raw nonblank IDs and does not prove canonical opaque tuple encoding, delimiter/brace rejection, or collision safety. The latter issues are not same-slot-safe identity proof for Redis Cluster, while the capacity families are unsupported for atomic multi-key use until central ownership registration is complete and the keys use one canonical scope hash tag/Redis Cluster slot, or the reservation is replaced with a single-key design. These are current implementation/proof gaps, not new authority. In the target state, PostgreSQL owns durable automation work, definitions, and persisted charge/admission truth, but the current implementation has no durable charge/admission markers or charge record: `ScriptQuotaServiceImpl`, `ScriptTenantBudgetServiceImpl`, and the readiness/dry-run capacity services make best-effort Redis counter/lease decisions. Current quota, tenant-budget, readiness, capacity, and queue-pointer decisions are therefore Redis best-effort and reset-sensitive; their loss may relax or tighten admission fairness or delay discovery, but cannot change the durable work and definition rows that currently exist. Before claiming the target boundary, register each family with its owner/class/reset behavior, define and enforce the queue retention policy, and either use one canonical encoded tuple builder for every key or prove canonical UUID parsing at every boundary, then add focused retention, collision/brace, same-scope slot, cluster, reset, and durable charge/admission proof. +Redis adoption has separate current gaps: the live `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` builders are named in the cache catalog but are not yet all represented in the central reset/ACL ownership inventory. Readiness and dry-run capacity reservations invoke the shared two-key counter/lease script with one documented hash tag shared by each pair, so the current pairs are not inherently cross-slot; central ownership registration, canonical key encoding, durable charge/admission, reset, retention, and idempotent lease-accounting proof remain incomplete. The live `automation:queue:{tenantInstanceTag}:*` projection also appends to lists without a pointer TTL or maximum-length bound, so it is not yet proven TTL-only; its current `AutomationRedisKeys` builder accepts raw nonblank IDs and does not prove canonical opaque tuple encoding, delimiter/brace rejection, or collision safety. These are current implementation/proof gaps, not new authority. In the target state, PostgreSQL owns durable automation work, definitions, and persisted charge/admission truth, but the current implementation has no durable charge/admission markers or charge record: `ScriptQuotaServiceImpl`, `ScriptTenantBudgetServiceImpl`, and the readiness/dry-run capacity services make best-effort Redis counter/lease decisions. Current quota, tenant-budget, readiness, capacity, and queue-pointer decisions are therefore Redis best-effort and reset-sensitive; their loss may relax or tighten admission fairness or delay discovery, but cannot change the durable work and definition rows that currently exist. Before claiming the target boundary, register each family with its owner/class/reset behavior, define and enforce the queue retention policy, and either use one canonical encoded tuple builder for every key or prove canonical UUID parsing at every boundary, then add focused retention, collision/brace, same-scope slot, cluster, reset, and durable charge/admission proof. The current dry-run and readiness capacity reservations also are not idempotent by work item: each retry generates a new lease token, increments the same counter, and overwrites the prior `(tenantId, workItemId)` lease. Releasing the earlier reservation then fails its token check and leaves one count occupied until expiry. The counters remain heuristic and reset-tolerant, but lease accounting must not leak on repeated reservation attempts; duplicate/retry and release-order proof is absent. -The current queue consumer has an additional bounded-drain limitation that must remain explicit: `drainWorkItems` and `drainIndexedWorkItemPointers` perform a non-atomic range/read followed by deletion, and the indexed path uses database-wide `KEYS("automation:queue:*")`; it can delete a whole list, including concurrently appended or unreturned pointers, before stopping at `maxPointers`. Durable claim fallback and the scheduled rebuild can recover eligible PostgreSQL rows, so this is projection delay/duplicate risk rather than durable-work authority, but the current path is not a cluster-safe discovery or retention proof. Target enqueue/rebuild must atomically apply `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY`, preserve or durably account for unreturned tails and concurrent appends, use an owner-maintained/cursor-based cluster-safe queue index rather than database-wide `KEYS`, and trigger bounded durable re-drive with exact identity/readback before reset-gate release. The two settings remain environment/service configuration (currently `TBD`); no target support claim is valid until each environment supplies validated positive bounds and focused concurrent-drain, truncation/expiry, cluster, and re-drive proof. +The current queue consumer has an additional bounded-drain limitation that must remain explicit: `drainWorkItems` and `drainIndexedWorkItemPointers` consume pointers with atomic Redis `LPOP`, so a producer's concurrent `RPUSH` is not discarded by a range/read followed by deletion. The indexed path still uses database-wide `KEYS("automation:queue:*")`, and the current lists have no pointer TTL or maximum-length bound, so the path is not a cluster-safe discovery or retention proof. Durable claim fallback can process pending PostgreSQL rows independently, but it does not establish a reset/rebuild recovery gate. Target enqueue/rebuild must atomically apply `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY`, preserve or durably account for unreturned tails and concurrent appends, use an owner-maintained/cursor-based cluster-safe queue index rather than database-wide `KEYS`, and trigger bounded durable re-drive with exact identity/readback before reset-gate release. The two settings remain environment/service configuration (currently `TBD`); no target support claim is valid until each environment supplies validated positive bounds and focused concurrent-drain, truncation/expiry, cluster, and re-drive proof. ## Architecture and Design Notes @@ -143,7 +143,7 @@ To avoid “DSL evaluated successfully but effects were silently dropped”, the - **Target state:** Admitted triggers seal the handler input manifest and produce `PENDING_EVALUATION` pre-DSL trigger records written to a PostgreSQL-backed outbox table keyed by the canonical Trigger Identity plus sequencing fields as needed. `playableStateNamespaceId` is the playable-state uniqueness dimension; `playableStateScope` is separately persisted and exact-validated policy/routing/authorization/migration-fence evidence and is excluded from Trigger Identity, schedule, and Command-Handoff uniqueness. Where the current repository/schema includes scope in uniqueness, that is current implementation drift and not target identity authority. - Target materialized `script_schedule_instances`, resume windows, due candidates, firing claims/audits, timer-generated pre-DSL trigger records, evaluated script work items, handoff events, and dead-letter rows preserve the same stable `playableStateNamespaceId` and gameplay `playableStateScope` evidence so scheduler-driven follow-up work stays in the same shared-versus-isolated state namespace as the original admitted event. The namespace participates in canonical schedule, Trigger, and Command-Handoff identities; `playableStateScope` evidence remains separate from those identities. Missing or mismatched evidence fails closed rather than being inferred or refreshed. Current schedule rows still lack `playableStateNamespaceId`, as recorded in the implementation-status boundary above. - `automation:queue:*` keys are derived coordination indexes that accelerate draining and batching, not the authoritative record of pending work. -- On restart, failover, or Cache/Rate-Limit Redis resets, the target service rebuilds `automation:queue:*` indexes from durable pending items. The current `rebuildPendingWorkItemIndex` also selects `EVALUATING` rows without a stale, owner, or compare-and-set gate, so queue reset/rebuild and resume are unavailable and must fail closed; a non-atomic status preflight cannot authorize the target PENDING-only path. The current scheduled implementation also uses `PageRequest.of(0, maxItems)` for each rebuild batch, so later eligible rows with missing pointers can be starved when earlier rows already have pointers; this bounded page-0 scan is not a completeness or readback proof. The durable claim fallback remains able to process pending PostgreSQL rows independently. Target reset/rebuild state requires a cursor- or owner-maintained index with an atomic status/owner/CAS gate that proves complete eligible-row coverage before the external maintenance gate is released. This implementation/proof gap is recorded in the [scripting runtime rebuild contract](../../system-architecture-scripting-runtime-execution.md#rebuild-and-deduplication-rules). +- On restart, failover, or Cache/Rate-Limit Redis resets, the target service rebuilds `automation:queue:*` indexes from durable pending items. The current `rebuildPendingWorkItemIndex` selects only `PENDING_EVALUATION` rows, but has no owner or compare-and-set gate, so queue reset/rebuild and resume are unavailable and must fail closed; a non-atomic status preflight cannot authorize the target PENDING-only path or establish a safe disposition for `EVALUATING` rows. The current scheduled implementation also uses `PageRequest.of(0, maxItems)` for each rebuild batch, so later eligible rows with missing pointers can be starved when earlier rows already have pointers; this bounded page-0 scan is not a completeness or readback proof. The durable claim fallback remains able to process pending PostgreSQL rows independently. Target reset/rebuild state requires a cursor- or owner-maintained index with an atomic status/owner/CAS gate that proves complete eligible-row coverage before the external maintenance gate is released. This implementation/proof gap is recorded in the [scripting runtime rebuild contract](../../system-architecture-scripting-runtime-execution.md#rebuild-and-deduplication-rules). This enables stage-aware outcomes in `script_event_audit`: the system can distinguish “DSL evaluation succeeded” from “handoff or enqueue succeeded”, and can re-drive delivery where appropriate without re-executing the DSL body for the same trigger. diff --git a/design/architecture/microservices/entity-management-service/operations.md b/design/architecture/microservices/entity-management-service/operations.md index 720f62a073..a073272903 100644 --- a/design/architecture/microservices/entity-management-service/operations.md +++ b/design/architecture/microservices/entity-management-service/operations.md @@ -58,7 +58,7 @@ Examples: - **Trade between two entities** – when a tick performs a trade between `fromEntityId` and `toEntityId`: - **Target state:** the complete Command-Handoff Identity identifies an admitted automation command and is an input to allocating or looking up that command's stable root `EffectId`; it does not replace the effect identity or participant guards. `(automationDispatchId, commandOrdinal)` is only that command identity's dispatch-group suffix and must be interpreted with the complete source/target scope; a non-automation command instead uses its admitted `commandId`. `scriptEventId`, participant/item fields, and mutable payload text are never fallback identities. Every retry and owner commit preserves the resulting root identity, typed operation/target projections, and immutable request digest. The live Game Session handoff does not yet carry the full automation command identity end to end, so the current path uses the admitted `commandId` and available persisted work-item/dispatch fields; it must reject a missing command identity rather than synthesize one from the participants. This target gap is tracked under `AS-1.5` in the [automation and scheduler runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status); - - **Illustrative proposal only (not an accepted canonical encoding):** before encoding, the handler would validate every identity-bearing and typed field against its declared type and domain; it would not encode malformed input, fallback identities, or alternate textual spellings. Quantity would be parsed as its declared numeric type and rendered as canonical base-10 decimal, so semantically equal values such as `1` and `01` produce identical bytes. The exact scalar/encoding contract remains pending human review in ADR 0182; + - **Illustrative proposal only (not an accepted canonical encoding):** before encoding, the handler would validate every identity-bearing and typed field against its declared type and domain; it would not encode malformed input, fallback identities, or alternate textual spellings. Quantity would be parsed as its declared numeric type and rendered as canonical base-10 decimal, so semantically equal values such as `1` and `01` produce identical bytes. The exact scalar/encoding contract remains pending human review in [ADR 0183](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); - **Illustrative proposal only (not an accepted canonical encoding):** the handler would serialize the admitted identity, the stable per-effect trade discriminator, and the validated canonical fields in a fixed versioned order using canonical UTF-8 length-prefixed fields, for example `trade:v1|:|:|:|:|:|:`. If later accepted, the exact resulting bytes would be the retry identity and would be reused unchanged, while sibling effects from one command and separate admitted trades would remain distinct; the pending ADR 0183 proposal is not an implementation or target-state requirement; - no canonical one-trade-per-`(fromEntityId,toEntityId,itemId)`-per-tick invariant exists, so the participant/item tuple alone cannot be the effect key; - it inserts one complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, effectId, rootEffectId, typedOperation, targetAggregateType=INVENTORY, targetAggregateId)` `tick_effect_guard` storage projection, linked to the mutation's persisted root-or-child `EffectId` and its enclosing root lineage, for each affected inventory aggregate before moving items between inventories. The S1/S2 participant-guard uniqueness tuple is `(tenantId, playableStateNamespaceId, effectId, typedOperation, targetAggregateType, targetAggregateId)`; `playableStateNamespaceId` is its canonical partition/key component, while `playableStateScope` is separately persisted immutable and exact-validated policy/routing/authorization/migration-fence evidence. `gameInstanceId`, `regionId`, `regionEpoch`, `tickId`, `effectKey`, and `rootEffectId` are active-runtime, descriptor, timeline, or lineage evidence, not uniqueness dimensions; and diff --git a/design/architecture/system-architecture-redis-cache-reference.md b/design/architecture/system-architecture-redis-cache-reference.md index f291d318c6..93966cc6f1 100644 --- a/design/architecture/system-architecture-redis-cache-reference.md +++ b/design/architecture/system-architecture-redis-cache-reference.md @@ -6,7 +6,7 @@ This companion document holds the reference-heavy material for Redis cache and r The `room:*` Class A cache contract below is target-state only. It is not a current correctness path until World Management has an opaque room component version and a proven invalidation path. Namespace-backed `inventory:*` and explicitly instance-scoped `inventory:room-ground:*` cache adoption is likewise target-state; current readers remain authoritative until Entity Management's owner-version/event validation is proven. Current readers must not substitute `worldSnapshotId` or `roomDynamicVersion` for that component version; they must use authoritative reads when the target validation contract is unavailable. A cache-embedded version, TTL, or invalidation event alone is not currentness proof. The current Game Session `ratelimit:` key is likewise a legacy implementation: `SessionRateLimiterImpl` writes it through the generic Game Session Redis client with a one-second window/TTL, while its Cache/Rate-Limit endpoint and ACL binding remain unproved. It must be registered as current legacy state, its writer stopped, and its maximum one-second TTL allowed to elapse with an empty-key readback before unversioned target rate-limit helpers consume the shared family; an adopter that cannot prove that drain must use a distinct versioned prefix. The current Game Session `lookcache::` writer is also legacy implementation drift: it is disposable and non-authoritative, but its incomplete scope and ten-minute TTL cannot satisfy target causal room-read semantics. Current composition remains authoritative/uncached until the target `view:room-look:*` contract is proven. The future reader, invalidation, and version-advance rules below remain normative. -The current Automation implementation also emits `automation:test:quota:*` and `automation:readiness:capacity:*` families. They are named in the catalog below as Cache/Rate-Limit, Class B, reset-tolerant projections, but the listed untagged shapes describe current/legacy implementation rather than a canonical cluster-safe target. Readiness and dry-run capacity counter/lease reservations currently pass two untagged keys to one Lua invocation, so a Redis Cluster deployment can reject them with `CROSSSLOT`. No canonical target family is registered until the owner chooses and proves either one shared hash-tag shape per atomic key set or a single-key reservation; this catalog does not invent that unresolved target. The current Game Session `IpConnectionLimiter` has the same current limitation: registration passes `ipconn:
` and `sessionip:` to one Lua invocation without a shared hash slot, so Redis Cluster returns `CROSSSLOT`; this is in addition to the raw-address/privacy drift. The target must follow ADR 0087's one-mutation/one-opaque-subject-bucket boundary, with session lifecycle correlation kept outside any exact cross-key atomicity requirement; no final reverse-index shape is assumed here. Destructive resets additionally require the external, generation-bound [Cache deployment maintenance gate](./system-architecture-redis-operations.md#external-cache-deployment-maintenance-gate), not a fence key stored in the cache being reset. +The current Automation implementation also emits `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` families. They are named in the catalog below as Cache/Rate-Limit, Class B, reset-tolerant projections. Current readiness and dry-run capacity counter/lease reservations pass two keys with one shared tenant or fixed-family hash tag to each Lua invocation, so each pair occupies one Redis Cluster slot and is not inherently `CROSSSLOT`. Central ownership registration, canonical key encoding, durable charge/admission, reset, retention, and idempotent lease-accounting proof remain incomplete; the same-slot shape alone does not establish a supported clustered workload. The current Game Session `IpConnectionLimiter` has a distinct live limitation: registration passes `ipconn:
` and `sessionip:` to one Lua invocation without a shared hash slot, so Redis Cluster returns `CROSSSLOT`; this is in addition to the raw-address/privacy drift. The target must follow ADR 0087's one-mutation/one-opaque-subject-bucket boundary, with session lifecycle correlation kept outside any exact cross-key atomicity requirement; no final reverse-index shape is assumed here. Destructive resets additionally require the external, generation-bound [Cache deployment maintenance gate](./system-architecture-redis-operations.md#external-cache-deployment-maintenance-gate), not a fence key stored in the cache being reset. ## Cache Adoption Checklist @@ -80,7 +80,7 @@ Cache/Rate-Limit Redis hosts prefixes that are not part of the coordination log | `screenbuffer:::` | Cache | TTL-only (Class B) | Reset-tolerant | Current Game Session disposable hot-cache prefix for durable semantic reconnect context; PostgreSQL `resume_transcript_entry` rows remain authoritative. This prefix is distinct from `view:room-look:*` and never serves as semantic authority. Current keying is `gameInstanceId`-based; target reconnect scope is `{tenantId, playableStateNamespaceId, characterId}` under ADR 0134, so namespace-key migration and complete reconnect-envelope/generation proof remain implementation gaps. The row records prefix semantics, not current endpoint/role wiring. | | `chat:say::`, `chat:whisper:::`, `chat:tell::`, `chat:guild::`, `chat:city::`, `chat:account::` | Cache | TTL-only (Class B) | Reset-tolerant | Social & Groups short-lived chat projections; current `SAY` is sender-account scoped. Any future gameplay-SAY projection must publish its exact recipient/view scope and original-view contract rather than infer it from a bare character ID. See the [canonical `chat:whisper` Class-B contract](#canonical-social--groups-chatwhisper-class-b-contract). | | `chat:whisper::` | Cache | TTL-only (Class B) | Reset-tolerant | Legacy `ChatService` account-keyed whisper implementation-drift prefix (`chat:whisper:%d:%d`); it does not provide the target playable-state/character scope and remains a reset-tolerant disposable projection during migration. | -| `automation:queue:{tenantInstanceTag}:*` | Cache / Rate-Limit | TTL-only (target Class B; current reset/rebuild unavailable) | **Current queue reset/recovery is unavailable and must fail closed**; the implementation's rebuild query includes `EVALUATING` rows without stale-owner/CAS reconciliation, so this projection must not be flushed, rebuilt, or resumed as a supported current operation. Once the owner-reconciled target path is implemented and proven, it may be reset and rebuilt from durable work. | Automation & Scripting derived work-item pointers; PostgreSQL remains authoritative. See the [Automation & Scripting runtime/data owner contract](./microservices/automation-scripting-service/runtime-and-data.md#redis-roles-and-prefixes) and [API implementation status](./microservices/automation-scripting-service/api-contracts.md#implementation-status). The current queue implementation has no per-list TTL/trim or declared key-count/payload-size envelope; those are adoption/proof gaps, not implied bounds. | +| `automation:queue:{tenantInstanceTag}:*` | Cache / Rate-Limit | TTL-only (target Class B; current reset/rebuild unavailable) | **Current queue reset/recovery is unavailable and must fail closed**; the implementation's rebuild query selects only `PENDING_EVALUATION`, but it lacks owner/CAS reconciliation and cannot establish a safe disposition for existing `EVALUATING` rows, so this projection must not be flushed, rebuilt, or resumed as a supported current operation. Once the owner-reconciled target path is implemented and proven, it may be reset and rebuilt from durable work. | Automation & Scripting derived work-item pointers; PostgreSQL remains authoritative. See the [Automation & Scripting runtime/data owner contract](./microservices/automation-scripting-service/runtime-and-data.md#redis-roles-and-prefixes) and [API implementation status](./microservices/automation-scripting-service/api-contracts.md#implementation-status). The current queue implementation has no per-list TTL/trim or declared key-count/payload-size envelope; those are adoption/proof gaps, not implied bounds. | | `automation:quota::*`, `automation:tenant-budget::tier:`, `automation:test:quota::script::tenant`, `automation:test:quota::script::principal:`, `automation:test:capacity:{}:*`, `automation:test:capacity:{automation-test-capacity}:cluster*`, `automation:readiness:capacity:{}:*`, `automation:readiness:capacity:{automation-readiness-capacity}:cluster*` | Cache / Rate-Limit | TTL-only (Class B) | Reset-tolerant | Automation & Scripting per-script quota and tenant-budget counters, one-minute dry-run/test tenant/principal quota counters, exact tenantless cluster capacity counters paired with tenant/work-scoped leases, and bounded tenant/cluster `PUBLISH_READINESS` capacity reservations. Capacity counter/lease pairs share the documented hash tag (`{}` for tenant-scoped pairs and fixed family tags for cluster pairs) so their Lua operations remain in one Redis Cluster slot. The owner settings and capacity bounds are defined in the [Automation service configuration](./microservices/automation-scripting-service/configuration.md#service-specific-variables); the implementation uses one-minute counter windows and ten-minute capacity-lease TTLs. The counters/leases are disposable Cache/Rate-Limit projections, not Coordination Redis state, and are not rebuilt from Redis after reset. The catalog currently has no per-prefix key-count or serialized-payload envelope for these families; do not infer one from the concurrency limits until the owner declares and proves it. Durable trigger/work-item/readiness state and execution correctness remain in PostgreSQL and the owning service. | | `ratelimit:::` | Cache / Rate-Limit | TTL-only (Class B) | Reset-tolerant | Spring Cloud Gateway and other edge/credential rate-limit buckets. Each individual subject has one opaque stable hash; no modulo collision pool or request-derived shard is used. Reset-induced heuristic shifts are acceptable, while hard authority remains outside evictable Redis. | | `ratelimit:` | Cache / Rate-Limit (current legacy; generic-client role unproved) | Legacy heuristic (not target Class B authority) | Reset-tolerant heuristic loss | Game Session's live `SessionRateLimiterImpl` command limiter. The current generic client may land on the wrong Redis role; the one-second counter/TTL is disposable and loss may relax or tighten heuristic limits. Cache-only writer registration and ACL proof do not make the legacy arity compatible with target helpers. Before any unversioned target `ratelimit:*` helper is enabled, stop the legacy writer, allow the maximum one-second TTL to elapse, and prove empty-key readback; an adopter that cannot prove that drain must use a distinct versioned prefix. | diff --git a/design/architecture/system-architecture-redis-cheatsheet.md b/design/architecture/system-architecture-redis-cheatsheet.md index a8e437a72d..ca325727e6 100644 --- a/design/architecture/system-architecture-redis-cheatsheet.md +++ b/design/architecture/system-architecture-redis-cheatsheet.md @@ -56,7 +56,7 @@ This table highlights representative prefixes and their intended Redis role. It | `automation:timer:{tenantRegionTag}`, `script-scheduler:{tenantRegionTag}:lastTickId` | **Coordination Redis (target-only, once implemented)** | Automation & Scripting Service | Reserved target-only timer/checkpoint projections; they are not current runtime keys and have no current reset operation. Once implemented, they are reset-tolerant derived hints rebuilt from durable PostgreSQL schedules, trigger-instance rows, and heartbeat progress; they are never the source of truth for automation work. | | `tick-events:{tenantRegionTag}` and `tick-events-offset:{tenantRegionTag}:` | **Coordination Redis** | Game Session Service / Automation & Scripting | Best-effort tick event stream and per-consumer offsets used only as observer/wakeup hints. `tenantRegionTag` is the opaque encoding of the complete `` scope and must include `gameInstanceId`; no tenant-plus-region alias is valid. The key's `tenantRegionTag` and `` are authoritative for the event-offset scope; each offset payload stores `{tenantId, gameInstanceId, regionId, consumerId, region_epoch, latestTickId, streamOffset}` and is not a standalone scope identifier. It is discarded before reuse when `region_epoch` differs from the control-plane epoch. Stream retention is capped (default `tick_events_maxlen = 2048` per region). Correctness derives from committed heartbeats/RegionStatus plus durable schedules; missing/duplicated events must not change which schedules eventually fire. | | `conflict:entity::` and `conflict:session::` | **Coordination Redis** | `common-data-runtime` helper used by Entity Management and Game Session | Reset-tolerant, non-authoritative hotspot diagnostics. Current generic-client placement and separate `INCR`/`EXPIRE` warning-only path are implementation drift; target role, finite cardinality, 300-second inactivity TTL, ACL, and atomic-helper convergence are defined in [Redis Architecture](./system-architecture-redis.md#coordination-vs-cache-prefixes). | -| `automation:queue:{tenantInstanceTag}:*` | **Cache/Rate-Limit Redis** (single-key ops) | Automation & Scripting Service | Non-authoritative, best-effort queue pointers. The target rebuild permits `PENDING_EVALUATION` and only an owner-reconciled/reclaimed safe non-stale `EVALUATING` row; stale or unresolved rows remain excluded. The current `rebuildPendingWorkItemIndex` unconditionally selects both statuses and has no stale, owner, or compare-and-set gate, so queue-prefix reset/rebuild and resume are unavailable and must fail closed; a non-atomic status preflight cannot authorize a safe PENDING-only path. Do not migrate or recover work from Redis payloads, or mix this single-key family with coordination prefixes in one Lua call. The adjacent timer/checkpoint projections remain target-only and unavailable. See [Redis Operations](./system-architecture-redis-operations.md#cache-rate-limit-redis-reset), [Redis incident handling](./system-architecture-redis-incident-runbook.md#automation-queue-schema-mistakes), and [Scripting Runtime Execution](./system-architecture-scripting-runtime-execution.md#redis-queue-index-and-durable-work-boundary). | +| `automation:queue:{tenantInstanceTag}:*` | **Cache/Rate-Limit Redis** (single-key ops) | Automation & Scripting Service | Non-authoritative, best-effort queue pointers. The target rebuild permits `PENDING_EVALUATION` and only an owner-reconciled/reclaimed safe non-stale `EVALUATING` row; stale or unresolved rows remain excluded. The current `rebuildPendingWorkItemIndex` selects only `PENDING_EVALUATION` rows, but has no owner or compare-and-set gate, so queue-prefix reset/rebuild and resume are unavailable and must fail closed; a non-atomic status preflight cannot authorize a safe PENDING-only path or establish a safe disposition for existing `EVALUATING` rows. Do not migrate or recover work from Redis payloads, or mix this single-key family with coordination prefixes in one Lua call. The adjacent timer/checkpoint projections remain target-only and unavailable. See [Redis Operations](./system-architecture-redis-operations.md#cache-rate-limit-redis-reset), [Redis incident handling](./system-architecture-redis-incident-runbook.md#automation-queue-schema-mistakes), and [Scripting Runtime Execution](./system-architecture-scripting-runtime-execution.md#redis-queue-index-and-durable-work-boundary). | | `automation:quota::` | **Cache/Rate-Limit Redis** | Automation & Scripting Service | Best-effort per-script quota counters. Safe to drop; budgets are re-established from configuration and durable state. | | `automation:tenant-budget::tier:` | **Cache/Rate-Limit Redis** | Automation & Scripting Service | Best-effort per-tenant live execution budget counters. Safe to drop; counters are re-established from configuration and durable work state. | | `automation:test:capacity:{}:tenant` and `automation:test:capacity:{}:lease:`; `automation:test:capacity:{automation-test-capacity}:cluster` and `automation:test:capacity:{automation-test-capacity}:cluster:lease::` | **Cache/Rate-Limit Redis** | Automation & Scripting Service | Best-effort dry-run/test capacity: the first pair is the tenant-scoped counter/lease and the second pair is the fixed-tag cluster counter plus tenant/work-scoped lease. Same-slot tenant keys use the canonical `{}` tag; cluster keys use the fixed `{automation-test-capacity}` tag. Safe to drop; lease/counter expiry or Redis state loss may temporarily over- or under-admit test work, so this is a best-effort fairness control rather than a hard correctness cap; separate live capacity remains protected. See the [canonical quota lifecycle](./system-architecture-scripting-quotas-and-operations.md#budget-accounting-rules). | diff --git a/design/architecture/system-architecture-redis-incident-runbook.md b/design/architecture/system-architecture-redis-incident-runbook.md index f5e1f82f72..73ac1566ae 100644 --- a/design/architecture/system-architecture-redis-incident-runbook.md +++ b/design/architecture/system-architecture-redis-incident-runbook.md @@ -183,11 +183,11 @@ Before entering this measured-SLO detect/decide path, verify that the affected d - Automation consumers log deserialization errors or unknown `schemaVersion` values for `automation:queue:{tenantInstanceTag}:*` keys. - Metrics show sustained failures processing automation work items. 2. **Decide** - - Treat the queue as a non-authoritative Cache/Rate-Limit projection. The admissible row states and owner-fenced stale-lease/release CAS are owned by the [Redis Operations queue rebuild/index contract](./system-architecture-redis-operations.md#cacherate-limit-redis-reset); this incident runbook records the local consequence. A target `EVALUATING` row may be reindexed only after the owner proves its lease is stale or explicitly releases it through one fenced CAS covering status, lease owner, freshness, and fence transition; non-stale, unresolved, or ambiguous rows remain excluded. Current `rebuildPendingWorkItemIndex` unconditionally selects both statuses and has no stale, owner, or compare-and-set gate, so the current queue-prefix flush/rebuild and resume path is unavailable and must fail closed; no live scheduled rebuild invokes it, and an explicit invocation is not authorized by an admission pause. Durable PostgreSQL `script_work_items` remain authoritative, and Redis contents are not migrated. This implementation/proof gap is owned by Automation's scripting recovery contract. + - Treat the queue as a non-authoritative Cache/Rate-Limit projection. The admissible row states and owner-fenced stale-lease/release CAS are owned by the [Redis Operations queue rebuild/index contract](./system-architecture-redis-operations.md#cacherate-limit-redis-reset); this incident runbook records the local consequence. A target `EVALUATING` row may be reindexed only after the owner proves its lease is stale or explicitly releases it through one fenced CAS covering status, lease owner, freshness, and fence transition; non-stale, unresolved, or ambiguous rows remain excluded. Current `rebuildPendingWorkItemIndex` selects only `PENDING_EVALUATION` rows, but has no owner or compare-and-set gate, so the current queue-prefix flush/rebuild and resume path is unavailable and must fail closed; no live scheduled rebuild invokes it, and an explicit invocation is not authorized by an admission pause. Durable PostgreSQL `script_work_items` remain authoritative, and Redis contents are not migrated. This implementation/proof gap is owned by Automation's scripting recovery contract. - Do not treat the reserved `automation:timer:{tenantRegionTag}` or `script-scheduler:{tenantRegionTag}:lastTickId` timer/checkpoint projections as available reset targets; they remain target-only and unavailable. 3. **Act** 1. Enumerate the affected `` scopes from the complete durable PostgreSQL/runtime scope inventory. Use Redis queue evidence only to supplement and locate symptoms, never to define inventory completeness, because lost queue pointers can omit affected instances. If the complete durable inventory is unavailable, keep the deployment and affected scopes fenced and escalate rather than applying a partial enumeration. In production recovery, pause Automation admission before applying Game Session containment; apply `SetAutomationAdmissionMode` with `mode=PAUSED_FOR_ROLLBACK` and a unique `controlPlaneRequestId` to each exact scope, then apply the shipped Game Session `PauseTicksForScope` control to the containing `{tenantId, gameInstanceId}` instance (it is instance-wide, so omit `regionId`) and verify a successful response plus `GetRuntimeOwnershipStatus` showing `paused=true` for that instance before proceeding. A tenant-wide or global pause is not a current Automation mutation; it must be represented by this complete per-instance enumeration. - 2. Do not flush or rebuild the affected `automation:queue:{tenantInstanceTag}:*` prefix as a current recovery workflow. The live combined-status query has no atomic PENDING-only/owner-fenced stale-lease-or-release CAS gate and cannot establish a safe `EVALUATING` disposition; therefore the current queue flush/rebuild path is unavailable. The callable `rebuildPendingWorkItemIndex` remains unsafe and has no owner/CAS gate; no live scheduled rebuild invokes it, but an explicit invocation is not authorized by an admission pause. Redis queue payloads are not recovery authority. + 2. Do not flush or rebuild the affected `automation:queue:{tenantInstanceTag}:*` prefix as a current recovery workflow. The current rebuild query is PENDING-only, but has no atomic owner-fenced CAS gate and cannot establish a safe disposition for existing `EVALUATING` rows; therefore the current queue flush/rebuild path is unavailable. The callable `rebuildPendingWorkItemIndex` remains unsafe without an owner/CAS gate; no live scheduled rebuild invokes it, but an explicit invocation is not authorized by an admission pause. Redis queue payloads are not recovery authority. 3. For the current fallback, stop or scale the Automation deployment so all executor processes cease. A process-level readiness state may be used only when an external deployment control can verify that it makes the whole process non-accepting; readiness is not a per-scope mutation. Verify that every executor claim and unsafe rebuild invocation has ceased, record the deployment-wide availability impact, and keep the exact scopes fenced. If no such deployment/process control exists, leave the service fenced and escalate through the Automation recovery owner; do not invent a queue-specific stop gate. 4. After process cessation is verified, read back the admission state and drain status for each exact scope and `admissionEpoch`. Require the matching `PAUSED_FOR_ROLLBACK` mode, a fresh observation, `activeExecutionCount=0`, `pendingCancelableWorkItemCount=0`, and a durable owner/deployment acknowledgement bound to the scope, admission epoch, and control-plane request proving that executors have ceased and no unsafe rebuild invocation remains. Zero counts observed before process cessation are diagnostic only; a pause request or read-only drain count alone is not drain proof. The current-live drain surface does not expose exact `scriptPinEpoch`; target-state recovery additionally requires exact script-pin-epoch equality and a pin-epoch-bound acknowledgement, but that equality is not a current-live prerequisite. 5. Do not resume current automation processing after this queue incident. A safe PENDING-only rebuild, owner-reconciled `EVALUATING` recovery, and the associated queue-specific stop/resume gate are target-state capabilities only; they may be used only after implementation and end-to-end proof. Monitor the paused scopes until the target recovery surface or an owner-approved replacement is available. diff --git a/design/architecture/system-architecture-redis-operations.md b/design/architecture/system-architecture-redis-operations.md index a77e19e738..c8ade22025 100644 --- a/design/architecture/system-architecture-redis-operations.md +++ b/design/architecture/system-architecture-redis-operations.md @@ -188,7 +188,7 @@ Cache/Rate-Limit Redis is fully reset-tolerant for the prefixes listed in [`syst - does not affect Coordination Redis keys such as `tick:*`, `timer:*`, `retry:*`, `session:*`, `tick-executor-lease:*`, `automation:timer:*`, or `script-scheduler:*` - increases load on backing services temporarily but must not lose authoritative game data -The current `automation:queue:{tenantInstanceTag}:*` family is a non-authoritative Cache/Rate-Limit projection. The target rebuild/index operation may index only safe durable `PENDING_EVALUATION` work, or an `EVALUATING` row only after the owner proves its lease is stale or explicitly releases it through one fenced CAS covering the status, lease owner, freshness, and fence transition. Non-stale, unresolved, or ambiguous rows remain excluded. Current `rebuildPendingWorkItemIndex` unconditionally selects both statuses and has no stale, owner, or compare-and-set gate, so queue-prefix reset/rebuild and resume are unavailable and must fail closed; a non-atomic status preflight cannot authorize a safe PENDING-only path. Redis queue payloads are never recovery authority. The reserved `automation:timer:{tenantRegionTag}` and `script-scheduler:{tenantRegionTag}:lastTickId` timer/checkpoint projections remain target-only and unavailable. +The current `automation:queue:{tenantInstanceTag}:*` family is a non-authoritative Cache/Rate-Limit projection. The target rebuild/index operation may index only safe durable `PENDING_EVALUATION` work, or an `EVALUATING` row only after the owner proves its lease is stale or explicitly releases it through one fenced CAS covering the status, lease owner, freshness, and fence transition. Non-stale, unresolved, or ambiguous rows remain excluded. Current `rebuildPendingWorkItemIndex` selects only `PENDING_EVALUATION` rows, but has no owner or compare-and-set gate, so queue-prefix reset/rebuild and resume are unavailable and must fail closed; a non-atomic status preflight cannot authorize a safe PENDING-only path or establish a safe disposition for existing `EVALUATING` rows. Redis queue payloads are never recovery authority. The reserved `automation:timer:{tenantRegionTag}` and `script-scheduler:{tenantRegionTag}:lastTickId` timer/checkpoint projections remain target-only and unavailable. ### Runbook: Environment-Scoped Cache Reset diff --git a/design/architecture/system-architecture-redis-reset-and-recovery.md b/design/architecture/system-architecture-redis-reset-and-recovery.md index 04ddc2ee36..8a5d3c3e82 100644 --- a/design/architecture/system-architecture-redis-reset-and-recovery.md +++ b/design/architecture/system-architecture-redis-reset-and-recovery.md @@ -263,7 +263,7 @@ A region- or tenant-scoped reset parent cannot claim global account- or issuer-i | `chat:say::*`, `chat:whisper:::*`, legacy `chat:whisper::`, `chat:tell::*`, `chat:guild::*`, `chat:city::*`, `chat:account::*` | Cache/Rate-Limit | **Reset-tolerant** | Target and live legacy chat projections are cleared; reads use or fall back to authoritative Social/PostgreSQL history where the communication type promises durable player history, while non-durable projections may rebuild or remain absent. Reset/TTL loss may create gaps or non-contiguous windows only in transient Redis projections and cannot create a durable-history entitlement gap. `chat:city` is a current legacy TTL projection, not durable history and not `SHOUT`. | `WHISPER` reset scope is the complete gameplay recipient namespace `(tenantId, playableStateNamespaceId, characterId)`, and reset cleanup includes the live legacy `chat:whisper::` prefix alongside the target prefix until migration completes. Resets drop recent in-memory history but do not lose persisted moderation logs where required; the legacy prefix must not be used for history/refill across same-account characters or namespaces. No `SHOUT` Redis/reset family exists until a selected profile publishes its type/storage/topology contract. | | `script-scheduler:{tenantRegionTag}:lastTickId` (target-only, once implemented) | Coordination | **Reset-tolerant (target-only, once implemented)** | Once implemented, Automation scheduler treats the next heartbeat as its baseline and may re-scan due interval boundaries, but durable trigger-instance uniqueness prevents duplicate logical trigger creation. Until then, no current reset operation is defined for this unimplemented target projection. | Target-state Automation scheduler checkpoint for “every N ticks” triggers; once implemented, losing it causes the scheduler to re-establish its baseline from the heartbeat stream while PostgreSQL-backed trigger-instance rows remain the de-duplication boundary. | | `automation:timer:{tenantRegionTag}` (target-only, once implemented) | Coordination | **Reset-tolerant (target-only, once implemented)** | Once implemented, Automation timer indexes for affected regions are discarded and rebuilt from durable schedules, trigger-instance rows, and heartbeat progress. Until then, no current reset operation is defined for this unimplemented target projection. | Target-state region-scoped coordination index for script timers/intervals. Once implemented, entries must remain instance-aware in payload and rebuild logic (`gameInstanceId`, and plugin identifiers when applicable) even though the Redis key is region-scoped for slotting/locality. | -| `automation:queue:{tenantInstanceTag}:*` | Cache/Rate-Limit | **Current reset/recovery unavailable; fail-closed (target reset-tolerant)** | Queue entries are disposable pointers: losing all Redis list contents does not lose PostgreSQL `script_work_items`, but missing pointers do not authorize resume. The current `rebuildPendingWorkItemIndex` selects both `PENDING_EVALUATION` and `EVALUATING` rows without a stale-owner or compare-and-set reconciliation gate, so queue reset, rebuild, and resume are unavailable. Do not flush, rebuild, or resume this projection as a supported current operation; keep the affected `{tenantId, gameInstanceId}` scope paused/fenced and escalate to the Automation owner. Once owner status reconciliation/reclamation, CAS fencing, and exact readback are implemented and proven, tooling may drop and rebuild only this pointer projection from the authoritative rows before releasing the scope. | The queue is a derived pointer projection, never execution authority; PostgreSQL work-item state remains authoritative. See the [Automation & Scripting API contract](./microservices/automation-scripting-service/api-contracts.md#implementation-status) and [runtime/data owner contract](./microservices/automation-scripting-service/runtime-and-data.md#redis-roles-and-prefixes). | +| `automation:queue:{tenantInstanceTag}:*` | Cache/Rate-Limit | **Current reset/recovery unavailable; fail-closed (target reset-tolerant)** | Queue entries are disposable pointers: losing all Redis list contents does not lose PostgreSQL `script_work_items`, but missing pointers do not authorize resume. The current `rebuildPendingWorkItemIndex` selects only `PENDING_EVALUATION` rows, but has no stale-owner or compare-and-set reconciliation gate and cannot establish a safe disposition for existing `EVALUATING` rows, so queue reset, rebuild, and resume are unavailable. Do not flush, rebuild, or resume this projection as a supported current operation; keep the affected `{tenantId, gameInstanceId}` scope paused/fenced and escalate to the Automation owner. Once owner status reconciliation/reclamation, CAS fencing, and exact readback are implemented and proven, tooling may drop and rebuild only this pointer projection from the authoritative rows before releasing the scope. | The queue is a derived pointer projection, never execution authority; PostgreSQL work-item state remains authoritative. See the [Automation & Scripting API contract](./microservices/automation-scripting-service/api-contracts.md#implementation-status) and [runtime/data owner contract](./microservices/automation-scripting-service/runtime-and-data.md#redis-roles-and-prefixes). | | `automation:quota::*`, `automation:tenant-budget::tier:`, `automation:test:quota::script::tenant`, `automation:test:quota::script::principal:`, `automation:test:capacity:{}:tenant`, `automation:test:capacity:{}:lease:`, `automation:test:capacity:{automation-test-capacity}:cluster`, `automation:test:capacity:{automation-test-capacity}:cluster:lease::`, `automation:readiness:capacity:{}:tenant`, `automation:readiness:capacity:{}:lease:`, `automation:readiness:capacity:{automation-readiness-capacity}:cluster`, `automation:readiness:capacity:{automation-readiness-capacity}:cluster:lease::` | Cache/Rate-Limit | **Reset-tolerant** | Quota windows and capacity reservations restart from an empty state; durable automation work/readiness state remains authoritative. The service does not rebuild the one-minute quota windows or ten-minute readiness leases; new requests acquire fresh disposable reservations. | Best-effort counters and owner-token leases; resets clear them but do not affect authoritative state. Repeated resets or lease expiry may temporarily relax test fairness or readiness concurrency, but must not change which durable work eventually runs. Only the Automation service's Cache/Rate-Limit ACL may access these families; they are not Coordination Redis scheduler/tick keys. Tenant counter/lease pairs use the tenant hash tag, while cluster counter/lease pairs use their fixed family hash tag. | | `tick-events-lease:{tenantRegionTag}` (target-only, once implemented) | Coordination | **Reset-tolerant (target-only, once implemented)** | The target lease is currently unavailable; once implemented, observer leases are dropped, consumers reacquire them, and may duplicate best-effort processing until offsets are re-established. | Used only to avoid duplicate tick-event consumption work. Losing it is safe because tick events are observers/hints; correctness derives from the committed heartbeat/RegionStatus timeline and durable domain state. | | `tick-events:{tenantRegionTag}` and all `tick-events-offset:{tenantRegionTag}:{consumerId}` keys (target-only, once implemented) | Coordination | **Reset-tolerant (target-only, once implemented)** | The target stream and offsets are currently unavailable; once implemented, tick event streams and every consumer's offset are dropped, and observers re-establish their baselines from the gRPC heartbeat and domain state. Any surviving per-consumer offset value is reusable only when its stored `region_epoch` matches the current control-plane epoch; otherwise it is discarded before resume. | Tick event streams are best-effort observer/wakeup hints (for example, reconnection hints and faster scheduler discovery). Each offset value stores `{tenantId, gameInstanceId, regionId, consumerId, region_epoch, latestTickId, streamOffset}`. Streams are retention-capped (default `tick_events_maxlen = 2048` per region). Correctness derives from the committed heartbeat/RegionStatus timeline plus durable PostgreSQL schedules/effects; missing or duplicated events must not change which schedules eventually fire. | diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index 68a056ae2f..2e92f3f34d 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -694,7 +694,7 @@ Redis features and assumptions in FireMUD must work across both single‑instanc | --- | --- | --- | --- | | Single‑node with AOF (coordination) | **Supported.** All coordination prefixes (`tick:*`, `timer:*`, `retry:*`, `session:game:*`, `session:auth:token:*`, `session:auth:generation:*`, `tick-executor-lease:*`, etc.) and shard‑local Lua patterns apply. Measured unreplicated-write exposure and AOF replay guarantees assume this profile or better. | **Supported** on a separate Cache/Rate‑Limit deployment (distinct process or container). | Recommended baseline for `dev_local` and `hobby_self_hosted` profiles. | | Single‑node without AOF (ephemeral coordination) | **Supported only for explicitly labelled one-shot test/CI stacks** (hosted `pr-preview` is excluded) that opt out of measured unreplicated-write SLOs and replay guarantees. Coordination keys are disposable and must be reset‑tolerant. | **Supported** on a separate Cache/Rate‑Limit deployment by default. An explicitly labelled one-shot test/CI stack may temporarily collapse both roles under ADR 0171's narrow exception. | Not appropriate for environments where role-isolation, tick replay, measured loss-window SLOs, or long‑lived coordination logs are required. | -| Redis Cluster (coordination) | **Supported for registered workloads** provided every registered coordination Lua script uses its applicable hash tag: `{tenantRegionTag}` for region/tick, maintenance, and automation-coordination flows; `{tenantInstanceTag}` for instance-scoped automation and remote-hint flows; `{tenantGameplayTag}` for session-only gameplay flows; the fixed `{gateway-connect-token-replay-v1}` for Gateway replay-admission flows; and `{issuerIndexLayoutTag}` for issuer-index partition flows. Multi-key coordination scripts must only touch keys that share one exact registered hash tag and slot; approved global or untagged single-key/reconciliation exceptions remain subject to their owner contracts and do not establish clustered multi-key support. The reserved Automation & Scripting families `automation:timer:*` and `script-scheduler:*` remain target-only and unimplemented, while the retired `automation:tick:*` path is not a current family. | **Target/registered workloads only.** Canonical single-bucket rate-limit operations and cache families with a registered scope/tag are supported without cross-slot atomicity; current legacy `ipconn:
` + `sessionip:` registration and Automation's untagged readiness/dry-run capacity reservations remain unsupported because they can fail `CROSSSLOT`. | Cluster deployment requires strict adherence to hash-tag and slotting rules described in [Key Naming and Shard Discipline](#key-naming-and-shard-discipline), including the issuer-layout and instance-scoped automation families; a general Cache/Rate-Limit support claim must not be used as proof for unregistered current families. | +| Redis Cluster (coordination) | **Supported for registered workloads** provided every registered coordination Lua script uses its applicable hash tag: `{tenantRegionTag}` for region/tick, maintenance, and automation-coordination flows; `{tenantInstanceTag}` for instance-scoped automation and remote-hint flows; `{tenantGameplayTag}` for session-only gameplay flows; the fixed `{gateway-connect-token-replay-v1}` for Gateway replay-admission flows; and `{issuerIndexLayoutTag}` for issuer-index partition flows. Multi-key coordination scripts must only touch keys that share one exact registered hash tag and slot; approved global or untagged single-key/reconciliation exceptions remain subject to their owner contracts and do not establish clustered multi-key support. The reserved Automation & Scripting families `automation:timer:*` and `script-scheduler:*` remain target-only and unimplemented, while the retired `automation:tick:*` path is not a current family. | **Target/registered workloads only.** Canonical single-bucket rate-limit operations and cache families with a registered scope/tag are supported without cross-slot atomicity. The current Automation readiness and dry-run capacity reservations use canonical shared hash tags for each counter/lease pair, so those pairs are not inherently cross-slot; they remain unregistered/unsupported as a complete clustered workload until central ownership inventory, canonical key encoding, and durable charge/admission proof are established. Current legacy `ipconn:
` + `sessionip:` registration remains unsupported because it can fail `CROSSSLOT`. | Cluster deployment requires strict adherence to hash-tag and slotting rules described in [Key Naming and Shard Discipline](#key-naming-and-shard-discipline), including the issuer-layout and instance-scoped automation families; a general Cache/Rate-Limit support claim must not be used as proof for unregistered current families. | In all non-ephemeral topologies: 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 83879605f0..e8381618a4 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -155,7 +155,7 @@ The evaluator's `recordOutcome` producer now conforms to [normative Table 4](../ The queue status below is an implementation description, not a recovery authorization: current reset/rebuild/resume is unavailable and must fail closed for every status mix because no atomic PENDING-only/CAS gate exists. The target owner-reconciled workflow remains target-only. -Automation never writes Game Session tick keys directly. The live queue uses instance-aware `automation:queue:{tenantInstanceTag}:*` pointers containing a documented outbox-pointer envelope (`schemaVersion`, `outboxWorkItemId`, and bounded identity metadata); the retired `automation:tick:*` staging path is not part of the live design. Quota counters use `automation:quota::`. Queue pointers are derived coordination indexes, not work truth: Redis drain deduplicates by `outboxWorkItemId`. The callable `rebuildPendingWorkItemIndex` unconditionally selects both statuses and has no stale, owner, or compare-and-set 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 the safe PENDING-only path. Bounded duplicate-pointer recovery remains the owner-controlled gap defined in the [scripting runtime rebuild contract](../../architecture/system-architecture-scripting-runtime-execution.md#current-queue-rebuild-concurrency-gap). Health inspection reports `automation_queue_orphaned_entries_total` and `automation_queue_oldest_entry_age_seconds`, and the executor drains pointers for discovery before claiming PostgreSQL work, falling back to durable scanning if Redis discovery fails. +Automation never writes Game Session tick keys directly. The live queue uses instance-aware `automation:queue:{tenantInstanceTag}:*` pointers containing a documented outbox-pointer envelope (`schemaVersion`, `outboxWorkItemId`, and bounded identity metadata); the retired `automation:tick:*` staging path is not part of the live design. Quota counters use `automation:quota::`. Queue pointers are derived coordination indexes, not work truth: Redis drain deduplicates by `outboxWorkItemId` and removes pointers with atomic `LPOP`, leaving unconsumed suffixes available when a pointer budget is reached. The callable `rebuildPendingWorkItemIndex` selects only `PENDING_EVALUATION` rows, but has no owner or compare-and-set 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 the safe PENDING-only path or establish a safe disposition for `EVALUATING` rows. Bounded duplicate-pointer recovery remains the owner-controlled gap defined in the [scripting runtime rebuild contract](../../architecture/system-architecture-scripting-runtime-execution.md#current-queue-rebuild-concurrency-gap). Health inspection reports `automation_queue_orphaned_entries_total` and `automation_queue_oldest_entry_age_seconds`, and the executor drains pointers for discovery before claiming PostgreSQL work, falling back to durable scanning if Redis discovery fails. Current enqueue/rebuild is RPUSH-only (with no target pointer TTL or maximum length), and `tenantInstanceTag` still concatenates raw IDs, so retention, memory-pressure, and collision-safe opaque encoding remain unproved. Canonical queue and Redis mechanics are owned by [Scripting Runtime Execution](../../architecture/system-architecture-scripting-runtime-execution.md) and [Redis](../../architecture/system-architecture-redis.md); this tracker records the current implementation gaps. From 820c28bb3946fd4b32c6dba0f3bc70fb6e1c82f2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 01:06:41 +1200 Subject: [PATCH 18/68] docs(redis): clarify reset release authority --- .../system-architecture-redis-reset-and-recovery.md | 2 +- ...em-architecture-redis-script-rollout-and-compatibility.md | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/design/architecture/system-architecture-redis-reset-and-recovery.md b/design/architecture/system-architecture-redis-reset-and-recovery.md index 8a5d3c3e82..ab7089f7da 100644 --- a/design/architecture/system-architecture-redis-reset-and-recovery.md +++ b/design/architecture/system-architecture-redis-reset-and-recovery.md @@ -45,7 +45,7 @@ Coordination Redis is treated as a **long‑lived, measured-exposure coordinatio - Preserves only `session:game:{tenantGameplayTag}::` records when operators explicitly choose `--preserve-sessions`; affected tenant-owned `session:game:index:*` projections are derived and may be dropped, but must reconcile before release. Untagged global account and issuer indexes are not narrow reset targets; replacement requires their complete owner-defined durable inventory, coverage proof, and exact readback before release. Pre-auth transport context is not covered by session preservation and is invalidated or rebuilt. - Does not clear Account-owned `session:auth:token:` records, live legacy account/tenant auth projections, authority-generation projections, or target exact-input `session:connect-token:v1:*` issuance-result projections. Region- and tenant-scoped resets preserve these families because they are not region-scoped coordination state. The unversioned legacy `session:connect-token:*` map is only preserved and read back while present through its configured TTL/retry horizon, then owner-cleaned; if it is missing, changed, or untrusted, the affected handshake remains fenced and operators escalate. A missing or untrusted target `session:connect-token:v1:*` projection requires Account exact durable repair and readback before the affected operation can release. A tenant reset may terminate affected gameplay bindings, but it must not turn a tenant-region coordination reset into account-wide token revocation. - Preserves only `session:game:{tenantGameplayTag}::` records when operators explicitly choose `--preserve-sessions`; the complete affected tenant-tagged character, account-tenant, tenant, and realm-grant `session:game:index:*` families may be dropped at this tenant scope, but must reconcile before release. A region-scoped reset instead reconciles only exact affected keys or members from durable inventory. Untagged global account and issuer indexes are not narrow reset targets; replacement requires their complete owner-defined durable inventory, coverage proof, and exact readback before release. Pre-auth transport context is not covered by session preservation and is invalidated or rebuilt. - - Does not clear Account-owned `session:auth:token:` records, live legacy account/tenant auth projections, exact-input `session:connect-token:tenant::account::scope::request:` issuance-result/idempotency records, or authority-generation projections. Region- and tenant-scoped resets preserve those records because they are not region-scoped coordination state; if any preserved projection is missing or untrusted, Account must repair and read it back before the affected operation can release. A tenant reset may terminate affected gameplay bindings, but it must not turn a tenant-region coordination reset into account-wide token revocation or permit a live connect request to receive a different result on retry. + - Does not clear Account-owned `session:auth:token:` records, live legacy account/tenant auth projections, target exact-input `session:connect-token:v1:*` issuance-result projections, or authority-generation projections. Region- and tenant-scoped resets preserve those records because they are not region-scoped coordination state. The unversioned legacy exact-input `session:connect-token:tenant::account::scope::request:` map is preserve/readback-only while present through its bounded TTL/retry horizon, then owner-cleaned; if it is missing, changed, or untrusted, the affected handshake remains fenced and requires escalation, never reconstruction, reminting, or repair as target authority. Target `session:connect-token:v1:*` projections are preserved by narrow resets and, if missing or untrusted, Account repairs and reads them back only from the exact durable issuance operation/encrypted envelope before the affected operation can release. A tenant reset may terminate affected gameplay bindings, but it must not turn a tenant-region coordination reset into account-wide token revocation or permit a live connect request to receive a different result on retry. - Often combined with an in‑game maintenance window or a revert/repin of tenant‑specific published content. - Used when: - A full in‑game reset is acceptable for a single tenant. diff --git a/design/architecture/system-architecture-redis-script-rollout-and-compatibility.md b/design/architecture/system-architecture-redis-script-rollout-and-compatibility.md index 2dc272630a..f38094f0ba 100644 --- a/design/architecture/system-architecture-redis-script-rollout-and-compatibility.md +++ b/design/architecture/system-architecture-redis-script-rollout-and-compatibility.md @@ -74,8 +74,9 @@ Potentially compatible when proven by tests: - `requires_region_reset` - `requires_tenant_reset` - `requires_cluster_reset` -6. Confirm reset safety before resuming: - - no `SCHEDULED` ledger rows remain for the affected scope +6. Confirm reset safety before continuing the script rollout, and apply the separate traffic-reopen gate: + - no executable or unowned `SCHEDULED` ledger work remains for the affected scope; any remaining old-epoch `SCHEDULED` row is completely enumerated, explicitly fenced, and owned by reconciliation + - the affected scope remains blocked from reopening while any such reconciliation-owned row lacks the policy-defined authority-fenced terminal decision - in-flight commands are retried or marked terminal appropriately The registry, together with its golden compatibility tests, remains the single source of truth for whether coordination state can be safely replayed across script versions or must be reset. From 18521e62efee13ee8237bda01deed809070bc580 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 02:12:35 +1200 Subject: [PATCH 19/68] docs(ticks): qualify aggregate watermark identities --- .../system-architecture-tick-failures-and-operations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/system-architecture-tick-failures-and-operations.md b/design/architecture/system-architecture-tick-failures-and-operations.md index dd6e86ade3..b208fd0ec7 100644 --- a/design/architecture/system-architecture-tick-failures-and-operations.md +++ b/design/architecture/system-architecture-tick-failures-and-operations.md @@ -733,7 +733,7 @@ When introducing a new command type that will run under tick control, design doc - If not, it may follow different idempotency rules and does not belong in this section. - **What is the idempotency key?** - Which frozen typed command/action contract or `ResolvedEffectPlan` supplies semantic order for the command's logical root effects, and how does it reject ambiguous/duplicate order before admission, persist the ordered manifest/digest, and allocate an opaque binding unique on `(tenantId, gameInstanceId, commandId, planOrdinal)` only after the durable command row freezes/binds its request fingerprint, resolved runtime scope, and applicable `playableStateNamespaceId`? Reuse must validate the same command row identity, frozen binding, ordinal, and manifest digest; any mismatch fails closed. A zero-effect command must allocate neither. Source ordering remains separate, and non-command-root work retains its owner/source-specific identity. - - For single-aggregate updates: which `(tenant_id, game_instance_id, playable_state_namespace_id, region_id, target_aggregate_type, aggregate_id)` key plus separately exact-validated `playable_state_scope` evidence and `(last_region_epoch, last_tick_id)` (or equivalent) fields and table enforce “at most one update per tick timeline” for that aggregate? + - For single-aggregate updates: has the owner proved that the aggregate receives at most one logical mutation per tick and declared its runtime family? An explicit S3 watermark uses the complete `(tenant_id, game_instance_id, playable_state_namespace_id, region_id, target_aggregate_type, aggregate_id)` key plus separately exact-validated `playable_state_scope` evidence and `(last_region_epoch, last_tick_id)` (or equivalent) fields. An S1/S2 watermark instead uses its owner-defined namespace partition and exact-validates the active `game_instance_id` only as separate authorization/fence evidence; it must not copy the S3 instance-keyed identity. Any aggregate capable of multiple effects in one tick uses the participant/effect guard contract below instead. - For multi-aggregate or multi-effect operations: what participant guard identity combines the mutation's persisted root-or-child `EffectId`, typed operation, and exact target aggregate, and how is the immutable request digest bound and checked? A generated child retains its enclosing root as lineage and reconciliation context; `effect_key` is a concrete storage projection/descriptor, not a replacement for that guard identity. - **Where is the guard persisted?** - Which schema/table holds the per-aggregate “last applied tick” state or `tick_effect_guard` entries? From 9dc2d0dd560333b20c07e62e55e0c915cf89df26 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 02:28:07 +1200 Subject: [PATCH 20/68] docs(automation): remove stale fence status --- .../automation-scripting-service/runtime-and-data.md | 2 -- 1 file changed, 2 deletions(-) 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 943094b640..ce0b60d3c7 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -23,8 +23,6 @@ The same V2 migration replaces handler work-item and audit identities so authent The current `script_event_ingress_audit` event-scope claim uses branch-specific `INSERT ... ON CONFLICT` claims: instance-scoped rows include their exact runtime identity and positive pin tuple, while pre-instance tenant-readiness `onLoad` rows use the nullable branch without inventing absent optional identity fields. The V5 indexes provide the corresponding positive-epoch instance and pre-instance uniqueness branches. Retained pre-fencing instance rows may keep a null epoch as historical evidence, but no live repository claim can create that shape; duplicate retained identities fail migration preflight for operator reconciliation rather than being deleted. The claim row carries a row-version/lease token. Before quota acquisition, work-item or projection fan-out, and handler-audit persistence, the owner renews that token with an atomic row-version/state check; stale reclaim advances the same fence, so a reclaimed slow owner fails before those effects. The implementation has unit and deterministic mocked concurrency proof for claim/reclaim fencing, but does not yet provide a full database-backed slow-owner/reclaim proof or rollback compensation for external quota counters; those remain implementation and proof gaps. -The current service validates and resolves handlers during admission, persists each admitted handler as a pre-DSL `PENDING_EVALUATION` trigger record, and later lets a scheduled executor claim the record and evaluate the sandboxed DSL; it carries only the narrower read-snapshot token field, does not yet seal the complete handler input manifest, and does not persist the separate evaluated-descriptor layer. Current admission, runtime projection, schedule rows, and handoff also do not propagate `scriptPinEpoch` end to end, so exact-epoch persistence and final fencing remain target-state gaps. The target Automation-owned `pluginActivationEpoch` and owner `lifecycleRevision` are likewise not yet persisted in plugin runtime/status/work records or propagated through handoff, retry, replay, and recovery, so same-version re-enable and same-epoch lifecycle fencing remain implementation and proof gaps. These are implementation and proof gaps; the target lifecycle and manifest contracts below remain normative. - The live `faction`/`faction_standing` schema and `FactionServiceImpl` currently make Automation the player-reputation writer and derive isolated standing identity from `gameInstanceId`. The target owner is Social & Groups under a stable playable-state namespace; Automation remains a consumer for NPC behavior. Owner migration, retained-row disposition, namespace-stable identity, and focused owner-read proof remain unimplemented. The live `script_event_audit` and `script_work_items` schema uniqueness constraints omit plugin provenance, and neither current row shape nor repository identity lookup carries the required resolved `bindingId`. Distinct plugin handlers can therefore alias or collide even though the target full Trigger Identity requires `pluginId`, `pluginVersionId`, and `bindingId` where applicable. A new owner-local migration, aligned jOOQ/repository identity, and focused multi-handler retry/concurrency proof are required; this is current implementation drift, not a change to Trigger Identity authority. From b58aa6067afda871e22977ed0b5fd583d112fa4e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 12:02:59 +1200 Subject: [PATCH 21/68] fix(runtime): persist cross-service intents before dispatch --- .../runtime-and-data.md | 4 +- .../system-architecture-transactions.md | 4 +- ...riptGameplayCommandHandoffServiceImpl.java | 544 +++++++++++++++--- .../ScriptWorkItemExecutionServiceImpl.java | 237 ++++++-- ...GameplayCommandHandoffServiceImplTest.java | 509 +++++++++++++--- ...criptWorkItemExecutionServiceImplTest.java | 135 +++++ .../WorldLifecycleCommandServiceImpl.java | 82 ++- ...orldInstanceActivationServiceImplTest.java | 112 +++- 8 files changed, 1371 insertions(+), 256 deletions(-) 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 ce0b60d3c7..d69fb50ef2 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -8,7 +8,9 @@ The unsupported NPC formation REST handlers and OpenAPI paths have been removed. **Target formation boundary:** keep the external public route absent, require exact tenant-bound internal `tenantAdmin` authorization without a global-role override, derive the tenant from that authority, and validate formation plus leader/member NPC ownership against the Entity Management owner read before every mutation/read. A missing or unavailable owner read, tenant/namespace mismatch, or caller-selected cross-tenant identifier fails closed before persistence or disclosure. Negative proof must cover unauthenticated access, tenant A selecting tenant B, and tenant A attaching tenant B's NPC to an otherwise tenant-A formation. The owning [API contract](./api-contracts.md#normative-target-contract) defines the complete target rule. -The current service validates and resolves handlers during admission, persists each admitted handler as pre-DSL `PENDING_EVALUATION` work, and later lets a scheduled executor claim the work and evaluate the sandboxed DSL; it carries only the narrower read-snapshot token field, does not yet seal the complete handler input manifest, and does not persist the separate evaluated-descriptor layer. Admission, runtime projection, schedule rows, and runtime replay now carry the authoritative exact `(scriptPatchVersion, scriptPinEpoch)` pair plus associated owner `controlPlaneRequestId` evidence, compare that captured evidence with owner and observed state, and fail closed on absent, stale, partial, or mismatched evidence. Automation now persists `pluginActivationEpoch` and `lifecycleRevision` in plugin runtime state and captures them on plugin-backed ingress, work, audit, schedule, and handoff rows. Admission and downstream evaluation reject absent or stale captured fence evidence, including same-version re-enable and same-epoch lifecycle changes. Pending-transition ownership, Game Session fence-install acknowledgement, complete retry/replay/recovery propagation, and final gameplay-effect enforcement remain implementation and proof gaps; the target lifecycle and manifest contracts below remain normative. +The current service validates and resolves handlers during admission, persists each admitted handler as pre-DSL `PENDING_EVALUATION` work, and later lets a scheduled executor claim the work and evaluate the sandboxed DSL; it carries only the narrower read-snapshot token field, does not yet seal the complete handler input manifest, and does not persist the separate evaluated-descriptor layer. For evaluated child commands, Automation commits a deterministic `HANDOFF_IN_FLIGHT` intent in a short local transaction before invoking Game Session with no Automation transaction active, then records a definitive response in a separate local transaction guarded by the work-item version. A dispatch or post-dispatch persistence ambiguity retains the intent for recovery, while a failure before the intent commits performs no RPC and returns a retryable rejection rather than falsely claiming an in-flight dispatch. Each child intent also reacquires the local admission lock and rereads the current admission state before it becomes dispatchable. The service still lacks the durable evaluated descriptor and reconciliation owner needed to resume every ambiguous handoff without re-evaluating the DSL, so the complete crash/restart contract remains unimplemented. + +Admission, runtime projection, schedule rows, and runtime replay now carry the authoritative exact `(scriptPatchVersion, scriptPinEpoch)` pair plus associated owner `controlPlaneRequestId` evidence, compare that captured evidence with owner and observed state, and fail closed on absent, stale, partial, or mismatched evidence. Automation now persists `pluginActivationEpoch` and `lifecycleRevision` in plugin runtime state and captures them on plugin-backed ingress, work, audit, schedule, and handoff rows. Admission and downstream evaluation reject absent or stale captured fence evidence, including same-version re-enable and same-epoch lifecycle changes. Pending-transition ownership, Game Session fence-install acknowledgement, complete retry/replay/recovery propagation, and final gameplay-effect enforcement remain implementation and proof gaps; the target lifecycle and manifest contracts below remain normative. Plugin lifecycle mutations use immutable request history keyed by `(tenantId, gameInstanceId, pluginId, controlPlaneRequestId)`, with the operation and canonical request fingerprint stored as bound payload. An exact retry returns the recorded result, while reuse for another operation or changed input fails before state, epoch, revision, lifecycle history, schedule, or notification mutation. Fresh same-target activation, already-`DRAINING`, already-`DISABLED`, and never-active `DISABLE` no-ops store one immutable successful request receipt while leaving runtime state, lifecycle event history, notifications, schedules, and counters unchanged. A new `DRAIN` against a plugin with no active `ENABLED` lifecycle records one immutable `FAILED_PRECONDITION` receipt without changing plugin state. Transient transition or fence-install failures are not terminalized by this receipt slice. V3 assigns a founding `(pluginActivationEpoch, lifecycleRevision)=(1,1)` only to retained runtime rows with a nonblank active version and to retained schedules whose tenant, instance, plugin, version, runtime region, and region epoch match exactly; contradictory executable rows fail migration, and schema/repository guards reject incoherent pairs or an active version at `0/0`, while historical work/audit/handoff evidence remains `0/0` and fenced because its winning admission cannot be reconstructed. Generic plugin-owned ingress also requires the later fence read to remain `ENABLED` before persisting work. Focused service and migration-shape proof executes locally; PostgreSQL receipt/concurrency and retained-data cases require Docker/Testcontainers. diff --git a/design/architecture/system-architecture-transactions.md b/design/architecture/system-architecture-transactions.md index a97799d5f5..08a1aa7088 100644 --- a/design/architecture/system-architecture-transactions.md +++ b/design/architecture/system-architecture-transactions.md @@ -6,9 +6,9 @@ Script evaluation and pin transitions are not a new transaction substrate. The s ## Implementation Status -The structured participant-guard request, deterministic command-plan root identity, shared `IdempotentEffectExecutor`, standardized tick-effect outcome metric, and replay-verification helper described below are target-state contracts. The current replay tables and helpers remain narrower and domain-local; complete propagation and validation of the plan's persisted `planOrdinal`/root-or-child `EffectId`, typed operation, target aggregate, owner-resolved S1/S2-versus-explicit-S3 guard partition, applicable `playableStateNamespaceId` and separately persisted `playableStateScope` evidence, separately validated active-instance fence, immutable request digest, complete participant set, and shared helper/metric behavior are not yet fully implemented or proven. Unknown or unclassified guard families must be rejected before any participant-guard allocation or admission; no implicit third partition exists. The current local instance-bound scripting handoff now carries, persists, and enforces the exact `scriptPinEpoch` tuple with its owner request evidence, including same-version old-epoch rejection; complete source/target remote tuple binding and full command identity remain implementation gaps rather than weakened target invariants. The target contract remains authoritative: matching requests may replay safely, while an operation, target, namespace, scope, active-instance evidence, or digest mismatch fails closed. +The structured participant-guard request, deterministic command-plan root identity, shared `IdempotentEffectExecutor`, standardized tick-effect outcome metric, and replay-verification helper described below are target-state contracts. The current replay tables and helpers remain narrower and domain-local; complete propagation and validation of the plan's persisted `planOrdinal`/root-or-child `EffectId`, typed operation, target aggregate, owner-resolved S1/S2-versus-explicit-S3 guard partition, applicable `playableStateNamespaceId` and separately persisted `playableStateScope` evidence, separately validated active-instance fence, immutable request digest, complete participant set, and shared helper/metric behavior are not yet fully implemented or proven. Unknown or unclassified guard families must be rejected before any participant-guard allocation or admission; no implicit third partition exists. The current local instance-bound scripting handoff now carries, persists, and enforces the exact `scriptPinEpoch` tuple with its owner request evidence, including same-version old-epoch rejection. Automation also commits each deterministic child `HANDOFF_IN_FLIGHT` intent before invoking Game Session outside a local transaction, then records a definitive response in a separate local transaction; ambiguous post-dispatch failures remain recoverable intent rather than being reported as a clean rejection. It does not yet implement the durable evaluated-descriptor and reconciliation owner needed to recover every ambiguous handoff. Complete source/target remote tuple binding and full command identity also remain implementation gaps rather than weakened target invariants. The target contract remains authoritative: matching requests may replay safely, while an operation, target, namespace, scope, active-instance evidence, or digest mismatch fails closed. -Lifecycle and authoring workflows follow the same local-transaction boundary. World Management commits its lifecycle row/epoch with database compare-and-set; Temporal coordinates retries and waits but is not a transaction or authority. Replacement cutover follows the canonical [PREPARING-to-ACTIVE proof sequence](./system-architecture-versioning-runtime.md#realm-routing-contract-for-player-addressable-realms) and [Game Session cutover boundary](./microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary): World owns the lifecycle CAS and one-shot cutover hold, while the Game Session owner-local cutover transaction validates the hold id/fence, expected pointer version, and exact source and target `ACTIVE` proofs before its pointer CAS. World finalizes the hold only after authoritative Game Session readback proves the local pointer/audit/prepared-execution/source-cleanup/drain-fence transaction; no global transaction spans the services. A multi-owner Draft commit carries the complete [ADR 0129](./decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) binding, including target `tenantId`/`versionId`, request or proposal identity, exact `baseCommitId`, canonical revision order, proposed input/digest, and the complete affected `(owner, aggregateId, scopeId, epoch)` set. It performs compare-and-set in each owner database, records durable per-owner outcomes, and publishes through a synchronized read fence; it never uses a global epoch, silent merge, or distributed transaction. These are control-plane workflows and do not add a global ACID path to ordinary gameplay. +Lifecycle and authoring workflows follow the same local-transaction boundary. World Management commits its lifecycle row/epoch with database compare-and-set; Temporal coordinates retries and waits but is not a transaction or authority. Current instance termination performs Entity cleanup outside the World database transaction and commits the World-owned row cleanup plus final `TERMINATED` state in one local transaction after that acknowledgement. This closes partial World-local cleanup on failure but does not implement the target frozen multi-owner cleanup snapshot, acknowledgement set, or complete recovery proof. Replacement cutover follows the canonical [PREPARING-to-ACTIVE proof sequence](./system-architecture-versioning-runtime.md#realm-routing-contract-for-player-addressable-realms) and [Game Session cutover boundary](./microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary): World owns the lifecycle CAS and one-shot cutover hold, while the Game Session owner-local cutover transaction validates the hold id/fence, expected pointer version, and exact source and target `ACTIVE` proofs before its pointer CAS. World finalizes the hold only after authoritative Game Session readback proves the local pointer/audit/prepared-execution/source-cleanup/drain-fence transaction; no global transaction spans the services. A multi-owner Draft commit carries the complete [ADR 0129](./decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) binding, including target `tenantId`/`versionId`, request or proposal identity, exact `baseCommitId`, canonical revision order, proposed input/digest, and the complete affected `(owner, aggregateId, scopeId, epoch)` set. It performs compare-and-set in each owner database, records durable per-owner outcomes, and publishes through a synchronized read fence; it never uses a global epoch, silent merge, or distributed transaction. These are control-plane workflows and do not add a global ACID path to ordinary gameplay. --- diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java index bf943d354b..1b1a774cce 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java @@ -1,11 +1,12 @@ package net.firedevops.firemud.automationscripting.service.impl; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.Set; import net.firedevops.firemud.automationscripting.client.GameSessionControlPlaneClient; import net.firedevops.firemud.automationscripting.entity.ScriptHandoffEvent; @@ -29,13 +30,11 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; @Service -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected collaborators are framework-managed and retained internally") public class ScriptGameplayCommandHandoffServiceImpl implements ScriptGameplayCommandHandoffService { private static final Logger LOGGER = @@ -44,6 +43,8 @@ public class ScriptGameplayCommandHandoffServiceImpl private static final String STATUS_PENDING_EVALUATION = "PENDING_EVALUATION"; private static final String STATUS_CANCELED = "CANCELED"; private static final String STATUS_DEAD_LETTERED = "DEAD_LETTERED"; + private static final String OUTCOME_HANDOFF_IN_FLIGHT = "HANDOFF_IN_FLIGHT"; + private static final String REASON_HANDOFF_IN_FLIGHT = "handoff_in_flight"; private static final String REMOTE_LATE_RESULT_POLICY = "late_result_safe_to_ignore"; private final GameSessionControlPlaneClient gameSessionClient; @@ -54,6 +55,8 @@ public class ScriptGameplayCommandHandoffServiceImpl private final AutomationQueueService automationQueueService; private final AutomationAdmissionStateService automationAdmissionStateService; private final ScriptPatchInstanceRolloutProjectionService rolloutProjectionService; + private final TransactionTemplate handoffTransactionTemplate; + private final TransactionTemplate rpcTransactionTemplate; private final ThreadLocal> aggregateFanouts = ThreadLocal.withInitial(HashSet::new); private final ThreadLocal> aggregateAdmissionSnapshots = ThreadLocal.withInitial(HashMap::new); @@ -73,7 +76,8 @@ public ScriptGameplayCommandHandoffServiceImpl( (DSLContext) null, null, automationAdmissionStateService, - rolloutProjectionService); + rolloutProjectionService, + null); } public ScriptGameplayCommandHandoffServiceImpl( @@ -92,7 +96,8 @@ public ScriptGameplayCommandHandoffServiceImpl( (DSLContext) null, null, automationAdmissionStateService, - rolloutProjectionService); + rolloutProjectionService, + null); } /** Legacy constructor retained for focused unit tests that do not exercise queue publication. */ @@ -112,10 +117,11 @@ public ScriptGameplayCommandHandoffServiceImpl( dsl, null, automationAdmissionStateService, - rolloutProjectionService); + rolloutProjectionService, + null); } - @Autowired + /** Compatibility constructor for focused tests that do not provide a transaction manager. */ public ScriptGameplayCommandHandoffServiceImpl( GameSessionControlPlaneClient gameSessionClient, ScriptWorkItemRepository workItemRepository, @@ -125,6 +131,54 @@ public ScriptGameplayCommandHandoffServiceImpl( AutomationQueueService automationQueueService, AutomationAdmissionStateService automationAdmissionStateService, ScriptPatchInstanceRolloutProjectionService rolloutProjectionService) { + this( + gameSessionClient, + workItemRepository, + auditRepository, + handoffEventRepository, + dsl, + automationQueueService, + automationAdmissionStateService, + rolloutProjectionService, + null); + } + + @Autowired + public ScriptGameplayCommandHandoffServiceImpl( + GameSessionControlPlaneClient gameSessionClient, + ScriptWorkItemRepository workItemRepository, + ScriptEventAuditRepository auditRepository, + ScriptHandoffEventRepository handoffEventRepository, + DSLContext dsl, + AutomationQueueService automationQueueService, + AutomationAdmissionStateService automationAdmissionStateService, + ScriptPatchInstanceRolloutProjectionService rolloutProjectionService, + PlatformTransactionManager transactionManager) { + this( + gameSessionClient, + workItemRepository, + auditRepository, + handoffEventRepository, + dsl, + automationQueueService, + automationAdmissionStateService, + rolloutProjectionService, + newTransactionTemplate(transactionManager, TransactionDefinition.PROPAGATION_REQUIRES_NEW), + newTransactionTemplate( + transactionManager, TransactionDefinition.PROPAGATION_NOT_SUPPORTED)); + } + + private ScriptGameplayCommandHandoffServiceImpl( + GameSessionControlPlaneClient gameSessionClient, + ScriptWorkItemRepository workItemRepository, + ScriptEventAuditRepository auditRepository, + ScriptHandoffEventRepository handoffEventRepository, + DSLContext dsl, + AutomationQueueService automationQueueService, + AutomationAdmissionStateService automationAdmissionStateService, + ScriptPatchInstanceRolloutProjectionService rolloutProjectionService, + TransactionTemplate handoffTransactionTemplate, + TransactionTemplate rpcTransactionTemplate) { this.gameSessionClient = gameSessionClient; this.workItemRepository = workItemRepository; this.auditRepository = auditRepository; @@ -133,21 +187,41 @@ public ScriptGameplayCommandHandoffServiceImpl( this.automationQueueService = automationQueueService; this.automationAdmissionStateService = automationAdmissionStateService; this.rolloutProjectionService = rolloutProjectionService; + this.handoffTransactionTemplate = handoffTransactionTemplate; + this.rpcTransactionTemplate = rpcTransactionTemplate; + } + + private static TransactionTemplate newTransactionTemplate( + PlatformTransactionManager transactionManager, int propagationBehavior) { + if (transactionManager == null) { + return null; + } + TransactionTemplate template = new TransactionTemplate(transactionManager); + template.setPropagationBehavior(propagationBehavior); + return template; } @Override - @Transactional(propagation = Propagation.MANDATORY) public void beginAggregateFanout(ScriptWorkItem workItem) { requireWorkItem(workItem); + HandoffPreflight preflight = preflight(workItem); + executeIntentBoundary(() -> beginAggregateFanoutInTransaction(workItem, preflight)); + } + + private void beginAggregateFanoutInTransaction( + ScriptWorkItem workItem, HandoffPreflight preflight) { lockAdmissionScope(workItem); aggregateFanouts.get().add(workItem.getId()); try { + String admissionFenceReason = + handoffTransactionTemplate == null + ? preflight.admissionFenceReason() + : admissionFenceReason(workItem); aggregateAdmissionSnapshots .get() .put( workItem.getId(), - new AggregateAdmissionSnapshot( - admissionFenceReason(workItem), runtimeRegionScopeStatus(workItem))); + new AggregateAdmissionSnapshot(admissionFenceReason, preflight.runtimeScopeStatus())); } catch (RuntimeException ex) { clearAggregateFanout(workItem.getId()); throw ex; @@ -174,29 +248,146 @@ private void clearAggregateFanout(Long workItemId) { } @Override - @Transactional public HandoffResult handoff(ScriptWorkItem workItem, EmittedCommand command) { requireWorkItem(workItem); requireCommand(command); String dispatchId = dispatchId(workItem, command.ordinal()); + AggregateAdmissionSnapshot aggregateSnapshot = + aggregateAdmissionSnapshots.get().get(workItem.getId()); + HandoffPreflight preflight = + aggregateSnapshot == null ? preflight(workItem) : HandoffPreflight.from(aggregateSnapshot); + HandoffPreparation preparation; + try { + preparation = executeIntentTransaction(workItem, command, dispatchId, preflight); + } catch (RuntimeException ex) { + LOGGER.warn( + "Unable to durably prepare script handoff for workItemId={} commandOrdinal={}", + workItem.getId(), + command.ordinal(), + ex); + return retryablePreparationResult(ex); + } + if (preparation.result() != null) { + return preparation.result(); + } + HandoffResult downstreamResult; + try { + downstreamResult = + executeRpcWithoutLocalTransaction( + () -> invokeDownstream(workItem, command, dispatchId, preparation.remoteHandoff())); + } catch (RuntimeException ex) { + LOGGER.warn( + "Script handoff RPC failed for workItemId={} commandOrdinal={}; retaining in-flight evidence", + workItem.getId(), + command.ordinal(), + ex); + return reconciliationRequiredResult(ex); + } + if (isReconciliationRequired(downstreamResult)) { + return downstreamResult; + } + try { + return executeResponseTransaction( + () -> + persistDownstreamResponse( + workItem, command, dispatchId, downstreamResult, preparation.intentRowVersion())); + } catch (RuntimeException ex) { + LOGGER.warn( + "Unable to persist script handoff response for workItemId={} commandOrdinal={}; retaining in-flight evidence", + workItem.getId(), + command.ordinal(), + ex); + return reconciliationRequiredResult(ex); + } + } + + private HandoffPreparation executeIntentTransaction( + ScriptWorkItem workItem, + EmittedCommand command, + String dispatchId, + HandoffPreflight preflight) { + if (handoffTransactionTemplate == null) { + return prepareHandoff(workItem, command, dispatchId, preflight); + } + return handoffTransactionTemplate.execute( + status -> prepareHandoff(workItem, command, dispatchId, preflight)); + } + + private void executeIntentBoundary(Runnable action) { + if (handoffTransactionTemplate == null) { + action.run(); + return; + } + handoffTransactionTemplate.execute( + status -> { + action.run(); + return null; + }); + } + + private HandoffResult executeRpcWithoutLocalTransaction(RpcCall rpcCall) { + if (rpcTransactionTemplate == null) { + return rpcCall.invoke(); + } + return rpcTransactionTemplate.execute(status -> rpcCall.invoke()); + } + + private HandoffResult executeResponseTransaction(ResponseCommit responseCommit) { + if (handoffTransactionTemplate == null) { + return responseCommit.commit(); + } + return handoffTransactionTemplate.execute(status -> responseCommit.commit()); + } + + @FunctionalInterface + private interface RpcCall { + HandoffResult invoke(); + } + + @FunctionalInterface + private interface ResponseCommit { + HandoffResult commit(); + } + + private record HandoffPreparation( + HandoffResult result, boolean remoteHandoff, int intentRowVersion) { + HandoffPreparation(HandoffResult result, boolean remoteHandoff) { + this(result, remoteHandoff, -1); + } + } + + private HandoffPreparation prepareHandoff( + ScriptWorkItem workItem, + EmittedCommand command, + String dispatchId, + HandoffPreflight preflight) { + requireWorkItem(workItem); + requireCommand(command); + // Every child intent owns a short local transaction. Reacquire the admission lock and reread + // the local fence in that transaction even when aggregate fanout retained a remote runtime + // snapshot; the aggregate snapshot is not local admission authority. lockAdmissionScope(workItem); AggregateAdmissionSnapshot aggregateSnapshot = aggregateAdmissionSnapshots.get().get(workItem.getId()); String admissionFenceReason = aggregateSnapshot == null - ? admissionFenceReason(workItem) - : aggregateSnapshot.admissionFenceReason(); + ? handoffTransactionTemplate == null + ? preflight.admissionFenceReason() + : admissionFenceReason(workItem) + : admissionFenceReason(workItem); if (ScriptHandoffOutcomeSupport.REASON_RUNTIME_PAUSED.equals(admissionFenceReason)) { Instant now = Instant.now(); cancelForAdmissionPause( workItem, command, dispatchId, now, deferAggregateTerminalization(workItem)); - return new HandoffResult( - false, - ScriptHandoffOutcomeSupport.REASON_RUNTIME_PAUSED, - "", - "", - "", - ScriptHandoffOutcomeSupport.ERROR_RUNTIME_PAUSED); + return new HandoffPreparation( + new HandoffResult( + false, + ScriptHandoffOutcomeSupport.REASON_RUNTIME_PAUSED, + "", + "", + "", + ScriptHandoffOutcomeSupport.ERROR_RUNTIME_PAUSED), + false); } if (ScriptHandoffOutcomeSupport.REASON_AUTHORITY_UNAVAILABLE.equals(admissionFenceReason)) { Instant now = Instant.now(); @@ -210,25 +401,34 @@ public HandoffResult handoff(ScriptWorkItem workItem, EmittedCommand command) { ScriptHandoffOutcomeSupport.ERROR_AUTHORITY_UNAVAILABLE, "automation admission state unavailable"); applyOutcome(workItem, command, dispatchId, result, now); - return result; + return new HandoffPreparation(result, false); } if (ScriptHandoffOutcomeSupport.REASON_ROLLBACK_EPOCH_ADVANCED.equals(admissionFenceReason)) { Instant now = Instant.now(); cancelForRollbackEpochAdvance( workItem, command, dispatchId, now, deferAggregateTerminalization(workItem)); - return new HandoffResult( - false, ScriptHandoffOutcomeSupport.REASON_ROLLBACK_EPOCH_ADVANCED, "", "", "", ""); + return new HandoffPreparation( + new HandoffResult( + false, ScriptHandoffOutcomeSupport.REASON_ROLLBACK_EPOCH_ADVANCED, "", "", "", ""), + false); } RuntimeRegionScopeStatus runtimeScopeStatus = aggregateSnapshot == null - ? runtimeRegionScopeStatus(workItem) + ? preflight.runtimeScopeStatus() : aggregateSnapshot.runtimeRegionScopeStatus(); if (runtimeScopeStatus == RuntimeRegionScopeStatus.ADVANCED) { Instant now = Instant.now(); cancelForRuntimeRegionScopeAdvance( workItem, command, dispatchId, now, deferAggregateTerminalization(workItem)); - return new HandoffResult( - false, ScriptHandoffOutcomeSupport.REASON_RUNTIME_REGION_SCOPE_ADVANCED, "", "", "", ""); + return new HandoffPreparation( + new HandoffResult( + false, + ScriptHandoffOutcomeSupport.REASON_RUNTIME_REGION_SCOPE_ADVANCED, + "", + "", + "", + ""), + false); } boolean remoteHandoff = requiresRemoteHandoff(workItem, command); if (runtimeScopeStatus != RuntimeRegionScopeStatus.CURRENT) { @@ -251,7 +451,7 @@ public HandoffResult handoff(ScriptWorkItem workItem, EmittedCommand command) { errorCode, message); applyOutcome(workItem, command, dispatchId, result, now); - return result; + return new HandoffPreparation(result, remoteHandoff); } if (remoteHandoff && !hasRepresentableDeadline(workItem, command)) { Instant now = Instant.now(); @@ -264,52 +464,92 @@ public HandoffResult handoff(ScriptWorkItem workItem, EmittedCommand command) { "", ScriptHandoffOutcomeSupport.ERROR_INVALID_ARGUMENT); applyOutcome(workItem, command, dispatchId, result, now); - return result; + return new HandoffPreparation(result, remoteHandoff); } Instant now = Instant.now(); + Optional existingHandoff = + handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal( + workItem.getTenantId(), workItem.getId(), command.ordinal()); + if (existingHandoff.isPresent()) { + ScriptHandoffEvent existing = existingHandoff.orElseThrow(); + if (!handoffIdentityMatches(existing, workItem, command, dispatchId)) { + return new HandoffPreparation( + new HandoffResult( + false, + ScriptHandoffOutcomeSupport.OUTCOME_REMOTE_REJECTED, + "", + "", + "", + ScriptHandoffOutcomeSupport.REASON_IDEMPOTENCY_CONFLICT, + "existing handoff child identity does not match request"), + remoteHandoff); + } + if (isAcceptedHandoff(existing)) { + return new HandoffPreparation(handoffResult(existing), remoteHandoff); + } + } workItem.setStatus(STATUS_HANDOFF_IN_FLIGHT); workItem.setUpdatedAt(now); workItemRepository.save(workItem); rolloutProjectionService.refreshForWorkItem(workItem); - EnqueueAutomationCommandIfAbsentResponse response = - remoteHandoff - ? null - : gameSessionClient.enqueueAutomationCommandIfAbsent( - toRequest(workItem, command, dispatchId)); - HandoffResult result; + ScriptHandoffEvent intent = appendHandoffIntent(workItem, command, dispatchId, now); + return new HandoffPreparation(null, remoteHandoff, intent.getRowVersion()); + } + + private HandoffResult invokeDownstream( + ScriptWorkItem workItem, EmittedCommand command, String dispatchId, boolean remoteHandoff) { if (remoteHandoff) { ScopeValidationResult scopeValidation = validateRemoteHandoffScope(workItem, command); if (scopeValidation != null) { - result = - new HandoffResult( - false, - ScriptHandoffOutcomeSupport.OUTCOME_REMOTE_REJECTED, - "", - "", - "", - scopeValidation.errorCode(), - scopeValidation.message()); - } else { - ScheduleRemoteFollowupResponse remoteResponse = - gameSessionClient.scheduleRemoteFollowup( - toRemoteScheduleRequest(workItem, command, dispatchId)); - result = remoteHandoffResult(remoteResponse); + return new HandoffResult( + false, + ScriptHandoffOutcomeSupport.OUTCOME_REMOTE_REJECTED, + "", + "", + "", + scopeValidation.errorCode(), + scopeValidation.message()); } - } else if (response == null) { - result = - new HandoffResult( - false, - ScriptHandoffOutcomeSupport.OUTCOME_REMOTE_REJECTED, - "", - "", - "", - ScriptHandoffOutcomeSupport.ERROR_REMOTE_RESPONSE_INVALID, - "local owner response was null"); - } else { - result = localHandoffResult(response); + ScheduleRemoteFollowupResponse remoteResponse = + gameSessionClient.scheduleRemoteFollowup( + toRemoteScheduleRequest(workItem, command, dispatchId)); + return remoteHandoffResult(remoteResponse); + } + EnqueueAutomationCommandIfAbsentResponse response = + gameSessionClient.enqueueAutomationCommandIfAbsent( + toRequest(workItem, command, dispatchId)); + if (response == null) { + return reconciliationRequiredResult("local owner response was null"); + } + return localHandoffResult(response); + } + + private HandoffResult persistDownstreamResponse( + ScriptWorkItem workItem, + EmittedCommand command, + String dispatchId, + HandoffResult result, + int intentRowVersion) { + if (isReconciliationRequired(result)) { + return result; } - applyOutcome(workItem, command, dispatchId, result, now); + if (handoffTransactionTemplate != null) { + Optional existingHandoff = + handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal( + workItem.getTenantId(), workItem.getId(), command.ordinal()); + if (existingHandoff.isEmpty()) { + return reconciliationRequiredResult("durable handoff intent was not found"); + } + ScriptHandoffEvent existing = existingHandoff.orElseThrow(); + if (isAcceptedHandoff(existing)) { + return handoffResult(existing); + } + if (intentRowVersion >= 0 && existing.getRowVersion() != intentRowVersion) { + return reconciliationRequiredResult("durable handoff intent fence advanced"); + } + } + applyOutcome(workItem, command, dispatchId, result, Instant.now()); return result; } @@ -352,27 +592,14 @@ private static HandoffResult localHandoffResult( if (normalize(response.getCommandId()).isBlank() || hasNonBlankErrorMetadata || !coherentOutcome) { - return new HandoffResult( - false, - ScriptHandoffOutcomeSupport.OUTCOME_REMOTE_REJECTED, - "", - "", - "", - ScriptHandoffOutcomeSupport.ERROR_REMOTE_RESPONSE_INVALID); + return reconciliationRequiredResult("local owner response was incomplete"); } return new HandoffResult(true, admissionOutcome, response.getCommandId(), "", "", ""); } private static HandoffResult remoteHandoffResult(ScheduleRemoteFollowupResponse remoteResponse) { if (remoteResponse == null) { - return new HandoffResult( - false, - ScriptHandoffOutcomeSupport.OUTCOME_REMOTE_REJECTED, - "", - "", - "", - ScriptHandoffOutcomeSupport.ERROR_REMOTE_RESPONSE_INVALID, - "remote owner response was null"); + return reconciliationRequiredResult("remote owner response was null"); } String remoteCoordinatorId = remoteResponse.getCoordinatorId(); String remoteFollowupId = remoteResponse.getFollowupId(); @@ -393,15 +620,114 @@ private static HandoffResult remoteHandoffResult(ScheduleRemoteFollowupResponse && !remoteCoordinatorId.isBlank() && remoteFollowupId != null && !remoteFollowupId.isBlank(); + if (!hasDurableIds) { + return reconciliationRequiredResult("remote owner response omitted durable identifiers"); + } return new HandoffResult( - hasDurableIds, - hasDurableIds - ? ScriptHandoffOutcomeSupport.OUTCOME_REMOTE_SCHEDULED - : ScriptHandoffOutcomeSupport.OUTCOME_REMOTE_REJECTED, + true, + ScriptHandoffOutcomeSupport.OUTCOME_REMOTE_SCHEDULED, "", remoteCoordinatorId, remoteFollowupId, - hasDurableIds ? "" : ScriptHandoffOutcomeSupport.ERROR_REMOTE_RESPONSE_INVALID); + ""); + } + + private static HandoffResult reconciliationRequiredResult(String message) { + return new HandoffResult( + false, + OUTCOME_HANDOFF_IN_FLIGHT, + "", + "", + "", + OUTCOME_HANDOFF_IN_FLIGHT, + message == null ? "" : message); + } + + private static HandoffResult reconciliationRequiredResult(Throwable failure) { + return reconciliationRequiredResult( + failure == null || failure.getMessage() == null ? "" : failure.getMessage()); + } + + private static HandoffResult retryablePreparationResult(Throwable failure) { + return new HandoffResult( + false, + ScriptHandoffOutcomeSupport.OUTCOME_REMOTE_REJECTED, + "", + "", + "", + "UNAVAILABLE", + failure == null || failure.getMessage() == null ? "" : failure.getMessage()); + } + + private static boolean isReconciliationRequired(HandoffResult result) { + return result != null + && (OUTCOME_HANDOFF_IN_FLIGHT.equalsIgnoreCase(normalize(result.outcome())) + || OUTCOME_HANDOFF_IN_FLIGHT.equalsIgnoreCase(normalize(result.errorCode()))); + } + + private static boolean isAcceptedHandoff(ScriptHandoffEvent event) { + String outcome = normalize(event.getHandoffOutcome()).trim().toUpperCase(Locale.ROOT); + return "ENQUEUED".equals(outcome) + || "DUPLICATE_NOOP".equals(outcome) + || "REMOTE_SCHEDULED".equals(outcome); + } + + private static HandoffResult handoffResult(ScriptHandoffEvent event) { + String outcome = normalize(event.getHandoffOutcome()).trim().toUpperCase(Locale.ROOT); + return new HandoffResult( + true, + outcome, + normalize(event.getGameSessionCommandId()), + normalize(event.getRemoteCoordinatorId()), + normalize(event.getRemoteFollowupId()), + ""); + } + + private static boolean handoffIdentityMatches( + ScriptHandoffEvent existing, + ScriptWorkItem workItem, + EmittedCommand command, + String dispatchId) { + RoutingBundleSupport.RoutingBundle routingBundle = + RoutingBundleSupport.normalize( + workItem.getWorldSlug(), workItem.getRealmSlug(), workItem.getPointerVersion()); + return Objects.equals(existing.getEventId(), handoffEventId(workItem, command.ordinal())) + && Objects.equals(existing.getTenantId(), workItem.getTenantId()) + && Objects.equals(existing.getGameInstanceId(), workItem.getGameInstanceId()) + && Objects.equals(existing.getScriptPatchVersion(), workItem.getScriptPatchVersion()) + && existing.getScriptPinEpoch() == workItem.getScriptPinEpoch() + && Objects.equals( + normalize(existing.getScriptPinControlPlaneRequestId()), + normalize(workItem.getScriptPinControlPlaneRequestId())) + && Objects.equals(existing.getScriptId(), workItem.getScriptId()) + && Objects.equals(normalize(existing.getBindingId()), normalize(workItem.getBindingId())) + && Objects.equals(normalize(existing.getPluginId()), normalize(workItem.getPluginId())) + && Objects.equals( + normalize(existing.getPluginVersionId()), normalize(workItem.getPluginVersionId())) + && existing.getPluginActivationEpoch() == workItem.getPluginActivationEpoch() + && existing.getLifecycleRevision() == workItem.getLifecycleRevision() + && Objects.equals(existing.getWorkItemId(), workItem.getId()) + && existing.getCommandOrdinal() == command.ordinal() + && Objects.equals(existing.getAutomationDispatchId(), dispatchId) + && Objects.equals( + normalize(existing.getTargetGameInstanceId()), + normalize(command.targetGameInstanceId())) + && Objects.equals( + normalize(existing.getTargetRegionId()), normalize(command.targetRegionId())) + && existing.getTargetRegionEpoch() == zeroIfNull(command.targetRegionEpoch()) + && Objects.equals(existing.getTargetEntityId(), command.targetEntityId()) + && Objects.equals( + normalize(existing.getPlayableStateScope()), + normalize(workItem.getPlayableStateScope())) + && Objects.equals(existing.getWorldSlug(), routingBundle.worldSlug()) + && Objects.equals(existing.getRealmSlug(), routingBundle.realmSlug()) + && Objects.equals(existing.getPointerVersion(), routingBundle.pointerVersion()) + && Objects.equals(existing.getSourceKind(), normalize(workItem.getSourceKind())) + && Objects.equals(existing.getSourceState(), normalize(workItem.getSourceState())) + && Objects.equals(existing.getSourceOrdinal(), workItem.getSourceOrdinal()) + && Objects.equals(existing.getSourceDueTickId(), workItem.getSourceDueTickId()) + && Objects.equals(existing.getSourceDueAtMs(), workItem.getSourceDueAtMs()) + && Objects.equals(existing.getEmittedCommandText(), command.commandText()); } private String admissionFenceReason(ScriptWorkItem workItem) { @@ -426,10 +752,9 @@ private String admissionFenceReason(ScriptWorkItem workItem) { } /** - * Uses the same transaction-scoped owner lock as admission mutations. The handoff method is - * transactional, so this lock remains held through the durable handoff outcome and the remote - * Game Session admission call; a concurrent pause cannot commit between the fence read and that - * call. Reentrant PostgreSQL advisory locks are safe for aggregate fan-out on one transaction. + * Uses the same transaction-scoped owner lock as admission mutations. The lock fences the pre-RPC + * admission read and intent commit; the RPC itself runs after that transaction commits and + * therefore never holds this local transaction open. */ private void lockAdmissionScope(ScriptWorkItem workItem) { if (dsl == null @@ -518,6 +843,31 @@ private enum RuntimeRegionScopeStatus { private record AggregateAdmissionSnapshot( String admissionFenceReason, RuntimeRegionScopeStatus runtimeRegionScopeStatus) {} + private record HandoffPreflight( + String admissionFenceReason, RuntimeRegionScopeStatus runtimeScopeStatus) { + static HandoffPreflight from(AggregateAdmissionSnapshot snapshot) { + return new HandoffPreflight( + snapshot.admissionFenceReason(), snapshot.runtimeRegionScopeStatus()); + } + } + + private HandoffPreflight preflight(ScriptWorkItem workItem) { + String admissionFenceReason = admissionFenceReason(workItem); + RuntimeRegionScopeStatus runtimeScopeStatus = + admissionFenceReason == null + ? runtimeRegionScopeStatusOutsideTransaction(workItem) + : RuntimeRegionScopeStatus.MALFORMED; + return new HandoffPreflight(admissionFenceReason, runtimeScopeStatus); + } + + private RuntimeRegionScopeStatus runtimeRegionScopeStatusOutsideTransaction( + ScriptWorkItem workItem) { + if (rpcTransactionTemplate == null) { + return runtimeRegionScopeStatus(workItem); + } + return rpcTransactionTemplate.execute(status -> runtimeRegionScopeStatus(workItem)); + } + private RuntimeRegionScopeStatus runtimeRegionScopeStatus(ScriptWorkItem workItem) { if (workItem.getTenantId() == null || workItem.getTenantId().isBlank() @@ -710,6 +1060,11 @@ private void applyOutcome( HandoffResult result, Instant now) { appendHandoffEvent(workItem, command, dispatchId, result, now); + if (isReconciliationRequired(result)) { + // A lost/ambiguous downstream response is not a terminal rejection. The child remains + // HANDOFF_IN_FLIGHT until a later exact-identity reconciliation determines the outcome. + return; + } if (result.accepted()) { // The executor owns the aggregate terminal outcome. This child is only durably accepted; // recording handoff_accepted here would falsely claim that all siblings were accepted. @@ -803,7 +1158,12 @@ private static String dispatchId(ScriptWorkItem workItem, int ordinal) { return "workItem:" + workItem.getId() + "#" + ordinal; } - private void appendHandoffEvent( + private ScriptHandoffEvent appendHandoffIntent( + ScriptWorkItem workItem, EmittedCommand command, String dispatchId, Instant now) { + return appendHandoffEvent(workItem, command, dispatchId, reconciliationRequiredResult(""), now); + } + + private ScriptHandoffEvent appendHandoffEvent( ScriptWorkItem workItem, EmittedCommand command, String dispatchId, @@ -859,7 +1219,8 @@ private void appendHandoffEvent( event.setId(existing.getId()); event.setRowVersion(existing.getRowVersion()); }); - handoffEventRepository.save(event); + ScriptHandoffEvent saved = handoffEventRepository.save(event); + return saved == null ? event : saved; } private static String handoffEventId(ScriptWorkItem workItem, int commandOrdinal) { @@ -867,6 +1228,9 @@ private static String handoffEventId(ScriptWorkItem workItem, int commandOrdinal } private static String handoffReason(HandoffResult result) { + if (isReconciliationRequired(result)) { + return REASON_HANDOFF_IN_FLIGHT; + } if (result.accepted()) { return result.remoteFollowupId().isBlank() ? "game_session_accepted" diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java index 52aa3ca923..c5a282cd35 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java @@ -58,6 +58,7 @@ public class ScriptWorkItemExecutionServiceImpl implements ScriptWorkItemExecuti private static final String STAGE_ADMISSION = "ADMISSION"; private static final String STAGE_DSL_EVAL = "DSL_EVAL"; private static final String OUTCOME_HANDOFF_ACCEPTED = "handoff_accepted"; + private static final String OUTCOME_HANDOFF_IN_FLIGHT = "HANDOFF_IN_FLIGHT"; private static final String OUTCOME_SANDBOX_ERROR = "sandbox_error"; private static final String OUTCOME_AUTHORITY_UNAVAILABLE_EXHAUSTED = "authority_unavailable_exhausted"; @@ -90,6 +91,26 @@ public class ScriptWorkItemExecutionServiceImpl implements ScriptWorkItemExecuti private final PluginRuntimeStateRepository pluginRuntimeStateRepository; private final TransactionTemplate transactionTemplate; + private record EvaluationResult( + boolean requiresHandoff, + List commands, + boolean completed) { + static EvaluationResult terminal(boolean completed) { + return new EvaluationResult(false, List.of(), completed); + } + + static EvaluationResult requiringHandoff( + List commands) { + return new EvaluationResult(true, List.copyOf(commands), false); + } + } + + private record HandoffExecutionResult( + String terminalFenceFailure, + ScriptGameplayCommandHandoffService.HandoffResult firstRejectedHandoff) {} + + private record EvaluationFencePrecheck(boolean checked, String failure) {} + /** Compatibility constructor for focused plugin-fence tests. */ public ScriptWorkItemExecutionServiceImpl( ScriptWorkItemService workItemService, @@ -428,13 +449,121 @@ public ExecutionBatchResult processPendingWorkItems(int maxItems) { return new ExecutionBatchResult(claimed.size(), completedCount, failedCount); } - /** Keeps each durable work-item transition and its remote calls in its own transaction. */ + /** + * Commits evaluation before entering the handoff loop. The handoff loop and its Game Session + * calls therefore never run inside this evaluator transaction; parent convergence is committed + * afterward in a separate local transaction. + */ private boolean processOneWorkItemInTransaction(ScriptWorkItem workItem) { + EvaluationFencePrecheck precheck = precheckEvaluationFences(workItem); + EvaluationResult evaluation = executeEvaluationTransaction(workItem, precheck); + if (!evaluation.requiresHandoff()) { + return evaluation.completed(); + } + String postEvaluationFenceFailure = validateCurrentExecutionFences(workItem); + if (postEvaluationFenceFailure != null) { + return executePostEvaluationFenceDisposition(workItem, postEvaluationFenceFailure); + } + commitPostEvaluationFenceState(workItem); + HandoffExecutionResult handoffResult = executeHandoffLoop(workItem, evaluation.commands()); + return executeHandoffFinalization(workItem, handoffResult); + } + + private EvaluationFencePrecheck precheckEvaluationFences(ScriptWorkItem workItem) { + if (authorityUnavailableRetryExpired(workItem, Instant.now())) { + return new EvaluationFencePrecheck(false, null); + } + return new EvaluationFencePrecheck(true, validateCurrentExecutionFences(workItem)); + } + + private EvaluationResult executeEvaluationTransaction( + ScriptWorkItem workItem, EvaluationFencePrecheck precheck) { if (transactionTemplate == null) { // Focused unit-test constructors intentionally have no transaction manager. - return processClaimedWorkItem(workItem); + return evaluateClaimedWorkItemTransaction(workItem, precheck); } - Boolean result = transactionTemplate.execute(status -> processClaimedWorkItem(workItem)); + EvaluationResult result = + transactionTemplate.execute( + status -> evaluateClaimedWorkItemTransaction(workItem, precheck)); + return result == null ? EvaluationResult.terminal(false) : result; + } + + private boolean executePostEvaluationFenceDisposition( + ScriptWorkItem workItem, String fenceFailure) { + if (transactionTemplate == null) { + applyPostEvaluationFenceDisposition(workItem, fenceFailure); + return false; + } + transactionTemplate.execute( + status -> { + applyPostEvaluationFenceDisposition(workItem, fenceFailure); + return null; + }); + return false; + } + + private void commitPostEvaluationFenceState(ScriptWorkItem workItem) { + if (transactionTemplate == null) { + clearAuthorityUnavailableRetryState(workItem); + return; + } + transactionTemplate.execute( + status -> { + clearAuthorityUnavailableRetryState(workItem); + return null; + }); + } + + private void applyPostEvaluationFenceDisposition(ScriptWorkItem workItem, String fenceFailure) { + Instant now = Instant.now(); + if (isTerminalFenceFailure(fenceFailure)) { + cancel(workItem, STAGE_ADMISSION, "stale_execution_fenced", fenceFailure, now); + } else { + requeueAfterAuthorityUnavailable(workItem, fenceFailure, now); + } + } + + private HandoffExecutionResult executeHandoffLoop( + ScriptWorkItem workItem, List commands) { + ScriptGameplayCommandHandoffService.HandoffResult firstRejectedHandoff = null; + String terminalFenceFailure = null; + handoffService.beginAggregateFanout(workItem); + try { + for (ScriptGameplayCommandHandoffService.EmittedCommand command : commands) { + PluginFenceValidation handoffPluginFence = validateCurrentPluginFence(workItem); + if (handoffPluginFence != null) { + if (handoffPluginFence.retryable()) { + throw new IllegalStateException(handoffPluginFence.reason()); + } + terminalFenceFailure = handoffPluginFence.reason(); + break; + } + ScriptGameplayCommandHandoffService.HandoffResult result = + handoffService.handoff(workItem, command); + if (!result.accepted() + && (firstRejectedHandoff == null + || isHandoffReconciliationRequired(result) + || (ScriptHandoffOutcomeSupport.isRetryable(firstRejectedHandoff) + && !ScriptHandoffOutcomeSupport.isRetryable(result)))) { + // Continue through the complete emitted set. The handoff owner records one durable + // attempted child per call; returning here would leave later siblings without either an + // attempted disposition or an explicit unattempted terminal record. + firstRejectedHandoff = result; + } + } + } finally { + handoffService.endAggregateFanout(workItem); + } + return new HandoffExecutionResult(terminalFenceFailure, firstRejectedHandoff); + } + + private boolean executeHandoffFinalization( + ScriptWorkItem workItem, HandoffExecutionResult handoffResult) { + if (transactionTemplate == null) { + return finalizeHandoff(workItem, handoffResult); + } + Boolean result = + transactionTemplate.execute(status -> finalizeHandoff(workItem, handoffResult)); return Boolean.TRUE.equals(result); } @@ -469,7 +598,8 @@ private List claimWorkItems(int maxItems) { return List.copyOf(combined); } - private boolean processClaimedWorkItem(ScriptWorkItem workItem) { + private EvaluationResult evaluateClaimedWorkItemTransaction( + ScriptWorkItem workItem, EvaluationFencePrecheck precheck) { Instant now = Instant.now(); if (authorityUnavailableRetryExpired(workItem, now)) { deadLetter( @@ -478,16 +608,16 @@ private boolean processClaimedWorkItem(ScriptWorkItem workItem) { OUTCOME_AUTHORITY_UNAVAILABLE_EXHAUSTED, OUTCOME_AUTHORITY_UNAVAILABLE_EXHAUSTED, now); - return false; + return EvaluationResult.terminal(false); } - String fenceFailure = validateCurrentExecutionFences(workItem); + String fenceFailure = precheck.checked() ? precheck.failure() : null; if (fenceFailure != null) { if (isTerminalFenceFailure(fenceFailure)) { cancel(workItem, STAGE_ADMISSION, "stale_execution_fenced", fenceFailure, now); } else { requeueAfterAuthorityUnavailable(workItem, fenceFailure, now); } - return false; + return EvaluationResult.terminal(false); } clearAuthorityUnavailableRetryState(workItem); PluginFenceValidation pluginFence = validateCurrentPluginFence(workItem); @@ -496,14 +626,14 @@ private boolean processClaimedWorkItem(ScriptWorkItem workItem) { throw new IllegalStateException(pluginFence.reason()); } cancel(workItem, STAGE_ADMISSION, "canceled", pluginFence.reason(), now); - return false; + return EvaluationResult.terminal(false); } if (!workItem.isDryRun() && ScriptQuotaClasses.consumesLiveTenantBudget(workItem.getQuotaClass()) && !tenantBudgetService.tryReserve( workItem.getTenantId(), normalizeReservationTier(workItem.getPriorityTag()))) { cancel(workItem, STAGE_ADMISSION, "tenant_budget_exceeded", "tenant_budget_exceeded", now); - return false; + return EvaluationResult.terminal(false); } if (!workItem.isDryRun() && ScriptQuotaClasses.usesPublishReadinessCapacity(workItem.getQuotaClass()) @@ -512,7 +642,7 @@ private boolean processClaimedWorkItem(ScriptWorkItem workItem) { readinessCapacityService.tryReserve(workItem.getTenantId(), requireWorkItemId(workItem)); if (reservation.isEmpty()) { cancel(workItem, STAGE_ADMISSION, "quota_denied", "onload_budget_exceeded", now); - return false; + return EvaluationResult.terminal(false); } try { return evaluateClaimedWorkItem(workItem, now); @@ -525,7 +655,7 @@ private boolean processClaimedWorkItem(ScriptWorkItem workItem) { dryRunCapacityService.tryReserve(workItem.getTenantId(), requireWorkItemId(workItem)); if (reservation.isEmpty()) { cancel(workItem, STAGE_ADMISSION, "quota_denied", "dry_run_capacity_exhausted", now); - return false; + return EvaluationResult.terminal(false); } try { return evaluateClaimedWorkItem(workItem, now); @@ -611,7 +741,7 @@ private String validateCurrentExecutionFences(ScriptWorkItem workItem) { workItem, activePluginVersionId, pluginState, pluginActivationEpoch, lifecycleRevision); } - private boolean evaluateClaimedWorkItem(ScriptWorkItem workItem, Instant now) { + private EvaluationResult evaluateClaimedWorkItem(ScriptWorkItem workItem, Instant now) { // Capacity admission may have taken time. Re-read plugin authority immediately before // definition lookup/DSL parsing so a stale or unavailable lifecycle cannot reach even a // zero-command success path. @@ -621,21 +751,21 @@ private boolean evaluateClaimedWorkItem(ScriptWorkItem workItem, Instant now) { throw new IllegalStateException(pluginFence.reason()); } cancel(workItem, STAGE_DSL_EVAL, "canceled", pluginFence.reason(), now); - return false; + return EvaluationResult.terminal(false); } final long tenantId; try { tenantId = parseTenantId(workItem); } catch (IllegalArgumentException ex) { deadLetter(workItem, STAGE_DSL_EVAL, "definition_invalid", "tenant_id_invalid", now); - return false; + return EvaluationResult.terminal(false); } Optional definition = scriptDefinitionRepository.findByTenantIdAndScriptVersionAndName( tenantId, workItem.getScriptPatchVersion(), workItem.getScriptId()); if (definition.isEmpty()) { deadLetter(workItem, STAGE_DSL_EVAL, "definition_missing", "script_definition_missing", now); - return false; + return EvaluationResult.terminal(false); } JsonNode definitionRoot; @@ -643,14 +773,14 @@ private boolean evaluateClaimedWorkItem(ScriptWorkItem workItem, Instant now) { definitionRoot = parseDefinitionRoot(definition.get().getDefinition()); } catch (IllegalArgumentException ex) { deadLetter(workItem, STAGE_DSL_EVAL, "definition_invalid", ex.getMessage(), now); - return false; + return EvaluationResult.terminal(false); } if (isOnLoad(workItem)) { if (declaresCommands(definitionRoot, workItem.getEventType())) { deadLetter( workItem, STAGE_DSL_EVAL, "definition_invalid", "onload_commands_not_allowed", now); - return false; + return EvaluationResult.terminal(false); } } @@ -665,7 +795,7 @@ private boolean evaluateClaimedWorkItem(ScriptWorkItem workItem, Instant now) { ? OUTCOME_SANDBOX_ERROR : "definition_invalid"; deadLetter(workItem, STAGE_DSL_EVAL, outcome, reason, now); - return false; + return EvaluationResult.terminal(false); } if (commands.isEmpty() || workItem.isDryRun()) { @@ -677,51 +807,30 @@ private boolean evaluateClaimedWorkItem(ScriptWorkItem workItem, Instant now) { ? "dry_run_no_handoff" : isOnLoad(workItem) ? "ready_for_tenant" : "script_emitted_no_commands", now); - return true; + return EvaluationResult.terminal(true); } - // DSL evaluation is not the effect boundary. Re-read every authoritative execution fence - // after evaluation and immediately before the first gameplay handoff so a repin, plugin ABA, - // lifecycle transition, or policy revocation that won during evaluation cannot emit effects. - String handoffFenceFailure = validateCurrentExecutionFences(workItem); - if (handoffFenceFailure != null) { - if (isTerminalFenceFailure(handoffFenceFailure)) { - cancel(workItem, STAGE_ADMISSION, "stale_execution_fenced", handoffFenceFailure, now); - } else { - requeueAfterAuthorityUnavailable(workItem, handoffFenceFailure, now); - } - return false; - } - clearAuthorityUnavailableRetryState(workItem); + // The final authoritative execution fence is read outside the evaluator transaction by the + // caller immediately before entering the handoff loop. This keeps Game Session RPCs outside + // every local transaction while preserving the post-evaluation fence boundary. + return EvaluationResult.requiringHandoff(commands); + } - ScriptGameplayCommandHandoffService.HandoffResult firstRejectedHandoff = null; - handoffService.beginAggregateFanout(workItem); - try { - for (ScriptGameplayCommandHandoffService.EmittedCommand command : commands) { - PluginFenceValidation handoffPluginFence = validateCurrentPluginFence(workItem); - if (handoffPluginFence != null) { - if (handoffPluginFence.retryable()) { - throw new IllegalStateException(handoffPluginFence.reason()); - } - cancel(workItem, STAGE_DSL_EVAL, "canceled", handoffPluginFence.reason(), now); - return false; - } - ScriptGameplayCommandHandoffService.HandoffResult result = - handoffService.handoff(workItem, command); - if (!result.accepted() - && (firstRejectedHandoff == null - || (ScriptHandoffOutcomeSupport.isRetryable(firstRejectedHandoff) - && !ScriptHandoffOutcomeSupport.isRetryable(result)))) { - // Continue through the complete emitted set. The handoff owner records one durable - // attempted child per call; returning here would leave later siblings without either an - // attempted disposition or an explicit unattempted terminal record. - firstRejectedHandoff = result; - } - } - } finally { - handoffService.endAggregateFanout(workItem); + private boolean finalizeHandoff(ScriptWorkItem workItem, HandoffExecutionResult handoffResult) { + Instant now = Instant.now(); + if (handoffResult.terminalFenceFailure() != null) { + cancel(workItem, STAGE_DSL_EVAL, "canceled", handoffResult.terminalFenceFailure(), now); + return false; } + ScriptGameplayCommandHandoffService.HandoffResult firstRejectedHandoff = + handoffResult.firstRejectedHandoff(); if (firstRejectedHandoff != null) { + if (isHandoffReconciliationRequired(firstRejectedHandoff)) { + // The durable child intent is already committed. An ambiguous downstream response must + // remain active for exact-identity reconciliation; requeueing or dead-lettering here would + // erase the distinction between unknown outcome and a definitive handoff failure. + return false; + } if (ScriptHandoffOutcomeSupport.isRetryable(firstRejectedHandoff)) { requeueAfterRetryableHandoff(workItem); return false; @@ -1296,6 +1405,18 @@ private void recordTerminalHandoffOutcome( now); } + private static boolean isHandoffReconciliationRequired( + ScriptGameplayCommandHandoffService.HandoffResult result) { + return result != null + && (OUTCOME_HANDOFF_IN_FLIGHT.equalsIgnoreCase(normalizeHandoffToken(result.outcome())) + || OUTCOME_HANDOFF_IN_FLIGHT.equalsIgnoreCase( + normalizeHandoffToken(result.errorCode()))); + } + + private static String normalizeHandoffToken(String value) { + return value == null ? "" : value.trim(); + } + private static long parseTenantId(ScriptWorkItem workItem) { return RequestIdValidation.requirePositiveLong(workItem.getTenantId(), "tenant_id"); } diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java index a342a028ea..4420912224 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java @@ -37,23 +37,24 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.SimpleTransactionStatus; import org.springframework.transaction.support.TransactionSynchronizationManager; class ScriptGameplayCommandHandoffServiceImplTest { @Test - void beginAggregateFanoutRequiresExistingTransaction() throws NoSuchMethodException { + void beginAggregateFanoutUsesShortIntentBoundary() throws NoSuchMethodException { Method method = ScriptGameplayCommandHandoffServiceImpl.class.getMethod( "beginAggregateFanout", ScriptWorkItem.class); - assertThat(method.getAnnotation(Transactional.class)).isNotNull(); - assertThat(method.getAnnotation(Transactional.class).propagation()) - .isEqualTo(org.springframework.transaction.annotation.Propagation.MANDATORY); + assertThat(method.getAnnotation(Transactional.class)).isNull(); } @Test - void locksAdmissionScopeBeforeFenceReadAndRemoteAdmissionInsideTransactionalBoundary() - throws NoSuchMethodException { + void preflightsAdmissionBeforeRuntimeReadAndRemoteAdmission() throws NoSuchMethodException { GameSessionControlPlaneClient gameSessionClient = Mockito.mock(GameSessionControlPlaneClient.class); when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) @@ -92,9 +93,10 @@ void locksAdmissionScopeBeforeFenceReadAndRemoteAdmissionInsideTransactionalBoun service.handoff( workItem(), emittedCommand("say hello", "target-entity-1", "7", "region-1", 12L, 34L, 0)); - org.mockito.InOrder ordering = Mockito.inOrder(dsl, admissionService, gameSessionClient); - ordering.verify(dsl).execute(Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); + org.mockito.InOrder ordering = Mockito.inOrder(admissionService, gameSessionClient, dsl); ordering.verify(admissionService).getState("1", "7", "region-1"); + ordering.verify(gameSessionClient).getGameInstanceRuntimeState("1", "7", "region-1"); + ordering.verify(dsl).execute(Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt()); ordering.verify(gameSessionClient).enqueueAutomationCommandIfAbsent(Mockito.any()); assertThat( ScriptGameplayCommandHandoffServiceImpl.class @@ -103,7 +105,7 @@ void locksAdmissionScopeBeforeFenceReadAndRemoteAdmissionInsideTransactionalBoun ScriptWorkItem.class, ScriptGameplayCommandHandoffService.EmittedCommand.class) .getAnnotation(Transactional.class)) - .isNotNull(); + .isNull(); assertThat( Arrays.stream(ScriptGameplayCommandHandoffServiceImpl.class.getConstructors()) .filter(constructor -> constructor.isAnnotationPresent(Autowired.class)) @@ -111,6 +113,144 @@ void locksAdmissionScopeBeforeFenceReadAndRemoteAdmissionInsideTransactionalBoun .isEqualTo(1L); } + @Test + void intentCommitsBeforeGameSessionRpcAndRpcRunsWithoutLocalTransaction() { + List operations = new ArrayList<>(); + RecordingTransactionManager transactionManager = new RecordingTransactionManager(operations); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenAnswer( + invocation -> { + operations.add( + "runtime:" + TransactionSynchronizationManager.isActualTransactionActive()); + return currentRuntimeState(); + }); + when(gameSessionClient.enqueueAutomationCommandIfAbsent(Mockito.any())) + .thenAnswer( + invocation -> { + operations.add( + "enqueue:" + TransactionSynchronizationManager.isActualTransactionActive()); + return EnqueueAutomationCommandIfAbsentResponse.newBuilder() + .setAccepted(true) + .setAdmissionOutcome("ENQUEUED") + .setCommandId("command-1") + .build(); + }); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + when(workItemRepository.save(Mockito.any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + ScriptHandoffEventRepository handoffEventRepository = + Mockito.mock(ScriptHandoffEventRepository.class); + List savedEvents = new ArrayList<>(); + when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) + .thenAnswer( + invocation -> + savedEvents.isEmpty() ? Optional.empty() : Optional.of(savedEvents.getLast())); + when(handoffEventRepository.save(Mockito.any())) + .thenAnswer( + invocation -> { + ScriptHandoffEvent event = invocation.getArgument(0); + savedEvents.add(event); + operations.add( + "handoff-save:" + + ("handoff_in_flight".equals(event.getHandoffOutcome()) + ? "intent" + : "response")); + return event; + }); + + ScriptGameplayCommandHandoffServiceImpl service = + new ScriptGameplayCommandHandoffServiceImpl( + gameSessionClient, + workItemRepository, + Mockito.mock(ScriptEventAuditRepository.class), + handoffEventRepository, + null, + null, + admissionStateService(), + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + transactionManager); + + TransactionSynchronizationManager.setActualTransactionActive(false); + try { + ScriptGameplayCommandHandoffService.HandoffResult result = + service.handoff( + workItem(), emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0)); + + assertThat(result.accepted()).isTrue(); + assertThat(operations) + .contains( + "runtime:false", "handoff-save:intent", "enqueue:false", "handoff-save:response"); + assertThat(operations.indexOf("handoff-save:intent")) + .isLessThan(operations.indexOf("tx-commit-2")); + assertThat(operations.indexOf("tx-commit-2")).isLessThan(operations.indexOf("enqueue:false")); + assertThat(operations.indexOf("enqueue:false")) + .isLessThan(operations.indexOf("handoff-save:response")); + assertThat(transactionManager.propagations()) + .containsExactly( + TransactionDefinition.PROPAGATION_NOT_SUPPORTED, + TransactionDefinition.PROPAGATION_REQUIRES_NEW, + TransactionDefinition.PROPAGATION_NOT_SUPPORTED, + TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } + + @Test + void failedIntentCommitIsRetryableAndNeverClaimsInFlightOrCallsCommandRpc() { + FailingIntentCommitTransactionManager transactionManager = + new FailingIntentCommitTransactionManager(); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenReturn(currentRuntimeState()); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + when(workItemRepository.save(Mockito.any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + ScriptHandoffEventRepository handoffEventRepository = + Mockito.mock(ScriptHandoffEventRepository.class); + when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) + .thenReturn(Optional.empty()); + when(handoffEventRepository.save(Mockito.any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + ScriptGameplayCommandHandoffServiceImpl service = + new ScriptGameplayCommandHandoffServiceImpl( + gameSessionClient, + workItemRepository, + Mockito.mock(ScriptEventAuditRepository.class), + handoffEventRepository, + null, + null, + admissionStateService(), + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + transactionManager); + + TransactionSynchronizationManager.setActualTransactionActive(false); + try { + ScriptGameplayCommandHandoffService.HandoffResult result = + service.handoff( + workItem(), emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0)); + + assertThat(result.accepted()).isFalse(); + assertThat(result.outcome()).isEqualTo("REMOTE_REJECTED"); + assertThat(result.errorCode()).isEqualTo("UNAVAILABLE"); + assertThat(ScriptHandoffOutcomeSupport.isRetryable(result)).isTrue(); + assertThat(result.outcome()).isNotEqualTo("HANDOFF_IN_FLIGHT"); + assertThat(result.errorCode()).isNotEqualTo("HANDOFF_IN_FLIGHT"); + verify(gameSessionClient).getGameInstanceRuntimeState("1", "7", "region-1"); + verify(gameSessionClient, never()).enqueueAutomationCommandIfAbsent(Mockito.any()); + verify(gameSessionClient, never()).scheduleRemoteFollowup(Mockito.any()); + assertThat(transactionManager.propagations()) + .containsExactly( + TransactionDefinition.PROPAGATION_NOT_SUPPORTED, + TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } + @Test void corruptAdmissionModeFailsClosedBeforeRuntimeOrGameSessionAdmission() { GameSessionControlPlaneClient gameSessionClient = @@ -415,20 +555,23 @@ void acceptedGameSessionOutcomeLeavesAggregateTerminalizationToExecutor() { assertThat(audit.getFinalReason()).isNull(); ArgumentCaptor handoffCaptor = ArgumentCaptor.forClass(ScriptHandoffEvent.class); - verify(handoffEventRepository).save(handoffCaptor.capture()); - assertThat(handoffCaptor.getValue().getAutomationDispatchId()).isEqualTo("workItem:99#0"); - assertThat(handoffCaptor.getValue().getGameSessionCommandId()).isEqualTo("auto-1"); - assertThat(handoffCaptor.getValue().getTargetGameInstanceId()).isEqualTo("7"); - assertThat(handoffCaptor.getValue().getTargetRegionId()).isEqualTo("region-1"); - assertThat(handoffCaptor.getValue().getTargetRegionEpoch()).isEqualTo(12L); - assertThat(handoffCaptor.getValue().getRemoteCoordinatorId()).isBlank(); - assertThat(handoffCaptor.getValue().getRemoteFollowupId()).isBlank(); - assertThat(handoffCaptor.getValue().getSourceKind()).isEqualTo("SCHEDULE_TIMER"); - assertThat(handoffCaptor.getValue().getSourceState()).isEqualTo("SCHEDULE_DUE_CLAIMED"); - assertThat(handoffCaptor.getValue().getSourceOrdinal()).isEqualTo(5000L); - assertThat(handoffCaptor.getValue().getEmittedCommandText()).isEqualTo("say hello"); - assertThat(handoffCaptor.getValue().getHandoffOutcome()).isEqualTo("enqueued"); - assertThat(handoffCaptor.getValue().getEventId()).isEqualTo("she-work-item-99-command-0"); + verify(handoffEventRepository, Mockito.times(2)).save(handoffCaptor.capture()); + assertThat(handoffCaptor.getAllValues().getFirst().getHandoffOutcome()) + .isEqualTo("handoff_in_flight"); + ScriptHandoffEvent persistedOutcome = handoffCaptor.getAllValues().getLast(); + assertThat(persistedOutcome.getAutomationDispatchId()).isEqualTo("workItem:99#0"); + assertThat(persistedOutcome.getGameSessionCommandId()).isEqualTo("auto-1"); + assertThat(persistedOutcome.getTargetGameInstanceId()).isEqualTo("7"); + assertThat(persistedOutcome.getTargetRegionId()).isEqualTo("region-1"); + assertThat(persistedOutcome.getTargetRegionEpoch()).isEqualTo(12L); + assertThat(persistedOutcome.getRemoteCoordinatorId()).isBlank(); + assertThat(persistedOutcome.getRemoteFollowupId()).isBlank(); + assertThat(persistedOutcome.getSourceKind()).isEqualTo("SCHEDULE_TIMER"); + assertThat(persistedOutcome.getSourceState()).isEqualTo("SCHEDULE_DUE_CLAIMED"); + assertThat(persistedOutcome.getSourceOrdinal()).isEqualTo(5000L); + assertThat(persistedOutcome.getEmittedCommandText()).isEqualTo("say hello"); + assertThat(persistedOutcome.getHandoffOutcome()).isEqualTo("enqueued"); + assertThat(persistedOutcome.getEventId()).isEqualTo("she-work-item-99-command-0"); } @Test @@ -470,11 +613,20 @@ void duplicateNoopRetryReusesStableHandoffEventIdentity() { ArgumentCaptor handoffCaptor = ArgumentCaptor.forClass(ScriptHandoffEvent.class); - verify(handoffEventRepository, Mockito.times(2)).save(handoffCaptor.capture()); + verify(handoffEventRepository, Mockito.times(4)).save(handoffCaptor.capture()); assertThat(handoffCaptor.getAllValues()) .extracting(ScriptHandoffEvent::getEventId) - .containsExactly("she-work-item-99-command-0", "she-work-item-99-command-0"); - assertThat(handoffCaptor.getAllValues().get(1).getHandoffOutcome()).isEqualTo("duplicate_noop"); + .containsExactly( + "she-work-item-99-command-0", + "she-work-item-99-command-0", + "she-work-item-99-command-0", + "she-work-item-99-command-0"); + assertThat(handoffCaptor.getAllValues().get(0).getHandoffOutcome()) + .isEqualTo("handoff_in_flight"); + assertThat(handoffCaptor.getAllValues().get(1).getHandoffOutcome()).isEqualTo("enqueued"); + assertThat(handoffCaptor.getAllValues().get(2).getHandoffOutcome()) + .isEqualTo("handoff_in_flight"); + assertThat(handoffCaptor.getAllValues().get(3).getHandoffOutcome()).isEqualTo("duplicate_noop"); } @Test @@ -520,13 +672,21 @@ void lostLocalResponseRetryConvergesToDuplicateNoopWithStableIdentity() { ArgumentCaptor handoffCaptor = ArgumentCaptor.forClass(ScriptHandoffEvent.class); - verify(handoffEventRepository, Mockito.times(2)).save(handoffCaptor.capture()); + verify(handoffEventRepository, Mockito.times(4)).save(handoffCaptor.capture()); assertThat(handoffCaptor.getAllValues()) .extracting(ScriptHandoffEvent::getEventId) - .containsExactly("she-work-item-99-command-0", "she-work-item-99-command-0"); + .containsExactly( + "she-work-item-99-command-0", + "she-work-item-99-command-0", + "she-work-item-99-command-0", + "she-work-item-99-command-0"); assertThat(handoffCaptor.getAllValues().get(0).getHandoffOutcome()) + .isEqualTo("handoff_in_flight"); + assertThat(handoffCaptor.getAllValues().get(1).getHandoffOutcome()) .isEqualTo("game_session_unavailable"); - assertThat(handoffCaptor.getAllValues().get(1).getHandoffOutcome()).isEqualTo("duplicate_noop"); + assertThat(handoffCaptor.getAllValues().get(2).getHandoffOutcome()) + .isEqualTo("handoff_in_flight"); + assertThat(handoffCaptor.getAllValues().get(3).getHandoffOutcome()).isEqualTo("duplicate_noop"); } @Test @@ -587,9 +747,42 @@ void reusedHandoffIdentityCarriesExistingRowVersionIntoOptimisticSave() { .build()); ScriptHandoffEventRepository handoffEventRepository = Mockito.mock(ScriptHandoffEventRepository.class); + ScriptWorkItem item = workItem(); + ScriptGameplayCommandHandoffService.EmittedCommand command = + emittedCommand("say hello", "target-entity-1", "7", "region-1", 12L, 34L, 0); ScriptHandoffEvent existing = new ScriptHandoffEvent(); existing.setId(44L); existing.setRowVersion(7); + existing.setEventId("she-work-item-99-command-0"); + existing.setTenantId(item.getTenantId()); + existing.setGameInstanceId(item.getGameInstanceId()); + existing.setScriptPatchVersion(item.getScriptPatchVersion()); + existing.setScriptPinEpoch(item.getScriptPinEpoch()); + existing.setScriptPinControlPlaneRequestId(item.getScriptPinControlPlaneRequestId()); + existing.setScriptId(item.getScriptId()); + existing.setBindingId(item.getBindingId()); + existing.setPluginId(item.getPluginId()); + existing.setPluginVersionId(item.getPluginVersionId()); + existing.setPluginActivationEpoch(item.getPluginActivationEpoch()); + existing.setLifecycleRevision(item.getLifecycleRevision()); + existing.setWorkItemId(item.getId()); + existing.setCommandOrdinal(command.ordinal()); + existing.setAutomationDispatchId("workItem:99#0"); + existing.setTargetGameInstanceId(command.targetGameInstanceId()); + existing.setTargetRegionId(command.targetRegionId()); + existing.setTargetRegionEpoch(command.targetRegionEpoch()); + existing.setTargetEntityId(command.targetEntityId()); + existing.setPlayableStateScope(item.getPlayableStateScope()); + existing.setWorldSlug(item.getWorldSlug()); + existing.setRealmSlug(item.getRealmSlug()); + existing.setPointerVersion(item.getPointerVersion()); + existing.setSourceKind(item.getSourceKind()); + existing.setSourceState(item.getSourceState()); + existing.setSourceOrdinal(item.getSourceOrdinal()); + existing.setSourceDueTickId(item.getSourceDueTickId()); + existing.setSourceDueAtMs(item.getSourceDueAtMs()); + existing.setEmittedCommandText(command.commandText()); + existing.setHandoffOutcome("handoff_in_flight"); when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) .thenReturn(Optional.of(existing)); ScriptGameplayCommandHandoffServiceImpl service = @@ -601,8 +794,7 @@ void reusedHandoffIdentityCarriesExistingRowVersionIntoOptimisticSave() { admissionStateService(), Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class)); - service.handoff( - workItem(), emittedCommand("say hello", "target-entity-1", "7", "region-1", 12L, 34L, 0)); + service.handoff(item, command); ArgumentCaptor handoffCaptor = ArgumentCaptor.forClass(ScriptHandoffEvent.class); @@ -663,13 +855,13 @@ void fanoutRejectionRecordsChildButDefersAggregateTerminalizationToExecutor() { assertThat(audit.getFinalStage()).isNull(); assertThat(audit.getFinalOutcome()).isNull(); verify(workItemRepository).save(Mockito.any(ScriptWorkItem.class)); - verify(handoffEventRepository).save(Mockito.any(ScriptHandoffEvent.class)); + verify(handoffEventRepository, Mockito.times(2)).save(Mockito.any(ScriptHandoffEvent.class)); verify(auditRepository, never()).save(Mockito.any(ScriptEventAudit.class)); service.handoff( item, emittedCommand("say hello again", "target-entity-2", "7", "region-1", 12L, 35L, 1)); verify(gameSessionClient, Mockito.times(1)).getGameInstanceRuntimeState("1", "7", "region-1"); - verify(admissionService, Mockito.times(1)).getState("1", "7", "region-1"); + verify(admissionService, Mockito.times(3)).getState("1", "7", "region-1"); } finally { service.endAggregateFanout(item); } @@ -678,7 +870,54 @@ void fanoutRejectionRecordsChildButDefersAggregateTerminalizationToExecutor() { item, emittedCommand("say hello after fanout", "target-entity-3", "7", "region-1", 12L, 35L, 2)); verify(gameSessionClient, Mockito.times(2)).getGameInstanceRuntimeState("1", "7", "region-1"); - verify(admissionService, Mockito.times(2)).getState("1", "7", "region-1"); + verify(admissionService, Mockito.times(4)).getState("1", "7", "region-1"); + } + + @Test + void aggregateChildRereadsAdmissionFenceBeforeIntentCommit() { + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenReturn(currentRuntimeState()); + AutomationAdmissionStateService admissionService = + Mockito.mock(AutomationAdmissionStateService.class); + when(admissionService.getState("1", "7", "region-1")) + .thenReturn( + new AutomationAdmissionStateService.AdmissionStateSummary( + "1", "7", "region-1", "NORMAL", 1L, "", "", 100L), + new AutomationAdmissionStateService.AdmissionStateSummary( + "1", "7", "region-1", "PAUSED_FOR_ROLLBACK", 1L, "admin", "pause", 101L)); + ScriptHandoffEventRepository handoffEventRepository = + Mockito.mock(ScriptHandoffEventRepository.class); + ScriptGameplayCommandHandoffServiceImpl service = + new ScriptGameplayCommandHandoffServiceImpl( + gameSessionClient, + Mockito.mock(ScriptWorkItemRepository.class), + Mockito.mock(ScriptEventAuditRepository.class), + handoffEventRepository, + admissionService, + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class)); + ScriptWorkItem item = workItem(); + + service.beginAggregateFanout(item); + try { + ScriptGameplayCommandHandoffService.HandoffResult result = + service.handoff( + item, emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0)); + + assertThat(result.accepted()).isFalse(); + assertThat(result.errorCode()).isEqualTo("RUNTIME_PAUSED"); + verify(admissionService, Mockito.times(2)).getState("1", "7", "region-1"); + verify(gameSessionClient, Mockito.never()).enqueueAutomationCommandIfAbsent(Mockito.any()); + verify(gameSessionClient, Mockito.never()).scheduleRemoteFollowup(Mockito.any()); + ArgumentCaptor handoffCaptor = + ArgumentCaptor.forClass(ScriptHandoffEvent.class); + verify(handoffEventRepository).save(handoffCaptor.capture()); + assertThat(handoffCaptor.getValue().getHandoffOutcome()).isEqualTo("runtime_paused"); + assertThat(handoffCaptor.getValue().getHandoffReason()).isEqualTo("runtime_paused"); + } finally { + service.endAggregateFanout(item); + } } @Test @@ -723,13 +962,12 @@ void fanoutExceptionCleanupAllowsLaterHandoffToRereadAuthority() { service.beginAggregateFanout(item); try { - org.assertj.core.api.Assertions.assertThatThrownBy( - () -> - service.handoff( - item, - emittedCommand("say hello", "target-entity-1", "7", "region-1", 12L, 34L, 0))) - .isInstanceOf(IllegalStateException.class) - .hasMessage("queue unavailable"); + ScriptGameplayCommandHandoffService.HandoffResult ambiguous = + service.handoff( + item, emittedCommand("say hello", "target-entity-1", "7", "region-1", 12L, 34L, 0)); + assertThat(ambiguous.accepted()).isFalse(); + assertThat(ambiguous.outcome()).isEqualTo("HANDOFF_IN_FLIGHT"); + assertThat(item.getStatus()).isEqualTo("HANDOFF_IN_FLIGHT"); } finally { service.endAggregateFanout(item); } @@ -741,11 +979,11 @@ void fanoutExceptionCleanupAllowsLaterHandoffToRereadAuthority() { assertThat(result.accepted()).isTrue(); verify(gameSessionClient, Mockito.times(2)).getGameInstanceRuntimeState("1", "7", "region-1"); - verify(admissionService, Mockito.times(2)).getState("1", "7", "region-1"); + verify(admissionService, Mockito.times(3)).getState("1", "7", "region-1"); } @Test - void malformedAcceptedGameSessionOutcomeIsRejectedWithoutAggregateAcceptance() { + void malformedAcceptedGameSessionOutcomeRetainsInFlightReconciliationEvidence() { GameSessionControlPlaneClient gameSessionClient = Mockito.mock(GameSessionControlPlaneClient.class); when(gameSessionClient.enqueueAutomationCommandIfAbsent(Mockito.any())) @@ -789,19 +1027,19 @@ void malformedAcceptedGameSessionOutcomeIsRejectedWithoutAggregateAcceptance() { item, emittedCommand("say hello", "target-entity-1", "7", "region-1", 12L, 34L, 0)); assertThat(result.accepted()).isFalse(); - assertThat(result.errorCode()).isEqualTo("REMOTE_RESPONSE_INVALID"); - assertThat(item.getStatus()).isEqualTo("DEAD_LETTERED"); - assertThat(item.getFailureGeneration()).isEqualTo(1L); - assertThat(result.outcome()).isEqualTo("REMOTE_REJECTED"); - assertThat(audit.getFinalStage()).isEqualTo("TICK_HANDOFF"); - assertThat(audit.getFinalOutcome()).isEqualTo("infrastructure_error"); - assertThat(audit.getFinalReason()).isEqualTo("remote_response_invalid"); + assertThat(result.errorCode()).isEqualTo("HANDOFF_IN_FLIGHT"); + assertThat(item.getStatus()).isEqualTo("HANDOFF_IN_FLIGHT"); + assertThat(item.getFailureGeneration()).isZero(); + assertThat(result.outcome()).isEqualTo("HANDOFF_IN_FLIGHT"); + assertThat(audit.getFinalStage()).isNull(); + assertThat(audit.getFinalOutcome()).isNull(); + assertThat(audit.getFinalReason()).isNull(); verify(handoffEventRepository) .save( Mockito.argThat( event -> - "remote_rejected".equals(event.getHandoffOutcome()) - && "remote_response_invalid".equals(event.getHandoffReason()))); + "handoff_in_flight".equals(event.getHandoffOutcome()) + && "handoff_in_flight".equals(event.getHandoffReason()))); } @Test @@ -857,8 +1095,8 @@ void nullLocalOwnerResponseFailsClosedWithoutSchedulingRemoteFollowup() { workItem(), emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0)); assertThat(result.accepted()).isFalse(); - assertThat(result.outcome()).isEqualTo("REMOTE_REJECTED"); - assertThat(result.errorCode()).isEqualTo("REMOTE_RESPONSE_INVALID"); + assertThat(result.outcome()).isEqualTo("HANDOFF_IN_FLIGHT"); + assertThat(result.errorCode()).isEqualTo("HANDOFF_IN_FLIGHT"); verify(gameSessionClient).enqueueAutomationCommandIfAbsent(Mockito.any()); verify(gameSessionClient, never()).scheduleRemoteFollowup(Mockito.any()); } @@ -1031,8 +1269,8 @@ void nullRemoteOwnerResponseFailsClosedWithoutLocalEnqueue() { workItem(), emittedCommand("say hello", "entity-remote", "8", "region-2", 77L, 45L, 0)); assertThat(result.accepted()).isFalse(); - assertThat(result.outcome()).isEqualTo("REMOTE_REJECTED"); - assertThat(result.errorCode()).isEqualTo("REMOTE_RESPONSE_INVALID"); + assertThat(result.outcome()).isEqualTo("HANDOFF_IN_FLIGHT"); + assertThat(result.errorCode()).isEqualTo("HANDOFF_IN_FLIGHT"); verify(gameSessionClient, never()).enqueueAutomationCommandIfAbsent(Mockito.any()); verify(gameSessionClient).scheduleRemoteFollowup(Mockito.any()); } @@ -1188,8 +1426,9 @@ void persistsIdempotencyConflictAsBoundedHandoffReason() { ArgumentCaptor handoffCaptor = ArgumentCaptor.forClass(ScriptHandoffEvent.class); - verify(handoffEventRepository).save(handoffCaptor.capture()); - assertThat(handoffCaptor.getValue().getHandoffReason()).isEqualTo("idempotency_conflict"); + verify(handoffEventRepository, Mockito.times(2)).save(handoffCaptor.capture()); + assertThat(handoffCaptor.getAllValues().getLast().getHandoffReason()) + .isEqualTo("idempotency_conflict"); } @Test @@ -1247,12 +1486,13 @@ void staleTimelineGameSessionOutcomeCancelsWorkItem() { assertThat(audit.getFinalReason()).isEqualTo("runtime_scope_changed"); ArgumentCaptor handoffCaptor = ArgumentCaptor.forClass(ScriptHandoffEvent.class); - verify(handoffEventRepository).save(handoffCaptor.capture()); - assertThat(handoffCaptor.getValue().getSourceKind()).isEqualTo("SCHEDULE_TIMER"); - assertThat(handoffCaptor.getValue().getSourceState()).isEqualTo("SCHEDULE_DUE_CLAIMED"); - assertThat(handoffCaptor.getValue().getEmittedCommandText()).isEqualTo("say hello"); - assertThat(handoffCaptor.getValue().getHandoffOutcome()).isEqualTo("rejected"); - assertThat(handoffCaptor.getValue().getHandoffReason()).isEqualTo("runtime_scope_changed"); + verify(handoffEventRepository, Mockito.times(2)).save(handoffCaptor.capture()); + ScriptHandoffEvent persistedOutcome = handoffCaptor.getAllValues().getLast(); + assertThat(persistedOutcome.getSourceKind()).isEqualTo("SCHEDULE_TIMER"); + assertThat(persistedOutcome.getSourceState()).isEqualTo("SCHEDULE_DUE_CLAIMED"); + assertThat(persistedOutcome.getEmittedCommandText()).isEqualTo("say hello"); + assertThat(persistedOutcome.getHandoffOutcome()).isEqualTo("rejected"); + assertThat(persistedOutcome.getHandoffReason()).isEqualTo("runtime_scope_changed"); } @Test @@ -1588,17 +1828,16 @@ void remoteTargetSchedulesDurableFollowupWithoutAggregateTerminalization() { .isEqualTo("pin-request-1"); ArgumentCaptor handoffCaptor = ArgumentCaptor.forClass(ScriptHandoffEvent.class); - verify(handoffEventRepository).save(handoffCaptor.capture()); - assertThat(handoffCaptor.getValue().getRemoteCoordinatorId()) + verify(handoffEventRepository, Mockito.times(2)).save(handoffCaptor.capture()); + ScriptHandoffEvent persistedOutcome = handoffCaptor.getAllValues().getLast(); + assertThat(persistedOutcome.getRemoteCoordinatorId()) .isEqualTo("remote-coordinator:workItem:99#0"); - assertThat(handoffCaptor.getValue().getRemoteFollowupId()) - .isEqualTo("remote-followup:workItem:99#0"); - assertThat(handoffCaptor.getValue().getTargetGameInstanceId()).isEqualTo("8"); - assertThat(handoffCaptor.getValue().getTargetRegionId()).isEqualTo("region-2"); - assertThat(handoffCaptor.getValue().getTargetRegionEpoch()).isEqualTo(77L); - assertThat(handoffCaptor.getValue().getScriptPinEpoch()).isEqualTo(2L); - assertThat(handoffCaptor.getValue().getScriptPinControlPlaneRequestId()) - .isEqualTo("pin-request-1"); + assertThat(persistedOutcome.getRemoteFollowupId()).isEqualTo("remote-followup:workItem:99#0"); + assertThat(persistedOutcome.getTargetGameInstanceId()).isEqualTo("8"); + assertThat(persistedOutcome.getTargetRegionId()).isEqualTo("region-2"); + assertThat(persistedOutcome.getTargetRegionEpoch()).isEqualTo(77L); + assertThat(persistedOutcome.getScriptPinEpoch()).isEqualTo(2L); + assertThat(persistedOutcome.getScriptPinControlPlaneRequestId()).isEqualTo("pin-request-1"); } @Test @@ -1779,7 +2018,7 @@ void remoteTargetRefusesUnavailableOrMalformedRuntimeOwnerEvidence() { } @Test - void remoteTargetDeadLettersWhenRemoteScheduleResponseOmitsDurableIds() { + void remoteTargetRetainsInFlightEvidenceWhenResponseOmitsDurableIds() { GameSessionControlPlaneClient gameSessionClient = Mockito.mock(GameSessionControlPlaneClient.class); when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) @@ -1817,23 +2056,21 @@ void remoteTargetDeadLettersWhenRemoteScheduleResponseOmitsDurableIds() { workItem(), emittedCommand("say hello", "entity-remote", "8", "region-2", 77L, 45L, 0)); assertThat(result.accepted()).isFalse(); - assertThat(result.outcome()).isEqualTo("REMOTE_REJECTED"); - assertThat(result.errorCode()).isEqualTo("REMOTE_RESPONSE_INVALID"); + assertThat(result.outcome()).isEqualTo("HANDOFF_IN_FLIGHT"); + assertThat(result.errorCode()).isEqualTo("HANDOFF_IN_FLIGHT"); ArgumentCaptor workItemCaptor = ArgumentCaptor.forClass(ScriptWorkItem.class); - verify(workItemRepository, Mockito.times(2)).save(workItemCaptor.capture()); - assertThat(workItemCaptor.getAllValues().get(1).getStatus()).isEqualTo("DEAD_LETTERED"); - assertThat(workItemCaptor.getAllValues().get(1).getCancelReason()) - .isEqualTo("remote_response_invalid"); - assertThat(audit.getFinalStage()).isEqualTo("TICK_HANDOFF"); - assertThat(audit.getFinalOutcome()).isEqualTo("infrastructure_error"); - assertThat(audit.getFinalReason()).isEqualTo("remote_response_invalid"); + verify(workItemRepository).save(workItemCaptor.capture()); + assertThat(workItemCaptor.getValue().getStatus()).isEqualTo("HANDOFF_IN_FLIGHT"); + assertThat(audit.getFinalStage()).isNull(); + assertThat(audit.getFinalOutcome()).isNull(); + assertThat(audit.getFinalReason()).isNull(); ArgumentCaptor handoffCaptor = ArgumentCaptor.forClass(ScriptHandoffEvent.class); verify(handoffEventRepository).save(handoffCaptor.capture()); assertThat(handoffCaptor.getValue().getRemoteCoordinatorId()).isBlank(); assertThat(handoffCaptor.getValue().getRemoteFollowupId()).isBlank(); - assertThat(handoffCaptor.getValue().getHandoffOutcome()).isEqualTo("remote_rejected"); - assertThat(handoffCaptor.getValue().getHandoffReason()).isEqualTo("remote_response_invalid"); + assertThat(handoffCaptor.getValue().getHandoffOutcome()).isEqualTo("handoff_in_flight"); + assertThat(handoffCaptor.getValue().getHandoffReason()).isEqualTo("handoff_in_flight"); } @Test @@ -1887,10 +2124,11 @@ void collapsesPartialRoutingBundleBeforeForwardingOrPersistingHandoff() { assertThat(requestCaptor.getValue().getPointerVersion()).isBlank(); ArgumentCaptor handoffCaptor = ArgumentCaptor.forClass(ScriptHandoffEvent.class); - verify(handoffEventRepository).save(handoffCaptor.capture()); - assertThat(handoffCaptor.getValue().getWorldSlug()).isBlank(); - assertThat(handoffCaptor.getValue().getRealmSlug()).isBlank(); - assertThat(handoffCaptor.getValue().getPointerVersion()).isBlank(); + verify(handoffEventRepository, Mockito.times(2)).save(handoffCaptor.capture()); + ScriptHandoffEvent persistedOutcome = handoffCaptor.getAllValues().getLast(); + assertThat(persistedOutcome.getWorldSlug()).isBlank(); + assertThat(persistedOutcome.getRealmSlug()).isBlank(); + assertThat(persistedOutcome.getPointerVersion()).isBlank(); } private static ScriptGameplayCommandHandoffService.EmittedCommand emittedCommand( @@ -1912,6 +2150,97 @@ private static ScriptGameplayCommandHandoffService.EmittedCommand emittedCommand ordinal); } + private static final class RecordingTransactionManager implements PlatformTransactionManager { + private final List operations; + private final List propagations = new ArrayList<>(); + private int commitCount; + + private RecordingTransactionManager(List operations) { + this.operations = operations; + } + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + int propagation = + definition == null + ? TransactionDefinition.PROPAGATION_REQUIRED + : definition.getPropagationBehavior(); + propagations.add(propagation); + operations.add("tx-begin:" + propagation); + TransactionSynchronizationManager.setActualTransactionActive( + propagation != TransactionDefinition.PROPAGATION_NOT_SUPPORTED); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + operations.add("tx-commit-" + ++commitCount); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Override + public void rollback(TransactionStatus status) { + operations.add("tx-rollback"); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + private List propagations() { + return propagations; + } + } + + private static final class FailingIntentCommitTransactionManager + implements PlatformTransactionManager { + private final List propagations = new ArrayList<>(); + private boolean failedIntentCommit; + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + int propagation = + definition == null + ? TransactionDefinition.PROPAGATION_REQUIRED + : definition.getPropagationBehavior(); + propagations.add(propagation); + TransactionSynchronizationManager.setActualTransactionActive( + propagation != TransactionDefinition.PROPAGATION_NOT_SUPPORTED); + return new TaggedTransactionStatus( + propagation == TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + @Override + public void commit(TransactionStatus status) { + if (status instanceof TaggedTransactionStatus tagged + && tagged.requiresNew() + && !failedIntentCommit) { + failedIntentCommit = true; + TransactionSynchronizationManager.setActualTransactionActive(false); + throw new IllegalStateException("intent commit unavailable"); + } + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Override + public void rollback(TransactionStatus status) { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + private List propagations() { + return propagations; + } + } + + private static final class TaggedTransactionStatus extends SimpleTransactionStatus { + private final boolean requiresNew; + + private TaggedTransactionStatus(boolean requiresNew) { + this.requiresNew = requiresNew; + } + + private boolean requiresNew() { + return requiresNew; + } + } + private static GetGameInstanceRuntimeStateResponse currentRuntimeState() { return GetGameInstanceRuntimeStateResponse.newBuilder() .setRuntimeState( diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java index a43cad384a..30e74a2e68 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java @@ -48,6 +48,10 @@ import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationManager; import tools.jackson.databind.ObjectMapper; @@ -1102,6 +1106,104 @@ void evaluatesAndHandsOffPluginWithExactCurrentFence() { verify(handoffService).handoff(Mockito.eq(item), Mockito.any()); } + @Test + void evaluationCommitsBeforeHandoffLoopStarts() { + List operations = new ArrayList<>(); + RecordingExecutionTransactionManager transactionManager = + new RecordingExecutionTransactionManager(operations); + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptDefinitionRepository definitionRepository = + Mockito.mock(ScriptDefinitionRepository.class); + ScriptGameplayCommandHandoffService handoffService = + Mockito.mock(ScriptGameplayCommandHandoffService.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptWorkItem item = workItem(); + ScriptDefinition definition = new ScriptDefinition(); + definition.setDefinition("{\"emitCommands\":[{\"commandText\":\"LOOK\"}]}"); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenAnswer( + invocation -> { + operations.add( + "runtime:" + TransactionSynchronizationManager.isActualTransactionActive()); + return runtimeStateResponse(); + }); + when(workItemService.claimPendingForEvaluation(1)).thenReturn(List.of(item)); + when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) + .thenReturn(Optional.of(definition)); + when(workItemRepository.save(Mockito.any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + Mockito.doAnswer( + invocation -> { + operations.add( + "begin-fanout:" + TransactionSynchronizationManager.isActualTransactionActive()); + return null; + }) + .when(handoffService) + .beginAggregateFanout(Mockito.eq(item)); + Mockito.doAnswer( + invocation -> { + operations.add( + "handoff:" + TransactionSynchronizationManager.isActualTransactionActive()); + return new ScriptGameplayCommandHandoffService.HandoffResult( + true, "ENQUEUED", "command-1", "", "", ""); + }) + .when(handoffService) + .handoff(Mockito.eq(item), Mockito.any()); + Mockito.doAnswer( + invocation -> { + operations.add( + "end-fanout:" + TransactionSynchronizationManager.isActualTransactionActive()); + return null; + }) + .when(handoffService) + .endAggregateFanout(Mockito.eq(item)); + + ScriptWorkItemExecutionService service = + new ScriptWorkItemExecutionServiceImpl( + null, + workItemService, + definitionRepository, + handoffService, + workItemRepository, + Mockito.mock(ScriptEventAuditRepository.class), + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + new ScriptOutputProperties(), + allowingTenantBudgetService(), + allowingDryRunCapacityService(), + null, + null, + new ObjectMapper(), + new SimpleMeterRegistry(), + gameSessionClient, + null, + transactionManager); + + TransactionSynchronizationManager.setActualTransactionActive(false); + try { + ScriptWorkItemExecutionService.ExecutionBatchResult result = + service.processPendingWorkItems(1); + + assertThat(result.completedCount()).isEqualTo(1); + assertThat(operations) + .containsExactly( + "runtime:false", + "tx-begin:0", + "tx-commit-1", + "runtime:false", + "tx-begin:0", + "tx-commit-2", + "begin-fanout:false", + "handoff:false", + "end-fanout:false", + "tx-begin:0", + "tx-commit-3"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } + @Test void coreWorkDoesNotConsultPluginLifecycleFence() { ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); @@ -3366,6 +3468,39 @@ private record ExecutionFixture( long initialFailureGeneration, ScriptWorkItemExecutionService.ExecutionBatchResult result) {} + private static final class RecordingExecutionTransactionManager + implements PlatformTransactionManager { + private final List operations; + private int commitCount; + + private RecordingExecutionTransactionManager(List operations) { + this.operations = operations; + } + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + int propagation = + definition == null + ? TransactionDefinition.PROPAGATION_REQUIRED + : definition.getPropagationBehavior(); + operations.add("tx-begin:" + propagation); + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + operations.add("tx-commit-" + ++commitCount); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + @Override + public void rollback(TransactionStatus status) { + operations.add("tx-rollback"); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } + private static ScriptTenantBudgetService allowingTenantBudgetService() { ScriptTenantBudgetService service = Mockito.mock(ScriptTenantBudgetService.class); when(service.tryReserve(Mockito.any(), Mockito.any())).thenReturn(true); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java index b401f78ce2..0b2d2f89de 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java @@ -1,6 +1,5 @@ package net.firedevops.firemud.worldmanagement.service.impl; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; @@ -38,13 +37,13 @@ import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionOperations; +import org.springframework.transaction.support.TransactionTemplate; @Service -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = - "Spring-managed collaborators are stored internally for world lifecycle commands.") public class WorldLifecycleCommandServiceImpl implements WorldLifecycleCommandService { private static final Logger logger = LoggingUtil.getLogger(WorldLifecycleCommandServiceImpl.class); @@ -69,6 +68,7 @@ public class WorldLifecycleCommandServiceImpl implements WorldLifecycleCommandSe private final GameDesignClient gameDesignClient; private final EntityManagementClient entityManagementClient; private final MeterRegistry meterRegistry; + private final TransactionOperations transactionOperations; private Counter prepareCounter; private Counter activateCounter; @@ -88,7 +88,40 @@ public WorldLifecycleCommandServiceImpl( WorldProperties worldProperties, GameDesignClient gameDesignClient, EntityManagementClient entityManagementClient, - MeterRegistry meterRegistry) { + MeterRegistry meterRegistry, + PlatformTransactionManager transactionManager) { + this( + worldInstanceRepository, + regionInstanceRepository, + zoneRepository, + zoneInstanceRepository, + roomRepository, + roomExitRepository, + roomInstanceRepository, + roomInstanceExitRepository, + worldEventRepository, + worldProperties, + gameDesignClient, + entityManagementClient, + meterRegistry, + transactionTemplate(transactionManager)); + } + + WorldLifecycleCommandServiceImpl( + WorldInstanceRepository worldInstanceRepository, + RegionInstanceRepository regionInstanceRepository, + ZoneRepository zoneRepository, + ZoneInstanceRepository zoneInstanceRepository, + RoomRepository roomRepository, + RoomExitRepository roomExitRepository, + RoomInstanceRepository roomInstanceRepository, + RoomInstanceExitRepository roomInstanceExitRepository, + WorldEventRepository worldEventRepository, + WorldProperties worldProperties, + GameDesignClient gameDesignClient, + EntityManagementClient entityManagementClient, + MeterRegistry meterRegistry, + TransactionOperations transactionOperations) { this.worldInstanceRepository = worldInstanceRepository; this.regionInstanceRepository = regionInstanceRepository; this.zoneRepository = zoneRepository; @@ -102,6 +135,7 @@ public WorldLifecycleCommandServiceImpl( this.gameDesignClient = gameDesignClient; this.entityManagementClient = entityManagementClient; this.meterRegistry = meterRegistry; + this.transactionOperations = transactionOperations; } WorldLifecycleCommandServiceImpl( @@ -130,7 +164,15 @@ public WorldLifecycleCommandServiceImpl( worldProperties, gameDesignClient, null, - meterRegistry); + meterRegistry, + (TransactionOperations) null); + } + + private static TransactionTemplate transactionTemplate( + PlatformTransactionManager transactionManager) { + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + return transactionTemplate; } @PostConstruct @@ -284,6 +326,7 @@ public WorldInstanceLifecycleSnapshotDto getWorldInstanceLifecycle( } @Override + @Transactional(propagation = org.springframework.transaction.annotation.Propagation.NOT_SUPPORTED) @Timed(value = "world.terminateInstance") public WorldInstanceLifecycleSnapshotDto terminateWorldInstance( long tenantId, @@ -323,17 +366,30 @@ public WorldInstanceLifecycleSnapshotDto terminateWorldInstance( throw new IllegalArgumentException( cleanupResponse.getError().getCode() + ": " + cleanupResponse.getError().getMessage()); } - cleanupWorldRuntimeState(tenantId, gameInstanceId); - worldInstance.setStatus(STATUS_TERMINATED); - worldInstance.setLifecycleEpoch(worldInstance.getLifecycleEpoch() + 1L); - worldInstance.setTerminatedAt(Instant.now()); - WorldInstance saved = worldInstanceRepository.save(worldInstance); + WorldInstance finalWorldInstance = worldInstance; + WorldInstanceLifecycleSnapshotDto terminatedSnapshot = + executeLocalTermination( + () -> { + cleanupWorldRuntimeState(tenantId, gameInstanceId); + finalWorldInstance.setStatus(STATUS_TERMINATED); + finalWorldInstance.setLifecycleEpoch(finalWorldInstance.getLifecycleEpoch() + 1L); + finalWorldInstance.setTerminatedAt(Instant.now()); + return snapshot(worldInstanceRepository.save(finalWorldInstance)); + }); logger.info( "Terminated world instance tenant={} gameInstanceId={} terminationRequestId={}", tenantId, gameInstanceId, terminationRequestId); - return snapshot(saved); + return terminatedSnapshot; + } + + private WorldInstanceLifecycleSnapshotDto executeLocalTermination( + java.util.function.Supplier termination) { + if (transactionOperations == null) { + return termination.get(); + } + return transactionOperations.execute(status -> termination.get()); } private void cleanupWorldRuntimeState(long tenantId, long gameInstanceId) { diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImplTest.java index 712524d5eb..22648a1eb2 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImplTest.java @@ -1,8 +1,10 @@ package net.firedevops.firemud.worldmanagement.service.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -10,12 +12,15 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; import java.util.Optional; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.entitymanagement.v1.CleanupRuntimeInstanceResponse; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse; import net.firedevops.firemud.gamedesign.v1.GetVersionStateResponse; import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; import net.firedevops.firemud.worldmanagement.client.GameDesignClient; import net.firedevops.firemud.worldmanagement.config.WorldProperties; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; @@ -33,8 +38,10 @@ import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionCallback; +import org.springframework.transaction.support.TransactionOperations; -class WorldLifecycleCommandServiceImplTest { +class WorldInstanceActivationServiceImplTest { private WorldInstanceRepository worldInstanceRepository; private RegionInstanceRepository regionInstanceRepository; private ZoneRepository zoneRepository; @@ -44,7 +51,9 @@ class WorldLifecycleCommandServiceImplTest { private RoomInstanceRepository roomInstanceRepository; private RoomInstanceExitRepository roomInstanceExitRepository; private WorldEventRepository worldEventRepository; + private EntityManagementClient entityManagementClient; private GameDesignClient gameDesignClient; + private AtomicBoolean localTransactionActive; private WorldLifecycleCommandServiceImpl service; @BeforeEach @@ -58,7 +67,22 @@ void setUp() { roomInstanceRepository = mock(RoomInstanceRepository.class); roomInstanceExitRepository = mock(RoomInstanceExitRepository.class); worldEventRepository = mock(WorldEventRepository.class); + entityManagementClient = mock(EntityManagementClient.class); gameDesignClient = mock(GameDesignClient.class); + localTransactionActive = new AtomicBoolean(); + TransactionOperations transactionOperations = + new TransactionOperations() { + @Override + public T execute(TransactionCallback action) { + assertFalse(localTransactionActive.get()); + localTransactionActive.set(true); + try { + return action.doInTransaction(null); + } finally { + localTransactionActive.set(false); + } + } + }; WorldProperties worldProperties = new WorldProperties(); worldProperties.setLocalShardId(7); service = @@ -74,7 +98,9 @@ void setUp() { worldEventRepository, worldProperties, gameDesignClient, - new SimpleMeterRegistry()); + entityManagementClient, + new SimpleMeterRegistry(), + transactionOperations); service.initMetrics(); when(gameDesignClient.getPublishedReleaseBundle(42L, 11L)) .thenReturn( @@ -238,6 +264,71 @@ void terminateWorldInstanceDeletesRuntimeWorldStateBeforeFinalizing() { verify(regionInstanceRepository).deleteByTenantIdAndGameInstanceId(42L, 101L); } + @Test + void terminateWorldInstanceDoesNotCommitTerminationWhenWorldCleanupFails() { + WorldInstance instance = activeWorldInstance(); + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenReturn(Optional.of(instance)); + when(worldInstanceRepository.save(any(WorldInstance.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + doThrow(new IllegalStateException("world cleanup failed")) + .when(roomInstanceExitRepository) + .deleteByTenantIdAndGameInstanceId(42L, 101L); + + assertThrows( + IllegalStateException.class, + () -> service.terminateWorldInstance(42L, 101L, 2L, "term-1", "stop")); + + assertEquals("TERMINATING", instance.getStatus()); + verify(worldInstanceRepository).save(instance); + verify(worldEventRepository).deleteByTenantIdAndGameInstanceId(42L, 101L); + verify(roomInstanceExitRepository).deleteByTenantIdAndGameInstanceId(42L, 101L); + } + + @Test + void terminateWorldInstanceRetriesSameRequestAfterLocalCleanupFailure() { + WorldInstance instance = activeWorldInstance(); + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenReturn(Optional.of(instance)); + when(worldInstanceRepository.save(any(WorldInstance.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + doThrow(new IllegalStateException("world cleanup failed")) + .when(roomInstanceExitRepository) + .deleteByTenantIdAndGameInstanceId(42L, 101L); + + assertThrows( + IllegalStateException.class, + () -> service.terminateWorldInstance(42L, 101L, 2L, "term-1", "stop")); + + org.mockito.Mockito.doNothing() + .when(roomInstanceExitRepository) + .deleteByTenantIdAndGameInstanceId(42L, 101L); + var snapshot = service.terminateWorldInstance(42L, 101L, 3L, "term-1", "stop"); + + assertEquals("TERMINATED", snapshot.status()); + verify(entityManagementClient, org.mockito.Mockito.times(2)) + .cleanupRuntimeInstance(42L, 101L, "term-1"); + } + + @Test + void entityCleanupRunsBeforeTheLocalWorldTransaction() { + WorldInstance instance = activeWorldInstance(); + when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) + .thenReturn(Optional.of(instance)); + when(worldInstanceRepository.save(any(WorldInstance.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + when(entityManagementClient.cleanupRuntimeInstance(42L, 101L, "term-1")) + .thenAnswer( + invocation -> { + assertFalse(localTransactionActive.get()); + return CleanupRuntimeInstanceResponse.newBuilder().build(); + }); + + service.terminateWorldInstance(42L, 101L, 2L, "term-1", "stop"); + + assertFalse(localTransactionActive.get()); + } + @Test void prepareWorldInstanceRejectsReleaseBundleMismatch() { when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) @@ -352,6 +443,23 @@ void prepareWorldInstanceRejectsMissingRequiredManifestAssetKeyProof() { error.getMessage()); } + private WorldInstance activeWorldInstance() { + WorldInstance instance = new WorldInstance(); + instance.setTenantId(42L); + instance.setGameInstanceId(101L); + instance.setGameTemplateId(7L); + instance.setControlPlaneRequestId("cp-1"); + instance.setLaunchDescriptorId("ld-1"); + instance.setVersionId(11L); + instance.setReleaseBundleId(77L); + instance.setGenerationConfigRevision("genrev-11"); + instance.setPublishedReleaseBundleRef("prb:42:11:77"); + instance.setVersionStateEpoch(77L); + instance.setLifecycleEpoch(2L); + instance.setStatus("ACTIVE"); + return instance; + } + private Room templateRoom(long tenantId, long roomId) { Zone zone = templateZone(tenantId, 11L); Room room = new Room(); From 77c91e40b2cb959a58b70e0068da620f202c35b2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 12:26:57 +1200 Subject: [PATCH 22/68] docs(runtime): align accepted-command recovery status --- .../game-session-runtime-and-tick-coordination.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index f4140a25e7..4c10185d52 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -40,7 +40,7 @@ These links add decision provenance only; they do not upgrade any Game Session i | `GR-1.1` Session front-end and execution routing | `partial`: WebSocket handshake/session bootstrap, protocol parsing, normalized routing, takeover-safe transport registration, and current local/remote admission are live; lease-owner forwarding for independently partitioned regions is not | `proven`: [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java), [GameSessionWebSocketHandshakeInterceptorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java), [SessionRoutingNormalizationServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java), and [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java) cover the shipped front-door and routing seams | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md) | [WebSocket handler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [handshake interceptor](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [session routing normalization](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [Game Session gRPC](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java) | [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [GameSessionWebSocketHandshakeInterceptorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [SessionRoutingNormalizationServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java) | `GR-1.3` ownership/fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); gateway/TCP edge behavior remains a secondary handoff | The API contract requires front-end-to-lease-owner forwarding to be fenced, with retry/ambiguity handling. The current owner boundary is game-instance scoped and does not implement that forwarding or true region partitioning; no new design decision is recorded. | | `GR-1.2` Tick timelines, action fairness, queues, and scheduling | `partial`: current bounded scheduler, per-entity queue selection, gameplay-command ordering (including timer/automation-origin work only after materialization as gameplay commands with retained provenance/order fields), durable batch/effect staging, pressure signals, and sealed selected-work manifests for gameplay commands are live; directly selected timer/retry/remote-follow-up source-claim manifests remain target-state; it still uses universal work-item selection and does not implement the accepted separate actor-action/passive-effect lane classification, phase budgets, or lane-preserving retry contract; the complete in-place command-status lifecycle accepted by [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) is not | `drift-found`: the shipped scheduler and queue/effect seams have focused proof, but lane/source classification, separate lane budgets, and passive/inbound non-actor-turn behavior are not proved; the accepted command-status lifecycle in [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) remains unimplemented and is not fully proved | [ticks](../../architecture/system-architecture-ticks.md); [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) | [TickScheduler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickScheduler.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [TickServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game-session-service.proto](../../../protos/game-session/v1/game_session_service.proto) | [TickSchedulerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickSchedulerTest.java); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java) | `AS-1.4` timer progress and `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); `GR-1.3` ownership in this tracker | Add the [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) acknowledgement dimensions, authoritative attempt history, bound-tick summary, convergence contract, persistence, and focused proof to `GetGameplayCommandStatus`; separately add TICK-01 source classification, lane/cost metadata, phase budgets, lane-preserving retry identity, and focused actor/passive scheduling proof; adaptive timing and true region-wide scheduling remain separate gaps. | | `GR-1.3` Region leases, fencing, and executor coordination | `partial`: durable runtime ownership, epoch/fence snapshots, pause/resume, stale-owner rejection/requeue, and current runtime-progress publication are live at the game-instance boundary; the TICK-02 Redis lease plus durable executor-fence install/revalidate handshake and true region takeover boundary remain target-state | `proven`: current tests cover fence/scope admission, tick progress, stale execution, and operator reads, but do not prove the TICK-02 lease/fence handshake or takeover reconciliation | [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md) | [RuntimeRegionStatus](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/RuntimeRegionStatus.java); [runtime ownership read](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java); [TickRuntimeProgressService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressService.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java); [TickRuntimeProgressServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressServiceTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java); [GameSessionControlPlaneGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | `GR-1.1` front-end routing in this tracker; `AS-1.1` ingress and `AS-1.4` timers in [Automation runtime tracker](./automation-and-scheduler-runtime.md); Redis lease coordination is the shared infrastructure handoff | The current durable owner row and lease boundary are game-instance scoped. Add proof for Redis lease acquisition/loss before and after durable fence installation, same-token revalidation, stale-fence rejection, and takeover reconciliation; true region-partitioned leases, cluster scheduling, and front-end forwarding remain unimplemented. | -| `GR-1.4` Runtime recovery, replay, and reconciliation | `partial`: durable command/batch/effect recovery, manifest-digest repair, stale-fence requeue, remote result reconciliation, and bounded restart/reset paths are live; current startup handling unsafely terminalizes old accepted-but-unstaged rows as `LOST_BEFORE_STAGING` without materialization evidence, so safe accepted-but-never-staged convergence remains an open gap; queue/pending loss before durable batch materialization and recovery of `STAGED` batches/effects after Redis loss remain unimplemented; lane-preserving replay and the complete TICK-02 takeover reconciliation remain target-state follow-through | `drift-found`: focused unit recovery tests cover accepted-row handling, serializer-free identity/payload-idempotent queue/pending behavior, remote reconciliation, and retryability on Redis/eligibility races, but do not prove safe accepted-but-never-staged convergence, lane/cost preservation, Redis-loss recovery of `STAGED` state, or the Redis lease plus durable-fence takeover handshake; the real-Redis serializer integration test is present but skipped when Docker is unavailable | [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [reconnection](../../architecture/system-architecture-reconnection.md); [Game Session operations](../../architecture/microservices/game-session-service/operations.md); [ADR 0013](../../architecture/decisions/adr-0013-bounded-invisible-non-edge-restart-recovery.md) | [DatabaseGameplayCommandRecoveryService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java); [GameplayCommandRepository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [TickQueueControlService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickQueueControlService.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [RemoteFollowupRuntimeServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [DatabaseGameplayCommandRecoveryServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java); [TickQueueControlServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java); [TickQueueControlServiceRedisIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceRedisIntegrationTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [RemoteFollowupRuntimeServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java); [RemoteFollowupDrainServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupDrainServiceImplTest.java); [DefaultDurableRemoteFollowupExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableRemoteFollowupExecutionServiceTest.java) | `GR-1.2` queue/replay and `GR-1.3` fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); downstream domain services own effect application/reconciliation | Downstream effect ledgers and replay/idempotency consumers beyond the migrated command families, full non-edge restart recovery, broader payload/work-source recovery, and a durable replay/reconciliation controller for Redis-loss `STAGED` command/batch state remain; add focused proof for lane/cost preservation, current epoch/fence validation, old-fence takeover reconciliation, and broader payload/work-source recovery; ADR 0013 is accepted and owns the bounded invisible non-edge restart target. | +| `GR-1.4` Runtime recovery, replay, and reconciliation | `partial`: durable command/batch/effect recovery, manifest-digest repair, stale-fence requeue, remote result reconciliation, and bounded restart/reset paths are live; startup recovery re-enqueues old accepted-but-unstaged commands under their existing identity and leaves them `ACCEPTED` when Redis, identity, eligibility, or a raced transition prevents safe materialization; queue/pending loss before durable batch materialization and recovery of `STAGED` batches/effects after Redis loss remain unimplemented; lane-preserving replay and the complete TICK-02 takeover reconciliation remain target-state follow-through | `drift-found`: focused unit recovery tests cover accepted-row re-drive, unchanged retryable state on uncertainty, serializer-free identity/payload-idempotent queue/pending behavior, remote reconciliation, and retryability on Redis/eligibility races, but do not provide combined PostgreSQL/real-Redis restart proof, lane/cost preservation, Redis-loss recovery of `STAGED` state, or the Redis lease plus durable-fence takeover handshake; the real-Redis serializer integration test is present but skipped when Docker is unavailable | [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [reconnection](../../architecture/system-architecture-reconnection.md); [Game Session operations](../../architecture/microservices/game-session-service/operations.md); [ADR 0013](../../architecture/decisions/adr-0013-bounded-invisible-non-edge-restart-recovery.md) | [DatabaseGameplayCommandRecoveryService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java); [GameplayCommandRepository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [TickQueueControlService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickQueueControlService.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [RemoteFollowupRuntimeServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [DatabaseGameplayCommandRecoveryServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java); [TickQueueControlServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java); [TickQueueControlServiceRedisIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceRedisIntegrationTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [RemoteFollowupRuntimeServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java); [RemoteFollowupDrainServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupDrainServiceImplTest.java); [DefaultDurableRemoteFollowupExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableRemoteFollowupExecutionServiceTest.java) | `GR-1.2` queue/replay and `GR-1.3` fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); downstream domain services own effect application/reconciliation | Downstream effect ledgers and replay/idempotency consumers beyond the migrated command families, full non-edge restart recovery, broader payload/work-source recovery, and a durable replay/reconciliation controller for Redis-loss `STAGED` command/batch state remain; add focused proof for lane/cost preservation, current epoch/fence validation, old-fence takeover reconciliation, and broader payload/work-source recovery; ADR 0013 is accepted and owns the bounded invisible non-edge restart target. | ### GR-1.2 Command-Status Dimensions @@ -77,7 +77,7 @@ After ingress validation, rate and queue-target resolution, Game Session writes Current pointer-CAS status/proof: routed Automation and remote gameplay-command insertion uses one PostgreSQL `INSERT ... SELECT` guarded by exactly one total current pointer row for the tenant/game-instance target, with that sole row matching the normalized world/realm selectors, pointer version, and required nonblank playable-state scope. Missing, mismatched, or ambiguous authority fails retryably before the insert. Existing pointer updates use expected-version CAS, and pointer creation serializes on the runtime target and fails closed when another route already owns it. Focused unit and compile proof has passed for this path, but live PostgreSQL/Testcontainers concurrency proof is unavailable locally and remains required before claiming full proof. This current pointer-CAS note does not establish target stable-namespace or `realmId` completeness. -The current command lifecycle is explicit: `ACCEPTED` means durable identity exists but staging has not succeeded; `STAGED` means Redis staging succeeded; `DRAINED` means a durable tick batch consumed the staged command; `RETRY_QUEUED` means an abandoned attempt was returned for another attempt; `FAILED` means staging failed before gameplay application; and target `LOST_BEFORE_STAGING` is the terminal recovery state only for explicitly volatile/no-batch accepted work that never reached staging. In the live implementation, startup recovery unsafely applies `LOST_BEFORE_STAGING` to every old `ACCEPTED` row with `stagedAt IS NULL`, without distinguishing durable from volatile/no-batch work. Target durable accepted work remains retryable under its original identity pending materialization evidence. Batch drain and abandonment update command rows, so status is not ingress-only. +The current command lifecycle is explicit: `ACCEPTED` means durable identity exists but staging has not succeeded; `STAGED` means Redis staging succeeded; `DRAINED` means a durable tick batch consumed the staged command; `RETRY_QUEUED` means an abandoned attempt was returned for another attempt; `FAILED` means staging failed before gameplay application; and target `LOST_BEFORE_STAGING` is the terminal recovery state only for explicitly volatile/no-batch accepted work that never reached staging. Live startup recovery re-enqueues old `ACCEPTED` rows under the same command identity and leaves the row `ACCEPTED` when materialization is uncertain or fails, so durable accepted work remains retryable rather than being terminalized without evidence. Batch drain and abandonment update command rows, so status is not ingress-only. `commandId` is carried in enqueue responses, Redis tick payloads, logs/MDC, batch manifests, effect rows, retries, and remote execution. `GetGameplayCommandStatus` is the single canonical Game Session read and currently resolves the command-id identity `(tenantId, gameInstanceId, commandId)`. The automation status lookup/correlation key `(tenantId, gameInstanceId, regionId, regionEpoch, automationDispatchId)` is the accepted target lookup but is not implemented by the live resolver; it is not the complete Command-Handoff Identity defined by the scripting normative contract table, which additionally carries command ordinal and applicable source/target scope fields. This tracker records the status lookup keys and their current/target status below under [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md). The read exposes `enqueueSeq`, the latest selected queue-source kind/state/ordinal and due-point tuple, lifecycle and routing data, and remote correlation/result fields. Logging & Admin exposes the implemented command-id read at `GET /gameplay-commands/{tenantId}/{gameInstanceId}/{commandId}` and validates tenant and game-instance identity before trusting the response. @@ -165,7 +165,7 @@ Game Session owns the implemented runtime feature-flag mutation and persists the The recorded proof covers durable command identity and sanitized persistence, restart/Redis-loss recovery at the ingress and ownership boundaries, single-record retry/replay updates, command correlation, batch/effect creation, manifest-digest replay repair, stale drain and post-drain fence rejection, durable `DRAINED` resumption, source-tuple preservation through timer/retry/remote claim-release transitions, fair selection in the local scheduler/queue path, and operator DTO/request mapping. Focused remote-runtime tests cover payload validation, bounded duplicate-window paging and de-duplication for due follow-up candidates, bounded durable result recording/replay, already-terminal follow-up replay, late-result handling, and selected reconciliation branches; this does not establish the full remote-follow-up fair-due-selection contract. They do not establish complete exact replay, safe accepted-but-never-staged convergence, general target-command convergence, complete terminal-failure mirroring, safe missing-coordinator recovery, or full origin reconciliation; those remain the target gaps described above. -Current handling proof for accepted-but-never-staged work is limited to the live [recovery helper](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java) and its [focused test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java): they show that old `ACCEPTED` unstaged rows are terminalized as `LOST_BEFORE_STAGING` based on `stagedAt IS NULL`. This is not proof of safe convergence; the helper unsafely terminalizes durable accepted work without materialization evidence. Target durable accepted work remains retryable under its original identity pending materialization evidence; only explicitly volatile/no-batch work may use `LOST_BEFORE_STAGING`. Deterministic remote-result replay, paused-origin/late-result reconciliation, target-command convergence, and tenant/scope/id guards therefore remain proof gaps rather than completed coverage. +Current handling proof for accepted-but-never-staged work is limited to the live [recovery helper](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java) and its [focused test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java): they show that old `ACCEPTED` unstaged rows are re-enqueued under their original identity and remain `ACCEPTED` when Redis, identity, eligibility, or a raced transition makes the outcome uncertain. This is focused unit evidence, not combined PostgreSQL/real-Redis restart proof or proof of safe `STAGED` recovery after Redis loss. Only explicitly volatile/no-batch work may use `LOST_BEFORE_STAGING`. Deterministic remote-result replay, paused-origin/late-result reconciliation, target-command convergence, and tenant/scope/id guards therefore remain proof gaps rather than completed coverage. Run-owned Compose mutation and teardown are implemented and proved at their bounded scope, but Game Session implementation and proof do not yet establish persistent/shared restricted-synthetic identity/namespace/fence isolation or independently isolated two-transport mutating parity. Shared/player-facing whole-stack reset is prohibited, and fixture teardown is not Coordination Redis reset authority; see the canonical [player-flow smoke and reset contract](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). From 9d2f0dd6cb4eb5b84d08e4954b38c7dad3dfe90d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 12:51:05 +1200 Subject: [PATCH 23/68] docs(publication): align current transaction status --- .../microservices/game-design-service/operations.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index 57b771363d..ec5eba5173 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -10,13 +10,13 @@ The target publish contract binds the stable `publish_request_id` to one canonical request digest. Game Design normalizes the complete preallocation caller intent, including `tenantId`, publish type, `notes`, and any other actual request inputs, before computing and durably recording that digest with the workflow/attempt identity. The owner-allocated `versionId` is not an input to that original digest because it does not exist at request admission; after allocation, it is immutable attempt/result evidence bound durably to the same workflow identity and exact replay/readback. A retry with the same `publish_request_id` and the same preallocation-intent digest may attach to or replay the existing workflow and recorded outcome. Reuse of that identity with a different digest is an identity conflict: it must fail closed without executing the new request or returning the prior outcome as though the requests matched. This is the Game Design adopter mapping of [ADR 0078](../../decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md). -**Current implementation gap:** `PublishWorkflowRequest` and the `publish_attempt` persistence currently carry no immutable normalized preallocation-intent digest or exact comparison. Temporal `AlreadyStarted` handling and existing-attempt reconciliation therefore reuse `publishWorkflowId` without comparing normalized caller intent; although the attempt stores the allocated `versionId`, it does not bind that result evidence to a request digest. The current implementation must not be treated as proof of the target different-digest conflict behavior; code and focused proof remain a future implementation gap tracked with the shared runtime contract. +**Current implementation status:** the full-version `publish_attempt` stores and exact-validates `publicationDigestRequest/v1`, binding tenant, allocated version scope, stable publish request, and derived workflow identity. That is the owner-to-owner publication-read binding and intentionally excludes notes and content. Game Design does not yet persist and compare the separate preallocation control-plane content digest that binds notes and every other caller input before version allocation. Temporal `AlreadyStarted` handling can therefore attach a changed-notes request to the same workflow identity even though its publication-read digest still matches. The current implementation proves the scoped owner-read binding, not the target different-control-plane-content conflict behavior. ### Publication terminality and attempt ownership The publication artifact/release-bundle state, allocated version state, participant/release evidence, and publish-attempt terminal state must commit atomically in one Game Design owner-local transaction. If the workflow boundary cannot provide that transaction, the adopter must use an explicit durable state machine with readback reconciliation; it must never expose `SUCCEEDED` until the artifact and version commit is durably readable and bound to the same immutable request and attempt evidence. A terminal attempt is therefore not an acknowledgement that a separate transaction was started: it is the commit/readback proof of the publication state. -**Current implementation gap:** `VersionPublishCommandServiceImpl` writes publication state and then calls `PublishAttemptServiceImpl.markSucceeded`, whose `REQUIRES_NEW` transaction can commit the attempt terminal state independently of the outer artifact/version transaction. The same `REQUIRES_NEW` boundary is used by `createAttempt` and `recordParticipantDigests`: an outer version rollback can therefore leave an attempt and participant rows committed with no committed version (the script-patch path has the same ordering). `publish_attempt.version_id` has no referential constraint to prevent that orphan. `PublishAttemptRepository` updates attempts by id without status/revision compare-and-set (CAS), and the failure path can mark failure and clean up while a concurrent publisher has already won. The current path consequently does not prove that `SUCCEEDED` is coupled to the artifact/version commit, that a failed preallocation can be recovered, or that losing cleanup cannot delete a winning publication. +**Current implementation status:** full-version publication reserves its Draft version and PENDING attempt in one owner-local transaction. After participant reads and object export, its final owner-local transaction records participant evidence, artifact state, release bundle, Published version, verified digests, and the SUCCEEDED attempt together. An ambiguous final commit is resolved by exact attempt/version/bundle/artifact readback rather than an independent terminal-success transaction. The remaining gap is the external phase: participant collection and mutable object-key export occur before that final transaction without a durable external-phase owner, private candidate namespace, or export deduplication. Same-request retries can therefore race before the final Game row lock; a late exporter can overwrite bytes after another attempt's release attestation, while definite-failure cleanup can race an active exporter. The final local transaction does not prove safe external-write ownership, cleanup, or ambiguous object-store recovery. The target attempt record must immutably bind the normalized preallocation request digest, workflow/request identity, allocated version, artifact/release identity, and owner evidence. Every attempt transition must CAS both the expected status and monotonic attempt revision; only the still-current attempt owner may publish a terminal result. Failure cleanup may delete or mark provisional state only when it conditionally owns the same still-current nonterminal attempt and the target has not been won or published. Same-identity/same-digest retries must read back and replay the existing state; a different digest, stale revision/status, or contradictory artifact/version readback fails closed. Focused proof must cover crashes before and after each commit/readback boundary, concurrent exact retries, different-digest reuse, and a losing failure cleanup racing a winning publisher. From 3e294152b748dd21f41290b6cb5bddde8c557c51 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 13:22:48 +1200 Subject: [PATCH 24/68] fix(game-session): fence accepted command retries --- ...e-session-runtime-and-tick-coordination.md | 2 +- ...mationGameplayCommandAdmissionSupport.java | 21 ++++- ...onGameplayCommandAdmissionSupportTest.java | 88 +++++++++++++++++++ 3 files changed, 106 insertions(+), 5 deletions(-) diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 4c10185d52..24ac1be4da 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -18,7 +18,7 @@ Adjudicated current recovery gap: the live queue-to-pending transition can leave Game Session remains the pin and rollout-history owner. Current implementation/proof persists the pin epoch, exposes the owner tuple on pinned-version and convergence reads, and commits pin/rollback through a durable request digest/result ledger with owner-row locking, expected-current-pin CAS, deterministic conflict/failure results, and exact previous/resulting tuple readback. Instance-bound Automation ingress, work-item, schedule/timer, and replay paths carry and validate positive `scriptPinEpoch`; local Game Session Automation admission, duplicate replay, durable tick staging/replay, and final-effect fencing now enforce the complete owner tuple. Remaining gaps include commit-time proof that external Game Design publication and Automation readiness remain valid through the local commit (the current protocol has no immutable preparation attestation or cross-owner CAS), complete history readback, source/target remote tuple binding, complete command identity, and remote final-effect fencing/proof. Automation readiness and observed-pin projections remain non-authoritative. Canonical rollout semantics and the remaining cross-service proof boundary are linked from [Scripting & Automation: Rollout and Rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md#pin-compare-and-set-preconditions) and the [canonical runtime-execution owner](../../architecture/system-architecture-scripting-runtime-execution.md#normative-target-contract). -The implemented local boundary is the exact `(scriptPatchVersion, scriptPinEpoch, scriptPinControlPlaneRequestId)` tuple for instance-scoped Automation commands. Game Session compares it with the locked current `GameInstance` before fresh admission or duplicate replay, commits the durable `gameplay_command` admission before Redis materialization, locks and rechecks the tuple while sealing fresh or replayed tick work, retains the tuple in the sealed work manifest, and compares it again immediately before final gameplay effects. Non-script player commands are unchanged; remote Automation follow-ups retain their separate legacy source/target path and are not widened by this slice. The combined three-service `check -PfullCheck` completed successfully. Its recorded test results were Automation 713 unit tests executed and 20 integration tests skipped; the current Game Session exact-head check records 1,591 unit tests total (1,574 executed and 17 skipped), 125 integration tests total (18 executed and 107 skipped), and 38 cross-service tests total (1 executed and 37 skipped); and Game Design 132 unit tests executed with 9 integration tests skipped. The focused exact-pin and forward-migration tests were also forced to rerun successfully. PostgreSQL/Testcontainers-backed migration and integration cases that remain skipped are not local runtime proof. +The implemented local boundary is the exact `(scriptPatchVersion, scriptPinEpoch, scriptPinControlPlaneRequestId)` tuple for instance-scoped Automation commands. Game Session compares it with the locked current `GameInstance` before fresh admission or duplicate replay, commits the durable `gameplay_command` admission before Redis materialization, locks and rechecks the tuple while sealing fresh or replayed tick work, retains the tuple in the sealed work manifest, and compares it again immediately before final gameplay effects. Before re-enqueuing an existing `ACCEPTED` but unstaged Automation command, Game Session also revalidates the request's captured region identity and epoch against current runtime ownership and rejects unavailable, paused, or advanced ownership without mutation; already-materialized or terminal exact retries retain stored-result readback behavior. Non-script player commands are unchanged; remote Automation follow-ups retain their separate legacy source/target path and are not widened by this slice. The combined three-service `check -PfullCheck` completed successfully. Its recorded test results were Automation 713 unit tests executed and 20 integration tests skipped; the current Game Session exact-head check records 1,591 unit tests total (1,574 executed and 17 skipped), 125 integration tests total (18 executed and 107 skipped), and 38 cross-service tests total (1 executed and 37 skipped); and Game Design 132 unit tests executed with 9 integration tests skipped. The focused exact-pin and forward-migration tests were also forced to rerun successfully. PostgreSQL/Testcontainers-backed migration and integration cases that remain skipped are not local runtime proof. Target rollback requires the scoped Automation admission barrier to pause new script admission before the pin/epoch commit and remain active through exact-artifact and schedule reconciliation/convergence; ordinary gameplay ticks continue on the routine fenced path. A full gameplay pause is valid only for a declared unfenced effect family, migration, or compatibility transition that cannot enforce the final `scriptPinEpoch` fence. Schedule reconciliation follows [ADR 0110](../../architecture/decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md)'s explicit opt-in continuity policy: cancel-and-recreate is the default, only explicitly compatible opted-in intervals preserve continuity, and one-shot timers remain outside that continuity rule. This script-specific boundary is distinct from the runtime `regionEpoch`, which fences broader region ownership and tick execution. Implementation and proof remain partial: current pause/purge seams and region fences do not prove that target. See [ADR 0103](../../architecture/decisions/adr-0103-single-authority-script-pins-with-exact-version-execution.md), [ADR 0106](../../architecture/decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md), [ADR 0109](../../architecture/decisions/adr-0109-game-session-owned-script-rollout-history.md), and [ADR 0110](../../architecture/decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md) for target boundaries; proof remains deferred to the focused Game Session/Automation transition suites. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupport.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupport.java index 524314c3f0..7d76b73303 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupport.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupport.java @@ -80,7 +80,8 @@ static DurableAdmission admitIfAbsentDurably( GameplayCommand requestedCommand = acceptedAutomationCommand(request); Optional existing = findExistingCommand(request, gameplayCommandRepository); if (existing.isPresent()) { - return existingDurableAdmission(existing.orElseThrow(), requestedCommand); + return existingDurableAdmission( + existing.orElseThrow(), requestedCommand, request, runtimeRegionStatusRepository); } return admitFreshDurably( @@ -125,7 +126,8 @@ static AdmissionResult admitRemoteIfAbsent( Optional existing = findExistingCommand(request, gameplayCommandRepository); if (existing.isPresent()) { return materializeAcceptedCommand( - existingDurableAdmission(existing.orElseThrow(), requestedCommand), + existingDurableAdmission( + existing.orElseThrow(), requestedCommand, request, runtimeRegionStatusRepository), request, gameplayCommandRepository, tickService); @@ -246,7 +248,8 @@ private static DurableAdmission admitFreshDurably( } command = insertResult.command(); if (!insertResult.inserted()) { - return existingDurableAdmission(command, requestedCommand); + return existingDurableAdmission( + command, requestedCommand, request, runtimeRegionStatusRepository); } return new DurableAdmission(null, command, true); } @@ -303,13 +306,23 @@ record DurableAdmission( } private static DurableAdmission existingDurableAdmission( - GameplayCommand existing, GameplayCommand requestedCommand) { + GameplayCommand existing, + GameplayCommand requestedCommand, + AdmissionRequest request, + RuntimeRegionStatusRepository runtimeRegionStatusRepository) { AdmissionResult result = existingAdmissionResult(existing, requestedCommand); boolean retryExisting = "ACCEPTED".equals(existing.getExecutionOutcome()) && existing.getStagedAt() == null && existing.getCompletedAt() == null && "UNAVAILABLE".equals(result.errorCode()); + if (retryExisting) { + Optional ownershipRejected = + rejectIfOwnershipClosed(request, runtimeRegionStatusRepository); + if (ownershipRejected.isPresent()) { + return new DurableAdmission(ownershipRejected.orElseThrow(), null, false); + } + } return new DurableAdmission(result, retryExisting ? existing : null, false, retryExisting); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java index f8200cfa04..9f80568bf2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java @@ -622,6 +622,8 @@ void reDrivesDuplicateWhileAdmissionIsStillAccepted() { .findByTenantIdAndGameInstanceIdAndRegionIdAndRegionEpochAndAutomationDispatchId( 1L, 2L, "region-alpha", 7L, "dispatch-1")) .thenReturn(Optional.of(inFlight)); + when(runtimeRegionStatusRepository.findByTenantIdAndRegionId(1L, "region-alpha")) + .thenReturn(Optional.of(runtimeOwnership(automationRequest()))); AdmissionResult result = AutomationGameplayCommandAdmissionSupport.admitIfAbsent( @@ -639,6 +641,92 @@ void reDrivesDuplicateWhileAdmissionIsStillAccepted() { verify(tickService).enqueueCommand(1L, 2L, "auto-in-flight", "say hello", false); } + @Test + void doesNotRedriveExistingAcceptedCommandWhenRuntimeIsPaused() { + GameInstanceRepository gameInstanceRepository = mockGameInstanceRepository(); + GameplayCommandRepository gameplayCommandRepository = mock(GameplayCommandRepository.class); + RuntimeRegionStatusRepository runtimeRegionStatusRepository = + mock(RuntimeRegionStatusRepository.class); + TickService tickService = mock(TickService.class); + + AdmissionRequest request = automationRequest(); + GameInstance instance = automationInstance(); + when(gameInstanceRepository.findById(request.gameInstanceId())) + .thenReturn(Optional.of(instance)); + + GameplayCommand existing = new GameplayCommand(); + populateAdmissionFields(existing, request); + existing.setCommandId("auto-paused"); + existing.setExecutionOutcome("ACCEPTED"); + when(gameplayCommandRepository + .findByTenantIdAndGameInstanceIdAndRegionIdAndRegionEpochAndAutomationDispatchId( + 1L, 2L, "region-alpha", 7L, "dispatch-1")) + .thenReturn(Optional.of(existing)); + + RuntimeRegionStatus pausedOwnership = runtimeOwnership(request); + pausedOwnership.setPaused(true); + when(runtimeRegionStatusRepository.findByTenantIdAndRegionId(1L, "region-alpha")) + .thenReturn(Optional.of(pausedOwnership)); + + AdmissionResult result = + AutomationGameplayCommandAdmissionSupport.admitIfAbsent( + request, + gameInstanceRepository, + gameplayCommandRepository, + runtimeRegionStatusRepository, + tickService); + + assertFalse(result.accepted()); + assertEquals("RUNTIME_PAUSED", result.admissionOutcome()); + assertEquals("runtime_paused", result.errorCode()); + verifyNoTickEnqueue(tickService); + } + + @Test + void doesNotRedriveExistingAcceptedRemoteCommandAfterOwnershipEpochAdvances() { + GameInstanceRepository gameInstanceRepository = mockGameInstanceRepository(); + GameplayCommandRepository gameplayCommandRepository = mock(GameplayCommandRepository.class); + RuntimeRegionStatusRepository runtimeRegionStatusRepository = + mock(RuntimeRegionStatusRepository.class); + GameplayAdmissionPointerAuthorityService pointerAuthority = + mock(GameplayAdmissionPointerAuthorityService.class); + TickService tickService = mock(TickService.class); + + AdmissionRequest request = remoteFollowupRequest("remote-accepted"); + GameInstance instance = automationInstance(); + when(gameInstanceRepository.findById(request.gameInstanceId())) + .thenReturn(Optional.of(instance)); + + GameplayCommand existing = new GameplayCommand(); + populateAdmissionFields(existing, request); + existing.setCommandId("rfcmd-remote-accepted"); + existing.setExecutionOutcome("ACCEPTED"); + when(gameplayCommandRepository + .findByTenantIdAndGameInstanceIdAndRegionIdAndRegionEpochAndRemoteFollowupId( + 1L, 2L, "region-alpha", 7L, "remote-accepted")) + .thenReturn(Optional.of(existing)); + + RuntimeRegionStatus advancedOwnership = runtimeOwnership(request); + advancedOwnership.setRegionEpoch(8L); + when(runtimeRegionStatusRepository.findByTenantIdAndRegionId(1L, "region-alpha")) + .thenReturn(Optional.of(advancedOwnership)); + + AdmissionResult result = + AutomationGameplayCommandAdmissionSupport.admitRemoteIfAbsent( + request, + gameInstanceRepository, + gameplayCommandRepository, + runtimeRegionStatusRepository, + pointerAuthority, + tickService); + + assertFalse(result.accepted()); + assertEquals("STALE_TIMELINE", result.admissionOutcome()); + assertEquals("stale_region_epoch", result.errorCode()); + verifyNoTickEnqueue(tickService); + verify(pointerAuthority, org.mockito.Mockito.never()).listByRuntimeTarget(anyLong(), anyLong()); + } + @Test void rejectsDuplicateWhenStoredAutomationPinEpochDiffers() { GameInstanceRepository gameInstanceRepository = mockGameInstanceRepository(); From 99d2af89f9c0ad21e249dbbb1b97ad1615543a92 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 14:06:12 +1200 Subject: [PATCH 25/68] docs(redis): remove duplicate tick reset policy --- .../architecture/system-architecture-redis-reset-and-recovery.md | 1 - 1 file changed, 1 deletion(-) diff --git a/design/architecture/system-architecture-redis-reset-and-recovery.md b/design/architecture/system-architecture-redis-reset-and-recovery.md index ab7089f7da..d6f50986e5 100644 --- a/design/architecture/system-architecture-redis-reset-and-recovery.md +++ b/design/architecture/system-architecture-redis-reset-and-recovery.md @@ -221,7 +221,6 @@ A region- or tenant-scoped reset parent cannot claim global account- or issuer-i | Prefix / Family | Role | Reset Policy (Coordination Reset) | Behavior When Dropped | Notes | | --- | --- | --- | --- | --- | -| `tick:{tenantRegionTag}:pending` and `tick:{tenantRegionTag}:queue:*` | Coordination | **Reset-tolerant** | In-flight ticks and queued commands for affected regions are discarded; future ticks process only new commands. | `pending` effects are reconciled through the tick-effect ledger under the [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy): evidence may permit `APPLIED`/`ABANDONED`, while inconclusive work remains a reconciliation-required non-terminal marker under its original `EffectId`; reset does not bulk-terminalize it. Idempotency prevents double-apply. Only command records with `ackLevel` = `ACCEPTED_VOLATILE` in `RECEIVED`/`ENQUEUED` and no surviving batch/binding are intentionally **lost** and not reconstructed from PostgreSQL; `ACCEPTED_DURABLE` records follow their feature-specific durable replay or post-abandon re-drive contract, while inconclusive batch-bound work remains non-terminal/reconciliation-required. See the [canonical command outcome convergence](./system-architecture-tick-execution-flows.md#command-outcome-convergence-required). | | `tick:{tenantRegionTag}:pending` and `tick:{tenantRegionTag}:queue:*` | Coordination | **Reset-tolerant** | In-flight ticks and queued commands for affected regions are discarded; future ticks process only new commands. | `pending` effects are reconciled through the tick effect ledger under the [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy): evidence may permit `APPLIED`/`ABANDONED`, while inconclusive work remains a reconciliation-required non-terminal marker under its original persisted mutation `EffectId`—the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child—with the enclosing `rootEffectId` retained separately as lineage and reconciliation context; reset does not bulk-terminalize it. Idempotency prevents double-apply. Only command records with `ackLevel` = `ACCEPTED_VOLATILE` in `RECEIVED`/`ENQUEUED` and no surviving batch/binding are intentionally **lost** and not reconstructed from PostgreSQL; `ACCEPTED_DURABLE` records follow their feature-specific durable replay or post-abandon re-drive contract, while inconclusive batch-bound work remains non-terminal/reconciliation-required. See the [canonical command outcome convergence](./system-architecture-tick-execution-flows.md#command-outcome-convergence-required). | | `tick:{tenantRegionTag}:meta` | Coordination | **Reset-tolerant** | Epoch/tick guard metadata is dropped; reset tooling re-establishes the new epoch baseline from durable RegionStatus state before normal progress. | The Redis metadata is a coordination view only; the reset handshake establishes the same new epoch and first-real-tick baseline in PostgreSQL and Redis. | | `tick:{tenantRegionTag}:session-binding:*` | Coordination | **Reset-tolerant with preserved-session rebind** | Region-local gameplay admission bindings are dropped. Preserved sessions remain fenced until the owner-defined session/recovery evidence contract qualifies them; invalidated sessions require fresh `LOGIN` / `PLAY`. | These keys are region-authoritative for gameplay command admission. The exact rebind, inventory, carrier, reservation, and admission predicates are owned by the [session and region-binding contract](./system-architecture-redis.md#session-and-region-binding-contract) and [active-binding recovery evidence contract](./system-architecture-redis-ops-access.md#canonical-active-binding-recovery-evidence-contract). | From bd9728099cae2e219245c75b5a23a7937c3c6b51 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 14:37:35 +1200 Subject: [PATCH 26/68] docs(redis): record hosted profile gaps --- design/architecture/system-architecture-redis-ops-access.md | 2 +- .../system-architecture-redis-usage-and-profiles.md | 2 ++ .../implementation-tracking/platform-operations-and-delivery.md | 2 +- .../shared-runtime-contracts-and-persistence.md | 2 +- 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/design/architecture/system-architecture-redis-ops-access.md b/design/architecture/system-architecture-redis-ops-access.md index 4272a20742..e6c815ca6a 100644 --- a/design/architecture/system-architecture-redis-ops-access.md +++ b/design/architecture/system-architecture-redis-ops-access.md @@ -27,7 +27,7 @@ Defining additional Redis users, ACL variations, or ad-hoc tools is considered * ## Coordination Redis Access Rules - Coordination Redis is treated as an **application-only write surface during normal operation**: - - Current normal-operation access uses the generic `common-data-runtime` `firemud.redis.*` properties and its auto-configured `RedisConnectionFactory`, `RedisTemplate`, and `StringRedisTemplate`; deployment configuration routes a service to the appropriate role-specific endpoint. The ADR 0176 owner-local descriptor/key-builder foundation, shared contract validation, and aggregated registry are target state and are not implemented. Target state requires all mutations to coordination prefixes (`tick:*`, `retry:*`, `timer:*`, `remote:*`, `session:*`, `tick-executor-lease:*`, and related keys) to use the owning service's registered typed key and mutation helpers, with the shared foundation validating descriptors and aggregation; it does not centralize owner-exclusive execution. Lua is mandatory for atomic multi-key behavior and may be used for an explicitly documented single-key atomic guard or compare-and-set contract. Ordinary single-key mutations use owner-local typed helpers without Lua, and executable helpers or Lua are shared only for mutations genuinely executed by multiple independently deployed callers. The audited incident-only break-glass path below is the explicit exception to this normal-operation rule and must follow its evidence, fencing, reset, and verification gates. + - Current normal-operation access uses the generic `common-data-runtime` `firemud.redis.*` properties and its auto-configured `RedisConnectionFactory`, `RedisTemplate`, and `StringRedisTemplate`; deployment configuration routes that generic client only to its configured endpoint. The shared hosted profile points that endpoint at `redis-cache`, and the role-specific environment variables are not consumed by this generic factory, so current Coordination callers cannot claim role-isolated routing. The ADR 0176 owner-local descriptor/key-builder foundation, shared contract validation, and aggregated registry are target state and are not implemented. Target state requires all mutations to coordination prefixes (`tick:*`, `retry:*`, `timer:*`, `remote:*`, `session:*`, `tick-executor-lease:*`, and related keys) to use the owning service's registered typed key and mutation helpers, with the shared foundation validating descriptors and aggregation; it does not centralize owner-exclusive execution. Lua is mandatory for atomic multi-key behavior and may be used for an explicitly documented single-key atomic guard or compare-and-set contract. Ordinary single-key mutations use owner-local typed helpers without Lua, and executable helpers or Lua are shared only for mutations genuinely executed by multiple independently deployed callers. The audited incident-only break-glass path below is the explicit exception to this normal-operation rule and must follow its evidence, fencing, reset, and verification gates. - In target state, application services (Game Session, Automation & Scripting, and any future tick participants) never bypass those helpers with raw Redis commands; current direct usages require reconciliation against the owner-local contract rather than being treated as proof that the target helpers exist. - Human operators and ad-hoc tools: - May use `redis-cli`, RedisInsight, or similar tools with **read-only ops users** to inspect coordination state. diff --git a/design/architecture/system-architecture-redis-usage-and-profiles.md b/design/architecture/system-architecture-redis-usage-and-profiles.md index db0ce50ea4..98403e600a 100644 --- a/design/architecture/system-architecture-redis-usage-and-profiles.md +++ b/design/architecture/system-architecture-redis-usage-and-profiles.md @@ -17,6 +17,8 @@ The shared `ConflictTracker` is another concrete consumer of this generic wiring The hosted Helm Cache/Rate-Limit Redis process has a separate configuration drift: the enabled hosted overlay provisions a persistent cache volume, while the in-chart `redis-cache` Deployment starts Redis with AOF enabled and does not set `maxmemory` or an eviction policy. This does not provide the bounded, eviction-driven Cache/Rate-Limit profile and can retain disposable cache/rate-limit state across restart; the hosted cache process must load the cache profile or declare equivalent bounded settings before this environment can claim the target cache posture. +The checked Coordination configurations (`config/redis/redis.conf`, the in-chart `redis-coord`, and production Coordination values) do not set an internal Redis `maxmemory` bound. Container and pod resource limits are external process constraints, not Redis `maxmemory`; while Redis defaults to `noeviction` when no policy is configured, the absent internal bound does not establish the required bounded Coordination profile. Concrete per-environment sizing and configuration remain with Platform Operations/6D. + --- ## Table of Contents diff --git a/design/project-management/implementation-tracking/platform-operations-and-delivery.md b/design/project-management/implementation-tracking/platform-operations-and-delivery.md index 93b5ac9a67..30e991e1bf 100644 --- a/design/project-management/implementation-tracking/platform-operations-and-delivery.md +++ b/design/project-management/implementation-tracking/platform-operations-and-delivery.md @@ -66,7 +66,7 @@ These links record implementation and proof gaps; they do not claim that the cor | `PO-2.3` Client protocol negotiation and structured protocol extensions | `partial` | `drift-found`: existing Telnet/WebSocket projection and transport tests cover current behavior, but schema-version compatibility and unsupported-version handling are not implemented/proven | [MUD client protocol](../../architecture/system-architecture-mud-client-protocol.md); [protocol bridging](../../architecture/system-architecture-protocol-bridging.md); [Input, output, and presentation](../../architecture/system-architecture-input-output-and-presentation.md) | [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [WebSocketOutputProjector.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjector.java) | [TelnetServerHandlerTest.java](../../../services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandlerTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [WebSocketOutputProjectorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java) | [Player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md) | Richer smart-client capabilities and first-party protocol extensions remain. Future focused proof must cover the sanitized bridge matrix: supported Telnet controls, unsupported options/subnegotiation, opaque markers, byte/line limits, and exact post-filter forwarding. The supported structured-client contract still needs explicit schema-version compatibility/unsupported-version proof; every envelope must retain a deterministic plain-text projection for Telnet and generic text WebSocket. | | `PO-2.4` Edge limits, backpressure, close taxonomy, and retry behavior | `partial`: current retry-count/delay handling, rate limits, close metrics, and bounded connection controls are live | `drift-found`: current tests prove the shipped attempt-based bridge, not ADR 0013's elapsed-time cutoff, bounded stall/rebind buffer, or terminal-versus-rebindable classification | [Gateway](../../architecture/system-architecture-gateway.md); [ADR 0007](../../architecture/decisions/adr-0007-edge-sharding-and-close-taxonomy.md); [ADR 0013](../../architecture/decisions/adr-0013-bounded-invisible-non-edge-restart-recovery.md); [ADR 0170](../../architecture/decisions/adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md) | [GameplayWebSocketBridgeProperties.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeProperties.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [GameplayWebSocketObservability.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservability.java); [IpConnectionLimiterImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/IpConnectionLimiterImpl.java); [GatewayRateLimiterConfig.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfig.java) | [GameplayWebSocketObservabilityTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservabilityTest.java); [GameplayWebSocketBridgeHandlerTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java); [GatewayRateLimiterConfigTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayRateLimiterConfigTest.java) | [Player access](./player-access-and-session.md); [player experience](./player-experience-commands-and-communication.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | Elapsed recovery cutoff, bounded stall/rebind handling, outcome classification, and focused proof remain incomplete. | | `PO-3.1` Packaging, CI/CD, deployment, promotion, and infrastructure topology | `partial` | `proven` for current packaging/deployment checks only; exact-plan authorization and evidence remain incomplete | [CI/CD](../../architecture/system-architecture-cicd.md); [infrastructure](../../architecture/infrastructure/README.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0097](../../architecture/decisions/adr-0097-git-and-ci-validated-single-operator-promotion-evidence.md); [ADR 0177](../../architecture/decisions/adr-0177-exact-plan-authorized-automated-production-deployment.md) | [build.gradle.kts](../../../build.gradle.kts); [runtime-images.yml](../../../.github/workflows/runtime-images.yml); [apps.yaml](../../../k8s/helm/firemud/templates/apps.yaml); [prod kustomization.yaml](../../../k8s/overlays/prod/kustomization.yaml) | [preview-eligibility-contract.sh](../../../dev-tools/tests/preview-eligibility-contract.sh); [smoke-image-env-contract.sh](../../../dev-tools/tests/smoke-image-env-contract.sh); [validate-helm.sh](../../../dev-tools/validation/validate-helm.sh); [validate-kustomize-overlays.sh](../../../dev-tools/deploy/validate-kustomize-overlays.sh) | [Authoring](./game-authoring-publishing-and-activation.md) | Current packaging and deployment checks pass, but exact-plan authorized deployment, promotion enforcement, attestation lineage, applicable maturity-scoped protobuf compatibility, and controller-authoritative recovery compatibility remain incomplete. | -| `PO-3.2` Environment, configuration, secret, certificate, and service-discovery delivery | `partial` | `proven` for local/static hosted identity contracts; live rollout remains unproved | [Environment/secrets](../../architecture/infrastructure/environment-and-secrets-overview.md); [deployment environments](../../architecture/infrastructure/deployment-environments.md); [ADR 0032](../../architecture/decisions/adr-0032-kubernetes-native-secret-delivery-without-mandatory-vault.md); [ADR 0152](../../architecture/decisions/adr-0152-phased-environment-bound-deployment-preflight-and-expected-bindings.md); [ADR 0171](../../architecture/decisions/adr-0171-separated-redis-role-processes-and-owned-keyspaces.md); [ADR 0182](../../architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md) | [preflight.py](../../../dev-tools/deploy/preflight.py); [hosted identity controller bootstrap](../../../dev-tools/hosted/controller/bootstrap-hosted-identity-controller.sh); [hosted identity controller kustomization](../../../k8s/hosted-identity-controller/kustomization.yaml); [shared-config.yaml](../../../k8s/helm/firemud/templates/shared-config.yaml); [JwtAuthProperties.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtAuthProperties.java) | [preflight-contract.sh](../../../dev-tools/tests/preflight-contract.sh); [secret-compliance-contract.sh](../../../dev-tools/tests/secret-compliance-contract.sh); [check-grpc-transport-config.sh](../../../dev-tools/validation/check-grpc-transport-config.sh); [validate-kustomize-overlays.sh](../../../dev-tools/deploy/validate-kustomize-overlays.sh); [helm-jwks-contract.sh](../../../dev-tools/tests/helm-jwks-contract.sh); [hosted-identity-controller-manifest-contract.sh](../../../dev-tools/tests/hosted-identity-controller-manifest-contract.sh); [hosted-identity-controller-workflow-contract.sh](../../../dev-tools/tests/hosted-identity-controller-workflow-contract.sh) | [Shared runtime](./shared-runtime-contracts-and-persistence.md); [player access](./player-access-and-session.md) | Secret/certificate custody, encryption/RBAC/audit evidence, credential rotation, outage continuity, served-certificate/consumer convergence, and live-cluster preflight proof remain incomplete. The hosted controller contract is local/static evidence only; binding-reference and fingerprint validators do not establish canonical operator binding-generation, operation identity, overlap, and readback evidence; the richer binding record remains target-only. Exact operator-rendered controller egress now removes broad CIDRs and statically covers the observed API, public probe, explicit Traefik TCP/8443 post-DNAT target, TCP Proxy TCP/2323 post-NodePort-DNAT target, Telnet, and scoped Gateway destinations, but PO-3.2 remains incomplete until the complete live allow/deny matrix, CNI post-DNAT behavior, and served Gateway↔TCP Proxy bridge proof are established. | +| `PO-3.2` Environment, configuration, secret, certificate, and service-discovery delivery | `partial` | `proven` for local/static hosted identity contracts; live rollout remains unproved | [Environment/secrets](../../architecture/infrastructure/environment-and-secrets-overview.md); [deployment environments](../../architecture/infrastructure/deployment-environments.md); [ADR 0032](../../architecture/decisions/adr-0032-kubernetes-native-secret-delivery-without-mandatory-vault.md); [ADR 0152](../../architecture/decisions/adr-0152-phased-environment-bound-deployment-preflight-and-expected-bindings.md); [ADR 0171](../../architecture/decisions/adr-0171-separated-redis-role-processes-and-owned-keyspaces.md); [ADR 0182](../../architecture/decisions/adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md) | [preflight.py](../../../dev-tools/deploy/preflight.py); [hosted identity controller bootstrap](../../../dev-tools/hosted/controller/bootstrap-hosted-identity-controller.sh); [hosted identity controller kustomization](../../../k8s/hosted-identity-controller/kustomization.yaml); [shared-config.yaml](../../../k8s/helm/firemud/templates/shared-config.yaml); [JwtAuthProperties.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/JwtAuthProperties.java) | [preflight-contract.sh](../../../dev-tools/tests/preflight-contract.sh); [secret-compliance-contract.sh](../../../dev-tools/tests/secret-compliance-contract.sh); [check-grpc-transport-config.sh](../../../dev-tools/validation/check-grpc-transport-config.sh); [validate-kustomize-overlays.sh](../../../dev-tools/deploy/validate-kustomize-overlays.sh); [helm-jwks-contract.sh](../../../dev-tools/tests/helm-jwks-contract.sh); [hosted-identity-controller-manifest-contract.sh](../../../dev-tools/tests/hosted-identity-controller-manifest-contract.sh); [hosted-identity-controller-workflow-contract.sh](../../../dev-tools/tests/hosted-identity-controller-workflow-contract.sh) | [Shared runtime](./shared-runtime-contracts-and-persistence.md); [player access](./player-access-and-session.md) | Secret/certificate custody, encryption/RBAC/audit evidence, credential rotation, outage continuity, served-certificate/consumer convergence, and live-cluster preflight proof remain incomplete. The hosted controller contract is local/static evidence only; binding-reference and fingerprint validators do not establish canonical operator binding-generation, operation identity, overlap, and readback evidence; the richer binding record remains target-only. Exact operator-rendered controller egress now removes broad CIDRs and statically covers the observed API, public probe, explicit Traefik TCP/8443 post-DNAT target, TCP Proxy TCP/2323 post-NodePort-DNAT target, Telnet, and scoped Gateway destinations, but PO-3.2 remains incomplete until the complete live allow/deny matrix, CNI post-DNAT behavior, served Gateway↔TCP Proxy bridge proof, and concrete Redis role-profile configuration—including an internal Coordination Redis `maxmemory` bound—are implemented and proved. Configuration and per-environment sizing remain owned by Platform Operations/6D. | | `PO-3.3` Object storage, CDN, registry, and platform asset delivery infrastructure | `partial` | `proven` | [Asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [infrastructure](../../architecture/infrastructure/README.md) | [AssetStoreConfig.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/config/AssetStoreConfig.java); [AssetController.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/AssetController.java); [V10__version_asset_artifact.sql](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql); [MinIO deployment.yaml](../../../k8s/minio/deployment.yaml); [runtime-images.yml](../../../.github/workflows/runtime-images.yml) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetArtifactRepositoryIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryIntegrationTest.java); [validate-helm.sh](../../../dev-tools/validation/validate-helm.sh); [smoke-image-env-contract.sh](../../../dev-tools/tests/smoke-image-env-contract.sh) | [Authoring](./game-authoring-publishing-and-activation.md); [player experience](./player-experience-commands-and-communication.md) | Production CDN lifecycle, richer registry operations, and creator-facing asset delivery remain. | | `PO-3.4` Backup, restore, disaster recovery, and self-hosted recovery | `partial` | `drift-found`: bounded online-dump and backup-verifier helper/image contract checks, non-executing restore wiring, reset, and restart seams are proven locally; no live backup existence/reachability is proven, and the broader recovery capability remains unproven | [Backup/recovery](../../architecture/system-architecture-backup-recovery.md); [recovery evidence](../../architecture/system-architecture-backup-recovery-evidence-and-compliance.md); [CI/CD](../../architecture/system-architecture-cicd.md) | [schedule.yaml](../../../k8s/velero/schedule.yaml); [verify-backups-cronjob.yaml](../../../k8s/velero/verify-backups-cronjob.yaml); [manual-backup-restore.yml](../../../.github/workflows/manual-backup-restore.yml); [pg-dump-rotate.sh](../../../dev-tools/backups/pg-dump-rotate.sh); [restore-cluster.sh](../../../dev-tools/restores/restore-cluster.sh); [reset-service-db.sh](../../../dev-tools/restores/reset-service-db.sh); [smoke-backup-verifier-image.sh](../../../dev-tools/backups/smoke-backup-verifier-image.sh) | [verify-backups.sh](../../../dev-tools/backups/verify-backups.sh); [verify-backups-velero-contract.sh](../../../dev-tools/tests/verify-backups-velero-contract.sh); [verify-backups-cronjob-contract.sh](../../../dev-tools/tests/verify-backups-cronjob-contract.sh); [backup-verifier-image-contract.sh](../../../dev-tools/tests/backup-verifier-image-contract.sh); [reset-service-db-contract.sh](../../../dev-tools/tests/reset-service-db-contract.sh); [verify-restart-state.sh](../../../dev-tools/verify-restart-state.sh) | [Shared runtime](./shared-runtime-contracts-and-persistence.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | The [Backup helper README](../../../dev-tools/backups/README.md) documents the helper boundaries. Measured verified-point RPO, immutable artifact and restore lineage, readable restore execution, environment-wide cold-start quarantine and reconciliation, post-restore trust reset, recovery-controller continuation, and controlled traffic reopen remain unimplemented or unproven. | | `PO-4.1` Logging, metrics, tracing, dashboards, and alerting | `partial` | `drift-found` | [ADR 0017](../../architecture/decisions/adr-0017-capability-gated-operational-tracing.md); [ADR 0162](../../architecture/decisions/adr-0162-profile-aware-asynchronous-end-to-end-log-queryability-evidence.md); [ADR 0167](../../architecture/decisions/adr-0167-allowlisted-sensitive-trace-attributes.md); [Logging/monitoring](../../architecture/system-architecture-logging-monitoring.md); [tracing](../../architecture/system-architecture-tracing.md) | [RuntimeIdentity.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtime/RuntimeIdentity.java); [MetricsInterceptor.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/MetricsInterceptor.java); [GameplayWebSocketObservability.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservability.java); [prometheus-rules-firemud.yaml](../../../k8s/monitoring/prometheus-rules-firemud.yaml) | [check-metrics-cardinality.py](../../../dev-tools/observability/check-metrics-cardinality.py); [validate-observability-contract.py](../../../dev-tools/observability/validate-observability-contract.py); [player-experience-smoke-runner-contract.sh](../../../dev-tools/tests/player-experience-smoke-runner-contract.sh); [GameplayWebSocketObservabilityTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservabilityTest.java) | [Shared runtime](./shared-runtime-contracts-and-persistence.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [player experience](./player-experience-commands-and-communication.md) | ADR 0017 level 1 (baseline observability) is the highest current advertisement: metrics and structured logs are the dependable surface, while generic RPC spans/export and trace-log correlation are best-effort. No named workflow has level-2 end-to-end proof; service-scoped sampling (level 3), tenant/game-instance/region sampling (level 4), broad region enrichment, embedded dashboards, and recovery-participant convergence observability remain unproved. The missing-source alert is fail-safe gap detection only and does not establish recovery readiness. The current profile overlays install only the applicable deadman rules; the player-flow canary and public-path blackbox alert families remain target-only and uninstalled pending deployment-owned gates. Capability-aware installation, deployment-owned external alert authority, atomic profile-transition cleanup, residual-series handling, and live proof remain implementation gaps. | diff --git a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md index 28594842a6..4dc6005dc1 100644 --- a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md +++ b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md @@ -54,7 +54,7 @@ The following current-state findings refine the existing partial/drift status; o - `SF-2.1`: Game Design’s historical `version.revision_ids` relationship was dropped before revisions were assigned to the latest tenant version, so immutable revision/version history is not proven. Retained-data disposition or a verified no-data boundary remains open; see [Versioning & Runtime Configuration](../../architecture/system-architecture-versioning-runtime.md#implementation-status). - `SF-2.1` / `SF-2.3`: Account’s connect-token path remains a bounded Redis map without durable issuance-operation, encrypted-response, or atomic exact-request-claim support. A read-then-mint/unconditional-write race can produce different tokens for one request identity, and the exact-result/recovery contract remains unimplemented. Current evidence and owner status are recorded in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). - `SF-2.2`: Gateway’s replay/deny/readiness implementation remains unaligned with the canonical Redis key grammar, reset, catalog, and proof boundaries; its current marker and the Account Redis map remain implementation drift. See [Redis](../../architecture/system-architecture-redis.md) and [Gateway Service](../../architecture/microservices/spring-cloud-gateway/README.md#implementation-status). -- `SF-2.1` / `SF-2.2`: Redis role-specific clients remain unimplemented: current Game Session correctness state and cache consumers can share one generic endpoint/template despite separate deployed coordination and cache Redis roles. Compose can route the generic binding to the eviction-enabled cache Redis, while base Kubernetes supplies no generic hostname and the default `redis` endpoint may be unavailable. A role-qualified client refactor plus focused routing, eviction-isolation, and readiness proof remain open; this tracker records the consequence without implementing that refactor. +- `SF-2.1` / `SF-2.2`: Redis role-specific clients remain unimplemented: current Game Session correctness state and cache consumers can share one generic endpoint/template despite separate deployed coordination and cache Redis roles. Compose can route the generic binding to the eviction-enabled cache Redis, while base Kubernetes supplies no generic hostname and the default `redis` endpoint may be unavailable. A role-qualified client refactor plus focused routing, eviction-isolation, and readiness proof remain open. The checked Coordination configs also lack an internal Redis `maxmemory` bound; external container/pod limits do not satisfy that requirement. This role-profile configuration gap remains jointly owned by shared runtime 5C and Platform Operations/6D; this tracker records the consequence without implying implementation. - `SF-1.2` / `SF-2.1`: Entity’s durable S1/S2 schema lacks the target namespace identity across character, inventory, equipment, and holder/containment associations, and nullable `item_stacks` uniqueness is paired with find-then-create writes. Migration, repository, isolation, and concurrency proof remain open; see [Entity Runtime and Data](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status). - `SF-2.1` / `SF-2.4`: Game Design-to-World publication currently uses a remote Draft-state pre-check before WMS mutation, without a durable WMS owner-freeze row or exact publication fence, so mutation can race publication. The implementation and proof gap is recorded in [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status) and [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff). - `SF-2.1`: `version_asset` and release-bundle referential-integrity proof remains incomplete for tenant-qualified ownership and cross-tenant readback; see [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#table-structure). From a38861d006521b1e604b525a01d21ba0ce2de8f3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 23 Sep 2026 15:46:46 +1200 Subject: [PATCH 27/68] docs(game-session): correct remote retry status --- .../microservices/game-session-service/runtime-and-data.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index e1fc8a00ca..6bde134316 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -20,7 +20,7 @@ The sections below define the target-state runtime contract. Current implementat - Current `onCommand` ingress uses the live `{tenantId, gameInstanceId}` boundary as a region surrogate until true region partitioning is shipped; it carries the current `regionEpoch` and a producer-supplied `readSnapshotToken` derived from the command and ownership fence. That token is retained only as an owner-specific manifest input or correlation value, not universal evaluation authority. The target handler-scoped input manifest is owned by the [DSL lifecycle contract](../../system-architecture-scripting-dsl-reference-and-lifecycle.md#read-consistency-contract); current producer/storage behavior is narrower and does not yet seal the complete manifest. - Durable command/effect execution currently covers movement and `PUT`, `TAKE`, `WEAR`, and `REMOVE` fully at the existing boundary. Current `GET` is the command spelling for the target `PICKUP`/`PickupVisibleRoomItem` family, and `GET` plus `DROP` also enqueue and execute on that durable command path, but their ADR 0054 spatial correctness remains incomplete until World `TargetingFactSnapshot` attestation/location-version propagation, the shared actor-lock/executor-fence critical section and durable barrier/handoff path, and stale-race proof are implemented. Current movement/item replay rows do not yet prove the ADR 0054 participant guard bound to root `EffectId`, typed operation, target, and request digest, or fail-closed changed reuse. - The target spatial/ambient reconciliation contract is not a current Game Session surface: the typed `EffectReconciliationAuthority`, durable `effect_reconciliation_backlog`/authority schema, immutable effect guards, durable action ledger/results, and list/retry/acknowledgement APIs remain unimplemented. Current persistence is limited to `tick_batch`/`tick_effect` and narrower domain/remote-follow-up reconciliation; see [Game Session API status](./api-contracts.md#implementation-status) and the normative [transaction reconciliation owner](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects). -- The target remote-follow-up contract makes terminal timeout/late outcomes immutable under the original identity: exact retries return the stored terminal outcome, and a late-applied result requires a separately documented feature-specific compensation flow. Current implementation/proof gap: an exact `scheduleFollowup` retry can reset an existing terminal timeout/late coordinator/follow-up pair to `PENDING_REMOTE`/`SCHEDULED`, mirror that pending state to the origin command, and clear mirrored terminal completion/failure fields. The live `late_result_requires_reconciliation` path also writes `LATE_RESULT_RECONCILED`/`PARTIAL` and mirrors `APPLIED`/`PARTIAL` to the origin without a separately identified compensation/saga flow; post-abandon re-drive and compensation ownership remain unproved. +- The target remote-follow-up contract makes terminal timeout/late outcomes immutable under the original identity: exact retries return the stored terminal outcome, and a late-applied result requires a separately documented feature-specific compensation flow. The current `scheduleFollowup` replay path returns an existing retryable-timeout pair or valid terminal pair without mutation, with focused unit proof for terminal-pair replay. This does not establish exact serialized timeout/result arbitration under concurrency, complete terminal-failure mirroring, missing-coordinator recovery, or late-result compensation. The live `late_result_requires_reconciliation` path also writes `LATE_RESULT_RECONCILED`/`PARTIAL` and mirrors `APPLIED`/`PARTIAL` to the origin without a separately identified compensation/saga flow; post-abandon re-drive and compensation ownership remain unproved. - Current tick staging has Redis-first windows that are not the target durable-first boundary: ingress pushes the queue payload before marking the durable command `STAGED`, and tick processing moves queue entries to Redis `pending` before creating the durable `tick_batch`/`tick_effect` rows. A crash or Redis loss in either window can strand a `STAGED` command with no batch/effect, while startup recovery only handles `ACCEPTED` rows with no staging timestamp and purge can classify a no-effect row as `LOST_BEFORE_STAGING`. Only explicitly classified volatile ingress may receive that evidence-qualified outcome; durable accepted work needs a durable source claim/materialization recovery path and its feature-specific replay/re-drive contract. The target boundary creates the durable batch/effect/source claim before `pending` staging and treats Redis-only residue as reconstructible coordination state; the current ordering and no-batch recovery are implementation drift. - The target stale-fence contract preserves a drained effect under its original mutation `EffectId` and enclosing root lineage while evidence-fenced reconciliation determines whether it is `APPLIED` or safely unapplied. `ABANDONED` requires authoritative participant/domain evidence; ordinary retry/replay retains the original command/effect identity, and only a conclusive post-abandon re-drive allocates a new command ID and root. The current implementation instead marks stale drained batches/effects `ABANDONED` on the fence/technical signal alone and requeues the same command, after which a later batch derives a new effect identity. This is unsafe implementation drift: a crash after participant mutation but before ledger terminalization can permit duplicate logical application or false abandonment. - `BLOCK` is also on the current durable effect replay/no-op seam; other state-changing command families still need to migrate onto it. From 0c53700f0f04424457f62ddc78feed87e8bbebd1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 25 Sep 2026 09:42:47 +1200 Subject: [PATCH 28/68] test(automation): use coherent identity fixtures for PostgreSQL claims --- ...AutomationScriptingServiceApplicationIntegrationTest.java | 5 ++++- ...AutomationClaimAndRetentionRepositoryIntegrationTest.java | 3 +-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/AutomationScriptingServiceApplicationIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/AutomationScriptingServiceApplicationIntegrationTest.java index 1862ef9978..2f67bba686 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/AutomationScriptingServiceApplicationIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/AutomationScriptingServiceApplicationIntegrationTest.java @@ -481,9 +481,11 @@ private static ScriptEventIngressAudit concurrentNullableIngressAudit(String scr audit.setWorldSlug(""); audit.setRealmSlug(""); audit.setPointerVersion(""); - audit.setEventType("onCommand"); + audit.setScriptId("script-nullable-ingress"); + audit.setEventType("onLoad"); audit.setEventSchemaVersion("v1"); audit.setScriptPatchVersion("patch-nullable-ingress"); + audit.setRequestDigest("a".repeat(64)); audit.setScriptEventId(scriptEventId); audit.setSourceService("integration-test"); audit.setTriggerMode("EVENT"); @@ -559,6 +561,7 @@ private static ScriptWorkItem concurrentReplayWorkItem() { item.setStatus("DEAD_LETTERED"); item.setFailureGeneration(7L); item.setScriptPinEpoch(1L); + item.setScriptPinControlPlaneRequestId("pin-request-concurrent-replay"); item.setCreatedAt(Instant.now()); item.setUpdatedAt(Instant.now()); return item; diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java index 175aa3a62b..442175e7a9 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java @@ -248,7 +248,6 @@ void handlerAuditInsertDiscriminatorPreservesTenantIdentityOnDuplicate() { assertThat(dsl.fetchCount(SCRIPT_EVENT_AUDIT)).isEqualTo(1); ScriptEventAudit duplicate = handlerAudit("tenant-handler-audit"); - duplicate.setSourceService("duplicate-service"); duplicate.setFinalOutcome("DUPLICATE_ATTEMPT"); duplicate.setFinalReason("duplicate-attempt"); @@ -958,7 +957,7 @@ void incompleteChildBlocksOnlyItsCorrelatedParentDuringAgeRetention() { ScriptHandoffEvent incompleteHandoff = retainedHandoff(incompleteParent.getId()); incompleteHandoff.setEventId("incomplete-correlated-parent"); incompleteHandoff.setHandoffOutcome(""); - handoffRepository.save(incompleteHandoff); + incompleteHandoff = handoffRepository.save(incompleteHandoff); ScriptWorkItem completeParent = retainedWorkItem(); completeParent.setScriptEventId("complete-correlated-parent"); From d04a57735862da9770964ccc086bb8950e6920dd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 25 Sep 2026 10:40:56 +1200 Subject: [PATCH 29/68] Format Automation PostgreSQL proof fixture --- .../AutomationScriptingServiceApplicationIntegrationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/AutomationScriptingServiceApplicationIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/AutomationScriptingServiceApplicationIntegrationTest.java index 6611f02124..7c8c818fdf 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/AutomationScriptingServiceApplicationIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/AutomationScriptingServiceApplicationIntegrationTest.java @@ -21,19 +21,19 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.automationscripting.dto.ScriptDefinitionDto; +import net.firedevops.firemud.automationscripting.entity.Faction; import net.firedevops.firemud.automationscripting.entity.ScriptDefinition; import net.firedevops.firemud.automationscripting.entity.ScriptEventBinding; import net.firedevops.firemud.automationscripting.entity.ScriptEventIngressAudit; import net.firedevops.firemud.automationscripting.entity.ScriptHandoffEvent; import net.firedevops.firemud.automationscripting.entity.ScriptWorkItem; -import net.firedevops.firemud.automationscripting.entity.Faction; import net.firedevops.firemud.automationscripting.mapper.ScriptDefinitionMapper; +import net.firedevops.firemud.automationscripting.repository.FactionRepository; import net.firedevops.firemud.automationscripting.repository.ScriptDefinitionRepository; import net.firedevops.firemud.automationscripting.repository.ScriptEventBindingRepository; import net.firedevops.firemud.automationscripting.repository.ScriptEventIngressAuditRepository; import net.firedevops.firemud.automationscripting.repository.ScriptHandoffEventRepository; import net.firedevops.firemud.automationscripting.repository.ScriptWorkItemRepository; -import net.firedevops.firemud.automationscripting.repository.FactionRepository; import net.firedevops.firemud.automationscripting.service.impl.BuiltInScriptEventRegistryService; import net.firedevops.firemud.automationscripting.service.impl.ScriptDefinitionServiceImpl; import net.firedevops.firemud.common.saga.SagaException; From 7e2de1eede3bab6f4a99df8005d986bb402bf2b9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 14:48:22 +1300 Subject: [PATCH 30/68] Preserve tick commit and handoff retry boundaries --- ...ystem-architecture-tick-execution-flows.md | 4 +- .../architecture/system-architecture-ticks.md | 5 +- dev-tools/tests/architecture-doc-contracts.sh | 20 ++++ ...riptGameplayCommandHandoffServiceImpl.java | 14 +-- .../ScriptWorkItemExecutionServiceImpl.java | 37 +++++-- ...GameplayCommandHandoffServiceImplTest.java | 33 +++++++ ...criptWorkItemExecutionServiceImplTest.java | 99 +++++++++++++++++++ ...mationGameplayCommandAdmissionSupport.java | 16 ++- ...onGameplayCommandAdmissionSupportTest.java | 40 ++++++++ 9 files changed, 246 insertions(+), 22 deletions(-) diff --git a/design/architecture/system-architecture-tick-execution-flows.md b/design/architecture/system-architecture-tick-execution-flows.md index e1570ecf26..9e7ba81305 100644 --- a/design/architecture/system-architecture-tick-execution-flows.md +++ b/design/architecture/system-architecture-tick-execution-flows.md @@ -372,7 +372,7 @@ Conceptually, tick commit proceeds through these phases: - Domain services process staged effects under participant guards keyed by the persisted mutation `EffectId` (root ID for a root mutation, child ID for a generated child), with `rootEffectId` retained separately as lineage, and update authoritative PostgreSQL state in their own databases. - Game Session records the outcome of each effect in its tick effect ledger (`SCHEDULED` → `APPLIED` or `ABANDONED`) only when the durable domain evidence and existing recovery policy permit that transition; inconclusive old-epoch work remains non-terminal reconciliation work under its original mutation `EffectId`, with enclosing `rootEffectId` retained as lineage and reconciliation context. Domain services do not write to the Game Session ledger directly. 4. **Commit visibility** - - For a non-empty batch, once all ledger rows that belong to that tick batch are terminal (`APPLIED` or `ABANDONED`) under the existing evidence policy, one fenced durable commit boundary transitions `tick_batch.status` to `COMMITTED` and advances the commit authority `RegionStatus.lastCommittedTickId` for the complete current scope under the same `executorFence`; only then may the target-state tick heartbeat be emitted. An inconclusive old-epoch row remains non-terminal and blocks this advancement. A truly empty boundary uses the separate fenced one-tick status transition and post-commit heartbeat branch above, with no batch ledger. The current-live deployment instead advances the committed tick fields on `RuntimeOwnershipStatus` under the current-live opaque fence; `ObserveRuntimeTickProgress` reports that progress, and neither `RegionStatus` nor `StreamTickHeartbeats` is implied to be live. + - For a non-empty batch, the current-epoch commit predicate: terminal (`APPLIED` or `ABANDONED`) evidence under the existing evidence policy is required for every required participant in that tick's complete expected current-epoch participant set. Once that predicate holds, one fenced durable commit boundary transitions `tick_batch.status` to `COMMITTED` and advances the commit authority `RegionStatus.lastCommittedTickId` for the complete current scope under the same `executorFence`; only then may the target-state tick heartbeat be emitted. Inconclusive old-epoch rows remain non-terminal reconciliation work outside this current-epoch commit predicate; they may still block unsafe next-tick progression, reset-scope convergence, or reopening. A truly empty boundary uses the separate fenced one-tick status transition and post-commit heartbeat branch above, with no batch ledger. The current-live deployment instead advances the committed tick fields on `RuntimeOwnershipStatus` under the current-live opaque fence; `ObserveRuntimeTickProgress` reports that progress, and neither `RegionStatus` nor `StreamTickHeartbeats` is implied to be live. - Cross-region coordinator rows such as `PENDING_REMOTE` are not part of this terminal set; they are durable workflow state outside the committing tick batch. 5. **Coordination cleanup** - A final commit/cleanup script clears the `pending` entry for the tick and releases any entity locks for that region only after exact equality between the pending envelope set and the durable batch/ledger expected set has been established. `expected_effect_count` and any digest are diagnostic hints and cannot authorize cleanup on their own. @@ -381,7 +381,7 @@ Conceptually, tick commit proceeds through these phases: From the perspective of the `(regionEpoch, tickId)` timeline: - A tick is `durable_committed` once: - - For a non-empty tick, all ledger rows owned by that tick batch for `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)` have reached a terminal state (`APPLIED` or `ABANDONED`) where the evidence policy permits terminalization; inconclusive old-epoch work remains non-terminal and prevents this boundary. A truly empty tick instead proves the authoritative no-due-work/source-claim condition and commits the fenced one-tick status transition, and + - For a non-empty tick, the current-epoch commit predicate: terminal (`APPLIED` or `ABANDONED`) evidence is required, where the evidence policy permits terminalization, for every required participant in that tick's complete expected current-epoch participant set. Inconclusive old-epoch rows remain non-terminal reconciliation work outside this current-epoch commit predicate; they may still block unsafe next-tick progression, reset-scope convergence, or reopening. A truly empty tick instead proves the authoritative no-due-work/source-claim condition and commits the fenced one-tick status transition, and - The target-state commit authority `RegionStatus.lastCommittedTickId`, or the current-live committed tick fields on `RuntimeOwnershipStatus`, has advanced to that `(regionEpoch, tickId)` under the applicable fence. `ObserveRuntimeTickProgress` may confirm current-live progress but does not replace the durable authority. - A tick is `coordination_cleared` once: - There is no remaining `pending` entry for that tick in Redis and lock cleanup for that tick has completed. diff --git a/design/architecture/system-architecture-ticks.md b/design/architecture/system-architecture-ticks.md index 7ef44d518a..d855a59394 100644 --- a/design/architecture/system-architecture-ticks.md +++ b/design/architecture/system-architecture-ticks.md @@ -34,9 +34,8 @@ Current live substrate to keep in mind while reading: - the live durable ownership and command-status boundary is currently keyed by `{tenantId, gameInstanceId}`, not true `regionId` partitioning; - the live control-plane/status APIs are `GetRuntimeOwnershipStatus` and the canonical `GetGameplayCommandStatus`; the live scheduler progress feed is `ObserveRuntimeTickProgress` carrying `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)`; `StreamTickHeartbeats` and `GetRegionTickStatus` remain target-state follow-through; - the live `executorFence` is an opaque generation token used for compare-and-match stale-fence protection, not yet the richer numeric ordering model used in some target-state examples; -- the live `tick_batch` / `tick_effect` substrate is real, and the current gameplay-command manifest now carries current-boundary `enqueueSeq`, `sourceType`, `dueTickId`, and explicit claimed-source state plus digest-checked replay reuse. The live `enqueueSeq` comes from one database-wide sequence; the region-scoped, cross-source allocator that remains monotonic across epoch resets is target-state. Timer/retry/remote-follow-up source-claim breadth and the cross-region result-return contract described below are also target-state follow-through rather than fully shipped behavior. +- the live `tick_batch` / `tick_effect` substrate is real, and the current gameplay-command manifest now carries current-boundary `enqueueSeq`, `sourceType`, `dueTickId`, and explicit claimed-source state plus digest-checked replay reuse. The live `enqueueSeq` comes from one database-wide sequence; target `entity_enqueue_seq` is monotonic within the entity's current region epoch under accepted [ADR 0065](./decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md). Timer/retry/remote-follow-up source-claim breadth and the cross-region result-return contract described below are also target-state follow-through rather than fully shipped behavior. - the live Game Session automation handoff carries `scriptPatchVersion`, positive `scriptPinEpoch`, and `scriptPinControlPlaneRequestId` on `EnqueueAutomationCommandIfAbsentRequest`; Game Session compares the tuple with authoritative owner state and rejects incomplete or stale evidence before staging or duplicate replay. Exact tuple checks also remain at the live instance-bound Automation ingress, timer, and work-item admission boundaries. The handoff still lacks `commandOrdinal` and the full Trigger Identity required for target-state per-command diagnostics. Live gameplay staging requires a present, nonblank durable `commandId` before Redis enqueue or durable batch staging, and `TickStagingService` derives `effectKey` as `command:`; complete source/target binding and remote final-effect fence proof remain implementation gaps. -- Any future region-scoped/cross-source ordering allocator, including its scope and reset sequence behavior, remains conditional and non-authoritative pending [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); it cannot change the accepted current `enqueueSeq` or replay/effect identity rules. Timer/retry/remote-follow-up source-claim breadth and the cross-region result-return contract described below are also target-state follow-through rather than fully shipped behavior. - the target deterministic command-plan root contract is not fully live: the owning command/action contract for the frozen typed command or `ResolvedEffectPlan` must supply semantic root order, with built-ins declaring equivalent stable order; ambiguous or duplicate order fails before admission. Before allocation, the durable gameplay command row must freeze/bind its request fingerprint, resolved runtime scope, and applicable `playableStateNamespaceId`. Game Session must persist the ordered plan manifest/digest and an opaque root allocation row unique on `(tenantId, gameInstanceId, commandId, planOrdinal)`; the row binds the manifest digest and validates the frozen command/runtime/namespace binding, and retries reuse it only when all of those values match, otherwise failing closed. For Automation, the complete applicable Command-Handoff Identity must exact-map at admission to one durable target `commandId`; allocation then uses that target command row's canonical key. The current `tickBatchId`/`effectKey` derivation is not evidence of that contract. --- @@ -98,7 +97,7 @@ Consumers that persist offsets must key stable consumer identity by `(tenantId, FireMUD uses two explicit tick boundaries for ``: - **`durable_committed`** (authoritative commit boundary): - - The Game Session tick effect ledger has reconciled each effect for that tick under authoritative evidence: `APPLIED` only when proven applied, `ABANDONED` only when proven unapplied, and inconclusive work remains nonterminal/reconciliation-required. There are no remaining `SCHEDULED` ledger rows for that tick. + - The current-epoch commit predicate: terminal (`APPLIED` or `ABANDONED`) evidence is required, where the evidence policy permits terminalization, for every required participant in that tick's complete expected current-epoch participant set. Inconclusive old-epoch rows remain non-terminal reconciliation work outside this current-epoch commit predicate; they may still block unsafe next-tick progression, reset-scope convergence, or reopening. There are no remaining `SCHEDULED` ledger rows for that tick's batch. - **Target-state only:** For a non-empty batch, `tick_batch.status` is `COMMITTED` in this same fenced durable visibility boundary; a `CREATED`, `REDIS_STAGED`, or otherwise non-committed batch cannot advertise committed progress. The current-live code retains `APPLIED` as its batch terminal status and uses the committed tick fields on `RuntimeOwnershipStatus` as its commit-authority watermark under the same opaque fence; `ObserveRuntimeTickProgress` is the progress feed and does not replace that durable authority. - Target-state `RegionStatus.lastCommittedTickId` has been advanced to the complete `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)` scope as part of that same durable visibility boundary. - **`coordination_cleared`** (in-flight clearance boundary): diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index d84f19aba1..bd2560c30e 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -2111,6 +2111,26 @@ require_absent( "service startup for each region to converge", ], ) +for tick_commit_path in ( + "design/architecture/system-architecture-tick-execution-flows.md", + "design/architecture/system-architecture-ticks.md", +): + require_contains( + tick_commit_path, + [ + "current-epoch commit predicate: terminal (`APPLIED` or `ABANDONED`) evidence", + "every required participant in that tick's complete expected current-epoch participant set", + "Inconclusive old-epoch rows remain non-terminal reconciliation work outside this current-epoch commit predicate", + "may still block unsafe next-tick progression, reset-scope convergence, or reopening", + ], + ) + require_absent( + tick_commit_path, + [ + "An inconclusive old-epoch row remains non-terminal and blocks this advancement", + "inconclusive old-epoch work remains non-terminal and prevents this boundary", + ], + ) automation_base = (root / "k8s/base/automation-scripting-service.yaml").read_text(encoding="utf-8") game_design_base = (root / "k8s/base/game-design-service.yaml").read_text(encoding="utf-8") diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java index 1b1a774cce..b32a408e9c 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java @@ -254,18 +254,20 @@ public HandoffResult handoff(ScriptWorkItem workItem, EmittedCommand command) { String dispatchId = dispatchId(workItem, command.ordinal()); AggregateAdmissionSnapshot aggregateSnapshot = aggregateAdmissionSnapshots.get().get(workItem.getId()); - HandoffPreflight preflight = - aggregateSnapshot == null ? preflight(workItem) : HandoffPreflight.from(aggregateSnapshot); HandoffPreparation preparation; try { + HandoffPreflight preflight = + aggregateSnapshot == null + ? preflight(workItem) + : HandoffPreflight.from(aggregateSnapshot); preparation = executeIntentTransaction(workItem, command, dispatchId, preflight); } catch (RuntimeException ex) { LOGGER.warn( - "Unable to durably prepare script handoff for workItemId={} commandOrdinal={}", + "Unable to prepare script handoff for workItemId={} commandOrdinal={}", workItem.getId(), command.ordinal(), ex); - return retryablePreparationResult(ex); + return retryablePreparationResult(); } if (preparation.result() != null) { return preparation.result(); @@ -648,7 +650,7 @@ private static HandoffResult reconciliationRequiredResult(Throwable failure) { failure == null || failure.getMessage() == null ? "" : failure.getMessage()); } - private static HandoffResult retryablePreparationResult(Throwable failure) { + private static HandoffResult retryablePreparationResult() { return new HandoffResult( false, ScriptHandoffOutcomeSupport.OUTCOME_REMOTE_REJECTED, @@ -656,7 +658,7 @@ private static HandoffResult retryablePreparationResult(Throwable failure) { "", "", "UNAVAILABLE", - failure == null || failure.getMessage() == null ? "" : failure.getMessage()); + "handoff preparation unavailable"); } private static boolean isReconciliationRequired(HandoffResult result) { diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java index c5a282cd35..1ae6d1f85f 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java @@ -527,8 +527,16 @@ private HandoffExecutionResult executeHandoffLoop( ScriptWorkItem workItem, List commands) { ScriptGameplayCommandHandoffService.HandoffResult firstRejectedHandoff = null; String terminalFenceFailure = null; - handoffService.beginAggregateFanout(workItem); try { + try { + handoffService.beginAggregateFanout(workItem); + } catch (RuntimeException ex) { + LOGGER.warn( + "Unable to preflight script handoff fanout for workItemId={}; scheduling retry", + workItem.getId(), + ex); + return new HandoffExecutionResult(null, retryableHandoffPreflightResult()); + } for (ScriptGameplayCommandHandoffService.EmittedCommand command : commands) { PluginFenceValidation handoffPluginFence = validateCurrentPluginFence(workItem); if (handoffPluginFence != null) { @@ -557,6 +565,18 @@ private HandoffExecutionResult executeHandoffLoop( return new HandoffExecutionResult(terminalFenceFailure, firstRejectedHandoff); } + private static ScriptGameplayCommandHandoffService.HandoffResult + retryableHandoffPreflightResult() { + return new ScriptGameplayCommandHandoffService.HandoffResult( + false, + ScriptHandoffOutcomeSupport.OUTCOME_REMOTE_REJECTED, + "", + "", + "", + "UNAVAILABLE", + "handoff preparation unavailable"); + } + private boolean executeHandoffFinalization( ScriptWorkItem workItem, HandoffExecutionResult handoffResult) { if (transactionTemplate == null) { @@ -818,19 +838,18 @@ private EvaluationResult evaluateClaimedWorkItem(ScriptWorkItem workItem, Instan private boolean finalizeHandoff(ScriptWorkItem workItem, HandoffExecutionResult handoffResult) { Instant now = Instant.now(); + ScriptGameplayCommandHandoffService.HandoffResult firstRejectedHandoff = + handoffResult.firstRejectedHandoff(); + if (isHandoffReconciliationRequired(firstRejectedHandoff)) { + // An earlier child may already have been accepted. Keep the parent active until that + // exact-identity handoff is reconciled, even if a later sibling hits a terminal fence. + return false; + } if (handoffResult.terminalFenceFailure() != null) { cancel(workItem, STAGE_DSL_EVAL, "canceled", handoffResult.terminalFenceFailure(), now); return false; } - ScriptGameplayCommandHandoffService.HandoffResult firstRejectedHandoff = - handoffResult.firstRejectedHandoff(); if (firstRejectedHandoff != null) { - if (isHandoffReconciliationRequired(firstRejectedHandoff)) { - // The durable child intent is already committed. An ambiguous downstream response must - // remain active for exact-identity reconciliation; requeueing or dead-lettering here would - // erase the distinction between unknown outcome and a definitive handoff failure. - return false; - } if (ScriptHandoffOutcomeSupport.isRetryable(firstRejectedHandoff)) { requeueAfterRetryableHandoff(workItem); return false; diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java index 4420912224..e2c80ad8ff 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java @@ -113,6 +113,39 @@ void preflightsAdmissionBeforeRuntimeReadAndRemoteAdmission() throws NoSuchMetho .isEqualTo(1L); } + @Test + void admissionPreflightFailureIsRetryableBeforeIntentOrRuntimeRead() { + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + AutomationAdmissionStateService admissionService = + Mockito.mock(AutomationAdmissionStateService.class); + when(admissionService.getState("1", "7", "region-1")) + .thenThrow(new IllegalStateException("admission store unavailable")); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + ScriptHandoffEventRepository handoffEventRepository = + Mockito.mock(ScriptHandoffEventRepository.class); + ScriptGameplayCommandHandoffServiceImpl service = + new ScriptGameplayCommandHandoffServiceImpl( + gameSessionClient, + workItemRepository, + auditRepository, + handoffEventRepository, + admissionService, + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class)); + + ScriptGameplayCommandHandoffService.HandoffResult result = + service.handoff( + workItem(), emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0)); + + assertThat(result.accepted()).isFalse(); + assertThat(result.errorCode()).isEqualTo("UNAVAILABLE"); + assertThat(ScriptHandoffOutcomeSupport.isRetryable(result)).isTrue(); + verify(admissionService).getState("1", "7", "region-1"); + verifyNoInteractions( + gameSessionClient, workItemRepository, auditRepository, handoffEventRepository); + } + @Test void intentCommitsBeforeGameSessionRpcAndRpcRunsWithoutLocalTransaction() { List operations = new ArrayList<>(); diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java index 30e74a2e68..2766cd07f7 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java @@ -1283,6 +1283,50 @@ void rejectsPluginStateChangedBetweenDslEvaluationAndHandoff() { verify(handoffService, Mockito.never()).handoff(Mockito.any(), Mockito.any()); } + @Test + void aggregatePreflightFailureRequeuesAndAlwaysEndsFanout() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptDefinitionRepository definitionRepository = + Mockito.mock(ScriptDefinitionRepository.class); + ScriptGameplayCommandHandoffService handoffService = + Mockito.mock(ScriptGameplayCommandHandoffService.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptWorkItem item = workItem(); + ScriptDefinition definition = new ScriptDefinition(); + definition.setDefinition("{\"emitCommands\":[{\"commandText\":\"LOOK\"}]}"); + when(workItemService.claimPendingForEvaluation(1)).thenReturn(List.of(item)); + when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) + .thenReturn(Optional.of(definition)); + when(workItemRepository.save(Mockito.any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + Mockito.doThrow(new IllegalStateException("admission store unavailable")) + .when(handoffService) + .beginAggregateFanout(item); + + ScriptWorkItemExecutionService service = + new ScriptWorkItemExecutionServiceImpl( + workItemService, + definitionRepository, + handoffService, + workItemRepository, + Mockito.mock(ScriptEventAuditRepository.class), + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + new ScriptOutputProperties(), + allowingTenantBudgetService(), + allowingDryRunCapacityService(), + new ObjectMapper()); + + ScriptWorkItemExecutionService.ExecutionBatchResult result = service.processPendingWorkItems(1); + + assertThat(result.claimedCount()).isEqualTo(1); + assertThat(result.completedCount()).isZero(); + assertThat(result.failedCount()).isEqualTo(1); + assertThat(item.getStatus()).isEqualTo("PENDING_EVALUATION"); + verify(handoffService).beginAggregateFanout(item); + verify(handoffService).endAggregateFanout(item); + verify(handoffService, Mockito.never()).handoff(Mockito.any(), Mockito.any()); + } + @Test void rechecksPluginFenceBeforeEveryHandoff() { ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); @@ -1332,6 +1376,61 @@ void rechecksPluginFenceBeforeEveryHandoff() { verify(handoffService, Mockito.times(1)).handoff(Mockito.eq(item), Mockito.any()); } + @Test + void ambiguousChildOutcomeRemainsInFlightWhenLaterPluginFenceIsTerminal() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptDefinitionRepository definitionRepository = + Mockito.mock(ScriptDefinitionRepository.class); + ScriptGameplayCommandHandoffService handoffService = + Mockito.mock(ScriptGameplayCommandHandoffService.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + PluginRuntimeStateRepository pluginRepository = + Mockito.mock(PluginRuntimeStateRepository.class); + ScriptWorkItem item = pluginWorkItem(); + ScriptEventAudit audit = new ScriptEventAudit(); + ScriptDefinition definition = new ScriptDefinition(); + definition.setDefinition( + "{\"emitCommands\":[{\"commandText\":\"LOOK\"},{\"commandText\":\"WAIT\"}]}"); + PluginRuntimeState current = pluginState(1L, 1L); + PluginRuntimeState changed = pluginState(2L, 1L); + when(workItemService.claimPendingForEvaluation(1)).thenReturn(List.of(item)); + when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) + .thenReturn(Optional.of(definition)); + when(pluginRepository.findByTenantIdAndGameInstanceIdAndPluginId("1", "7", "plugin-1")) + .thenReturn( + Optional.of(current), Optional.of(current), Optional.of(current), Optional.of(changed)); + when(auditRepository.findByWorkItemId(99L)).thenReturn(Optional.of(audit)); + when(workItemRepository.save(Mockito.any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + when(handoffService.handoff(Mockito.eq(item), Mockito.any())) + .thenAnswer( + invocation -> { + item.setStatus("HANDOFF_IN_FLIGHT"); + return new ScriptGameplayCommandHandoffService.HandoffResult( + false, "HANDOFF_IN_FLIGHT", "", "", "", "HANDOFF_IN_FLIGHT"); + }); + + ScriptWorkItemExecutionService service = + pluginFenceService( + workItemService, + definitionRepository, + handoffService, + workItemRepository, + auditRepository, + allowingTenantBudgetService(), + pluginRepository); + + service.processPendingWorkItems(1); + + assertThat(item.getStatus()).isEqualTo("HANDOFF_IN_FLIGHT"); + assertThat(audit.getFinalStage()).isNull(); + assertThat(audit.getFinalOutcome()).isNull(); + verify(handoffService, Mockito.times(1)).handoff(Mockito.eq(item), Mockito.any()); + verify(pluginRepository, Mockito.times(4)) + .findByTenantIdAndGameInstanceIdAndPluginId("1", "7", "plugin-1"); + } + @Test void unexpectedItemFailureDoesNotAbortLaterClaimedItems() { ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupport.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupport.java index 7d76b73303..72a9a06d5f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupport.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupport.java @@ -317,8 +317,20 @@ private static DurableAdmission existingDurableAdmission( && existing.getCompletedAt() == null && "UNAVAILABLE".equals(result.errorCode()); if (retryExisting) { - Optional ownershipRejected = - rejectIfOwnershipClosed(request, runtimeRegionStatusRepository); + final Optional ownershipRejected; + try { + ownershipRejected = rejectIfOwnershipClosed(request, runtimeRegionStatusRepository); + } catch (RuntimeException ex) { + return new DurableAdmission( + new AdmissionResult( + false, + "RETRY_QUEUED", + existing.getCommandId(), + "UNAVAILABLE", + "Runtime ownership is temporarily unavailable"), + null, + false); + } if (ownershipRejected.isPresent()) { return new DurableAdmission(ownershipRejected.orElseThrow(), null, false); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java index 9f80568bf2..b30dd1da36 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java @@ -682,6 +682,46 @@ void doesNotRedriveExistingAcceptedCommandWhenRuntimeIsPaused() { verifyNoTickEnqueue(tickService); } + @Test + void keepsExistingAcceptedCommandRetryableWhenOwnershipReadFails() { + GameInstanceRepository gameInstanceRepository = mockGameInstanceRepository(); + GameplayCommandRepository gameplayCommandRepository = mock(GameplayCommandRepository.class); + RuntimeRegionStatusRepository runtimeRegionStatusRepository = + mock(RuntimeRegionStatusRepository.class); + TickService tickService = mock(TickService.class); + + AdmissionRequest request = automationRequest(); + GameInstance instance = automationInstance(); + when(gameInstanceRepository.findById(request.gameInstanceId())) + .thenReturn(Optional.of(instance)); + + GameplayCommand existing = new GameplayCommand(); + populateAdmissionFields(existing, request); + existing.setCommandId("auto-owner-read-failed"); + existing.setExecutionOutcome("ACCEPTED"); + when(gameplayCommandRepository + .findByTenantIdAndGameInstanceIdAndRegionIdAndRegionEpochAndAutomationDispatchId( + 1L, 2L, "region-alpha", 7L, "dispatch-1")) + .thenReturn(Optional.of(existing)); + when(runtimeRegionStatusRepository.findByTenantIdAndRegionId(1L, "region-alpha")) + .thenThrow(new IllegalStateException("database connection failed")); + + AdmissionResult result = + AutomationGameplayCommandAdmissionSupport.admitIfAbsent( + request, + gameInstanceRepository, + gameplayCommandRepository, + runtimeRegionStatusRepository, + tickService); + + assertFalse(result.accepted()); + assertEquals("RETRY_QUEUED", result.admissionOutcome()); + assertEquals("UNAVAILABLE", result.errorCode()); + assertEquals("auto-owner-read-failed", result.commandId()); + verify(gameplayCommandRepository, never()).insertIfAbsentByIdempotencyIdentity(any()); + verifyNoTickEnqueue(tickService); + } + @Test void doesNotRedriveExistingAcceptedRemoteCommandAfterOwnershipEpochAdvances() { GameInstanceRepository gameInstanceRepository = mockGameInstanceRepository(); From f6dea7b012de2bf9c57201732069623a04fe81c9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 21:30:46 +1300 Subject: [PATCH 31/68] Fence handoff responses to prepared intent row --- ...riptGameplayCommandHandoffServiceImpl.java | 71 +++++++--- ...GameplayCommandHandoffServiceImplTest.java | 122 ++++++++++++++++++ 2 files changed, 177 insertions(+), 16 deletions(-) diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java index b32a408e9c..04e3fa29bf 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java @@ -292,7 +292,12 @@ public HandoffResult handoff(ScriptWorkItem workItem, EmittedCommand command) { return executeResponseTransaction( () -> persistDownstreamResponse( - workItem, command, dispatchId, downstreamResult, preparation.intentRowVersion())); + workItem, + command, + dispatchId, + downstreamResult, + preparation.intentId(), + preparation.intentRowVersion())); } catch (RuntimeException ex) { LOGGER.warn( "Unable to persist script handoff response for workItemId={} commandOrdinal={}; retaining in-flight evidence", @@ -352,9 +357,9 @@ private interface ResponseCommit { } private record HandoffPreparation( - HandoffResult result, boolean remoteHandoff, int intentRowVersion) { + HandoffResult result, boolean remoteHandoff, Long intentId, int intentRowVersion) { HandoffPreparation(HandoffResult result, boolean remoteHandoff) { - this(result, remoteHandoff, -1); + this(result, remoteHandoff, null, -1); } } @@ -496,7 +501,7 @@ private HandoffPreparation prepareHandoff( rolloutProjectionService.refreshForWorkItem(workItem); ScriptHandoffEvent intent = appendHandoffIntent(workItem, command, dispatchId, now); - return new HandoffPreparation(null, remoteHandoff, intent.getRowVersion()); + return new HandoffPreparation(null, remoteHandoff, intent.getId(), intent.getRowVersion()); } private HandoffResult invokeDownstream( @@ -532,11 +537,16 @@ private HandoffResult persistDownstreamResponse( EmittedCommand command, String dispatchId, HandoffResult result, + Long intentId, int intentRowVersion) { if (isReconciliationRequired(result)) { return result; } - if (handoffTransactionTemplate != null) { + HandoffRowFence responseFence = null; + if (handoffTransactionTemplate != null || intentId != null) { + if (intentId == null || intentRowVersion < 0) { + return reconciliationRequiredResult("durable handoff intent identity was unavailable"); + } Optional existingHandoff = handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal( workItem.getTenantId(), workItem.getId(), command.ordinal()); @@ -547,14 +557,18 @@ private HandoffResult persistDownstreamResponse( if (isAcceptedHandoff(existing)) { return handoffResult(existing); } - if (intentRowVersion >= 0 && existing.getRowVersion() != intentRowVersion) { + if (!Objects.equals(existing.getId(), intentId) + || existing.getRowVersion() != intentRowVersion) { return reconciliationRequiredResult("durable handoff intent fence advanced"); } + responseFence = new HandoffRowFence(intentId, intentRowVersion); } - applyOutcome(workItem, command, dispatchId, result, Instant.now()); + applyOutcome(workItem, command, dispatchId, result, Instant.now(), responseFence); return result; } + private record HandoffRowFence(Long id, int rowVersion) {} + private static ScopeValidationResult validateRemoteHandoffScope( ScriptWorkItem workItem, EmittedCommand command) { if (!requiresRemoteHandoff(workItem, command)) { @@ -1061,7 +1075,17 @@ private void applyOutcome( String dispatchId, HandoffResult result, Instant now) { - appendHandoffEvent(workItem, command, dispatchId, result, now); + applyOutcome(workItem, command, dispatchId, result, now, null); + } + + private void applyOutcome( + ScriptWorkItem workItem, + EmittedCommand command, + String dispatchId, + HandoffResult result, + Instant now, + HandoffRowFence handoffRowFence) { + appendHandoffEvent(workItem, command, dispatchId, result, now, handoffRowFence); if (isReconciliationRequired(result)) { // A lost/ambiguous downstream response is not a terminal rejection. The child remains // HANDOFF_IN_FLIGHT until a later exact-identity reconciliation determines the outcome. @@ -1171,6 +1195,16 @@ private ScriptHandoffEvent appendHandoffEvent( String dispatchId, HandoffResult result, Instant now) { + return appendHandoffEvent(workItem, command, dispatchId, result, now, null); + } + + private ScriptHandoffEvent appendHandoffEvent( + ScriptWorkItem workItem, + EmittedCommand command, + String dispatchId, + HandoffResult result, + Instant now, + HandoffRowFence handoffRowFence) { String outcome = result.outcome().toLowerCase(Locale.ROOT); String reason = handoffReason(result); RoutingBundleSupport.RoutingBundle routingBundle = @@ -1213,14 +1247,19 @@ private ScriptHandoffEvent appendHandoffEvent( event.setHandoffOutcome(outcome); event.setHandoffReason(reason); event.setObservedAt(now); - handoffEventRepository - .findByTenantIdAndWorkItemIdAndCommandOrdinal( - workItem.getTenantId(), workItem.getId(), command.ordinal()) - .ifPresent( - existing -> { - event.setId(existing.getId()); - event.setRowVersion(existing.getRowVersion()); - }); + if (handoffRowFence != null) { + event.setId(handoffRowFence.id()); + event.setRowVersion(handoffRowFence.rowVersion()); + } else { + handoffEventRepository + .findByTenantIdAndWorkItemIdAndCommandOrdinal( + workItem.getTenantId(), workItem.getId(), command.ordinal()) + .ifPresent( + existing -> { + event.setId(existing.getId()); + event.setRowVersion(existing.getRowVersion()); + }); + } ScriptHandoffEvent saved = handoffEventRepository.save(event); return saved == null ? event : saved; } diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java index e2c80ad8ff..4ebe471405 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java @@ -12,6 +12,8 @@ import java.util.Arrays; import java.util.List; import java.util.Optional; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.automationscripting.client.GameSessionControlPlaneClient; import net.firedevops.firemud.automationscripting.entity.ScriptEventAudit; import net.firedevops.firemud.automationscripting.entity.ScriptHandoffEvent; @@ -184,6 +186,12 @@ void intentCommitsBeforeGameSessionRpcAndRpcRunsWithoutLocalTransaction() { .thenAnswer( invocation -> { ScriptHandoffEvent event = invocation.getArgument(0); + if (event.getId() == null) { + event.setId(44L); + event.setRowVersion(0); + } else { + event.setRowVersion(event.getRowVersion() + 1); + } savedEvents.add(event); operations.add( "handoff-save:" @@ -212,6 +220,9 @@ void intentCommitsBeforeGameSessionRpcAndRpcRunsWithoutLocalTransaction() { workItem(), emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0)); assertThat(result.accepted()).isTrue(); + assertThat(savedEvents.getLast().getId()).isEqualTo(44L); + assertThat(savedEvents.getLast().getRowVersion()).isEqualTo(1); + assertThat(savedEvents.getLast().getGameSessionCommandId()).isEqualTo("command-1"); assertThat(operations) .contains( "runtime:false", "handoff-save:intent", "enqueue:false", "handoff-save:response"); @@ -231,6 +242,107 @@ void intentCommitsBeforeGameSessionRpcAndRpcRunsWithoutLocalTransaction() { } } + @Test + void concurrentAcceptedResultAfterResponseCheckCannotBeReplacedByStaleResponse() { + List operations = new ArrayList<>(); + RecordingTransactionManager transactionManager = new RecordingTransactionManager(operations); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenReturn(currentRuntimeState()); + when(gameSessionClient.enqueueAutomationCommandIfAbsent(Mockito.any())) + .thenReturn( + EnqueueAutomationCommandIfAbsentResponse.newBuilder() + .setAccepted(true) + .setAdmissionOutcome("ENQUEUED") + .setCommandId("late-command") + .build()); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + when(workItemRepository.save(Mockito.any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + ScriptHandoffEventRepository handoffEventRepository = + Mockito.mock(ScriptHandoffEventRepository.class); + AtomicReference persisted = new AtomicReference<>(); + AtomicReference attemptedResponseWrite = new AtomicReference<>(); + AtomicInteger findCount = new AtomicInteger(); + AtomicInteger saveCount = new AtomicInteger(); + when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) + .thenAnswer( + invocation -> { + int call = findCount.incrementAndGet(); + if (call <= 2) { + return Optional.empty(); + } + if (call == 3) { + ScriptHandoffEvent intent = persisted.get(); + ScriptHandoffEvent checkedIntent = + handoffRow(intent.getId(), intent.getRowVersion(), "handoff_in_flight", ""); + // Model a retry that commits after this response transaction has read the intent + // but before it attempts to append its older downstream response. + persisted.set( + handoffRow( + intent.getId(), + intent.getRowVersion() + 1, + "duplicate_noop", + "winner-command")); + return Optional.of(checkedIntent); + } + return Optional.of(persisted.get()); + }); + when(handoffEventRepository.save(Mockito.any())) + .thenAnswer( + invocation -> { + ScriptHandoffEvent event = invocation.getArgument(0); + saveCount.incrementAndGet(); + ScriptHandoffEvent current = persisted.get(); + if (event.getId() == null) { + event.setId(44L); + event.setRowVersion(5); + persisted.set(event); + return event; + } + attemptedResponseWrite.set(event); + if (current == null + || !event.getId().equals(current.getId()) + || event.getRowVersion() != current.getRowVersion()) { + throw new IllegalStateException("stale handoff event write"); + } + event.setRowVersion(event.getRowVersion() + 1); + persisted.set(event); + return event; + }); + ScriptGameplayCommandHandoffServiceImpl service = + new ScriptGameplayCommandHandoffServiceImpl( + gameSessionClient, + workItemRepository, + Mockito.mock(ScriptEventAuditRepository.class), + handoffEventRepository, + null, + null, + admissionStateService(), + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + transactionManager); + + TransactionSynchronizationManager.setActualTransactionActive(false); + try { + ScriptGameplayCommandHandoffService.HandoffResult result = + service.handoff( + workItem(), emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0)); + + assertThat(result.accepted()).isFalse(); + assertThat(result.outcome()).isEqualTo("HANDOFF_IN_FLIGHT"); + assertThat(persisted.get().getHandoffOutcome()).isEqualTo("duplicate_noop"); + assertThat(persisted.get().getGameSessionCommandId()).isEqualTo("winner-command"); + assertThat(persisted.get().getRowVersion()).isEqualTo(6); + assertThat(attemptedResponseWrite.get().getId()).isEqualTo(44L); + assertThat(attemptedResponseWrite.get().getRowVersion()).isEqualTo(5); + assertThat(findCount.get()).isEqualTo(3); + assertThat(saveCount.get()).isEqualTo(2); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } + @Test void failedIntentCommitIsRetryableAndNeverClaimsInFlightOrCallsCommandRpc() { FailingIntentCommitTransactionManager transactionManager = @@ -2164,6 +2276,16 @@ void collapsesPartialRoutingBundleBeforeForwardingOrPersistingHandoff() { assertThat(persistedOutcome.getPointerVersion()).isBlank(); } + private static ScriptHandoffEvent handoffRow( + Long id, int rowVersion, String outcome, String commandId) { + ScriptHandoffEvent event = new ScriptHandoffEvent(); + event.setId(id); + event.setRowVersion(rowVersion); + event.setHandoffOutcome(outcome); + event.setGameSessionCommandId(commandId); + return event; + } + private static ScriptGameplayCommandHandoffService.EmittedCommand emittedCommand( String commandText, String targetEntityId, From 696900cfe99958355748cf3dc8f01c1e083289fe Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 27 Sep 2026 23:21:26 +1300 Subject: [PATCH 32/68] Assert PostgreSQL migration catalog counts as longs --- ...omationClaimAndRetentionRepositoryIntegrationTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java index e1c64a8684..4e23d8110f 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java @@ -120,16 +120,16 @@ void flywayV4EvolvesV3EligibilityWithoutLosingReplayEvidence() { "SELECT count(*) FROM pg_indexes WHERE schemaname = 'public'" + " AND tablename = 'script_work_items'" + " AND indexname = 'idx_script_work_items_status_eligible_created'", - Integer.class)) - .isEqualTo(1); + Long.class)) + .isEqualTo(1L); assertThat( dsl.fetchValue( "SELECT count(*) FROM information_schema.tables" + " WHERE table_schema = 'public'" + " AND table_name IN ('script_dead_letter_replay_requests'," + " 'script_dead_letter_replay_results')", - Integer.class)) - .isEqualTo(2); + Long.class)) + .isEqualTo(2L); } @Test From de66e664ead2147c8104a35329e66a1f8ab751a9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 28 Sep 2026 23:54:48 +1300 Subject: [PATCH 33/68] Validate accepted handoff replay identity and clarify pending allocator scope --- design/architecture/decisions/README.md | 2 +- ...effect-id-allocation-and-replay-binding.md | 33 +++--- ...riptGameplayCommandHandoffServiceImpl.java | 20 +++- ...GameplayCommandHandoffServiceImplTest.java | 104 ++++++++++++++++-- 4 files changed, 128 insertions(+), 31 deletions(-) diff --git a/design/architecture/decisions/README.md b/design/architecture/decisions/README.md index cdf7cc0dc8..ec7d55bd7c 100644 --- a/design/architecture/decisions/README.md +++ b/design/architecture/decisions/README.md @@ -277,7 +277,7 @@ Validation precedence is fixed: first parse every checked queue row and validate | [ADR 0180](./adr-0180-account-owned-hosted-terms-acceptance-gate.md) | Accepted | `AA-1.3` | `AA-1.5`, `AR-1.1`, `AR-1.4`, `AR-1.5`, `EA-3.2`, `PO-1.3`, `SF-2.3` | Account-owned hosted-terms catalog, acceptance evidence, and official-hosted creator mutation gate | | [ADR 0181](./adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) | Accepted | `PO-1.3` | `AA-1.3`, `AA-1.4`, `AA-1.5`, `AR-1.1`, `AR-1.4`, `AR-1.5`, `EA-3.2`, `SF-2.3` | Changed hosted-terms decline, prior-terms continuity, lifecycle-reducing access, and finite transition | | [ADR 0182](./adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md) | Accepted | `PO-3.2` | `PO-3.1`, `PO-4.4`, `SF-1.3`, `PO-1.1` | Separated hosted runtime and certificate-identity lifecycles | -| [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) | Proposed - Pending Human Review | `GR-1.2` | `GR-1.4`, `GR-4.1`, `AS-1.2`, `AS-1.4`, `SF-1.4`, `SF-2.3`, `PO-4.2` | Pending deterministic command-plan and generated-child EffectId allocation and replay binding | +| [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) | Proposed - Pending Human Review | `GR-1.2` | `GR-1.4`, `GR-4.1`, `AS-1.2`, `AS-1.4`, `SF-1.4`, `SF-2.3`, `PO-4.2` | Pending UUIDv7 scalar, canonical serialization, and generated-child/fan-out allocation refinements; ADR 0069's command-root owner/key/manifest-digest foundation is accepted | | [ADR 0184](./adr-0184-emergency-tcp-proxy-identity-withdrawal.md) | Accepted | `SF-1.3` | `PO-2.1`, `PO-2.2`, `PO-3.2`, `PO-4.4` | Emergency trust cutoff for a withdrawn TCP Proxy bridge identity | Capability identifiers are defined in the [FireMUD Product Capability Taxonomy](../../product/capability-taxonomy.md). diff --git a/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md b/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md index 03f2d51121..994e1c7de9 100644 --- a/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md +++ b/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md @@ -6,7 +6,7 @@ Proposed - Pending Human Review ## Implementation Status -This proposal is not current target state and is not an accepted implementation requirement. The current services, wire contracts, and focused proof remain implementation gaps as recorded by the linked canonical documents. No implementation may treat this proposal as approved before human review. +The additional requirements in this proposal are not current target state or accepted implementation requirements. The command-root owner, key, frozen binding, and ordered manifest digest remain accepted target state under ADR 0069. The current services, wire contracts, and focused proof remain implementation gaps as recorded by the linked canonical documents. No implementation may treat this proposal's refinements as approved before human review. The move from the conflicting draft number ADR 0182 to ADR 0183 is mechanical preservation only. It neither accepts this allocator decision nor authorizes proposal-dependent implementation; independently authoritative effect and replay obligations continue to apply on their own authority. @@ -25,11 +25,11 @@ The move from the conflicting draft number ADR 0182 to ADR 0183 is mechanical pr ## Context -[ADR 0069](./adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) accepts at-least-once execution and one logical terminal outcome, but its accepted decision does not select the allocator contract for generated children or a precise scalar format. The current implementation also derives effect IDs from batch or effect-key material and exposes narrower service-local replay tables. Those paths are documented implementation gaps and cannot be made canonical by inference. +[ADR 0069](./adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) already accepts the command-root foundation: Game Session owns the opaque root allocation row, unique on `(tenantId, gameInstanceId, commandId, planOrdinal)`, and binds it to the frozen command/runtime evidence and ordered command-plan manifest digest. It also accepts semantic plan order and reuse only for the same binding. This proposal does not reopen or replace that contract. ADR 0069 leaves the exact scalar format and generated-child allocation contract unresolved; it also does not select the additional versioned canonical serialization and atomic manifest/allocation details proposed here. The current implementation derives effect IDs from batch or effect-key material and exposes narrower service-local replay tables. Those paths are documented implementation gaps and cannot be made canonical by inference. -Generated chains and global fan-out need an identity that survives retries, crashes, replay, runtime replacement, and reconciliation without turning semantic fields into an ID. Command roots additionally need a durable plan/ordinal binding so a changed plan cannot silently reuse an old root. Candidate suppression must remain auditable without inventing an ID for work that never entered execution. +Generated chains and global fan-out need an identity that survives retries, crashes, replay, runtime replacement, and reconciliation without turning semantic fields into an ID. ADR 0069 already requires command roots to use a durable plan/ordinal binding so a changed plan cannot silently reuse an old root; this proposal adds exact scalar and canonical serialization refinements to that foundation. Candidate suppression must remain auditable without inventing an ID for work that never entered execution. -This proposal supplies one owner-bound allocation contract for those gaps. It is deliberately pending: its exact format and cross-service persistence boundary require human approval before any accepted ADR or implementation depends on them. +This proposal supplies refinements for those gaps while preserving ADR 0069's accepted command-root owner, key, frozen binding, and manifest-digest contract. Its exact UUIDv7 scalar, versioned canonical serialization, generated-child/fan-out manifest, and atomic allocation details remain deliberately pending human approval before any accepted ADR or implementation depends on them. ## Decision @@ -41,11 +41,11 @@ Game Session owns command-root allocation. The owner of a generated child, non-c Retries, replay, failover, and reconciliation read and reuse the persisted mapping and exact scalar. Participants receive the persisted mutation identity and use it in their guard, ledger, response, and terminal outcome. The enclosing root remains lineage and reconciliation context for a child; it does not replace the child's identity or collapse siblings. A post-abandon re-drive receives a new explicitly linked identity under its own admission contract. -### Command roots and versioned plan manifests +### Proposed command-root serialization refinements -Before staging a non-empty admitted command, Game Session freezes the typed command/action or `ResolvedEffectPlan` semantic order and persists a versioned root-plan manifest. The manifest records its schema version, registered canonical serialization identifier, canonical bytes/digest, ordered logical operations, and the frozen request/runtime/namespace binding. A root receives one `planOrdinal` in that order and one allocated opaque `EffectId`; zero-effect plans allocate neither. +ADR 0069 already requires Game Session to persist the ordered plan manifest and its digest before tick staging, assigns each logical root its stable `planOrdinal` in the supplied semantic order, and binds the opaque root allocation row to the frozen command/runtime evidence. The following are additional proposed refinements, not prerequisites that redefine that accepted foundation: the manifest has an explicit schema version, registered canonical serialization identifier, and canonical bytes; and its serialized content includes ordered logical operations and frozen request/runtime/namespace binding. A root still receives the accepted `planOrdinal` and opaque `EffectId`; zero-effect plans allocate neither. -The durable allocation row is unique on `(tenantId, gameInstanceId, commandId, planOrdinal)` and binds the manifest schema version, serializer, digest, exact root scalar claim, and frozen command binding. Replay and reuse require every one of those values to match. Unknown, duplicate, ambiguous, noncanonical, or changed order/manifest evidence fails before staging or side effects. Automation handoff identity maps exactly to one durable target command before this command-root allocation is attempted; trigger and correlation identities are not allocation inputs. +The accepted durable allocation row remains unique on `(tenantId, gameInstanceId, commandId, planOrdinal)` and binds the frozen command binding and ordered plan-manifest digest. This proposal additionally binds the manifest schema version, serializer, canonical bytes, and exact root scalar claim, requiring exact matches on replay. Unknown, duplicate, ambiguous, noncanonical, or changed order/manifest evidence fails before staging or side effects under the accepted ordering and digest contract, with the additional serialization checks pending. Automation handoff identity maps exactly to one durable target command before this command-root allocation is attempted; trigger and correlation identities are not allocation inputs. ### Generated-child candidates and suppression @@ -63,7 +63,7 @@ The child scalar and all binding fields are persisted before wake delivery. Retr ## Rationale -An exact scalar format makes wire and storage compatibility testable while keeping identity opaque. Durable allocation separates identity from semantic derivation and allows a participant or coordinator to prove that a replay is the same logical mutation. Versioned canonical manifests make plan and fan-out interpretation stable across deployments, while ID-free suppression evidence prevents rejected work from appearing to have executed. A serializable allocation/budget boundary preserves chain accounting under concurrency and a frozen fan-out set prevents topology changes from creating new work during recovery. +The proposed exact scalar format makes wire and storage compatibility testable while keeping identity opaque. Durable allocation separates identity from semantic derivation and allows a participant or coordinator to prove that a replay is the same logical mutation. The proposed versioned canonical manifests make plan and fan-out interpretation stable across deployments, while ID-free suppression evidence prevents rejected work from appearing to have executed. The proposed serializable allocation/budget boundary preserves chain accounting under concurrency, and a frozen fan-out set prevents topology changes from creating new work during recovery. ## Alternatives Considered @@ -85,16 +85,17 @@ Rejected because notifications can be lost or duplicated and cannot own durable ## Consequences -- Game Session and each generated-effect or fan-out owner need durable allocation rows with uniqueness, immutable binding fields, and conflict-safe replay behavior. -- Root and child manifests require registered schema versions and canonical serializers whose bytes and digests are stable across supported readers. -- Chain admission must use a serializable or explicitly equivalent atomic boundary and retain ID-free suppression evidence. -- Existing string protobuf and database fields remain wire/storage-compatible with a 36-character scalar, but current derivation, optional fields, and narrower replay guards remain gaps until separately implemented and proved. +- The accepted ADR 0069 Game Session command-root allocation owner, key, frozen binding, and ordered manifest digest remain the foundation; the exact UUIDv7 scalar and the additional versioned serialization fields proposed here remain pending. +- Each generated-effect or fan-out owner would need the proposed durable allocation rows, manifest bindings, and conflict-safe atomic replay behavior if this proposal is accepted. +- If accepted, this proposal would require root and child manifests to use registered schema versions and canonical serializers whose bytes and digests are stable across supported readers. +- If accepted, chain admission would use a serializable or explicitly equivalent atomic boundary and retain ID-free suppression evidence. +- The proposed 36-character scalar fits existing string protobuf and database fields; current derivation, optional fields, and narrower replay guards remain gaps until independently converged on an accepted contract and proved. - Participants, ledgers, coordinators, and operational reconciliation must carry both mutation identity and enclosing-root lineage where applicable. - Adoption is a breaking target convergence for identity allocation; compatibility shims must not preserve semantic derivation or silently accept conflicting formats. ## Reversibility and Revisit Triggers -Before acceptance, human review may change the scalar format, allocator ownership, or manifest boundary without a migration obligation. After acceptance and persisted use, changing the scalar or canonical serialization requires a versioned migration and explicit old/new binding and replay policy; it must not reinterpret existing IDs. Revisit UUIDv7 only if a reviewed cross-service identity standard provides equal exact textual compatibility, opaque semantics, collision handling, and operational proof. +Before acceptance, human review may change the proposed scalar format, generated-child/fan-out ownership, or added serialization boundary without a migration obligation; ADR 0069's accepted command-root owner, key, and digest binding remain in force. After acceptance and persisted use, changing the scalar or canonical serialization requires a versioned migration and explicit old/new binding and replay policy; it must not reinterpret existing IDs. Revisit UUIDv7 only if a reviewed cross-service identity standard provides equal exact textual compatibility, opaque semantics, collision handling, and operational proof. ## Security and Privacy @@ -108,9 +109,9 @@ Game Session or the owning allocation boundary exposes durable allocation, colli Implementation and focused proof must cover: -- lowercase, hyphenated, exactly 36-character UUIDv7 scalar validation and opaque treatment at every supported wire/storage boundary; -- one-time allocation, insert-if-absent uniqueness, collision/conflict failure, crash recovery, concurrent allocation races, and exact replay/reconciliation reuse; -- zero-, one-, and multi-root plans; frozen semantic order; root manifest schema version, serializer, canonical bytes/digest, ordinal, command binding, and mismatch rejection; +- if accepted, lowercase, hyphenated, exactly 36-character UUIDv7 scalar validation and opaque treatment at every supported wire/storage boundary; +- the accepted ADR 0069 command-root allocation binding plus, if this proposal is accepted, one-time scalar claims, insert-if-absent uniqueness, collision/conflict failure, crash recovery, concurrent allocation races, and exact replay/reconciliation reuse for the additional allocation boundaries; +- zero-, one-, and multi-root plans; frozen semantic order; the accepted ADR 0069 root key, command binding, ordered manifest digest, and mismatch rejection; if this proposal is accepted, also prove the proposed root manifest schema version, serializer, canonical bytes, exact scalar claim, and their mismatch rejection; - child-candidate schema version/serializer/digest, candidate ordering, depth and budget revisions, serializable sibling admission, no double charge, and no partial commit; - ID-free suppression evidence proving no enqueue/apply and preserving committed parent/earlier-child outcomes; - fan-out frozen region/topology set, exact child ordinal and target binding, child-manifest schema/serializer/digest, request digest, pre-wake durability, duplicate wake, late result, and topology-conflict handling; diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java index 342852b185..d7b104c1ab 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java @@ -254,11 +254,11 @@ public HandoffResult handoff(ScriptWorkItem workItem, EmittedCommand command) { requireCommand(command); // An accepted child is immutable retry evidence; replay it before consulting today's // admission or runtime owner, which may have advanced after the original dispatch. - HandoffResult acceptedResult = acceptedHandoffResult(workItem, command); + String dispatchId = dispatchId(workItem, command.ordinal()); + HandoffResult acceptedResult = acceptedHandoffResult(workItem, command, dispatchId); if (acceptedResult != null) { return acceptedResult; } - String dispatchId = dispatchId(workItem, command.ordinal()); AggregateAdmissionSnapshot aggregateSnapshot = aggregateAdmissionSnapshots.get().get(workItem.getId()); HandoffPreparation preparation; @@ -381,7 +381,7 @@ private HandoffPreparation prepareHandoff( // the local fence in that transaction even when aggregate fanout retained a remote runtime // snapshot; the aggregate snapshot is not local admission authority. lockAdmissionScope(workItem); - HandoffResult acceptedResult = acceptedHandoffResult(workItem, command); + HandoffResult acceptedResult = acceptedHandoffResult(workItem, command, dispatchId); if (acceptedResult != null) { return new HandoffPreparation(acceptedResult, false); } @@ -580,7 +580,8 @@ private HandoffResult persistDownstreamResponse( private record HandoffRowFence(Long id, int rowVersion) {} - private HandoffResult acceptedHandoffResult(ScriptWorkItem workItem, EmittedCommand command) { + private HandoffResult acceptedHandoffResult( + ScriptWorkItem workItem, EmittedCommand command, String dispatchId) { ScriptHandoffEvent existing = handoffEventRepository .findByTenantIdAndWorkItemIdAndCommandOrdinal( @@ -589,6 +590,17 @@ private HandoffResult acceptedHandoffResult(ScriptWorkItem workItem, EmittedComm if (existing == null) { return null; } + if (isAcceptedHandoff(existing) + && !handoffIdentityMatches(existing, workItem, command, dispatchId)) { + return new HandoffResult( + false, + ScriptHandoffOutcomeSupport.OUTCOME_REMOTE_REJECTED, + "", + "", + "", + ScriptHandoffOutcomeSupport.REASON_IDEMPOTENCY_CONFLICT, + "existing handoff child identity does not match request"); + } return switch (normalize(existing.getHandoffOutcome()).trim().toLowerCase(Locale.ROOT)) { case "enqueued" -> new HandoffResult( diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java index eabc7ce0cb..197e664749 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java @@ -743,8 +743,10 @@ void persistedAcceptedOutcomeSurvivesLaterAdmissionFence( Mockito.mock(AutomationAdmissionStateService.class); ScriptPatchInstanceRolloutProjectionService rolloutProjectionService = Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class); - ScriptHandoffEvent acceptedEvent = new ScriptHandoffEvent(); - acceptedEvent.setHandoffOutcome(persistedOutcome); + ScriptWorkItem item = workItem(); + ScriptGameplayCommandHandoffService.EmittedCommand command = + emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0); + ScriptHandoffEvent acceptedEvent = acceptedHandoffEvent(item, command, persistedOutcome); acceptedEvent.setGameSessionCommandId("command-accepted"); acceptedEvent.setRemoteCoordinatorId("coordinator-accepted"); acceptedEvent.setRemoteFollowupId("followup-accepted"); @@ -763,9 +765,7 @@ void persistedAcceptedOutcomeSurvivesLaterAdmissionFence( admissionService, rolloutProjectionService); - ScriptGameplayCommandHandoffService.HandoffResult result = - service.handoff( - workItem(), emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0)); + ScriptGameplayCommandHandoffService.HandoffResult result = service.handoff(item, command); assertThat(result.accepted()).isTrue(); assertThat(result.outcome()).isEqualTo(expectedOutcome); @@ -805,8 +805,10 @@ void persistedAcceptedOutcomeSurvivesLaterRuntimeOwnerFence() { ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); ScriptHandoffEventRepository handoffEventRepository = Mockito.mock(ScriptHandoffEventRepository.class); - ScriptHandoffEvent acceptedEvent = new ScriptHandoffEvent(); - acceptedEvent.setHandoffOutcome("enqueued"); + ScriptWorkItem item = workItem(); + ScriptGameplayCommandHandoffService.EmittedCommand command = + emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0); + ScriptHandoffEvent acceptedEvent = acceptedHandoffEvent(item, command, "enqueued"); acceptedEvent.setGameSessionCommandId("command-accepted"); when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) .thenReturn(Optional.of(acceptedEvent)); @@ -821,9 +823,7 @@ void persistedAcceptedOutcomeSurvivesLaterRuntimeOwnerFence() { admissionStateService(), rolloutProjectionService); - ScriptGameplayCommandHandoffService.HandoffResult result = - service.handoff( - workItem(), emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0)); + ScriptGameplayCommandHandoffService.HandoffResult result = service.handoff(item, command); assertThat(result.accepted()).isTrue(); assertThat(result.outcome()).isEqualTo("ENQUEUED"); @@ -833,6 +833,52 @@ void persistedAcceptedOutcomeSurvivesLaterRuntimeOwnerFence() { verifyNoInteractions(auditRepository, rolloutProjectionService); } + @ParameterizedTest + @CsvSource({"command", "target", "pin"}) + void acceptedReplayRejectsChangedIdentityWithoutMutation(String changedIdentity) { + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + ScriptHandoffEventRepository handoffEventRepository = + Mockito.mock(ScriptHandoffEventRepository.class); + AutomationAdmissionStateService admissionService = + Mockito.mock(AutomationAdmissionStateService.class); + ScriptPatchInstanceRolloutProjectionService rolloutProjectionService = + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class); + ScriptWorkItem item = workItem(); + ScriptGameplayCommandHandoffService.EmittedCommand command = + emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0); + ScriptHandoffEvent acceptedEvent = acceptedHandoffEvent(item, command, "enqueued"); + when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) + .thenReturn(Optional.of(acceptedEvent)); + if ("command".equals(changedIdentity)) { + command = emittedCommand("say goodbye", "entity-1", "7", "region-1", 12L, 34L, 0); + } else if ("target".equals(changedIdentity)) { + command = emittedCommand("say hello", "entity-2", "7", "region-1", 12L, 34L, 0); + } else { + item.setScriptPinControlPlaneRequestId("pin-request-2"); + } + ScriptGameplayCommandHandoffService service = + new ScriptGameplayCommandHandoffServiceImpl( + gameSessionClient, + workItemRepository, + auditRepository, + handoffEventRepository, + admissionService, + rolloutProjectionService); + + ScriptGameplayCommandHandoffService.HandoffResult result = service.handoff(item, command); + + assertThat(result.accepted()).isFalse(); + assertThat(result.errorCode()) + .isEqualTo(ScriptHandoffOutcomeSupport.REASON_IDEMPOTENCY_CONFLICT); + verifyNoInteractions( + gameSessionClient, admissionService, auditRepository, rolloutProjectionService); + verify(handoffEventRepository, never()).save(Mockito.any()); + verify(workItemRepository, never()).save(Mockito.any()); + } + @Test void nonAcceptedPersistedOutcomeStillProcessesLaterAdmissionFence() { GameSessionControlPlaneClient gameSessionClient = @@ -2692,6 +2738,44 @@ private static ScriptHandoffEvent handoffRow( return event; } + private static ScriptHandoffEvent acceptedHandoffEvent( + ScriptWorkItem item, + ScriptGameplayCommandHandoffService.EmittedCommand command, + String outcome) { + ScriptHandoffEvent event = new ScriptHandoffEvent(); + event.setEventId("she-work-item-" + item.getId() + "-command-" + command.ordinal()); + event.setTenantId(item.getTenantId()); + event.setGameInstanceId(item.getGameInstanceId()); + event.setScriptPatchVersion(item.getScriptPatchVersion()); + event.setScriptPinEpoch(item.getScriptPinEpoch()); + event.setScriptPinControlPlaneRequestId(item.getScriptPinControlPlaneRequestId()); + event.setScriptId(item.getScriptId()); + event.setBindingId(item.getBindingId()); + event.setPluginId(item.getPluginId()); + event.setPluginVersionId(item.getPluginVersionId()); + event.setPluginActivationEpoch(item.getPluginActivationEpoch()); + event.setLifecycleRevision(item.getLifecycleRevision()); + event.setWorkItemId(item.getId()); + event.setCommandOrdinal(command.ordinal()); + event.setAutomationDispatchId("workItem:" + item.getId() + "#" + command.ordinal()); + event.setTargetGameInstanceId(command.targetGameInstanceId()); + event.setTargetRegionId(command.targetRegionId()); + event.setTargetRegionEpoch(command.targetRegionEpoch()); + event.setTargetEntityId(command.targetEntityId()); + event.setPlayableStateScope(item.getPlayableStateScope()); + event.setWorldSlug(item.getWorldSlug()); + event.setRealmSlug(item.getRealmSlug()); + event.setPointerVersion(item.getPointerVersion()); + event.setSourceKind(item.getSourceKind()); + event.setSourceState(item.getSourceState()); + event.setSourceOrdinal(item.getSourceOrdinal()); + event.setSourceDueTickId(item.getSourceDueTickId()); + event.setSourceDueAtMs(item.getSourceDueAtMs()); + event.setEmittedCommandText(command.commandText()); + event.setHandoffOutcome(outcome); + return event; + } + private static ScriptGameplayCommandHandoffService.EmittedCommand emittedCommand( String commandText, String targetEntityId, From 222c5e4500956945362d4cbf7a2482374ecf45d8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:10:57 +1300 Subject: [PATCH 34/68] Align Redis scheduler claim identity with namespace authority --- .../system-architecture-redis-usage-and-profiles.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/design/architecture/system-architecture-redis-usage-and-profiles.md b/design/architecture/system-architecture-redis-usage-and-profiles.md index 98403e600a..abe43b3c0e 100644 --- a/design/architecture/system-architecture-redis-usage-and-profiles.md +++ b/design/architecture/system-architecture-redis-usage-and-profiles.md @@ -101,11 +101,13 @@ Keep the cheat sheet and the owning service Redis sections aligned with the cano A small set of automation/scheduler-specific prefixes is target-only and will be **reset-tolerant once implemented**; no current reset operation is defined for these unimplemented target projections: +The schedule-candidate and firing-claim identities below consume the [canonical scripting identity contract](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields): `playableStateNamespaceId` is the durable identity component, while `playableStateScope` is separately persisted and exact-validated fence evidence, not a uniqueness dimension. + - `script-scheduler:{tenantRegionTag}:lastTickId` (target-only, once implemented) - Role: Coordination Redis. - Owner: Automation & Scripting Service. - Purpose: per-region derived discovery hint for “every N ticks” schedulers tied to the canonical `(regionEpoch, tickId)` timeline. Its value is `{regionEpoch, latestTickId}`; consumers reject and rebuild it when the stored epoch differs from the authoritative epoch. It does not store `streamOffset`; `tick-events-offset:{tenantRegionTag}:` is the sole event-stream offset record for each consumer. - - Reset behavior: target-only reset-tolerant projection once implemented; region/tenant/cluster resets may drop this key. Until that target projection exists, no current reset operation is defined for it; current scheduling rebuilds due work from PostgreSQL schedules and the Game Session `ObserveRuntimeTickProgress` feed as described in the tick and scripting docs. Duplicate trigger prevention comes from a durable PostgreSQL trigger-instance or outbox row with a uniqueness projection over the applicable identity branch. For schedule-derived triggers, the pre-claim branch includes `(tenantId, gameInstanceId, playableStateScope, stableOwnerKind, stableOwnerId, regionId, regionEpoch, entityId only when targetScopeType is entity-scoped, scriptId, eventType, eventSchemaVersion, scriptPatchVersion, scriptPinEpoch, isDryRun, scheduleDefinitionId, targetScopeType, targetScopeId, duePoint, triggerMode)`, plus `resumeWindowId` only when `triggerMode=CATCH_UP` and plugin identity `(pluginId, pluginVersionId, bindingId)` when applicable; `resumeWindowId` is absent otherwise. The paired `scriptPinControlPlaneRequestId` remains immutable owner evidence on the candidate and claim and is exact-compared during admission/replay, but it is excluded from their uniqueness and derived `scriptEventId`. For plugin-owned schedules, the captured `pluginActivationEpoch` is an additional tagged dimension of due-candidate and firing-claim identity and therefore of the derived event-scope scheduler `scriptEventId`; the captured `lifecycleRevision` travels alongside as immutable non-identity lifecycle-fence evidence. Neither field is a per-command child-key dimension, and both are revalidated through admission, retry, replay, and recovery. The winning claim then derives one immutable event-scope scheduler `scriptEventId` from that complete candidate identity and propagates it into each resolved handler's normalized Trigger Identity; `pluginActivationEpoch` remains excluded from that handler identity. Contenders reuse the winning event-scope ID instead of including a generated value in the race key. `duePoint` is exactly `dueTickId:` or `dueAt:`; if physical storage uses nullable `dueTickId`/`dueAt` columns, the alternate field is explicitly `NULL`, never an empty/zero substitute, and both fields may not be null or populated together. For an immediate event-driven trigger, the scheduler-only fields `scheduleDefinitionId`, `duePoint`, and `triggerMode` are absent, both physical due columns are `NULL`, and the event-driven branch includes the generated stable `scriptEventId` as the occurrence discriminator. Storage must represent the event-driven versus scheduler-derived branch explicitly, for example with a discriminator or branch-specific unique constraints, rather than allowing nullable scheduler fields to alias distinct event triggers. The per-command `automationDispatchId` and `commandOrdinal` are separately unique under the same runtime timeline and link the trigger claim to each emitted command; they remain child handoff identity and do not replace the full Trigger Identity. The row retains the full schedule projection when applicable (`cadence`, `unit`, `priorityTag`, `targetScopeType`, `targetScopeId`, binding priority/exclusivity, `scheduleSemanticsHash`, the pin operation's `controlPlaneRequestId`, owner/version metadata, due-point state, and `runtimeRegionId`/`runtimeRegionEpoch`), including the captured plugin lifecycle pair when applicable; it is not reduced to this Redis checkpoint or a schedule ID alone. + - Reset behavior: target-only reset-tolerant projection once implemented; region/tenant/cluster resets may drop this key. Until that target projection exists, no current reset operation is defined for it; current scheduling rebuilds due work from PostgreSQL schedules and the Game Session `ObserveRuntimeTickProgress` feed as described in the tick and scripting docs. Duplicate trigger prevention comes from a durable PostgreSQL trigger-instance or outbox row with a uniqueness projection over the applicable identity branch. For schedule-derived triggers, the pre-claim branch includes `(tenantId, gameInstanceId, playableStateNamespaceId, stableOwnerKind, stableOwnerId, regionId, regionEpoch, entityId only when targetScopeType is entity-scoped, scriptId, eventType, eventSchemaVersion, scriptPatchVersion, scriptPinEpoch, isDryRun, scheduleDefinitionId, targetScopeType, targetScopeId, duePoint, triggerMode)`, plus `resumeWindowId` only when `triggerMode=CATCH_UP` and plugin identity `(pluginId, pluginVersionId, bindingId)` when applicable; `resumeWindowId` is absent otherwise. The paired `scriptPinControlPlaneRequestId` remains immutable owner evidence on the candidate and claim and is exact-compared during admission/replay, but it is excluded from their uniqueness and derived `scriptEventId`. For plugin-owned schedules, the captured `pluginActivationEpoch` is an additional tagged dimension of due-candidate and firing-claim identity and therefore of the derived event-scope scheduler `scriptEventId`; the captured `lifecycleRevision` travels alongside as immutable non-identity lifecycle-fence evidence. Neither field is a per-command child-key dimension, and both are revalidated through admission, retry, replay, and recovery. The winning claim then derives one immutable event-scope scheduler `scriptEventId` from that complete candidate identity and propagates it into each resolved handler's normalized Trigger Identity; `pluginActivationEpoch` remains excluded from that handler identity. Contenders reuse the winning event-scope ID instead of including a generated value in the race key. `duePoint` is exactly `dueTickId:` or `dueAt:`; if physical storage uses nullable `dueTickId`/`dueAt` columns, the alternate field is explicitly `NULL`, never an empty/zero substitute, and both fields may not be null or populated together. For an immediate event-driven trigger, the scheduler-only fields `scheduleDefinitionId`, `duePoint`, and `triggerMode` are absent, both physical due columns are `NULL`, and the event-driven branch includes the generated stable `scriptEventId` as the occurrence discriminator. Storage must represent the event-driven versus scheduler-derived branch explicitly, for example with a discriminator or branch-specific unique constraints, rather than allowing nullable scheduler fields to alias distinct event triggers. The per-command `automationDispatchId` and `commandOrdinal` are separately unique under the same runtime timeline and link the trigger claim to each emitted command; they remain child handoff identity and do not replace the full Trigger Identity. The row retains the full schedule projection when applicable (`cadence`, `unit`, `priorityTag`, `targetScopeType`, `targetScopeId`, binding priority/exclusivity, `scheduleSemanticsHash`, the pin operation's `controlPlaneRequestId`, owner/version metadata, due-point state, and `runtimeRegionId`/`runtimeRegionEpoch`), including the captured plugin lifecycle pair when applicable; it is not reduced to this Redis checkpoint or a schedule ID alone. - `automation:timer:{tenantRegionTag}` (target-only, once implemented) - Role: Coordination Redis. - Owner: Automation & Scripting Service. @@ -135,7 +137,7 @@ Automation workloads split into two broad classes, with different expectations a - Current implementation boundary: `EnqueueAutomationCommandIfAbsent` does not yet carry or fully enforce the target lane, one-root actor-slot, or bounded-cost guarantees. Its current wire, durable-storage, and admission path remains narrower than the target contract (including the complete Trigger Identity, `commandOrdinal`, `lane`, and `cost_class`), so current enqueue success is not proof of those guarantees. - Canonical handoff contract (target state): - When work references a revocable component, the durable trigger/admission row and handoff payload retain the applicable component-revocation security-policy fence as independent parent evidence. It is included in the canonical handoff request digest and immutable readback/conflict comparison, revalidated through handoff, retry, replay, recovery, and final-effect boundaries, and excluded from Trigger Identity, Command-Handoff Identity, and their uniqueness keys; a changed or unavailable fence fails closed under the established disposition rather than minting a replacement identity. - - Automation & Scripting creates or reuses a durable PostgreSQL trigger-instance / outbox row keyed by the applicable Trigger Identity branch. A schedule-derived pre-claim row uses `(tenantId, gameInstanceId, playableStateScope, stableOwnerKind, stableOwnerId, regionId, regionEpoch, entityId only when targetScopeType is entity-scoped, scriptId, eventType, eventSchemaVersion, scriptPatchVersion, scriptPinEpoch, isDryRun, scheduleDefinitionId, targetScopeType, targetScopeId, duePoint, triggerMode)`, plus `resumeWindowId` only when `triggerMode=CATCH_UP` and plugin identity `(pluginId, pluginVersionId, bindingId)` when applicable; `resumeWindowId` is absent otherwise. The paired `scriptPinControlPlaneRequestId` remains immutable owner evidence on the row and is exact-compared during admission, handoff, retry, replay, and recovery, but is excluded from uniqueness and derived `scriptEventId`. For plugin-owned schedules, the captured `pluginActivationEpoch` is an additional tagged dimension of due-candidate and firing-claim identity and therefore of the derived `scriptEventId`; the captured `lifecycleRevision` travels alongside as immutable non-identity lifecycle-fence evidence. Neither field is a per-command child-key dimension, and both are carried and revalidated through admission, handoff, retry, replay, and recovery per [Scripting Contracts §8](./system-architecture-scripting-contracts.md#8-plugin-version-fencing-and-control-plane-scope). The winning claim derives one immutable `scriptEventId`, and retries reuse it. An immediate event-driven row omits the scheduler-only fields and uses its generated stable `scriptEventId` to distinguish one event occurrence from another; its storage uniqueness branch must remain distinct from scheduled rows and includes the server-derived `sourceService` in its event-scope claim when the event is custom or service-specific. The immutable source Trigger Identity, including source `regionId` and `regionEpoch`, is retained on the row; current enqueue routing fields are separate. The complete per-command child handoff identity comprises the source runtime scope, optional distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`; it is stored separately from the parent Trigger Identity. The row also retains `cadence`, `unit`, `priorityTag`, `targetScopeType`, `targetScopeId`, binding priority/exclusivity, `scheduleSemanticsHash`, the pin operation's `controlPlaneRequestId`, owner/version metadata, due-point state, and `runtimeRegionId`/`runtimeRegionEpoch` when those fields apply, plus the captured plugin lifecycle pair when applicable. + - Automation & Scripting creates or reuses a durable PostgreSQL trigger-instance / outbox row keyed by the applicable Trigger Identity branch. A schedule-derived pre-claim row uses `(tenantId, gameInstanceId, playableStateNamespaceId, stableOwnerKind, stableOwnerId, regionId, regionEpoch, entityId only when targetScopeType is entity-scoped, scriptId, eventType, eventSchemaVersion, scriptPatchVersion, scriptPinEpoch, isDryRun, scheduleDefinitionId, targetScopeType, targetScopeId, duePoint, triggerMode)`, plus `resumeWindowId` only when `triggerMode=CATCH_UP` and plugin identity `(pluginId, pluginVersionId, bindingId)` when applicable; `resumeWindowId` is absent otherwise. The paired `scriptPinControlPlaneRequestId` remains immutable owner evidence on the row and is exact-compared during admission, handoff, retry, replay, and recovery, but is excluded from uniqueness and derived `scriptEventId`. For plugin-owned schedules, the captured `pluginActivationEpoch` is an additional tagged dimension of due-candidate and firing-claim identity and therefore of the derived `scriptEventId`; the captured `lifecycleRevision` travels alongside as immutable non-identity lifecycle-fence evidence. Neither field is a per-command child-key dimension, and both are carried and revalidated through admission, handoff, retry, replay, and recovery per [Scripting Contracts §8](./system-architecture-scripting-contracts.md#8-plugin-version-fencing-and-control-plane-scope). The winning claim derives one immutable `scriptEventId`, and retries reuse it. An immediate event-driven row omits the scheduler-only fields and uses its generated stable `scriptEventId` to distinguish one event occurrence from another; its storage uniqueness branch must remain distinct from scheduled rows and includes the server-derived `sourceService` in its event-scope claim when the event is custom or service-specific. The immutable source Trigger Identity, including source `regionId` and `regionEpoch`, is retained on the row; current enqueue routing fields are separate. The complete per-command child handoff identity comprises the source runtime scope, optional distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`; it is stored separately from the parent Trigger Identity. The row also retains `cadence`, `unit`, `priorityTag`, `targetScopeType`, `targetScopeId`, binding priority/exclusivity, `scheduleSemanticsHash`, the pin operation's `controlPlaneRequestId`, owner/version metadata, due-point state, and `runtimeRegionId`/`runtimeRegionEpoch` when those fields apply, plus the captured plugin lifecycle pair when applicable. - Automation & Scripting then calls a Game Session gRPC/API contract such as `EnqueueAutomationCommandIfAbsent`, carrying the complete immutable Trigger Identity and child handoff identity: - Parent Trigger/event-scope evidence: `tenantId`, `gameInstanceId`, `playableStateScope`, source `regionId`, source `regionEpoch`, `entityId` only for an entity-scoped trigger, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch`, paired `scriptPinControlPlaneRequestId`, `scriptEventId`, and `isDryRun`, plus applicable plugin identity `(pluginId, pluginVersionId, bindingId)`, captured `(pluginActivationEpoch, lifecycleRevision)` lifecycle-fence evidence, and the server-derived `sourceService` for custom or service-specific events. - Scheduled rows also carry `scheduleDefinitionId`, `targetScopeType`, `targetScopeId`, `triggerMode`, exactly one tagged `duePoint`: `dueTickId:` or `dueAt:`, and `resumeWindowId` only when `triggerMode=CATCH_UP`; immediate event-driven rows use the separate event branch, omit scheduler-only fields and `duePoint`, and carry a stable `scriptEventId`; their physical `dueTickId` and `dueAt` fields are both `NULL`. From 79926ff94f66fbaf5fdd8fd9ee07cc4ef081cc4c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:23:40 +1300 Subject: [PATCH 35/68] Prove post-evaluation routing fence after parent reconciliation --- ...criptWorkItemExecutionServiceImplTest.java | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java index ffd25d3b12..2683b139c0 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java @@ -389,6 +389,71 @@ void rejectsChangedRoutingPointerBeforeZeroCommandEvaluation() { Mockito.verifyNoInteractions(definitionRepository, handoffService); } + @Test + void cancelsEvaluatedCommandsWhenRoutingPointerChangesBeforeHandoff() { + ScriptWorkItem item = workItem(); + ScriptDefinition definition = scriptDefinition(); + definition.setDefinition("{\"emitCommands\": [{\"commandText\": \"LOOK\"}]}"); + ScriptDefinitionRepository definitionRepository = + Mockito.mock(ScriptDefinitionRepository.class); + when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) + .thenReturn(Optional.of(definition)); + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + when(workItemService.claimPendingForEvaluation(1)).thenReturn(List.of(item)); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + when(workItemRepository.save(Mockito.any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + ScriptEventAudit audit = new ScriptEventAudit(); + ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); + when(auditRepository.findByWorkItemId(99L)).thenReturn(Optional.of(audit)); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + var changedRuntime = + runtimeStateResponse().getRuntimeState().toBuilder() + .setPointerVersion(18L) + .clearCurrentAdmissionPointers() + .addCurrentAdmissionPointers(currentPointer("SHARED", 18L)) + .build(); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenReturn( + runtimeStateResponse(), + GetGameInstanceRuntimeStateResponse.newBuilder() + .setRuntimeState(changedRuntime) + .build()); + ScriptGameplayCommandHandoffService handoffService = + Mockito.mock(ScriptGameplayCommandHandoffService.class); + ScriptWorkItemExecutionService service = + new ScriptWorkItemExecutionServiceImpl( + workItemService, + definitionRepository, + handoffService, + workItemRepository, + auditRepository, + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + new ScriptOutputProperties(), + allowingTenantBudgetService(), + allowingDryRunCapacityService(), + new ObjectMapper(), + new SimpleMeterRegistry(), + null, + null, + null, + gameSessionClient, + Mockito.mock(PluginRuntimeStateRepository.class)); + + ScriptWorkItemExecutionService.ExecutionBatchResult result = service.processPendingWorkItems(1); + + assertThat(result.failedCount()).isEqualTo(1); + assertThat(item.getStatus()).isEqualTo("CANCELED"); + assertThat(item.getCancelReason()).isEqualTo("routing_bundle_changed"); + assertThat(audit.getFinalStage()).isEqualTo("ADMISSION"); + assertThat(audit.getFinalOutcome()).isEqualTo("stale_execution_fenced"); + assertThat(audit.getFinalReason()).isEqualTo("routing_bundle_changed"); + verify(definitionRepository).findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1"); + verify(gameSessionClient, Mockito.times(2)).getGameInstanceRuntimeState("1", "7", "region-1"); + Mockito.verifyNoInteractions(handoffService); + } + @Test void terminalizesNonAvailabilityPluginRepositoryFailureWithoutRetry() { ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); From 58a6e317afd3e61b60f830e011cff55101a85c64 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 22:09:03 +1300 Subject: [PATCH 36/68] fix: reconcile failed handoff intent and skipped preflight safely --- ...riptGameplayCommandHandoffServiceImpl.java | 64 ++++++- .../ScriptWorkItemExecutionServiceImpl.java | 22 ++- ...GameplayCommandHandoffServiceImplTest.java | 180 +++++++++++++++++- ...criptWorkItemExecutionServiceImplTest.java | 75 +++++++- 4 files changed, 322 insertions(+), 19 deletions(-) diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java index d7b104c1ab..e1e6250caf 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java @@ -261,12 +261,22 @@ public HandoffResult handoff(ScriptWorkItem workItem, EmittedCommand command) { } AggregateAdmissionSnapshot aggregateSnapshot = aggregateAdmissionSnapshots.get().get(workItem.getId()); - HandoffPreparation preparation; + HandoffPreflight preflight; try { - HandoffPreflight preflight = + preflight = aggregateSnapshot == null ? preflight(workItem) : HandoffPreflight.from(aggregateSnapshot); + } catch (RuntimeException ex) { + LOGGER.warn( + "Unable to preflight script handoff for workItemId={} commandOrdinal={}", + workItem.getId(), + command.ordinal(), + ex); + return retryablePreparationResult(); + } + HandoffPreparation preparation; + try { preparation = executeIntentTransaction(workItem, command, dispatchId, preflight); } catch (RuntimeException ex) { LOGGER.warn( @@ -274,7 +284,7 @@ public HandoffResult handoff(ScriptWorkItem workItem, EmittedCommand command) { workItem.getId(), command.ordinal(), ex); - return retryablePreparationResult(); + return reconcileFailedIntentPreparation(workItem, command, dispatchId); } if (preparation.result() != null) { return preparation.result(); @@ -434,6 +444,12 @@ private HandoffPreparation prepareHandoff( aggregateSnapshot == null ? preflight.runtimeScopeStatus() : aggregateSnapshot.runtimeRegionScopeStatus(); + if (runtimeScopeStatus == RuntimeRegionScopeStatus.SKIPPED) { + // The preflight skipped the remote read because admission was unavailable or fenced. If + // admission recovered before this transaction, do not reinterpret that skipped read as a + // malformed owner response; let the caller retry with a fresh preflight outside the tx. + return new HandoffPreparation(retryablePreparationResult(), false); + } if (runtimeScopeStatus == RuntimeRegionScopeStatus.ADVANCED) { Instant now = Instant.now(); cancelForRuntimeRegionScopeAdvance( @@ -935,7 +951,8 @@ private enum RuntimeRegionScopeStatus { CURRENT, ADVANCED, UNAVAILABLE, - MALFORMED + MALFORMED, + SKIPPED } private record AggregateAdmissionSnapshot( @@ -954,10 +971,47 @@ private HandoffPreflight preflight(ScriptWorkItem workItem) { RuntimeRegionScopeStatus runtimeScopeStatus = admissionFenceReason == null ? runtimeRegionScopeStatusOutsideTransaction(workItem) - : RuntimeRegionScopeStatus.MALFORMED; + : RuntimeRegionScopeStatus.SKIPPED; return new HandoffPreflight(admissionFenceReason, runtimeScopeStatus); } + private HandoffResult reconcileFailedIntentPreparation( + ScriptWorkItem workItem, EmittedCommand command, String dispatchId) { + try { + return executeRpcWithoutLocalTransaction( + () -> { + Optional persistedWorkItem = + workItemRepository.findById(workItem.getId()); + Optional persistedIntent = + handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal( + workItem.getTenantId(), workItem.getId(), command.ordinal()); + if (persistedIntent.isPresent()) { + ScriptHandoffEvent intent = persistedIntent.orElseThrow(); + ScriptWorkItem identitySource = persistedWorkItem.orElse(workItem); + if (!handoffIdentityMatches(intent, identitySource, command, dispatchId)) { + return reconciliationRequiredResult( + "persisted handoff intent identity does not match request; reconciliation is required"); + } + return reconciliationRequiredResult( + "handoff intent may have committed; reconciliation is required"); + } + if (persistedWorkItem.isEmpty() + || !"EVALUATING".equals(persistedWorkItem.orElseThrow().getStatus())) { + return reconciliationRequiredResult( + "handoff preparation outcome could not be confirmed"); + } + return retryablePreparationResult(); + }); + } catch (RuntimeException readbackFailure) { + LOGGER.warn( + "Unable to read back failed script handoff preparation for workItemId={} commandOrdinal={}; retaining in-flight evidence", + workItem.getId(), + command.ordinal(), + readbackFailure); + return reconciliationRequiredResult(readbackFailure); + } + } + private RuntimeRegionScopeStatus runtimeRegionScopeStatusOutsideTransaction( ScriptWorkItem workItem) { if (rpcTransactionTemplate == null) { diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java index 849a6d66ff..97f13a7371 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java @@ -114,7 +114,8 @@ static EvaluationResult requiringHandoff( private record HandoffExecutionResult( String terminalFenceFailure, PluginFenceValidation retryableFence, - ScriptGameplayCommandHandoffService.HandoffResult firstRejectedHandoff) {} + ScriptGameplayCommandHandoffService.HandoffResult firstRejectedHandoff, + boolean childHandoffAttempted) {} private record EvaluationFencePrecheck(boolean checked, String failure) {} @@ -535,6 +536,7 @@ private HandoffExecutionResult executeHandoffLoop( ScriptGameplayCommandHandoffService.HandoffResult firstRejectedHandoff = null; String terminalFenceFailure = null; PluginFenceValidation retryableFence = null; + boolean childHandoffAttempted = false; try { try { handoffService.beginAggregateFanout(workItem); @@ -543,7 +545,7 @@ private HandoffExecutionResult executeHandoffLoop( "Unable to preflight script handoff fanout for workItemId={}; scheduling retry", workItem.getId(), ex); - return new HandoffExecutionResult(null, null, retryableHandoffPreflightResult()); + return new HandoffExecutionResult(null, null, retryableHandoffPreflightResult(), false); } for (int commandIndex = 0; commandIndex < commands.size(); commandIndex++) { ScriptGameplayCommandHandoffService.EmittedCommand command = commands.get(commandIndex); @@ -562,6 +564,7 @@ private HandoffExecutionResult executeHandoffLoop( } break; } + childHandoffAttempted = true; ScriptGameplayCommandHandoffService.HandoffResult result = handoffService.handoff(workItem, command); if (!result.accepted() @@ -578,7 +581,8 @@ private HandoffExecutionResult executeHandoffLoop( } finally { handoffService.endAggregateFanout(workItem); } - return new HandoffExecutionResult(terminalFenceFailure, retryableFence, firstRejectedHandoff); + return new HandoffExecutionResult( + terminalFenceFailure, retryableFence, firstRejectedHandoff, childHandoffAttempted); } private static ScriptGameplayCommandHandoffService.HandoffResult @@ -916,7 +920,17 @@ private boolean finalizeHandoff(ScriptWorkItem workItem, HandoffExecutionResult } if (firstRejectedHandoff != null && ScriptHandoffOutcomeSupport.isRetryable(firstRejectedHandoff)) { - requeueAfterRetryableFailure(workItem); + ScriptWorkItem retryableWorkItem = workItem; + if (handoffResult.childHandoffAttempted()) { + // A child transaction may mutate the detached entity before rollback, including to + // statuses other than HANDOFF_IN_FLIGHT. Requeue only from an authoritative row that + // confirms the work item remains EVALUATING; otherwise retain it for reconciliation. + retryableWorkItem = workItemRepository.findById(workItem.getId()).orElse(null); + if (retryableWorkItem == null || !"EVALUATING".equals(retryableWorkItem.getStatus())) { + return false; + } + } + requeueAfterRetryableFailure(retryableWorkItem); return false; } markTerminalSuccess( diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java index 197e664749..3f71618ea3 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java @@ -356,14 +356,23 @@ void failedIntentCommitIsRetryableAndNeverClaimsInFlightOrCallsCommandRpc() { when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) .thenReturn(currentRuntimeState()); ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptWorkItem persistedWorkItem = workItem(); + persistedWorkItem.setStatus("EVALUATING"); + when(workItemRepository.findById(99L)).thenReturn(Optional.of(persistedWorkItem)); when(workItemRepository.save(Mockito.any())) - .thenAnswer(invocation -> invocation.getArgument(0)); + .thenAnswer( + invocation -> { + ScriptWorkItem saved = invocation.getArgument(0); + saved.setRowVersion(saved.getRowVersion() + 1); + return saved; + }); ScriptHandoffEventRepository handoffEventRepository = Mockito.mock(ScriptHandoffEventRepository.class); when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) .thenReturn(Optional.empty()); when(handoffEventRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); + ScriptWorkItem item = workItem(); ScriptGameplayCommandHandoffServiceImpl service = new ScriptGameplayCommandHandoffServiceImpl( gameSessionClient, @@ -380,21 +389,182 @@ void failedIntentCommitIsRetryableAndNeverClaimsInFlightOrCallsCommandRpc() { try { ScriptGameplayCommandHandoffService.HandoffResult result = service.handoff( - workItem(), emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0)); + item, emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0)); assertThat(result.accepted()).isFalse(); assertThat(result.outcome()).isEqualTo("REMOTE_REJECTED"); assertThat(result.errorCode()).isEqualTo("UNAVAILABLE"); assertThat(ScriptHandoffOutcomeSupport.isRetryable(result)).isTrue(); - assertThat(result.outcome()).isNotEqualTo("HANDOFF_IN_FLIGHT"); - assertThat(result.errorCode()).isNotEqualTo("HANDOFF_IN_FLIGHT"); + assertThat(item.getStatus()).isEqualTo("HANDOFF_IN_FLIGHT"); + assertThat(item.getRowVersion()).isEqualTo(1); + assertThat(persistedWorkItem.getStatus()).isEqualTo("EVALUATING"); + assertThat(persistedWorkItem.getRowVersion()).isZero(); verify(gameSessionClient).getGameInstanceRuntimeState("1", "7", "region-1"); verify(gameSessionClient, never()).enqueueAutomationCommandIfAbsent(Mockito.any()); verify(gameSessionClient, never()).scheduleRemoteFollowup(Mockito.any()); assertThat(transactionManager.propagations()) .containsExactly( TransactionDefinition.PROPAGATION_NOT_SUPPORTED, - TransactionDefinition.PROPAGATION_REQUIRES_NEW); + TransactionDefinition.PROPAGATION_REQUIRES_NEW, + TransactionDefinition.PROPAGATION_NOT_SUPPORTED); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } + + @Test + void recoveredAdmissionAfterSkippedRuntimePreflightRetriesWithoutMarkingMalformed() { + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + AutomationAdmissionStateService admissionService = + Mockito.mock(AutomationAdmissionStateService.class); + when(admissionService.getState("1", "7", "region-1")) + .thenReturn( + new AutomationAdmissionStateService.AdmissionStateSummary( + "1", "7", "region-1", "CORRUPT", 1L, "", "", 100L), + new AutomationAdmissionStateService.AdmissionStateSummary( + "1", "7", "region-1", "NORMAL", 1L, "", "", 100L), + new AutomationAdmissionStateService.AdmissionStateSummary( + "1", "7", "region-1", "NORMAL", 1L, "", "", 100L)); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptHandoffEventRepository handoffEventRepository = + Mockito.mock(ScriptHandoffEventRepository.class); + ScriptGameplayCommandHandoffServiceImpl service = + new ScriptGameplayCommandHandoffServiceImpl( + gameSessionClient, + workItemRepository, + Mockito.mock(ScriptEventAuditRepository.class), + handoffEventRepository, + null, + null, + admissionService, + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + new RecordingTransactionManager(new ArrayList<>())); + ScriptWorkItem item = workItem(); + ScriptGameplayCommandHandoffService.EmittedCommand command = + emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0); + + service.beginAggregateFanout(item); + ScriptGameplayCommandHandoffService.HandoffResult result = service.handoff(item, command); + service.endAggregateFanout(item); + + assertThat(ScriptHandoffOutcomeSupport.isRetryable(result)).isTrue(); + assertThat(result.errorCode()).isEqualTo("UNAVAILABLE"); + assertThat(item.getStatus()).isEqualTo("PENDING_EVALUATION"); + verify(gameSessionClient, never()) + .getGameInstanceRuntimeState(Mockito.any(), Mockito.any(), Mockito.any()); + verify(handoffEventRepository, never()).save(Mockito.any()); + verify(workItemRepository, never()).save(Mockito.any()); + } + + @Test + void failedIntentCommitWithDurableInFlightReadbackRequiresReconciliation() { + FailingIntentCommitTransactionManager transactionManager = + new FailingIntentCommitTransactionManager(); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenReturn(currentRuntimeState()); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptWorkItem persistedWorkItem = workItem(); + persistedWorkItem.setStatus("HANDOFF_IN_FLIGHT"); + persistedWorkItem.setRowVersion(1); + when(workItemRepository.findById(99L)).thenReturn(Optional.of(persistedWorkItem)); + when(workItemRepository.save(Mockito.any())) + .thenAnswer( + invocation -> { + ScriptWorkItem saved = invocation.getArgument(0); + saved.setRowVersion(saved.getRowVersion() + 1); + return saved; + }); + ScriptHandoffEventRepository handoffEventRepository = + Mockito.mock(ScriptHandoffEventRepository.class); + when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) + .thenReturn(Optional.empty()); + when(handoffEventRepository.save(Mockito.any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + ScriptGameplayCommandHandoffServiceImpl service = + new ScriptGameplayCommandHandoffServiceImpl( + gameSessionClient, + workItemRepository, + Mockito.mock(ScriptEventAuditRepository.class), + handoffEventRepository, + null, + null, + admissionStateService(), + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + transactionManager); + ScriptWorkItem item = workItem(); + + TransactionSynchronizationManager.setActualTransactionActive(false); + try { + ScriptGameplayCommandHandoffService.HandoffResult result = + service.handoff( + item, emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0)); + + assertThat(result.errorCode()).isEqualTo("HANDOFF_IN_FLIGHT"); + assertThat(ScriptHandoffOutcomeSupport.isRetryable(result)).isFalse(); + assertThat(persistedWorkItem.getStatus()).isEqualTo("HANDOFF_IN_FLIGHT"); + verify(gameSessionClient, never()).enqueueAutomationCommandIfAbsent(Mockito.any()); + verify(gameSessionClient, never()).scheduleRemoteFollowup(Mockito.any()); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + } + + @Test + void failedIntentCommitWithMismatchedDurableIdentityStillRequiresReconciliation() { + FailingIntentCommitTransactionManager transactionManager = + new FailingIntentCommitTransactionManager(); + GameSessionControlPlaneClient gameSessionClient = + Mockito.mock(GameSessionControlPlaneClient.class); + when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) + .thenReturn(currentRuntimeState()); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptWorkItem persistedWorkItem = workItem(); + persistedWorkItem.setStatus("EVALUATING"); + when(workItemRepository.findById(99L)).thenReturn(Optional.of(persistedWorkItem)); + when(workItemRepository.save(Mockito.any())) + .thenAnswer( + invocation -> { + ScriptWorkItem saved = invocation.getArgument(0); + saved.setRowVersion(saved.getRowVersion() + 1); + return saved; + }); + ScriptHandoffEventRepository handoffEventRepository = + Mockito.mock(ScriptHandoffEventRepository.class); + ScriptWorkItem item = workItem(); + ScriptGameplayCommandHandoffService.EmittedCommand command = + emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0); + ScriptHandoffEvent mismatchedIntent = acceptedHandoffEvent(item, command, "handoff_in_flight"); + mismatchedIntent.setEmittedCommandText("different command identity"); + when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) + .thenReturn( + Optional.empty(), Optional.empty(), Optional.empty(), Optional.of(mismatchedIntent)); + when(handoffEventRepository.save(Mockito.any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + ScriptGameplayCommandHandoffServiceImpl service = + new ScriptGameplayCommandHandoffServiceImpl( + gameSessionClient, + workItemRepository, + Mockito.mock(ScriptEventAuditRepository.class), + handoffEventRepository, + null, + null, + admissionStateService(), + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + transactionManager); + + TransactionSynchronizationManager.setActualTransactionActive(false); + try { + ScriptGameplayCommandHandoffService.HandoffResult result = service.handoff(item, command); + + assertThat(result.errorCode()).isEqualTo("HANDOFF_IN_FLIGHT"); + assertThat(result.errorMessage()) + .contains("persisted handoff intent identity does not match request"); + assertThat(ScriptHandoffOutcomeSupport.isRetryable(result)).isFalse(); + verify(gameSessionClient, never()).enqueueAutomationCommandIfAbsent(Mockito.any()); + verify(gameSessionClient, never()).scheduleRemoteFollowup(Mockito.any()); } finally { TransactionSynchronizationManager.setActualTransactionActive(false); } diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java index 2683b139c0..cdec0ee64f 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java @@ -1852,7 +1852,7 @@ void ambiguousChildOutcomeRemainsInFlightWhenLaterPluginFenceIsTerminal() { when(handoffService.handoff(Mockito.eq(item), Mockito.any())) .thenAnswer( invocation -> { - item.setStatus("HANDOFF_IN_FLIGHT"); + item.setStatus("CANCELED"); return new ScriptGameplayCommandHandoffService.HandoffResult( false, "HANDOFF_IN_FLIGHT", "", "", "", "HANDOFF_IN_FLIGHT"); }); @@ -1869,7 +1869,7 @@ void ambiguousChildOutcomeRemainsInFlightWhenLaterPluginFenceIsTerminal() { service.processPendingWorkItems(1); - assertThat(item.getStatus()).isEqualTo("HANDOFF_IN_FLIGHT"); + assertThat(item.getStatus()).isEqualTo("CANCELED"); assertThat(audit.getFinalStage()).isNull(); assertThat(audit.getFinalOutcome()).isNull(); verify(handoffService, Mockito.times(1)).handoff(Mockito.eq(item), Mockito.any()); @@ -1958,6 +1958,13 @@ void retryableHandoffRequeuesAndPublishesPointerAfterCommit() { .thenReturn( new ScriptGameplayCommandHandoffService.HandoffResult( false, "REMOTE_REJECTED", "", "", "", "QUEUE_UNAVAILABLE")); + ScriptWorkItem persistedWorkItem = new ScriptWorkItem(); + persistedWorkItem.setId(item.getId()); + persistedWorkItem.setTenantId(item.getTenantId()); + persistedWorkItem.setStatus("EVALUATING"); + persistedWorkItem.setRowVersion(item.getRowVersion()); + persistedWorkItem.setNextEligibleAt(eligibleAtBeforeRetry); + when(workItemRepository.findById(item.getId())).thenReturn(Optional.of(persistedWorkItem)); when(workItemRepository.save(Mockito.any())) .thenAnswer( invocation -> { @@ -2000,9 +2007,10 @@ void retryableHandoffRequeuesAndPublishesPointerAfterCommit() { service.processPendingWorkItems(10); assertThat(result.failedCount()).isEqualTo(1); - assertThat(item.getStatus()).isEqualTo("PENDING_EVALUATION"); - assertThat(item.getAuthorityUnavailableRetryCount()).isZero(); - assertThat(item.getNextEligibleAt()).isEqualTo(eligibleAtBeforeRetry); + assertThat(item.getStatus()).isEqualTo("EVALUATING"); + assertThat(persistedWorkItem.getStatus()).isEqualTo("PENDING_EVALUATION"); + assertThat(persistedWorkItem.getAuthorityUnavailableRetryCount()).isZero(); + assertThat(persistedWorkItem.getNextEligibleAt()).isEqualTo(eligibleAtBeforeRetry); assertThat(operations).containsExactly("save:PENDING_EVALUATION", "refresh"); assertThat(TransactionSynchronizationManager.getSynchronizations()).hasSize(1); @@ -2013,6 +2021,63 @@ void retryableHandoffRequeuesAndPublishesPointerAfterCommit() { } } + @Test + void retryableHandoffReadbackRequeuesUsingRolledBackRowVersion() { + ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); + ScriptDefinitionRepository definitionRepository = + Mockito.mock(ScriptDefinitionRepository.class); + ScriptGameplayCommandHandoffService handoffService = + Mockito.mock(ScriptGameplayCommandHandoffService.class); + ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); + ScriptWorkItem item = workItem(); + ScriptWorkItem persistedAfterRollback = new ScriptWorkItem(); + persistedAfterRollback.setId(item.getId()); + persistedAfterRollback.setTenantId(item.getTenantId()); + persistedAfterRollback.setStatus("EVALUATING"); + persistedAfterRollback.setRowVersion(7); + ScriptDefinition definition = scriptDefinition(); + definition.setDefinition("{\"emitCommands\":[{\"commandText\":\"LOOK\"}]}"); + when(workItemService.claimPendingForEvaluation(1)).thenReturn(List.of(item)); + when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) + .thenReturn(Optional.of(definition)); + when(handoffService.handoff(Mockito.eq(item), Mockito.any())) + .thenAnswer( + invocation -> { + item.setStatus("CANCELED"); + item.setRowVersion(8); + return new ScriptGameplayCommandHandoffService.HandoffResult( + false, "REMOTE_REJECTED", "", "", "", "QUEUE_UNAVAILABLE"); + }); + when(workItemRepository.findById(item.getId())).thenReturn(Optional.of(persistedAfterRollback)); + when(workItemRepository.save(Mockito.any())) + .thenAnswer(invocation -> invocation.getArgument(0)); + + ScriptWorkItemExecutionService service = + new ScriptWorkItemExecutionServiceImpl( + workItemService, + definitionRepository, + handoffService, + workItemRepository, + Mockito.mock(ScriptEventAuditRepository.class), + Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class), + new ScriptOutputProperties(), + allowingTenantBudgetService(), + allowingDryRunCapacityService(), + new ObjectMapper()); + + ScriptWorkItemExecutionService.ExecutionBatchResult result = service.processPendingWorkItems(1); + + assertThat(result.failedCount()).isEqualTo(1); + assertThat(item.getStatus()).isEqualTo("CANCELED"); + assertThat(item.getRowVersion()).isEqualTo(8); + assertThat(persistedAfterRollback.getStatus()).isEqualTo("PENDING_EVALUATION"); + assertThat(persistedAfterRollback.getRowVersion()).isEqualTo(7); + ArgumentCaptor saved = ArgumentCaptor.forClass(ScriptWorkItem.class); + verify(workItemRepository).save(saved.capture()); + assertThat(saved.getValue()).isSameAs(persistedAfterRollback); + assertThat(saved.getValue().getRowVersion()).isEqualTo(7); + } + @Test void retryablePluginFenceDuringFanoutRequeuesWorkAndContinuesWithSibling() { ScriptWorkItemService workItemService = Mockito.mock(ScriptWorkItemService.class); From 13a07d3256483251e5abf863eaaf50725ac685e4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 29 Sep 2026 23:31:43 +1300 Subject: [PATCH 37/68] Separate proposed effect allocator from accepted replay contract --- design/architecture/decisions/README.md | 2 +- ...ution-with-one-logical-terminal-outcome.md | 21 +++++------------- ...ount-bounds-for-generated-effect-chains.md | 4 ++-- ...effect-id-allocation-and-replay-binding.md | 22 +++++++++---------- ...system-architecture-identifier-glossary.md | 6 ++--- ...ure-scripting-normative-contract-tables.md | 6 ++--- ...ystem-architecture-tick-execution-flows.md | 6 ++--- ...chitecture-tick-failures-and-operations.md | 15 ++++++------- .../architecture/system-architecture-ticks.md | 10 ++++----- .../system-architecture-transactions.md | 16 +++++++------- .../automation-and-scheduler-runtime.md | 4 ++-- ...e-session-runtime-and-tick-coordination.md | 6 ++--- .../gameplay-rules-entities-and-effects.md | 2 +- 13 files changed, 55 insertions(+), 65 deletions(-) diff --git a/design/architecture/decisions/README.md b/design/architecture/decisions/README.md index ec7d55bd7c..9311640191 100644 --- a/design/architecture/decisions/README.md +++ b/design/architecture/decisions/README.md @@ -277,7 +277,7 @@ Validation precedence is fixed: first parse every checked queue row and validate | [ADR 0180](./adr-0180-account-owned-hosted-terms-acceptance-gate.md) | Accepted | `AA-1.3` | `AA-1.5`, `AR-1.1`, `AR-1.4`, `AR-1.5`, `EA-3.2`, `PO-1.3`, `SF-2.3` | Account-owned hosted-terms catalog, acceptance evidence, and official-hosted creator mutation gate | | [ADR 0181](./adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) | Accepted | `PO-1.3` | `AA-1.3`, `AA-1.4`, `AA-1.5`, `AR-1.1`, `AR-1.4`, `AR-1.5`, `EA-3.2`, `SF-2.3` | Changed hosted-terms decline, prior-terms continuity, lifecycle-reducing access, and finite transition | | [ADR 0182](./adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md) | Accepted | `PO-3.2` | `PO-3.1`, `PO-4.4`, `SF-1.3`, `PO-1.1` | Separated hosted runtime and certificate-identity lifecycles | -| [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) | Proposed - Pending Human Review | `GR-1.2` | `GR-1.4`, `GR-4.1`, `AS-1.2`, `AS-1.4`, `SF-1.4`, `SF-2.3`, `PO-4.2` | Pending UUIDv7 scalar, canonical serialization, and generated-child/fan-out allocation refinements; ADR 0069's command-root owner/key/manifest-digest foundation is accepted | +| [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) | Proposed - Pending Human Review | `GR-1.2` | `GR-1.4`, `GR-4.1`, `AS-1.2`, `AS-1.4`, `SF-1.4`, `SF-2.3`, `PO-4.2` | Pending command-plan ordering, `planOrdinal`, command-root allocation, UUIDv7 scalar, canonical serialization, and generated-child/fan-out allocation design | | [ADR 0184](./adr-0184-emergency-tcp-proxy-identity-withdrawal.md) | Accepted | `SF-1.3` | `PO-2.1`, `PO-2.2`, `PO-3.2`, `PO-4.4` | Emergency trust cutoff for a withdrawn TCP Proxy bridge identity | Capability identifiers are defined in the [FireMUD Product Capability Taxonomy](../../product/capability-taxonomy.md). diff --git a/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md b/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md index e6bc471fde..c098cb5dcf 100644 --- a/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md +++ b/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md @@ -6,7 +6,7 @@ Accepted ## Implementation Status -The command/effect boundary, deterministic command-plan root identity, and single logical terminal outcome are target state; complete durable identity guards, evidence-based reconciliation, and focused crash/replay proof remain incomplete. +The command/effect boundary and single logical terminal outcome are accepted target state; complete durable identity guards, evidence-based reconciliation, and focused crash/replay proof remain incomplete. Deterministic command-plan ordering, `planOrdinal`, and root-allocation details are proposed separately in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) and are not accepted by this decision. ## Canonical Design @@ -36,7 +36,7 @@ Describing this as “exactly-once execution” would wrongly imply one physical ## Decision -An `ACCEPTED_VOLATILE` command still in `RECEIVED` or `ENQUEUED`, with no surviving durable `tickBatchId`, effect ledger, or source/effect claim, may terminate as lost before durable staging only when an atomic owner-defined no-batch CAS/version-fenced check wins. A pre-staging plan manifest or root-allocation row alone is a non-executable identity reservation, not a batch/effect binding and does not disqualify this outcome; it remains linked to the terminal command as evidence and cannot be reused for another command: +An `ACCEPTED_VOLATILE` command still in `RECEIVED` or `ENQUEUED`, with no surviving durable `tickBatchId`, effect ledger, or source/effect claim, may terminate as lost before durable staging only when an atomic owner-defined no-batch CAS/version-fenced check wins: - `executionOutcome = LOST_BEFORE_STAGING`; and - `gameplayResult = NOT_APPLIED`. @@ -47,19 +47,11 @@ Before any participant verification, the canonical Game Session context binds ea The owning domain's durable idempotency guard permits at most one logical authoritative state mutation for that identity and digest. Reuse of the identity with a conflicting digest fails closed. -The accepted decision does not select a generated-child allocator or exact scalar format. Those unresolved target-state questions are recorded, without authority, in the pending [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +The exact scalar format and allocation boundary for root or generated-child effect identities remain unresolved and are proposed in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). This decision requires retries and replay to preserve the persisted mutation identity and immutable request digest; it does not define command-plan ordering, `planOrdinal`, or a root-allocation key. -### Deterministic command plans and root identity +Command receipts, tick batches, and selected-work manifests are S3 instance-scoped operational evidence: they may be cleaned up only after linked source claims and effects are terminal, replay/restore and reconciliation horizons have elapsed, and the owner cleanup fence permits it. Participant guards remain owner-domain durable evidence, with their own namespace/state classification and retention contract; they are not disposable Redis coordination state. A reset or replacement alone never authorizes bulk deletion or abandonment. -An admitted command has one deterministic effect plan: the ordered set of logical root effects admitted for that command. The order is supplied by the frozen typed command or `ResolvedEffectPlan` semantic order owned by the command/action contract; Game Session does not infer it from scheduler selection. Built-in commands declare an equivalent stable semantic order. An ambiguous or duplicate root order fails before admission, and Game Session persists the ordered plan manifest and its digest before tick staging. Each logical operation in the plan has exactly one root `EffectId`, with any affected participants represented by guards beneath that root. A conserved multi-participant operation normally shares one root across its participants, but still follows [ADR 0053](./adr-0053-command-atomicity-by-invariant-class.md)'s required/optional classification and its co-location or reservation/escrow rules; one root does not claim global atomicity. - -The plan assigns a stable zero-based `planOrdinal` in that supplied semantic order. A single-root plan uses `planOrdinal=0`; a multi-root plan uses `0..n-1`; a zero-effect plan allocates no ordinal and no root `EffectId`. Before allocation, the durable gameplay command row freezes/binds its request fingerprint, resolved runtime scope, applicable `playableStateNamespaceId`, and separately persisted `playableStateScope` fence evidence. Game Session owns an opaque root `EffectId` allocation row unique on `(tenantId, gameInstanceId, commandId, planOrdinal)`; that row also binds the ordered plan manifest digest and exact-validates the command row's frozen binding, including the namespace and scope evidence. Reuse requires the same command row identity, frozen command/runtime binding, `planOrdinal`, and manifest digest; any mismatch fails closed. `playableStateNamespaceId` and `playableStateScope` are bound evidence, not additional allocation-key dimensions. For Automation, the complete applicable Command-Handoff Identity, including any optional distinct target runtime fields, is the admission/deduplication identity and must exact-map to one durable target `commandId`; after that mapping, root allocation uses the target command row's same canonical key. Trigger Identity and `scriptEventId` remain handler/correlation identities, not root-allocation inputs. Ordinary retries, replay, and reconciliation read and reuse the binding; the opaque ID is not derived by participants. - -`planOrdinal` and this allocation binding apply only to command-root work. Passive, inbound/remote, timer, retry, and already-generated effects retain their owner/source-specific root identity contracts and do not synthesize a command plan unless they materialize as an admitted command; generated children remain beneath the enclosing root. Random `tickBatchId`, mutable command text, `effectKey`, `sourceOrdinal`/`enqueueSeq`, participant tuples, Trigger Identity or `scriptEventId`, and child ordinals cannot substitute for the durable command row identity or allocation binding; they retain their existing staging, ordering, descriptor, participant, handler, and lineage roles. - -Command receipts, root-allocation records, tick batches, and selected-work manifests are S3 instance-scoped operational evidence: they may be cleaned up only after linked source claims and effects are terminal, replay/restore and reconciliation horizons have elapsed, and the owner cleanup fence permits it. Participant guards remain owner-domain durable evidence, with their own namespace/state classification and retention contract; they are not disposable Redis coordination state. A reset or replacement alone never authorizes bulk deletion or abandonment. - -The plan root is distinct from the command ingress identity, source-claim identity, Automation Command-Handoff Identity, participant guard identity, and generated child identity. A post-abandon command re-drive may receive a fresh root only under the existing conclusive `ABANDONED` and source-terminalization rules and must create a new durable `commandId` linked to the abandoned command and effect lineage; reusing the old `commandId` returns its prior terminal result and cannot allocate another plan root. A non-command source follows its owner-specific linked re-drive identity. An ordinary retry or replay never allocates a fresh root. +An ordinary retry or replay preserves the original persisted mutation identity and digest. A post-abandon re-drive is permitted only under conclusive `ABANDONED` and source-terminalization rules and follows the source owner's admission and identity contract, linked to the abandoned command/effect lineage. This decision does not define command-root allocation for that re-drive. Every staged effect ledger row reaches at most one terminal status, and terminalization occurs only when the applicable evidence policy permits it: @@ -80,7 +72,6 @@ The system does not silently drop staged effects, leave them permanently ambiguo - Recovery may retry physical work without duplicating authoritative gameplay state. - Operators and callers can distinguish command results, effect terminal states, and replay reasons. - Owner services require durable identity-and-digest guards and authoritative evidence queries. -- Deterministic plans make command-root admission and replay stable without deriving the allocation binding from scheduler selection, staging coordinates, source ordering, or handler identity. - Multi-participant conservation remains governed by command atomicity/co-location or reservation semantics; a shared root is not a distributed transaction. - The ledger and recovery controller must retain unresolved staged effects until they reach a justified terminal outcome. - Presentation output can duplicate even while authoritative state remains logically single-apply. @@ -105,7 +96,7 @@ Rejected as the normal contract because unresolved effects could remain ambiguou ## Implementation and Proof Obligations -Proof must cover accepted-command loss before staging without an invented effect row, including a surviving pre-staging plan/root allocation but no batch/effect binding; semantic zero-, single-, and multi-root plan ordering supplied by the frozen typed command/action contract, including built-in stable order and ambiguous/duplicate-order rejection; freezing/binding of command request fingerprint, runtime scope, `playableStateNamespaceId`, and separately persisted/exact-validated `playableStateScope`; persistence of the ordered plan manifest/digest and opaque allocation-row binding; uniqueness on `(tenantId, gameInstanceId, commandId, planOrdinal)`; reuse only with the same command row identity, frozen command/runtime binding, `planOrdinal`, and manifest digest, with mismatch rejection; Automation handoff admission exact-mapping to one durable target command; preservation of separate source-ordering, participant, handler, and child identities; command-root-only scope; conserved multi-participant handling under ADR 0053; sealed root/operation/digest/participant/manifest binding before participant verification and conflict rejection; crashes before and after domain commit; lost acknowledgements; duplicate physical invocation with one logical mutation; authoritative `REPLAY_NOOP` evidence terminalizing as `APPLIED`; evidence-qualified `ABANDONED` outcomes with timeout, retry-exhaustion, missing-coordination, age, and technical-failure rejection; command-result derivation across zero, one, and multiple required effects; duplicate presentation feedback without duplicate state; replay and reset convergence; and absence of silent drop or permanently ambiguous staged rows. +Proof must cover accepted-command loss before staging without an invented effect row; sealed mutation identity/operation/digest/participant/manifest binding before participant verification and conflict rejection; crashes before and after domain commit; lost acknowledgements; duplicate physical invocation with one logical mutation; authoritative `REPLAY_NOOP` evidence terminalizing as `APPLIED`; evidence-qualified `ABANDONED` outcomes with timeout, retry-exhaustion, missing-coordination, age, and technical-failure rejection; command-result derivation from required-effect terminal outcomes; duplicate presentation feedback without duplicate state; replay and reset convergence; and absence of silent drop or permanently ambiguous staged rows. Command-plan ordering, ordinal allocation, and root-allocation proof belong to ADR 0183 only if that proposal is accepted. The current implementation and runtime proof are not claimed to satisfy this decision. diff --git a/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md b/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md index 8495bbded5..b59690d31a 100644 --- a/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md +++ b/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md @@ -43,7 +43,7 @@ The platform retains a hard generated-effect depth ceiling with `8` as the share Platform hard ceilings bound every setting. Operators may configure lower environment bounds, and an authored feature may lower its own limits further, but a feature can never exceed the resolved operator or platform bounds. -Every generated child carries an immutable parent identity, immutable root identity, depth equal to `parent.depth + 1`, and an owner-defined deterministic child ordinal allocated and persisted by the owning contract for replay-stable reuse. For generated work under an admitted command, the immutable root identity is the opaque Game Session root `EffectId` allocated for the enclosing command plan and its `planOrdinal`; this decision introduces no second root authority. Generated work under a passive, inbound/remote, timer, retry, or other non-command-root contract retains that owner's root identity and does not acquire a `planOrdinal` unless it materializes as an admitted command. A generated child never allocates a new command plan root, and its child ordinal is lineage/accounting metadata rather than an input to the root allocation binding. The sealed root manifest also persists the resolved platform, operator, and feature depth/count/cost/per-target limits, cost weights, and cost-model version. Retry, replay, and reconciliation reuse those persisted resolved values and never re-resolve them. Replay reuses the recorded child identity, lineage, ordinal, and budget accounting; it does not increment them again or mint a replacement identity. +Every generated child carries an immutable parent identity, immutable enclosing-root lineage, depth equal to `parent.depth + 1`, and an owner-defined child ordinal allocated and persisted by the owning contract for replay-stable reuse. This decision does not define command-plan roots or `planOrdinal`; those allocation choices remain pending in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). The sealed chain manifest also persists the resolved platform, operator, and feature depth/count/cost/per-target limits, cost weights, and cost-model version. Retry, replay, and reconciliation reuse those persisted resolved values and never re-resolve them. Replay reuses the recorded child identity, lineage, ordinal, and budget accounting; it does not increment them again or mint a replacement identity. The owner-scope/root/parent/ordinal mapping to each child `EffectId` is one atomic durable admission record. The owning contract must persist the child `EffectId` and complete mapping before enqueue/apply; retry, replay, and reconciliation read and reuse that mapping and its sealed accounting, while a missing or conflicting mapping fails closed rather than allocating another child identity. @@ -96,7 +96,7 @@ Rejected because the parent may already be durably committed across authoritativ ## Implementation and Proof Obligations -Implement one canonical generated-chain admission and accounting path with the platform hard depth ceiling, shared depth bootstrap default of `8`, deterministic total count and cost budgets, per-target caps, operator bounds, and feature-lowering rules. When the enclosing work is command-root work, persist its `planOrdinal`/opaque root allocation binding; otherwise retain the owner/source-specific root identity. Persist immutable parent and root identities, `parent.depth + 1`, owner-defined deterministic child ordinals allocated and persisted for replay-stable reuse, required or optional classification, and the complete suppression evidence; child ordinals must not allocate or replace a command plan root. +Implement one canonical generated-chain admission and accounting path with the platform hard depth ceiling, shared depth bootstrap default of `8`, deterministic total count and cost budgets, per-target caps, operator bounds, and feature-lowering rules. Preserve the persisted enclosing-root identity under its owning contract; command-plan and root allocation details remain pending in ADR 0183. Persist immutable parent and root identities, `parent.depth + 1`, owner-defined child ordinals allocated and persisted for replay-stable reuse, required or optional classification, and the complete suppression evidence. Prove hard-ceiling and lower-bound resolution; depth, count, cost, and per-target suppression at each boundary; deterministic admission order; cost accounting; immutable lineage and ordinals; request-digest validation; crash and replay without re-incrementing accounting or reminting identity; suppression of only the new child; preservation of committed parents and earlier children; truthful `SUCCESS`, `PARTIAL`, and `FAILED` derivation; complete durable evidence; bounded metric labels and bands; raw-identity exclusion from Prometheus; audit-query retrieval; one-off optional audit behavior; repeated optional designer warnings; prompt required-suppression alerts; and operational paging for sustained aggregate suppression or tick degradation. The pending [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not proved or accepted by this ADR. diff --git a/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md b/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md index 994e1c7de9..2cade3fd26 100644 --- a/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md +++ b/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md @@ -6,7 +6,7 @@ Proposed - Pending Human Review ## Implementation Status -The additional requirements in this proposal are not current target state or accepted implementation requirements. The command-root owner, key, frozen binding, and ordered manifest digest remain accepted target state under ADR 0069. The current services, wire contracts, and focused proof remain implementation gaps as recorded by the linked canonical documents. No implementation may treat this proposal's refinements as approved before human review. +All allocation requirements in this proposal are pending and do not define current target state or accepted implementation requirements. ADR 0069 accepts persisted mutation identity and digest-bound replay, together with evidence-qualified terminal outcomes; it does not select deterministic command-plan ordering, `planOrdinal`, a command-root owner or key, or an ordered plan manifest/allocation binding. No implementation or proof may treat this proposal as approved before human review. The move from the conflicting draft number ADR 0182 to ADR 0183 is mechanical preservation only. It neither accepts this allocator decision nor authorizes proposal-dependent implementation; independently authoritative effect and replay obligations continue to apply on their own authority. @@ -25,11 +25,11 @@ The move from the conflicting draft number ADR 0182 to ADR 0183 is mechanical pr ## Context -[ADR 0069](./adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) already accepts the command-root foundation: Game Session owns the opaque root allocation row, unique on `(tenantId, gameInstanceId, commandId, planOrdinal)`, and binds it to the frozen command/runtime evidence and ordered command-plan manifest digest. It also accepts semantic plan order and reuse only for the same binding. This proposal does not reopen or replace that contract. ADR 0069 leaves the exact scalar format and generated-child allocation contract unresolved; it also does not select the additional versioned canonical serialization and atomic manifest/allocation details proposed here. The current implementation derives effect IDs from batch or effect-key material and exposes narrower service-local replay tables. Those paths are documented implementation gaps and cannot be made canonical by inference. +[ADR 0069](./adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) establishes the at-least-once effect, persisted mutation identity, immutable request-digest, replay, and terminal-outcome rules. It does not select command-plan ordering, `planOrdinal`, a command-root allocation owner or key, or a plan manifest/allocation binding. This proposal presents those command-root choices alongside generated-child and fan-out allocation. It also proposes an exact scalar format, versioned canonical serialization, and atomic manifest/allocation behavior. The current implementation derives effect IDs from batch or effect-key material and exposes narrower service-local replay tables. Those paths are implementation gaps and cannot determine the pending design by inference. -Generated chains and global fan-out need an identity that survives retries, crashes, replay, runtime replacement, and reconciliation without turning semantic fields into an ID. ADR 0069 already requires command roots to use a durable plan/ordinal binding so a changed plan cannot silently reuse an old root; this proposal adds exact scalar and canonical serialization refinements to that foundation. Candidate suppression must remain auditable without inventing an ID for work that never entered execution. +Generated chains and global fan-out need an identity that survives retries, crashes, replay, runtime replacement, and reconciliation without turning semantic fields into an ID. This proposal considers a durable semantic command plan, stable `planOrdinal`, and command-root binding, as well as generated-child and fan-out allocation. Candidate suppression must remain auditable without inventing an ID for work that never entered execution. -This proposal supplies refinements for those gaps while preserving ADR 0069's accepted command-root owner, key, frozen binding, and manifest-digest contract. Its exact UUIDv7 scalar, versioned canonical serialization, generated-child/fan-out manifest, and atomic allocation details remain deliberately pending human approval before any accepted ADR or implementation depends on them. +This proposal records design options for command-plan order and root allocation, exact UUIDv7 scalar identity, versioned canonical serialization, generated-child/fan-out manifests, and atomic allocation. All remain pending human approval. ADR 0069's independently accepted identity, replay, and terminal-outcome rules continue to apply without establishing any of these allocation choices. ## Decision @@ -37,15 +37,15 @@ This proposal supplies refinements for those gaps while preserving ADR 0069's ac The canonical scalar `EffectId` is an opaque, lowercase, hyphenated UUIDv7 textual value of exactly 36 characters. UUIDv7 supplies collision-resistant allocation ordering properties without giving producers semantic parsing or meaning. Producers and participants must treat the value as an opaque scalar; they must not derive it from command text, batch IDs, effect keys, participant fields, ordinals, operation names, targets, or mutable payloads. -Game Session owns command-root allocation. The owner of a generated child, non-command root, or remote/fan-out leg owns its corresponding allocation boundary. Each boundary allocates once, durably persists the value, and atomically binds it to the complete immutable owner scope, operation, exact target where applicable, request digest, enclosing root, parent, and stable ordinal. Insert-if-absent uniqueness covers the logical mapping and the scalar claim. A collision or any conflicting binding fails closed; it never remints or substitutes an ID. +If accepted, Game Session would own command-root allocation, while the owner of a generated child, non-command root, or remote/fan-out leg would own its corresponding allocation boundary. Each boundary would allocate once, durably persist the value, and atomically bind it to the complete immutable owner scope, operation, exact target where applicable, request digest, enclosing root, parent, and stable ordinal. Insert-if-absent uniqueness would cover the logical mapping and scalar claim. A collision or any conflicting binding would fail closed; it would not remint or substitute an ID. Retries, replay, failover, and reconciliation read and reuse the persisted mapping and exact scalar. Participants receive the persisted mutation identity and use it in their guard, ledger, response, and terminal outcome. The enclosing root remains lineage and reconciliation context for a child; it does not replace the child's identity or collapse siblings. A post-abandon re-drive receives a new explicitly linked identity under its own admission contract. ### Proposed command-root serialization refinements -ADR 0069 already requires Game Session to persist the ordered plan manifest and its digest before tick staging, assigns each logical root its stable `planOrdinal` in the supplied semantic order, and binds the opaque root allocation row to the frozen command/runtime evidence. The following are additional proposed refinements, not prerequisites that redefine that accepted foundation: the manifest has an explicit schema version, registered canonical serialization identifier, and canonical bytes; and its serialized content includes ordered logical operations and frozen request/runtime/namespace binding. A root still receives the accepted `planOrdinal` and opaque `EffectId`; zero-effect plans allocate neither. +The proposal assigns each logical command root a stable `planOrdinal` in semantic order and binds an opaque root `EffectId` to a frozen command/runtime context and ordered plan manifest. It further proposes an explicit manifest schema version, registered canonical serialization identifier, canonical bytes, and serialized ordered logical operations and request/runtime/namespace binding. These command-plan, ordinal, and root-allocation choices are all pending; they are not requirements of ADR 0069. Under this proposed model, a zero-effect plan allocates neither an ordinal nor a root `EffectId`. -The accepted durable allocation row remains unique on `(tenantId, gameInstanceId, commandId, planOrdinal)` and binds the frozen command binding and ordered plan-manifest digest. This proposal additionally binds the manifest schema version, serializer, canonical bytes, and exact root scalar claim, requiring exact matches on replay. Unknown, duplicate, ambiguous, noncanonical, or changed order/manifest evidence fails before staging or side effects under the accepted ordering and digest contract, with the additional serialization checks pending. Automation handoff identity maps exactly to one durable target command before this command-root allocation is attempted; trigger and correlation identities are not allocation inputs. +The proposed durable allocation row is unique on `(tenantId, gameInstanceId, commandId, planOrdinal)` and binds the frozen command context and ordered plan-manifest digest. This proposal also binds the manifest schema version, serializer, canonical bytes, and exact root scalar claim, requiring exact matches on replay. Unknown, duplicate, ambiguous, noncanonical, or changed order/manifest evidence fails before staging or side effects if this design is accepted. Automation handoff identity would map exactly to one durable target command before this command-root allocation; trigger and correlation identities would not be allocation inputs. ### Generated-child candidates and suppression @@ -85,7 +85,7 @@ Rejected because notifications can be lost or duplicated and cannot own durable ## Consequences -- The accepted ADR 0069 Game Session command-root allocation owner, key, frozen binding, and ordered manifest digest remain the foundation; the exact UUIDv7 scalar and the additional versioned serialization fields proposed here remain pending. +- If accepted, the command-plan, `planOrdinal`, command-root ownership/key/binding, and manifest-digest requirements proposed here would join ADR 0069's identity, replay, and terminal-outcome rules. - Each generated-effect or fan-out owner would need the proposed durable allocation rows, manifest bindings, and conflict-safe atomic replay behavior if this proposal is accepted. - If accepted, this proposal would require root and child manifests to use registered schema versions and canonical serializers whose bytes and digests are stable across supported readers. - If accepted, chain admission would use a serializable or explicitly equivalent atomic boundary and retain ID-free suppression evidence. @@ -95,7 +95,7 @@ Rejected because notifications can be lost or duplicated and cannot own durable ## Reversibility and Revisit Triggers -Before acceptance, human review may change the proposed scalar format, generated-child/fan-out ownership, or added serialization boundary without a migration obligation; ADR 0069's accepted command-root owner, key, and digest binding remain in force. After acceptance and persisted use, changing the scalar or canonical serialization requires a versioned migration and explicit old/new binding and replay policy; it must not reinterpret existing IDs. Revisit UUIDv7 only if a reviewed cross-service identity standard provides equal exact textual compatibility, opaque semantics, collision handling, and operational proof. +Before acceptance, human review may change the proposed command-plan ordering, `planOrdinal`, root owner/key/binding, scalar format, generated-child/fan-out ownership, or serialization boundary without a migration obligation. After acceptance and persisted use, changing the scalar or canonical serialization requires a versioned migration and explicit old/new binding and replay policy; it must not reinterpret existing IDs. Revisit UUIDv7 only if a reviewed cross-service identity standard provides equal exact textual compatibility, opaque semantics, collision handling, and operational proof. ## Security and Privacy @@ -110,8 +110,8 @@ Game Session or the owning allocation boundary exposes durable allocation, colli Implementation and focused proof must cover: - if accepted, lowercase, hyphenated, exactly 36-character UUIDv7 scalar validation and opaque treatment at every supported wire/storage boundary; -- the accepted ADR 0069 command-root allocation binding plus, if this proposal is accepted, one-time scalar claims, insert-if-absent uniqueness, collision/conflict failure, crash recovery, concurrent allocation races, and exact replay/reconciliation reuse for the additional allocation boundaries; -- zero-, one-, and multi-root plans; frozen semantic order; the accepted ADR 0069 root key, command binding, ordered manifest digest, and mismatch rejection; if this proposal is accepted, also prove the proposed root manifest schema version, serializer, canonical bytes, exact scalar claim, and their mismatch rejection; +- if accepted, command-plan ordering; zero-, one-, and multi-root plans; `planOrdinal`; command-root owner/key/binding; ordered manifest digest; mismatch rejection; one-time scalar claims; insert-if-absent uniqueness; collision/conflict failure; crash recovery; concurrent allocation races; and exact replay/reconciliation reuse; +- if accepted, the proposed root manifest schema version, serializer, canonical bytes, exact scalar claim, and their mismatch rejection; - child-candidate schema version/serializer/digest, candidate ordering, depth and budget revisions, serializable sibling admission, no double charge, and no partial commit; - ID-free suppression evidence proving no enqueue/apply and preserving committed parent/earlier-child outcomes; - fan-out frozen region/topology set, exact child ordinal and target binding, child-manifest schema/serializer/digest, request digest, pre-wake durability, duplicate wake, late result, and topology-conflict handling; diff --git a/design/architecture/system-architecture-identifier-glossary.md b/design/architecture/system-architecture-identifier-glossary.md index ec0c199166..42ea1dc8d3 100644 --- a/design/architecture/system-architecture-identifier-glossary.md +++ b/design/architecture/system-architecture-identifier-glossary.md @@ -84,9 +84,9 @@ World Management may use a numeric room row key as `roomInstanceId` only when it Tick-driven, cross-service mutations are at-least-once and must be idempotent. -- `EffectId` – the opaque stable identity for one logical effect. For command-root work, Game Session allocates the root `EffectId` under the durable command-plan binding owned by [Transaction Strategies](./system-architecture-transactions.md#command-atomicity-and-outcome-aggregation); retries, replays, and reconciliation of that admitted command-root work reuse the same root. A generated child has its own persisted deterministic child `EffectId` while retaining the enclosing root and parent lineage; it does not allocate another command-plan root. Passive, inbound/remote, timer, and retry work that is not materialized as an admitted command retains its owner/source-specific root rather than being assigned a command-plan root. Participants never derive or replace an admitted identity. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative and does not change this accepted glossary contract. -- `deterministic effect plan` – the frozen semantic order of logical command-root effects admitted for one command. Its owner-supplied order, persisted manifest, allocation binding, replay checks, Automation handoff mapping, and command-only scope are defined once by [Transaction Strategies](./system-architecture-transactions.md#command-atomicity-and-outcome-aggregation). -- `planOrdinal` – the stable zero-based position of a root in its command's deterministic effect plan, assigned in the supplied semantic order. It is command-root binding metadata, not a scheduler/source-ordering, staging, participant, trigger, or generated-child ordinal. +- `EffectId` – the persisted mutation identity for one logical effect. Retries, replay, and reconciliation preserve the same mutation identity and immutable request digest under the accepted effect contract. A generated child has its own persisted child `EffectId` while retaining enclosing-root and parent lineage where applicable. Command-root allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +- `deterministic effect plan` – a proposed ordered set of command-root effects described in pending [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); it is not an accepted canonical term or requirement. +- `planOrdinal` – a proposed command-root allocation field described in pending [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); it is not an accepted identity or ordering contract. - **Participant guard identity** – a deterministic uniqueness identity under the owning runtime-family contract. For owner-classified S1/S2 families, the durable guard partition is `(tenantId, playableStateNamespaceId)` plus the owning identity/effect (`EffectId`, typed operation, and target aggregate); `gameInstanceId` is not a uniqueness dimension and is carried and exact-validated separately as active-runtime authorization/fence evidence. Only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)` as its durable partition; an unknown or unclassified family is rejected before any participant-guard allocation or admission and is never treated as S3 by default. A root effect uses its root `EffectId`; a generated child mutation uses its persisted child `EffectId`, while the enclosing root remains lineage and reconciliation context rather than collapsing sibling guards. The child ordinal participates in deterministic child-ID derivation under the owning contract but is not a second guard-key field. For S1/S2, `playableStateNamespaceId` is the uniqueness partition; `playableStateScope` and `gameInstanceId` are separately persisted, exact-validated routing/authorization/fence evidence and are not additional uniqueness dimensions. Same family-partitioned guard identity with the same request and evidence returns the prior result; a changed tenant, namespace, owning effect, operation, target, scope, digest, or separately validated active-instance fence fails closed. Work explicitly outside playable-state scope must use an accepted owner-specific idempotency/partition contract; it cannot omit namespace/scope and proceed under this gameplay participant-guard contract. The durable outcome and other evidence/reconciliation fields are mutable guard-row state protected by CAS, not part of uniqueness identity. A conserved multi-participant operation normally shares one effect identity but still follows [ADR 0053](./decisions/adr-0053-command-atomicity-by-invariant-class.md)'s atomicity/co-location/reservation semantics. - The root effect identity, required participant set, and participant outcomes are Game Session reconciliation data. The durable plan allocation and guard/effect behavior are owned by [Transaction Strategies](./system-architecture-transactions.md) and must not be replaced with an ad-hoc service-local key. diff --git a/design/architecture/system-architecture-scripting-normative-contract-tables.md b/design/architecture/system-architecture-scripting-normative-contract-tables.md index 26770ad87a..bb2d64be0e 100644 --- a/design/architecture/system-architecture-scripting-normative-contract-tables.md +++ b/design/architecture/system-architecture-scripting-normative-contract-tables.md @@ -39,7 +39,7 @@ Trigger Identity is the composite idempotency identity for logical handler work For applicable gameplay/runtime identities, `playableStateNamespaceId` is the durable playable-state uniqueness/allocation dimension. The server-derived `playableStateScope` is immutable within one playable-state lifecycle and is policy/routing/authorization/migration-fence evidence that must be persisted and exact-validated; a missing, stale, or mismatched scope fails closed. `playableStateScope` is not a Trigger Identity, event-scope, handoff, schedule, resume-window, or other uniqueness/deduplication dimension. A presented scope mismatch therefore requires authoritative reconciliation before admission: only stale or incorrect evidence with unchanged authoritative scope may reuse the namespace-keyed identity; an authoritative scope-policy transition starts a new playable-state lifecycle and selects or allocates a new `playableStateNamespaceId` before fresh durable identity is admitted. -Downstream gameplay effects emitted by a handler use Game Session's deterministic command-plan root contract, not Trigger Identity. Full Trigger Identity governs handler and handoff identity only. The frozen typed command or `ResolvedEffectPlan`-owned command/action contract supplies semantic root order; built-in commands declare an equivalent stable order, and ambiguous or duplicate order fails before admission. After the complete applicable Command-Handoff Identity is admitted/deduplicated and exact-maps to one durable target `commandId`, the durable command row freezes/binds its request fingerprint and resolved runtime scope, and Game Session persists the ordered plan manifest/digest plus an opaque root allocation row unique on `(tenantId, gameInstanceId, commandId, planOrdinal)`; the row binds the manifest digest and validates that frozen binding, with mismatches failing closed. Downstream authoritative mutation then uses the Game Session root `EffectId`, typed operation, exact target aggregate, and immutable request digest. For Automation, the complete applicable Command-Handoff Identity is the admission/deduplication identity that maps to the durable target command, not the root allocation key; ordinary player/built-in plans use their complete canonical admitted command/runtime identity. `scriptEventId`, the rest of Trigger Identity, and handler lineage remain separate correlation identities. A zero-command evaluation allocates no gameplay root. +Downstream gameplay effects emitted by a handler use the ordinary Game Session effect-admission boundary, not Trigger Identity. Full Trigger Identity governs handler and handoff identity only. The complete applicable Command-Handoff Identity governs Automation handoff admission and deduplication; `scriptEventId`, the rest of Trigger Identity, and handler lineage remain separate correlation identities. The accepted effect contract requires downstream mutations to preserve the persisted mutation `EffectId`, typed operation, exact target aggregate, and immutable request digest through retries and participant guards. Deterministic command-plan ordering, `planOrdinal`, and root-allocation behavior remain proposal-only in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Ordinary producer event-ingress RPCs into Automation & Scripting (for example `TriggerScriptEvent`) use two-stage deduplication: @@ -233,12 +233,12 @@ The source runtime identity fields are required for gameplay/runtime commands; t A command-handoff reference exists only for an emitted evaluated descriptor. Pre-DSL trigger records have no child Command-Handoff Identity or `commandOrdinal` and must not be represented by an `automationDispatchId`, parent `outboxWorkItemId`, parent Trigger Identity, or `scriptEventId` as a synthetic child/handoff reference. Read-only inspection may expose an emitted descriptor reference with the complete identity above, including `commandOrdinal`; mutation APIs currently accept bounded explicit `workItemIds[]` only. Descriptor references and filter selectors are listing/preview inputs, and descriptor-level replay or purge remains deferred until preview plus stable per-row proof. -The downstream plan root remains a separate Game Session identity: after the complete applicable Command-Handoff Identity is admitted/deduplicated and exact-maps to one durable target `commandId`, Game Session consumes the frozen command/action semantic order, persists the ordered plan manifest/digest, and assigns `planOrdinal` plus an opaque root `EffectId` allocation row unique on `(tenantId, gameInstanceId, commandId, planOrdinal)` in its local durable plan/staging transaction. The durable command row's frozen request fingerprint and resolved runtime scope are validated, and the allocation row binds the manifest digest; reuse requires the same command row identity, frozen binding, ordinal, and manifest digest, otherwise failing closed. For Automation, the complete applicable Command-Handoff Identity, including optional distinct target runtime fields, is the admission/deduplication identity that maps to the target command, not the root allocation key; it is not reduced to `(automationDispatchId, commandOrdinal)`. Full Trigger Identity governs handler/handoff identity only, while `scriptEventId` and handler lineage remain correlation identities. Automation does not allocate a competing root. A zero-command evaluation has no downstream plan root. +The downstream command-plan root design, including semantic order, `planOrdinal`, and allocation binding, remains pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Automation handoff identity and Trigger Identity retain their separate admission and handler/correlation roles under this document's existing contracts; those roles do not establish the pending root-allocation design. Supplementary post-handoff correlation rule: - **Target-state command-ordinal contract:** execution-time version/plugin fence drops that happen after tick handoff must not be left as metrics-only signals. They must be exposed on the affected per-command handoff disposition keyed by the complete Command-Handoff Identity, including `targetPlayableStateNamespaceId` when a distinct target playable-state namespace applies; retain source and target `playableStateScope`/`targetPlayableStateScope` as separately persisted exact-validated policy/routing/authorization/fence evidence, excluded from uniqueness, with the parent Trigger Identity and its exact `scriptPatchVersion`/`scriptPinEpoch` pair retained for correlation. Missing or mismatched scope evidence fails closed. Use `plugin_binding_mismatch` only for a proven plugin/lifecycle binding mismatch; use `plugin_activation_epoch_mismatch` for a captured activation-epoch mismatch, `plugin_disabled` for a lifecycle disablement or revocation that invalidates admitted work, `plugin_version_not_published` for publication failure, `plugin_component_policy_blocked` for a proven component-policy block, `signer_revoked` for signer revocation, and `authority_unavailable`, `component_policy_unavailable`, or `signer_policy_unavailable` when the applicable evidence is unavailable or unverifiable. `script_patch_mismatch` remains the script-version reason. -- **Current live fallback:** the Game Session handoff currently carries `automationDispatchId`, command id/text, selected provenance fields, and parent work-item correlation, but not `commandOrdinal`, the complete Trigger Identity, or the deterministic plan-root `planOrdinal`/root binding. Current diagnostics use those fields and must be labeled as the narrower fallback rather than as proof of the target-state contract. +- **Current live fallback:** the Game Session handoff currently carries `automationDispatchId`, command id/text, selected provenance fields, and parent work-item correlation, but not `commandOrdinal` or the complete Trigger Identity. Current diagnostics use those fields and must be labeled as the narrower fallback rather than as proof of the handoff target-state contract. The proposed plan-root allocation is not a live or accepted requirement. Per-command handoff correlation rule: diff --git a/design/architecture/system-architecture-tick-execution-flows.md b/design/architecture/system-architecture-tick-execution-flows.md index 9e7ba81305..5b35199a09 100644 --- a/design/architecture/system-architecture-tick-execution-flows.md +++ b/design/architecture/system-architecture-tick-execution-flows.md @@ -44,7 +44,7 @@ Within a region’s tick, root actor commands and their effects proceed through 1. **Enqueue** - Game Session accepts commands from Telnet and WebSocket clients, AI, or automation. - Work-bearing commands are enqueued into per-entity (or occasionally per-region) queues such as `tick:{tenantRegionTag}:queue:`. - - If admission resolves a zero-effect plan, the same durable command-status transaction records the canonical terminal outcome (`ingressStatus=TERMINAL`, `executionOutcome=APPLIED`, and `gameplayResult=SUCCESS` under [ADR 0053](./decisions/adr-0053-command-atomicity-by-invariant-class.md) and [ADR 0016](./decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md)). This status-only write allocates or persists no `planOrdinal` or root `EffectId`, creates no effect ledger row or `tick_batch`, advances no tick-domain state, and does not enqueue the command; an accepted zero-effect command therefore cannot remain `ENQUEUED`, and retries return its stored terminal outcome. + - If admission resolves to no gameplay effects, the same durable command-status transaction records the canonical terminal outcome (`ingressStatus=TERMINAL`, `executionOutcome=APPLIED`, and `gameplayResult=SUCCESS` under [ADR 0053](./decisions/adr-0053-command-atomicity-by-invariant-class.md) and [ADR 0016](./decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md)). This status-only write creates no effect ledger row or `tick_batch`, advances no tick-domain state, and does not enqueue the command; an accepted no-effect command therefore cannot remain `ENQUEUED`, and retries return its stored terminal outcome. Command-plan ordinal and root-allocation treatment is pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). 2. **Target Resolution (read-only)** - During the tick, the executor resolves targets from the pinned snapshot for that ``: - Single-target actions select a specific entity or room. @@ -74,7 +74,7 @@ Within a region’s tick, root actor commands and their effects proceed through - Many commands do not need global awareness of “all regions finished”; origin and target regions can operate independently with eventual consistency. - For flows that truly require end-to-end completion (for example, complex cross-region trades), the origin region tracks participating-region outcomes in that separate coordinator record and later applies a final status in a subsequent origin-region tick only under the command family’s ADR 0053 declaration. `PARTIAL` is a permitted terminal subset only when declared before execution; unresolved required work, inconclusive evidence, or a timeout that does not prove a permitted terminal combination remains `PENDING`/reconciliation-required. -Every phase must use its phase-specific durable identity so replays after failure do not double-apply logical work. Command ingress uses `(tenantId, gameInstanceId, commandId)`; source claims use their durable owner identity and bound target/timeline; command-root effects use the persisted plan/root binding and participant guards owned by Transaction Strategies; inbound/remote, timer, retry, and generated work retain their owner/source roots unless materialized as admitted commands; and cross-region completion uses the coordinator plus target ledger/result identity. Ordinary retry/replay preserves those identities. Retry metadata never rewrites the original timeline or root/operation/target projection. A post-abandon command re-drive uses a new linked `commandId`; reusing the old id returns its terminal result. A command or source item may cross tick boundaries without changing its ingress or source identity. +Every phase must use its phase-specific durable identity so replays after failure do not double-apply logical work. Command ingress uses `(tenantId, gameInstanceId, commandId)`; source claims use their durable owner identity and bound target/timeline; staged effects use their persisted mutation identity and participant guards; inbound/remote, timer, retry, and generated work retain their owner/source identities; and cross-region completion uses the coordinator plus target ledger/result identity. Command-root allocation detail remains pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Ordinary retry/replay preserves persisted effect identity. Retry metadata never rewrites the original timeline or root/operation/target projection. A post-abandon re-drive follows its source owner's admission and identity contract while retaining lineage. A command or source item may cross tick boundaries without changing its ingress or source identity. ### Command Ingress Acknowledgement Contract (Required) @@ -299,7 +299,7 @@ Conceptually, tick commit proceeds through these phases: - If the current owner encounters prior-fence work, it must not continue that batch on the hot path or transfer it based on inferred fence recency. It pauses the affected region and uses the fence-guarded recovery path while preserving the unique tick coordinate, manifest, effect identities, and command bindings where proof permits; inconclusive old-epoch work remains non-terminal reconciliation work under its original persisted mutation `EffectId`, with any enclosing `rootEffectId` retained separately as lineage and reconciliation context. - If recovery or transfer preconditions fail or any effect might have started, reconciliation must not bulk-abandon the batch. It determines each effect from durable domain state and authoritative effect guards: an effect becomes `APPLIED` only when that evidence proves it is reflected, becomes `ABANDONED` only when that evidence proves it was not applied, and otherwise remains `SCHEDULED`. `reconciliation_required`, its reason, the observed epochs/fences, and the last proof attempt are recovery metadata outside the closed effect status enum; they are not another effect state. - After obtaining the domain evidence, one fence-guarded Game Session PostgreSQL transaction must atomically persist all conclusive effect outcomes together with the corresponding command statuses and source-claim disposition. If any effect is inconclusive, the transaction records reconciliation-required metadata, leaves its effect and dependent command/source claim non-terminal, and keeps the region paused. Unresolved work is ineligible for ordinary effect retry, Redis retry insertion, source requeue, source-claim release, batch transfer, or commit-watermark advancement. - - Independently retryable work becomes eligible for a **post-abandon re-drive** only after the original effect is conclusively `ABANDONED` and its command/source claim is terminalized in that same transaction. The recovery controller must then eventually assign that work a later `(regionEpoch, tickId)` coordinate and new `tick_batch_id`, a fresh root identity under the applicable owner contract with its ledger/participant-guard projections, and a new retry/source-claim identity before the region resumes; if it is re-admitted as a command, Game Session allocates a fresh command plan/root binding under the same contract. It records lineage to the original identities and never reuses or requeues into the old coordinate. Ordinary retry/replay keeps the original root `EffectId`. Until that fresh-root allocation succeeds, the work remains durable recovery work and cannot return to an ordinary queue. + - Independently retryable work becomes eligible for a **post-abandon re-drive** only after the original effect is conclusively `ABANDONED` and its command/source claim is terminalized in that same transaction. The recovery controller must then eventually assign that work a later `(regionEpoch, tickId)` coordinate and new `tick_batch_id`, a fresh identity under the applicable owner contract with its ledger/participant-guard projections, and a new retry/source-claim identity before the region resumes. If it is re-admitted as a command, its root allocation follows the design in pending [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). It records lineage to the original identities and never reuses or requeues into the old coordinate. Ordinary retry/replay keeps the original mutation `EffectId`. Until fresh identity admission succeeds, the work remains durable recovery work and cannot return to an ordinary queue. - If the caller's expected epoch or fence is not current in authoritative status, the caller is stale. It must stop without modifying the batch, replaying effects, or requeueing source work. It must never infer recency from `executorFence`, create a second batch for the same unique coordinate, or requeue work into that same coordinate. - The target-state tick-batch record stores at minimum: - `tick_batch_id` diff --git a/design/architecture/system-architecture-tick-failures-and-operations.md b/design/architecture/system-architecture-tick-failures-and-operations.md index b208fd0ec7..45b3490aa1 100644 --- a/design/architecture/system-architecture-tick-failures-and-operations.md +++ b/design/architecture/system-architecture-tick-failures-and-operations.md @@ -16,7 +16,7 @@ This document describes the full target-state recovery and operator model. Curre - the live `tick_batch` / `tick_effect` ledger is real and now carries the current gameplay-command selected-work manifest on `tick_batch`, including current-boundary `enqueueSeq`, source metadata, and digest-checked replay reuse for surviving staged batches; live selected-work manifests do not yet preserve the required declared `phase`, `lane`, and `cost_class` metadata. The live `enqueueSeq` is allocated by one database-wide sequence; the region-scoped, cross-source allocator defined below is target-state. Timer/retry/remote-follow-up source-claim manifests, region-scoped replay controller breadth, and cross-region result-return semantics also remain target-state follow-through. - the live gameplay-command staging path does not yet provide the complete target automation handoff identity: it derives `effectKey` from `commandId` and uses a deterministic text/slot fallback when no command ID is available. The target fail-closed contract below assigns the stable root `EffectId` before acknowledgement when possible and rejects before acknowledgement when assignment fails. If an already acknowledged `ACCEPTED_VOLATILE` command cannot receive that identity, `LOST_BEFORE_STAGING` remains limited to eligible `RECEIVED`/`ENQUEUED` work with no surviving batch; batch-bound or inconclusive work remains non-terminal/reconciliation-required and is never evidence-free `ABANDONED`. This document does not claim that target behavior is already live. - The live rollback purge path is weaker than that target boundary: `TickQueueControlService.purgeCandidate` checks only `GameplayCommandRepository.hasDurableTickEffect(commandId)` before selecting `ABANDONED` versus `LOST_BEFORE_STAGING`. That non-atomic existence check does not prove the absence of a surviving batch, effect, or source claim, and it can race concurrent staging, drain, or effect ownership. The target atomic owner-defined CAS/no-batch proof remains unimplemented and unproved; this is a current implementation/proof gap, not a relaxation of the target `ACCEPTED_VOLATILE`/`RECEIVED`/`ENQUEUED` eligibility contract. -- The target deterministic command-plan root contract is also not live: the owning command/action contract for the frozen typed command or `ResolvedEffectPlan` must supply semantic root order, with built-ins declaring equivalent stable order and ambiguous or duplicate order rejected before admission. Before allocation, the durable gameplay command row must freeze/bind its request fingerprint and resolved runtime scope. Game Session must persist the ordered plan manifest/digest and allocate an opaque root `EffectId` row unique on `(tenantId, gameInstanceId, commandId, planOrdinal)`; the row binds the manifest digest and validates the frozen command/runtime binding, and reuse requires all of those values to match or fails closed. For Automation, the complete applicable Command-Handoff Identity is the admission/deduplication identity and must exact-map to one durable target `commandId`; allocation then uses the target command row's canonical key. The current `tickBatchId`/`effectKey` fallback does not prove that contract, and no global allocator is implied. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not current target state. +- Deterministic command-plan ordering, `planOrdinal`, and command-root allocation are proposal-only in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md), not current tick target state or proof obligations. The current `tickBatchId`/`effectKey` path does not prove any proposal-specific allocation behavior. - The accepted lane and fencing consequences are target-state requirements in this recovery model: selected-work manifests and replay records must preserve each item's declared `phase`, `lane`, and `cost_class`, while takeover reconciliation remains subject to the Redis lease plus durable executor-fence handshake owned by [Tick System and Runtime Design](./system-architecture-ticks.md). This document does not duplicate that owner protocol. Naming convention: API, workflow, and EffectId prose uses `regionEpoch`. Snake-case forms such as `region_epoch`, `last_region_epoch`, and `target_region_epoch` are reserved for explicitly identified SQL/storage fields, Redis payloads/keys, or schema examples. @@ -79,7 +79,6 @@ To make replays observable and bounded, Game Session maintains a **tick effect l - `tick_batch_id` - `effect_id` (persisted mutation identity used by the participant guard: the root `EffectId` for a root mutation or the deterministic child `EffectId` for a generated child) - `root_effect_id` (enclosing stable logical root identity retained on every ledger projection for lineage and reconciliation; equal to `effect_id` for a root mutation) - - `plan_ordinal` (stable zero-based root position in the command's deterministic plan; absent for a zero-effect command because no effect row exists) - `typed_operation` (canonical operation identity retained alongside the mutation `effect_id` and enclosing root on every participant projection) - `effect_key` (stable, human-readable descriptor passed through from staging) - declared `phase`, `lane` ∈ {`actor_action`, `passive_effect`}, and bounded `cost_class`; recovery and replay preserve all three values @@ -91,7 +90,7 @@ To make replays observable and bounded, Game Session maintains a **tick effect l - `reason` / `outcome` - replay-verification audit metadata when a replay proves that the effect was already applied (for example verifier, timestamp, and evidence digest/reference) - `created_at`, `updated_at` -- The ledger retains the enclosing root's `plan_ordinal`/`root_effect_id` binding as command-plan identity and reconciliation metadata. A root mutation uses that root as its participant-guard `effect_id`; a generated child uses its persisted deterministic child `EffectId` as `effect_id` while retaining the enclosing root for lineage and reconciliation. A shared root for a conserved multi-participant operation does not replace ADR 0053 atomicity, co-location, or reservation semantics. For command-root work, the root is allocated by Game Session's local durable plan/staging transaction from the opaque binding unique on `(tenantId, gameInstanceId, commandId, planOrdinal)`; the durable command row's frozen request/runtime binding, applicable `playableStateNamespaceId`, and ordered plan manifest digest are validated on reuse, and a mismatch fails closed. Passive, inbound/remote, timer, retry, and already-generated effects retain their owner/source-specific root identities unless they materialize as an admitted command. Random batch, mutable command, effect-key, source-ordering, participant, trigger, and generated-child identities cannot substitute for that durable command row identity or allocation binding; child-ID persistence uses its owning deterministic child contract and does not create another command-root allocator. +- The ledger retains the persisted mutation `EffectId` and, where applicable, enclosing root lineage for participant guards and reconciliation. A generated child uses its persisted child `EffectId` as the mutation identity and retains the enclosing root for lineage and reconciliation. A shared effect identity for a conserved multi-participant operation does not replace ADR 0053 atomicity, co-location, or reservation semantics. Command-root ordering and allocation details are pending proposal-only work in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); this ledger contract does not define `planOrdinal`, a command-root key, or an allocation owner. - Target-state requires one durable tick-batch record per `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)`, owned by Game Session, and stores at minimum: - `tick_batch_id` - `executor_fence` (or equivalent opaque durable fence captured at batch allocation time); this is the canonical durable fence used for compare-and-match protection. @@ -298,7 +297,7 @@ Recovery-specific behavior is: ### EffectId, Ledger Rows, and Guard Keys -The canonical root and plan allocation are owned by [Transaction Strategies](./system-architecture-transactions.md#command-atomicity-and-outcome-aggregation). This operations document owns their failure consequences: the ledger retains the persisted mutation `EffectId`, enclosing root lineage, `plan_ordinal`, timeline, typed operation, exact target, digest, participant projection, and replay lineage; ordinary retry and uncertain replay preserve them. A root mutation uses its root `EffectId`; a generated child uses its persisted deterministic child `EffectId` while retaining the enclosing root as lineage and reconciliation context. Retry eligibility is mutable operational metadata and never rewrites that binding. A post-abandon command re-drive requires conclusive terminal evidence, a new durable `commandId`, and explicit lineage to the abandoned command/effect; reusing the old command id returns its terminal result. Non-command sources follow their owner-specific linked re-drive identity. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not current target state. +The ledger retains the persisted mutation `EffectId`, enclosing root lineage where applicable, timeline, typed operation, exact target, digest, participant projection, and replay lineage; ordinary retry and uncertain replay preserve them. A generated child uses its persisted child `EffectId` while retaining the enclosing root as lineage and reconciliation context. Retry eligibility is mutable operational metadata and never rewrites that binding. A post-abandon re-drive requires conclusive terminal evidence and follows its source owner's admission and identity contract, retaining explicit lineage to the abandoned command/effect. Command-plan and root-allocation details remain pending proposal-only work in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). - Tick coordination in Redis. - Tick effect ledger rows in PostgreSQL. @@ -310,7 +309,7 @@ In schema terms: - The storage projection includes at minimum `(effect_id, root_effect_id, typed_operation, tenant_id, game_instance_id, playable_state_namespace_id, playable_state_scope, region_id, region_epoch, tick_id, target_aggregate_type, target_aggregate_id)`. `playable_state_scope` and the tick/region coordinates are persisted and exact-validated evidence or ordering metadata, not uniqueness dimensions. The ledger's logical uniqueness key is exactly `(effect_id, typed_operation, target_aggregate_type, target_aggregate_id)`, where `effect_id` is the root `EffectId` for a root mutation and the persisted child `EffectId` for a generated child; `root_effect_id` is retained as enclosing-root lineage and reconciliation context, not as a substitute for `effect_id`. An owner-local physical partition, if used, is storage placement only and cannot alter logical uniqueness or deduplication. The physical schema must enforce or project that exact logical identity without promoting `playable_state_scope` or tick coordinates into guard uniqueness. `effect_key` may be stored in the projection for stable descriptor/correlation metadata, but it is not the mutation identity or sole collision protection. Mutable `status`, `reason`, `outcome`, evidence/reconciliation fields, and timestamps remain outside the uniqueness key. The physical schema may encode target identity separately, but it must retain an explicit collision-safe projection containing `effect_id`, `root_effect_id`, `typed_operation`, and the exact target aggregate. - Additional columns such as `command_id`, `automation_dispatch_id`, or `command_ordinal` may exist for queryability and scripting correlation, but they do not replace the persisted mutation `EffectId` or participant guard identity. - On reuse of the persisted mutation identity, the writer exact-compares all immutable scope, lineage, timeline, descriptor, namespace, and request-digest bindings, including the stored projection fields, and fails closed on any conflict; it must not insert another row for a conflicting reuse. For a root mutation, `effect_id` is the root `EffectId`; for a generated child, the persisted child `EffectId` remains the distinct mutation identity while `root_effect_id` retains the enclosing-root lineage used for reconciliation. -- For the Game Session command-root and tick-ledger contract in this document, the command-root allocation identity remains the opaque `(tenantId, gameInstanceId, commandId, planOrdinal)` binding and its collision-safe runtime allocation partition remains `(tenantId, gameInstanceId)`; that command allocation scope is distinct from owner-local participant-guard uniqueness. Every ledger row retains the namespace-complete tick/recovery projection above even when the owner-declared mutation identity or allocation partition uses a narrower uniqueness key. `effect_key` remains descriptor metadata, and mutable status, reason, outcome, evidence, and timestamps remain outside identity protection. +- The command-root allocation identity and any collision-safe allocation partition remain pending in ADR 0183. Every ledger row retains the namespace-complete tick/recovery projection above, while `effect_key` remains descriptor metadata and mutable status, reason, outcome, evidence, and timestamps remain outside identity protection. - Guard tables such as `tick_effect_guard` implement the deterministic participant projection for multi-effect operations: - Their uniqueness identity follows the owner-declared runtime family: S1/S2 uses the `(tenantId, playableStateNamespaceId)` partition plus the mutation's persisted root-or-child `EffectId`, typed operation, and exact target aggregate; only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)` plus those identity fields. For S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence. The immutable request digest and applicable namespace binding are exact-compared on every replay; `playableStateScope`, active-instance evidence, timeline, and lineage remain immutable evidence, while durable outcome/reconciliation fields are mutable row state protected by CAS and are not uniqueness inputs. Unknown or unclassified families fail closed before guard admission and are never inferred to be S3. - The concrete tick/ledger projection columns remain storage scope/order/lookup metadata, not an alternative guard identity. Handlers must not invent alternative idempotency keys for tick-driven effects or use enclosing-root lineage, child ordinal, `effect_key`, outcome, or evidence state as guard identity. Work explicitly outside playable-state scope must use an accepted owner-specific idempotency/partition contract; it cannot omit namespace/scope and proceed under this gameplay participant-guard contract. @@ -526,7 +525,7 @@ Operationally: Tick-driven domain calls use the mutation's persisted root-or-child `EffectId` plus a shared participant guard contract for retries: -- For command-root work, Game Session assigns the opaque root `EffectId` from the durable command row's `(tenantId, gameInstanceId, commandId, planOrdinal)` allocation binding, which also validates the frozen request fingerprint/runtime scope, applicable `playableStateNamespaceId`, and ordered plan manifest digest. Passive, inbound/remote, timer, retry, and already-generated work retain their owner/source-specific root identity unless they materialize as an admitted command. A generated child uses its persisted deterministic child `EffectId` under the owning child contract and does not create another command-plan root or allocator. A concrete ledger/guard/storage projection must carry the namespace-complete applicable mutation identity and tick context `(effectId, rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` for scope, ordering, and exact target lookup; generated children retain `rootEffectId` as lineage and reconciliation context. The command-root/tick-ledger allocation binding remains distinct from participant-guard uniqueness: each participant derives its guard identity from the owner-declared runtime-family partition—`(tenantId, playableStateNamespaceId)` for S1/S2 or `(tenantId, gameInstanceId)` only for explicit S3—plus the mutation's persisted root-or-child `EffectId`, typed operation, and exact target aggregate, binding the immutable request digest and applicable namespace evidence. For S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence; durable outcome/evidence state is mutable guard-row state protected by CAS. Unknown or unclassified families, and work explicitly outside playable-state scope without an accepted owner-specific partition, fail closed before guard admission. Additional operation-specific distinctions belong in that typed operation/target/request-digest contract; they must not create a competing root identity. The exact allocator and versioned fan-out binding remain conditional on the non-authoritative [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +- A concrete ledger/guard/storage projection must carry the namespace-complete applicable mutation identity and tick context `(effectId, rootEffectId, typedOperation, tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` for scope, ordering, and exact target lookup; generated children retain `rootEffectId` as lineage and reconciliation context. Participant-guard uniqueness remains distinct from any effect-allocation binding: each participant derives its guard identity from the owner-declared runtime-family partition—`(tenantId, playableStateNamespaceId)` for S1/S2 or `(tenantId, gameInstanceId)` only for explicit S3—plus the mutation's persisted `EffectId`, typed operation, and exact target aggregate, binding the immutable request digest and applicable namespace evidence. For S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence; durable outcome/evidence state is mutable guard-row state protected by CAS. Unknown or unclassified families, and work explicitly outside playable-state scope without an accepted owner-specific partition, fail closed before guard admission. Additional operation-specific distinctions belong in that typed operation/target/request-digest contract; they must not create a competing mutation identity. Command-root allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). - Game Session passes the mutation's persisted root-or-child `EffectId` plus the structured operation, target, immutable request digest, and any concrete ledger projection fields to each tick-invoked handler. Generated children also carry their enclosing root/parent lineage binding. Handlers validate and project that contract into their own guards; they must not generate fresh random IDs, re-derive from mutable payload, or silently drop required scope or target fields. Every gRPC endpoint that can be invoked from tick execution must document and implement: @@ -710,7 +709,7 @@ Select validation commands and assign evidence ownership according to [Validatio - The first call mutates state as expected. - Subsequent calls are treated as replays and do not apply additional logical effects (HP changes, inventory moves, etc.). - Repeat the same `effectKey` against a different `targetAggregateType` or `targetAggregateId` and assert that the distinct target is not incorrectly deduplicated. For script-generated fan-out effects, vary `commandOrdinal` under one `automationDispatchId` and assert distinct logical identities, then replay the same dispatch/ordinal pair and assert stable deduplication; also vary, as applicable, the persisted root-or-child `EffectId`, enclosing root lineage, typed operation, and target aggregate. `effectKey` is projection/storage metadata, never guard uniqueness, and a request-digest mismatch for the same guard or dispatch/ordinal identity must fail closed. -- Exercise deterministic command-plan admission with zero, one, and multiple roots: assert that semantic order comes from the frozen typed command/action contract or `ResolvedEffectPlan`, built-ins declare equivalent stable order, ambiguous/duplicate order fails before admission, and the ordered plan manifest/digest plus opaque `(tenantId, gameInstanceId, commandId, planOrdinal)` allocation binding persist in the local plan/staging transaction and reuse only when the command row identity, frozen request/runtime/namespace binding, ordinal, and manifest digest match. Assert no root allocation for zero effects, and that random batch IDs, mutable text, effect keys, source ordering, participant tuples, Trigger Identity/`scriptEventId`, and generated child ordinals cannot substitute for the durable command row identity. Exercise Automation handoff admission exact-mapping to one durable target `commandId`, and exercise passive, inbound/remote, timer, retry, and already-generated work through their existing owner/source-specific root identities rather than synthesizing a command plan unless materialized as an admitted command. +- If ADR 0183 is accepted, add focused proof for its command-plan ordering, `planOrdinal`, and root-allocation requirements in that ADR's proof checklist. Those proposed requirements are not accepted proof obligations here. - Exercise both idempotency strategies: - Per-aggregate `last_tick_id` tables (for single-entity updates). - Operation-level `tick_effect_guard` tables (for multi-entity effects). @@ -732,7 +731,7 @@ When introducing a new command type that will run under tick control, design doc - Does it run because an entry is dequeued from `tick:{tenantRegionTag}:queue:` or because a tick timer/retry fired? - If not, it may follow different idempotency rules and does not belong in this section. - **What is the idempotency key?** - - Which frozen typed command/action contract or `ResolvedEffectPlan` supplies semantic order for the command's logical root effects, and how does it reject ambiguous/duplicate order before admission, persist the ordered manifest/digest, and allocate an opaque binding unique on `(tenantId, gameInstanceId, commandId, planOrdinal)` only after the durable command row freezes/binds its request fingerprint, resolved runtime scope, and applicable `playableStateNamespaceId`? Reuse must validate the same command row identity, frozen binding, ordinal, and manifest digest; any mismatch fails closed. A zero-effect command must allocate neither. Source ordering remains separate, and non-command-root work retains its owner/source-specific identity. + - Command-plan ordering, ordinal assignment, and root-allocation behavior are pending in ADR 0183. Do not treat those proposal details as accepted invariants or proof obligations unless that ADR is accepted. - For single-aggregate updates: has the owner proved that the aggregate receives at most one logical mutation per tick and declared its runtime family? An explicit S3 watermark uses the complete `(tenant_id, game_instance_id, playable_state_namespace_id, region_id, target_aggregate_type, aggregate_id)` key plus separately exact-validated `playable_state_scope` evidence and `(last_region_epoch, last_tick_id)` (or equivalent) fields. An S1/S2 watermark instead uses its owner-defined namespace partition and exact-validates the active `game_instance_id` only as separate authorization/fence evidence; it must not copy the S3 instance-keyed identity. Any aggregate capable of multiple effects in one tick uses the participant/effect guard contract below instead. - For multi-aggregate or multi-effect operations: what participant guard identity combines the mutation's persisted root-or-child `EffectId`, typed operation, and exact target aggregate, and how is the immutable request digest bound and checked? A generated child retains its enclosing root as lineage and reconciliation context; `effect_key` is a concrete storage projection/descriptor, not a replacement for that guard identity. - **Where is the guard persisted?** diff --git a/design/architecture/system-architecture-ticks.md b/design/architecture/system-architecture-ticks.md index d855a59394..7736de2334 100644 --- a/design/architecture/system-architecture-ticks.md +++ b/design/architecture/system-architecture-ticks.md @@ -36,7 +36,7 @@ Current live substrate to keep in mind while reading: - the live `executorFence` is an opaque generation token used for compare-and-match stale-fence protection, not yet the richer numeric ordering model used in some target-state examples; - the live `tick_batch` / `tick_effect` substrate is real, and the current gameplay-command manifest now carries current-boundary `enqueueSeq`, `sourceType`, `dueTickId`, and explicit claimed-source state plus digest-checked replay reuse. The live `enqueueSeq` comes from one database-wide sequence; target `entity_enqueue_seq` is monotonic within the entity's current region epoch under accepted [ADR 0065](./decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md). Timer/retry/remote-follow-up source-claim breadth and the cross-region result-return contract described below are also target-state follow-through rather than fully shipped behavior. - the live Game Session automation handoff carries `scriptPatchVersion`, positive `scriptPinEpoch`, and `scriptPinControlPlaneRequestId` on `EnqueueAutomationCommandIfAbsentRequest`; Game Session compares the tuple with authoritative owner state and rejects incomplete or stale evidence before staging or duplicate replay. Exact tuple checks also remain at the live instance-bound Automation ingress, timer, and work-item admission boundaries. The handoff still lacks `commandOrdinal` and the full Trigger Identity required for target-state per-command diagnostics. Live gameplay staging requires a present, nonblank durable `commandId` before Redis enqueue or durable batch staging, and `TickStagingService` derives `effectKey` as `command:`; complete source/target binding and remote final-effect fence proof remain implementation gaps. -- the target deterministic command-plan root contract is not fully live: the owning command/action contract for the frozen typed command or `ResolvedEffectPlan` must supply semantic root order, with built-ins declaring equivalent stable order; ambiguous or duplicate order fails before admission. Before allocation, the durable gameplay command row must freeze/bind its request fingerprint, resolved runtime scope, and applicable `playableStateNamespaceId`. Game Session must persist the ordered plan manifest/digest and an opaque root allocation row unique on `(tenantId, gameInstanceId, commandId, planOrdinal)`; the row binds the manifest digest and validates the frozen command/runtime/namespace binding, and retries reuse it only when all of those values match, otherwise failing closed. For Automation, the complete applicable Command-Handoff Identity must exact-map at admission to one durable target `commandId`; allocation then uses that target command row's canonical key. The current `tickBatchId`/`effectKey` derivation is not evidence of that contract. +- Deterministic command-plan ordering, `planOrdinal`, and command-root allocation are proposed in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) and are not accepted tick requirements. The current `tickBatchId`/`effectKey` derivation does not establish any proposal-specific allocation behavior. --- @@ -53,7 +53,7 @@ Conceptually, FireMUD treats time as **localized pulses** rather than a single g - Per-service database transactions guarded by effect identity and idempotency, and - Replayable coordination via Redis and the tick effect ledger rather than a single cross-service ACID boundary. -Before staging, each admitted command is materialized as a deterministic plan: the ordered set of logical root effects for that command in the frozen typed command or `ResolvedEffectPlan` semantic order supplied by its owning command/action contract. Built-in commands declare an equivalent stable order; ambiguous or duplicate order fails before admission. The durable gameplay command row freezes/binds its request fingerprint and resolved runtime scope before Game Session persists the ordered plan manifest/digest and owns an opaque local durable allocation row unique on `(tenantId, gameInstanceId, commandId, planOrdinal)`. The row binds the manifest digest and validates that frozen command/runtime binding; retries reuse it only when the command row identity, frozen binding, ordinal, and digest match, otherwise failing closed. One logical operation has one root `EffectId` with participant guards beneath it. A single-root plan uses `planOrdinal=0`, a multi-root plan uses stable zero-based ordinals, and a zero-effect plan allocates no ordinal or root. For Automation, the complete applicable Command-Handoff Identity exact-maps at admission to one durable target `commandId`, after which allocation uses that target command row's canonical key. This command-root contract does not synthesize plans for passive, inbound/remote, timer, retry, or already-generated effects that retain owner/source-specific identities unless they materialize as an admitted command. A shared root for a conserved multi-participant operation does not replace ADR 0053 atomicity, co-location, or reservation semantics. +The command-plan order, `planOrdinal`, and command-root allocation design remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Tick selection, staging, and replay do not define those proposal details. The accepted effect contract continues to require one persisted mutation identity and immutable request digest across retries and participant guards; any conserved multi-participant operation still follows ADR 0053 atomicity, co-location, or reservation semantics. For the precise cross-service transaction model and when sagas are required, see `system-architecture-transactions.md`. @@ -425,7 +425,7 @@ Isolation and replay guarantees rely on: - A shared coordination timeline `(regionEpoch, tickId)` per `` as described in the Redis architecture docs. - Domain-level idempotency rules use root/participant guards and namespace-complete effect projections for logical identity; `(regionEpoch, tickId)` remains ordering and fencing context rather than a universal mutation token. -Crash recovery re-invokes a domain handler for a staged effect only when durable evidence proves that the `SCHEDULED` effect was unapplied and replay is safe under its owner contract; a missing response or ambiguous guard leaves the effect `SCHEDULED` and reconciliation-required. Replays must not double-apply logical effects. Redis loss is evaluated against the measured `redis_unreplicated_write_window_slo_ms`; `ticks_exposed` is diagnostic only. The namespace-complete storage projection tuple `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` identifies the ledger/storage view; durable projections also retain the persisted root-or-child `EffectId`, enclosing `rootEffectId` lineage, typed operation, immutable request digest, and required command/source bindings where allocated. `playableStateScope` is separately persisted and exact-validated evidence, while `regionEpoch` and `tickId` provide ordering/timeline context rather than guard uniqueness. Participant-guard logical uniqueness is the owner-declared runtime-family partition plus the persisted root-or-child `EffectId`, typed operation, and exact target aggregate: root operations use the root `EffectId`, while generated children use their persisted child `EffectId` and retain `rootEffectId` only as enclosing lineage and reconciliation context. S1/S2 uses `(tenantId, playableStateNamespaceId)` and only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)`; the partition must be sealed and exact-validated and cannot create a second guard or fork the same logical mutation. For S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence; for all families, `playableStateScope`, timeline, digest, and lineage remain immutable bound projection evidence rather than additional uniqueness dimensions. Game Session command-root allocation remains the opaque durable command-row identity `(tenantId, gameInstanceId, commandId, planOrdinal)`; passive, inbound/remote, timer, retry, and already-generated effects retain owner/source-specific identities. The combination of the coordination timeline, tick effect ledger, and per-service idempotency guards applies the ADR 0058 class-specific outcomes: each projection converges to a single terminal outcome (`APPLIED` or `ABANDONED`) only when the evidence policy permits terminalization; an inconclusive old-epoch projection remains reconciliation-required and non-terminal under its original mutation `EffectId`, with enclosing `rootEffectId` retained as lineage and reconciliation context. See [ADR 0058](./decisions/adr-0058-class-specific-redis-loss-outcomes.md) and [Tick Failure and Operations](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy). +Crash recovery re-invokes a domain handler for a staged effect only when durable evidence proves that the `SCHEDULED` effect was unapplied and replay is safe under its owner contract; a missing response or ambiguous guard leaves the effect `SCHEDULED` and reconciliation-required. Replays must not double-apply logical effects. Redis loss is evaluated against the measured `redis_unreplicated_write_window_slo_ms`; `ticks_exposed` is diagnostic only. The namespace-complete storage projection tuple `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)` identifies the ledger/storage view; durable projections also retain the persisted mutation `EffectId`, enclosing root lineage where applicable, typed operation, immutable request digest, and required command/source bindings where allocated. `playableStateScope` is separately persisted and exact-validated evidence, while `regionEpoch` and `tickId` provide ordering/timeline context rather than guard uniqueness. Participant-guard logical uniqueness is the owner-declared runtime-family partition plus the persisted mutation `EffectId`, typed operation, and exact target aggregate. S1/S2 uses `(tenantId, playableStateNamespaceId)` and only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)`; the partition must be sealed and exact-validated and cannot create a second guard or fork the same logical mutation. For S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence; for all families, `playableStateScope`, timeline, digest, and lineage remain immutable bound projection evidence rather than additional uniqueness dimensions. Command-root allocation detail remains pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). The combination of the coordination timeline, tick effect ledger, and per-service idempotency guards applies the ADR 0058 class-specific outcomes: each projection converges to a single terminal outcome (`APPLIED` or `ABANDONED`) only when the evidence policy permits terminalization; an inconclusive old-epoch projection remains reconciliation-required and non-terminal under its original mutation `EffectId`, with enclosing root lineage retained as reconciliation context. See [ADR 0058](./decisions/adr-0058-class-specific-redis-loss-outcomes.md) and [Tick Failure and Operations](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy). --- @@ -464,7 +464,7 @@ See `system-architecture-tick-failures-and-operations.md` for the full crash-rec ## Domain Idempotency Rules (Timeline Context + Owner Guards) -Domain services use the region-scoped tick timeline `(regionEpoch, tickId)` for ordering and fencing, not as the canonical idempotency token for a logical effect. The default mutation boundary is the mutation's stable persisted `EffectId` plus a participant guard containing the typed operation, exact target aggregate, and immutable request digest. Root effects use the root `EffectId`; generated child mutations use their deterministic persisted child `EffectId` and retain the enclosing root as lineage. A narrow last-tick watermark is permitted only for an explicitly documented aggregate proven to receive at most one logical mutation per tick timeline; it must not replace the effect/participant guard for general command effects. Exact allocator format and allocation-boundary details remain pending and non-authoritative in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +Domain services use the region-scoped tick timeline `(regionEpoch, tickId)` for ordering and fencing, not as the canonical idempotency token for a logical effect. The default mutation boundary is the mutation's stable persisted `EffectId` plus a participant guard containing the typed operation, exact target aggregate, and immutable request digest. A child mutation retains its persisted child `EffectId` and enclosing-root lineage. A narrow last-tick watermark is permitted only for an explicitly documented aggregate proven to receive at most one logical mutation per tick timeline; it must not replace the effect/participant guard for general command effects. Command-plan ordering and root-allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). - Single-aggregate updates may use an epoch-aware “last applied tick” pattern (for example storing and comparing `(last_region_epoch, last_tick_id)` for the aggregate) only when the owning contract proves that at most one logical update for that aggregate can occur in each tick. Without that one-update-per-aggregate-per-tick invariant, each logical effect requires a participant guard derived from the stable root `EffectId`, typed operation, and target aggregate; a root-only ledger or guard is insufficient. The timeline tuple is ordering/fence context and is not sufficient idempotency identity. - Multi-aggregate operations use explicit `tick_effect_guard` storage projections that retain the namespace-complete fields (for example `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)`) and link each row to the enclosing root lineage plus the mutation's persisted root-or-child `EffectId` and derived typed operation/target guard identity. The guard uniqueness identity follows the owner-declared runtime family: S1/S2 uses the `(tenantId, playableStateNamespaceId)` partition plus `EffectId`, typed operation, and exact target aggregate, while only an explicit S3 family uses `(tenantId, gameInstanceId)` plus those identity fields. For S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence; `playableStateScope`, timeline, digest, and lineage remain immutable evidence, not uniqueness dimensions. Unknown or unclassified families fail closed and are never inferred to be S3. @@ -474,7 +474,7 @@ Domain services use the region-scoped tick timeline `(regionEpoch, tickId)` for Effect identity and idempotency rules are defined jointly by: - The `(regionEpoch, tickId)` carried on tick-driven calls as ordering/fencing context. -- **Target-state plan-root identity:** Game Session supplies tick execution with the persisted deterministic command-plan root binding owned by [Transaction Strategies](./system-architecture-transactions.md#command-atomicity-and-outcome-aggregation). That frozen binding includes the applicable `playableStateNamespaceId` as exact runtime evidence and provides the stable root `EffectId`; participant guards derive from that root or a deterministic persisted child, typed operation, exact target aggregate, and immutable request digest. Tick scheduling and `(regionEpoch, tickId)` fence that work but never allocate, replace, or reinterpret its `EffectId`/`planOrdinal`; owner/source-specific non-command roots remain distinct. Script-generated commands retain `(automationDispatchId, commandOrdinal)` in their admitted operation identity, so `scriptEventId` alone cannot distinguish fan-out commands. The current live path is documented above and remains a tracked implementation gap. +- **Target-state effect identity:** Tick work carries the persisted mutation `EffectId`, typed operation, exact target aggregate, and immutable request digest used by the participant guard. Tick scheduling and `(regionEpoch, tickId)` provide ordering and fencing context; they do not replace that mutation identity. Command-plan ordering, `planOrdinal`, and root-allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Script-generated command handoff identity remains distinct from handler correlation identity under the scripting owner contract. The root identity and generated-child identity distinction is canonical in `system-architecture-transactions.md`; ledger records retain the enclosing root lineage, while participant guards use the mutation's persisted root-or-child `EffectId` with its deterministic operation/target projection rather than ad-hoc keys. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative. diff --git a/design/architecture/system-architecture-transactions.md b/design/architecture/system-architecture-transactions.md index 08a1aa7088..18830c7cd0 100644 --- a/design/architecture/system-architecture-transactions.md +++ b/design/architecture/system-architecture-transactions.md @@ -6,7 +6,7 @@ Script evaluation and pin transitions are not a new transaction substrate. The s ## Implementation Status -The structured participant-guard request, deterministic command-plan root identity, shared `IdempotentEffectExecutor`, standardized tick-effect outcome metric, and replay-verification helper described below are target-state contracts. The current replay tables and helpers remain narrower and domain-local; complete propagation and validation of the plan's persisted `planOrdinal`/root-or-child `EffectId`, typed operation, target aggregate, owner-resolved S1/S2-versus-explicit-S3 guard partition, applicable `playableStateNamespaceId` and separately persisted `playableStateScope` evidence, separately validated active-instance fence, immutable request digest, complete participant set, and shared helper/metric behavior are not yet fully implemented or proven. Unknown or unclassified guard families must be rejected before any participant-guard allocation or admission; no implicit third partition exists. The current local instance-bound scripting handoff now carries, persists, and enforces the exact `scriptPinEpoch` tuple with its owner request evidence, including same-version old-epoch rejection. Automation also commits each deterministic child `HANDOFF_IN_FLIGHT` intent before invoking Game Session outside a local transaction, then records a definitive response in a separate local transaction; ambiguous post-dispatch failures remain recoverable intent rather than being reported as a clean rejection. It does not yet implement the durable evaluated-descriptor and reconciliation owner needed to recover every ambiguous handoff. Complete source/target remote tuple binding and full command identity also remain implementation gaps rather than weakened target invariants. The target contract remains authoritative: matching requests may replay safely, while an operation, target, namespace, scope, active-instance evidence, or digest mismatch fails closed. +The structured participant-guard request, shared `IdempotentEffectExecutor`, standardized tick-effect outcome metric, and replay-verification helper described below are target-state contracts. The current replay tables and helpers remain narrower and domain-local; complete propagation and validation of the persisted mutation `EffectId`, typed operation, target aggregate, owner-resolved S1/S2-versus-explicit-S3 guard partition, applicable `playableStateNamespaceId` and separately persisted `playableStateScope` evidence, separately validated active-instance fence, immutable request digest, complete participant set, and shared helper/metric behavior are not yet fully implemented or proven. Deterministic command-plan ordering, `planOrdinal`, and command-root allocation are pending proposal-only requirements in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md), not current target state or proof obligations. Unknown or unclassified guard families must be rejected before any participant-guard allocation or admission; no implicit third partition exists. The current local instance-bound scripting handoff now carries, persists, and enforces the exact `scriptPinEpoch` tuple with its owner request evidence, including same-version old-epoch rejection. Automation also commits each deterministic child `HANDOFF_IN_FLIGHT` intent before invoking Game Session outside a local transaction, then records a definitive response in a separate local transaction; ambiguous post-dispatch failures remain recoverable intent rather than being reported as a clean rejection. It does not yet implement the durable evaluated-descriptor and reconciliation owner needed to recover every ambiguous handoff. Complete source/target remote tuple binding and full command identity also remain implementation gaps rather than weakened target invariants. The accepted effect contract remains authoritative: matching mutation identity and digest may replay safely, while an operation, target, namespace, scope, active-instance evidence, or digest mismatch fails closed. Lifecycle and authoring workflows follow the same local-transaction boundary. World Management commits its lifecycle row/epoch with database compare-and-set; Temporal coordinates retries and waits but is not a transaction or authority. Current instance termination performs Entity cleanup outside the World database transaction and commits the World-owned row cleanup plus final `TERMINATED` state in one local transaction after that acknowledgement. This closes partial World-local cleanup on failure but does not implement the target frozen multi-owner cleanup snapshot, acknowledgement set, or complete recovery proof. Replacement cutover follows the canonical [PREPARING-to-ACTIVE proof sequence](./system-architecture-versioning-runtime.md#realm-routing-contract-for-player-addressable-realms) and [Game Session cutover boundary](./microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary): World owns the lifecycle CAS and one-shot cutover hold, while the Game Session owner-local cutover transaction validates the hold id/fence, expected pointer version, and exact source and target `ACTIVE` proofs before its pointer CAS. World finalizes the hold only after authoritative Game Session readback proves the local pointer/audit/prepared-execution/source-cleanup/drain-fence transaction; no global transaction spans the services. A multi-owner Draft commit carries the complete [ADR 0129](./decisions/adr-0129-durable-fenced-multi-owner-draft-commits.md) binding, including target `tenantId`/`versionId`, request or proposal identity, exact `baseCommitId`, canonical revision order, proposed input/digest, and the complete affected `(owner, aggregateId, scopeId, epoch)` set. It performs compare-and-set in each owner database, records durable per-owner outcomes, and publishes through a synchronized read fence; it never uses a global epoch, silent merge, or distributed transaction. These are control-plane workflows and do not add a global ACID path to ordinary gameplay. @@ -32,7 +32,7 @@ Lifecycle and authoring workflows follow the same local-transaction boundary. Wo Commands whose temporary partial state could violate unique ownership, value conservation/non-negative balance, conditional exchange, irreversible consumption, premium entitlement, or external commitment do not use independent tick effects. They use one co-located authoritative transaction where possible, otherwise a durable reservation/escrow workflow with idempotent steps and transactional outbox delivery. Routine distributed two-phase commit is not a gameplay pattern. -Before tick staging, Game Session materializes the command's deterministic effect plan as the ordered set of logical root effects admitted for that command. The owning command/action contract for the frozen typed command or `ResolvedEffectPlan` supplies semantic order; built-in commands declare an equivalent stable order, and ambiguous or duplicate order fails before admission. Game Session persists the ordered plan manifest and digest. Each logical operation has one root `EffectId` and any number of participant guards beneath it. Single-root plans use `planOrdinal=0`, multi-root plans use stable zero-based `0..n-1`, and zero-effect plans allocate neither an ordinal nor a root. The durable gameplay command row freezes/binds its request fingerprint and resolved runtime scope before allocation. Game Session owns an opaque allocation row unique on `(tenantId, gameInstanceId, commandId, planOrdinal)`; it also binds the ordered plan manifest digest and validates that frozen command/runtime binding in the same local durable plan/staging transaction. Reuse requires the same command row identity, frozen command/runtime binding, `planOrdinal`, and manifest digest; any mismatch fails closed. For Automation, the complete applicable Command-Handoff Identity, including optional distinct target runtime fields when present, is the admission/deduplication identity and must exact-map to one durable target `commandId`; after that mapping, allocation uses the target command row's same canonical key. Trigger Identity and `scriptEventId` remain handler/correlation identities, not allocation inputs. A conserved multi-participant operation normally shares one root, but its atomicity still comes from the applicable ADR 0053 co-location or reservation/escrow boundary; the shared root is not global transaction authority. `tickBatchId`, mutable command text, `effectKey`, source ordering, participant tuples, and generated child ordinals cannot substitute for the durable command row identity or allocation binding; no global allocator is introduced. Exact allocator details remain pending and non-authoritative in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +The command-plan ordering, `planOrdinal`, and root-allocation design are proposed in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) and remain pending human review. This transaction contract does not assign a command-root order, allocation owner or key, or manifest binding. Under the accepted effect contract, each staged mutation uses its persisted `EffectId`, typed operation, exact target, and immutable request digest; any participant guard must validate that binding and fail closed on conflict. A conserved multi-participant operation still follows the applicable ADR 0053 co-location or reservation/escrow boundary; a shared effect identity does not create global transaction authority. All real-time gameplay logic — movement, combat, item use, AI — is executed inside **ticks**. Each command is: @@ -84,14 +84,14 @@ If a proposed gameplay feature truly requires stronger semantics than this model Tick execution is replayable: retries, failover, and Redis AOF replay can cause the same logical effect to be attempted more than once. For gameplay commands this is expected and safe only because tick-invoked domain mutations are required to be idempotent with respect to the stable persisted mutation `EffectId`—the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child mutation—with any enclosing `rootEffectId` retained only as lineage and reconciliation context, as defined by the identifier glossary. -- **Target-state identity and guard contract:** The deterministic command-plan allocation above is the canonical command-root contract. Participant-guard durability follows the owning runtime-family classification: S1/S2 owner families use `(tenantId, playableStateNamespaceId)` plus the owning identity/effect (`EffectId`, typed operation, and target aggregate), while only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)` as its durable partition. For S1/S2, the active `gameInstanceId` remains separately exact-validated authorization/fence evidence and does not create a second guard identity; unknown or unclassified families are rejected before any participant-guard allocation or admission and are never inferred to be S3. Root effects use the root `EffectId`, while generated child mutations use their deterministic persisted child `EffectId` and retain the enclosing root as lineage and reconciliation context. The guard row binds the immutable request digest and stores mutable outcome/evidence state under CAS. Matching replay returns the stored result, while a tenant, namespace, owning effect, operation, target, scope, active-instance evidence, or digest mismatch fails closed. Work explicitly outside playable-state scope must use an accepted owner-specific idempotency/partition contract; it cannot omit namespace/scope and proceed under this gameplay participant-guard contract. Exact child allocation remains outside this accepted guard decision and is described only by non-authoritative [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). -- **Post-abandon re-drive:** A fresh root is not an ordinary retry or replay. After conclusive `ABANDONED` evidence and source terminalization, a command re-drive creates a new durable `commandId` linked to the prior command/effect lineage before allocating its later-coordinate plan root; reusing the old `commandId` returns its terminal result. Non-command sources use their owner-specific linked re-drive identity. Until the new allocation commits, the work remains recovery work and is not returned to an ordinary queue. +- **Target-state identity and guard contract:** Participant-guard durability follows the owning runtime-family classification: S1/S2 owner families use `(tenantId, playableStateNamespaceId)` plus the owning mutation identity (`EffectId`, typed operation, and target aggregate), while only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)` as its durable partition. For S1/S2, the active `gameInstanceId` remains separately exact-validated authorization/fence evidence and does not create a second guard identity; unknown or unclassified families are rejected before any participant-guard allocation or admission and are never inferred to be S3. A generated child mutation uses its persisted child `EffectId` and retains the enclosing root as lineage and reconciliation context. The guard row binds the immutable request digest and stores mutable outcome/evidence state under CAS. Matching replay returns the stored result, while a tenant, namespace, owning effect, operation, target, scope, active-instance evidence, or digest mismatch fails closed. Work explicitly outside playable-state scope must use an accepted owner-specific idempotency/partition contract; it cannot omit namespace/scope and proceed under this gameplay participant-guard contract. Command-root and generated-child allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +- **Post-abandon re-drive:** A fresh mutation identity is not an ordinary retry or replay. After conclusive `ABANDONED` evidence and source terminalization, any re-drive follows its source owner's admission and identity contract and remains linked to the prior effect lineage. Ordinary retries and replay preserve the original mutation identity. Command-root re-drive allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). - **Command/effect boundary:** An `ACCEPTED_VOLATILE` command lost before durable staging may terminalize only at command scope as `executionOutcome = LOST_BEFORE_STAGING` and `gameplayResult = NOT_APPLIED` while its ingress status is `RECEIVED` or `ENQUEUED` and no `tickBatchId` survives; an `ACCEPTED_DURABLE` command follows its feature-specific durable replay/re-drive contract instead. No effect ledger row is invented for either command unless an effect was durably claimed or staged. A durable pre-staging source/effect claim establishes recoverability but does not itself make physical execution at least once; only a staged or otherwise dispatchable effect enters physical execution, after which its immutable identity/digest guard permits at most one logical mutation. Staged effects terminalize as `APPLIED` or `ABANDONED` only when authoritative evidence permits; inconclusive work remains `SCHEDULED`/reconciliation-required, explicitly including timeout, retry exhaustion, or missing coordination. `REPLAY_NOOP` is an `APPLIED` reason, never a third status. Command `SUCCESS`, `PARTIAL`, `FAILED`, `TIMEOUT`, and `NOT_APPLIED` remain derived player-result vocabulary under ADR 0053. See [ADR 0069](./decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md). -- **Single propagation contract:** The coordinator sends the mutation's persisted root-or-child `EffectId`, typed operation, target, immutable request digest, conditional owner-family partition, separately validated active-instance authorization/fence evidence, and required-participant context; generated children also carry their enclosing root/parent lineage binding. Game Session retains the command root's associated `planOrdinal` in its plan/ledger binding. Participants validate the complete binding and atomically commit their guard with effect-visible rows before acknowledging. They do not generate a fresh identity or bind a guard to mutable payload. -- **Current live implementation gap:** The live Game Session proto does not yet carry `commandOrdinal`, the complete applicable Command-Handoff Identity, or the deterministic plan manifest/opaque root allocation binding for this handoff. `TickStagingService` derives the live `effectKey` from `commandId`; it retains a deterministic command-text-plus-slot fallback helper for selection metadata, but durable tick batching rejects any queued entry without a `commandId` before staging or effect persistence. That fallback is therefore not a live staging, replay, or recovery identity, and it is not the target-state automation handoff or command-plan identity; the complete Command-Handoff Identity and root allocation binding are not yet enforced live. -- **Effect-key boundary:** `effectKey` remains a source-specific descriptor, ordering, or correlation field under its owning contract; it is not the root allocation identity. Existing source-specific validation or serialization may remain where already defined. Root allocation uses the opaque Game Session binding on the durable command row's `(tenantId, gameInstanceId, commandId, planOrdinal)` key plus its frozen command/runtime binding and ordered plan manifest digest; retries reuse the stored binding, and any mismatch fails closed. +- **Single propagation contract:** The coordinator sends the mutation's persisted `EffectId`, typed operation, target, immutable request digest, conditional owner-family partition, separately validated active-instance authorization/fence evidence, and required-participant context; generated children also carry their enclosing root/parent lineage binding. Participants validate the complete accepted effect binding and atomically commit their guard with effect-visible rows before acknowledging. They do not generate a fresh identity or bind a guard to mutable payload. Command-root `planOrdinal` propagation remains pending in ADR 0183. +- **Current live implementation gap:** The live Game Session proto does not yet carry `commandOrdinal` or the complete applicable Command-Handoff Identity for this handoff. Plan-root manifest/allocation behavior remains proposed in ADR 0183 and is not a current implementation gap against accepted target state. `TickStagingService` derives the live `effectKey` from `commandId`; it retains a deterministic command-text-plus-slot fallback helper for selection metadata, but durable tick batching rejects any queued entry without a `commandId` before staging or effect persistence. That fallback is therefore not a live staging, replay, or recovery identity. +- **Effect-key boundary:** `effectKey` remains a source-specific descriptor, ordering, or correlation field under its owning contract; it is not a substitute for persisted mutation identity. Existing source-specific validation or serialization may remain where already defined. Command-root allocation details, including the command row key and manifest binding, remain pending in ADR 0183. - Owning services implement durable idempotency guards (unique constraints, monotonic updates, transactional outbox) under the derived participant guard identity. Duplicate matching attempts become prior-result/no-op outcomes; a guard conflict fails closed. Each service persists its guard outcome and any outbox/reconciliation reference, while Game Session aggregates required participant outcomes under the enclosing root `EffectId`. -- **Generated effect chains:** Generated children carry immutable parent/root identity, `depth = parent.depth + 1`, a stable child ordinal allocated and persisted by the owning contract for replay-stable reuse, and deterministic root-chain count/cost/per-target accounting. When generated work is under an admitted command, it remains beneath that command's root; otherwise it retains its owner/source-specific identity and does not synthesize a command plan. Only a child exceeding a bound is suppressed; committed parents and earlier children remain authoritative. Required/optional authored classification derives truthful `SUCCESS`, `PARTIAL`, or `FAILED` outcomes, and suppression evidence uses bounded metric dimensions with raw identities retained for audit. The owning contract's child-admission transaction must durably map its complete owner scope, enclosing root identity, immutable parent identity, and deterministic child ordinal to exactly one child `EffectId` using CAS, insert-if-absent, or an equivalent atomic boundary. The mapping is persisted before enqueue/apply; exact retries/replays read and reuse the persisted child identity, lineage, and accounting, while any scope, identity, lineage, ordinal, or immutable-request-digest conflict fails closed before enqueue/apply. This source-specific mapping does not replace participant-guard uniqueness (child `EffectId`, typed operation, exact target) or the separate Automation Command-Handoff/global-fanout identity contracts. See [ADR 0075](./decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). Exact scalar/allocation details remain non-authoritative in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +- **Generated effect chains:** Generated children carry immutable parent/root identity, `depth = parent.depth + 1`, a stable child ordinal allocated and persisted by the owning contract for replay-stable reuse, and deterministic root-chain count/cost/per-target accounting. When generated work is associated with command work, its enclosing-root association follows the owner contract; command-plan association remains pending in ADR 0183. Otherwise, it retains its owner/source-specific identity. Only a child exceeding a bound is suppressed; committed parents and earlier children remain authoritative. Required/optional authored classification derives truthful `SUCCESS`, `PARTIAL`, or `FAILED` outcomes, and suppression evidence uses bounded metric dimensions with raw identities retained for audit. The owning contract's child-admission transaction must durably map its complete owner scope, enclosing root identity, immutable parent identity, and deterministic child ordinal to exactly one child `EffectId` using CAS, insert-if-absent, or an equivalent atomic boundary. The mapping is persisted before enqueue/apply; exact retries/replays read and reuse the persisted child identity, lineage, and accounting, while any scope, identity, lineage, ordinal, or immutable-request-digest conflict fails closed before enqueue/apply. This source-specific mapping does not replace participant-guard uniqueness (child `EffectId`, typed operation, exact target) or the separate Automation Command-Handoff/global-fanout identity contracts. See [ADR 0075](./decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). Exact scalar/allocation details remain non-authoritative in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). - For gameplay-visible mutations, derived participant-guard rows backed by the mutation's stable persisted root-or-child `EffectId` are the default idempotency boundary. Simpler `last_tick_id` watermark patterns are allowed only for aggregates explicitly documented as receiving at most one logical mutation per tick. - **Target-state shared idempotency helper contract (not yet fully implemented or proven):** To keep this contract consistent across services, tick-driven handlers use a shared idempotency helper from `common-data-runtime` (for example an `IdempotentEffectExecutor`) instead of ad-hoc “check or insert” patterns. The helper: - **Target-state request shape:** Accepts a structured `ParticipantGuardRequest` containing the owner-resolved runtime-family classification and conditional durable partition—S1/S2 uses `(tenantId, playableStateNamespaceId)` plus the owning identity/effect, while only an explicitly owner-classified S3 uses `(tenantId, gameInstanceId)`—and separately carries the active `gameInstanceId` authorization/fence evidence for S1/S2. The request also contains mutation guard `EffectId` (`effectId`), typed operation, target aggregate type, target aggregate ID, applicable `playableStateNamespaceId` evidence, separately persisted server-derived `playableStateScope` evidence, and immutable request digest (`requestDigest`), plus callbacks for “apply-if-first” and “handle-replay”. A generated child request also carries its enclosing `rootEffectId` and parent/child lineage binding; for S1/S2, namespace is the uniqueness partition while scope and active-instance evidence are exact-validated sealed-context fences, and lineage fields do not replace the conditional partition, `effectId`, operation, and exact target in guard uniqueness. Unknown or unclassified families, or a request with no accepted owner-specific partition, are rejected before any participant-guard allocation or admission; they are never inferred to be S3. 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 94f635733c..557ab6fc5f 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -169,7 +169,7 @@ The live Game Session handoff provides idempotent admission for the direct enque The target remote-follow-up contract is owned by [Scripting & Automation: Cross-Service Contracts](../../architecture/system-architecture-scripting-contracts.md#3-version-fencing-rollback-safety). Current `ScriptHandoffEvent` persistence and readback now carry the source `scriptPinEpoch`, but they do not yet bind the source tuple to the target tuple or prove downstream target admission against that binding. The legacy target-side `trigger_script_event` path is therefore deterministically disabled until the complete source/target tuple-plus-owner binding exists: missing, malformed, or mismatched tuple evidence is a terminal fail-closed outcome, while unavailable authority remains non-admitted and retryable. Same-instance cross-region work and semantic target `UNPINNED` handling remain subject to that owner contract. -Game Session owns deterministic command-plan root allocation; Automation's current handoff does not yet carry or prove complete command-level mapping, deduplication, or root binding. This remains a target/proof gap under the canonical owners above, not an implementation claim. +Automation's current handoff does not yet carry or prove complete command-level mapping or deduplication. Command-plan ordering, `planOrdinal`, and root allocation are pending proposal-only requirements in [ADR 0183](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md), not accepted target/proof gaps. The bounded evaluator supports command-specific `targetEntityId`, structured `commandAlias` plus templated `arguments`, `when`/`unless` conditions, and multi-target `targetEntityIds[]` fan-out with stable command ordinals. **Target state:** durable handoff history is per command and preserves rendered command text, script/plugin/source/dispatch identity, captured plugin `(pluginActivationEpoch, lifecycleRevision)` when applicable, target scope, remote coordinator/follow-up ids, and later Game Session gameplay execution/outcome plus remote-state tail. Target `ListScriptHandoffEvents` directly filters by remote scope, remote ids, origin identity, command id, target entity, routing bundle, and source/state instead of reconstructing history from payloads; its exhaustive plugin-backed output retains the captured lifecycle revision beside the activation epoch. The current handoff storage/proto remains narrower and does not yet prove this target projection. @@ -200,7 +200,7 @@ Game Session pin reads remain distinct: `GetPinnedScriptPatchVersion` reports pi - The first scheduler ownership model is complete, but richer scheduler dashboards and a later explicit leader-checkpoint substrate are not part of it. TICK-01 lane declaration, actor-versus-passive selection, cost-class enforcement, and focused proof remain unimplemented; any future timer, retry, remote, or script-generated source must declare its lane and cost class and use the existing selected-work, region-fence, routing, quota, and durable-result contracts. - The accepted [ADR 0072](../../architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md) timer classes, durable resume-window identity, and `SKIP_MISSED`/`COALESCE_ONE` outcomes do not promote the current best-effort scheduler to complete recovery; durable correctness-bearing timer intent and focused recovery proof remain gaps. - [ADR 0063](../../architecture/decisions/adr-0063-durable-per-dispatch-script-handoff.md) and [ADR 0064](../../architecture/decisions/adr-0064-stage-qualified-script-outcomes.md) require one durable child dispatch per emitted command and separate ingress, handler, and command outcome authorities. Current handoff paths remain bounded/partial where downstream execution-disposition readback and stage-qualified proof are absent. -- [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) remains an implementation and proof gap for the Automation-to-Game-Session handoff and command-plan/root binding. The [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary) own the canonical handoff details, while the [Game Session tracker](./game-session-runtime-and-tick-coordination.md) records current implementation and proof status. +- The accepted ADR 0069 implementation and proof gap covers effect identity, replay, and terminal outcomes. Automation-to-Game-Session handoff mapping and deduplication remain implementation gaps under [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary); command-plan/root allocation details remain proposal-only in [ADR 0183](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). The [Game Session tracker](./game-session-runtime-and-tick-coordination.md) records related implementation and proof status. - [ADR 0075](../../architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md), [ADR 0076](../../architecture/decisions/adr-0076-failure-class-specific-durable-tick-retries.md), and [ADR 0078](../../architecture/decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md) are target contracts only: generated-chain budgets, class-specific durable retry owners, and adopter-side digest-conflict guards remain unimplemented or unproved in this runtime. - Additional publish-adjacent or script-patch rollout Temporalization is not implemented by this tracker. It is justified only by a concrete long-lived workflow need; surviving short synchronous saga seams remain explicitly scoped for the later boundary cleanup. - Custom event families and future gameplay lifecycle producers do not yet exist as additional implementation families. They must extend the manifest-backed ingress and payload contract rather than create local semantics. diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 6ec2e75f0d..96e478ff3d 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -24,7 +24,7 @@ Target rollback requires the scoped Automation admission barrier to pause new sc Distinct-instance remote follow-up has bounded durable coordinator/follow-up persistence and handoff paths live. Current `ScriptHandoffEvent` persistence and the handoff wire retain the source `scriptPinEpoch` and source owner-request evidence, but do not yet retain or enforce the complete source/target pin-tuple binding. The remaining target implementation/proof gap is source revalidation, target admission under a frozen target tuple, complete source/target fencing and retry/replay proof, and plugin `pluginActivationEpoch`/owner `lifecycleRevision` propagation where applicable. The legacy target-side `trigger_script_event` path is deterministically disabled until that durable source/target binding exists; it must not derive a Trigger ingress tuple from mutable target state or generic patch metadata. Game Session's local plugin projection, lexicographic lifecycle-fence CAS, durable lifecycle install acknowledgement, and exact final revision fence are also not implemented or proved. Game Session owns the remote coordinator/follow-up records and its local plugin projection; Automation owns authoritative plugin activation/lifecycle state and the owner `pluginActivationEpoch`/`lifecycleRevision` fence evidence. The tuple, fence, durable install acknowledgement, and exact final revision requirements remain cross-service target obligations; see the [canonical scripting contract](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary), [ADR 0119](../../architecture/decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md), and [normative remote-follow-up tuple-binding contract](../../architecture/system-architecture-scripting-normative-contract-tables.md#remote-follow-up-tuple-binding-normative) for target semantics. -The deterministic command-plan/root boundary remains a Game Session implementation and proof gap. Current command/effect and Automation handoff paths use narrower current identities and do not yet persist or prove the target bindings. See [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), [Transaction Strategies](../../architecture/system-architecture-transactions.md#command-atomicity-and-outcome-aggregation), and [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary) for the canonical command-plan, participant/replay, ordering, and handoff contracts. +Current command/effect and Automation handoff paths use narrower identities and do not yet implement the accepted effect-identity, replay, and terminal-outcome contracts. Deterministic command-plan ordering, `planOrdinal`, and root allocation remain pending proposal-only requirements in [ADR 0183](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). See [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) for accepted effect semantics and [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary) for the handoff boundary. ## Packet 4 Status and Proof Gaps @@ -120,7 +120,7 @@ After Redis drain commit, Game Session executes `DRAINED` effects from the durab Malformed or orphaned tick queue/pending entries have no token-fenced atomic quarantine and convergent-removal implementation or proof; a separate-check `LREM` is not an authorized cleanup path. Stale drain, fresh-stage rollback, and manifest-mismatch repair requeue actual commands, advance their queue-source state deliberately, and increment `tick_requeued_action_total` by action count and durable source (`player`, `automation`, bounded `remote_followup`, or `unknown`). Requeue preserves sealed source identity, comparable ordinal, due point, and source state; mutable command-row state cannot replace the sealed ordering facts. Only the first current migrated command families consume the post-drain effect seam, while pure views remain direct reads. -The complete target command-plan/root replay and reconciliation bindings are not yet persisted or proved; see [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), [Transaction Strategies](../../architecture/system-architecture-transactions.md#command-atomicity-and-outcome-aggregation), and [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary) for the owning contracts. +The accepted effect identity, replay, and terminal-outcome rules are not yet fully persisted or proved; see [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md). Command-plan/root allocation and replay details remain proposal-only in [ADR 0183](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). The [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary) owns the separate Automation handoff boundary. ### Gameplay Mutation Consumers @@ -178,7 +178,7 @@ The recorded Markdown and contract checks for these slices include `./gradlew li ## Active Gaps - TICK-03 is now the accepted command-level boundary: required versus optional effects, permitted terminal combinations, intentional `PARTIAL`, and stronger atomicity routing must be classified per command family. Current implementation and proof remain partial; no status promotion is implied. -- TICK-04 remains partial and proof remains incomplete: deterministic command-plan admission, operation/digest-bound participant guards, stable `planOrdinal`/root `EffectId` persistence and reuse, and focused crash/retry/dead-letter coverage across World and Entity are still gaps. The canonical effect/root and durable-commit contracts are defined by [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) and [ADR 0071](../../architecture/decisions/adr-0071-durable-tick-commit-before-fenced-coordination-cleanup.md); this tracker records only the implementation and proof gaps. +- TICK-04 remains partial and proof remains incomplete: operation/digest-bound participant guards and focused crash/retry/dead-letter coverage across World and Entity are still gaps under accepted contracts. Command-plan admission, `planOrdinal`, and root allocation are proposal-only in ADR 0183 and are not implementation or proof gaps unless that proposal is accepted. ADR 0069 owns effect identity, replay, and terminal-outcome rules; ADR 0071 owns durable tick commit before fenced coordination cleanup. - Replacement cutover remains partial at the Game Session boundary: the current wire/durable record/reconciler has no complete proof of exact cross-service cutover binding, post-swap readback, safe abort, or finalization, and must not infer success from a pointer write or an in-memory termination request. See the canonical [World Management replacement cutover hold contract](../../architecture/microservices/world-management-service/api-contracts.md#replacement-cutover-hold-contract) and [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). - The current Game Session movement seam is a room-binding/projection seam, not World-authoritative location/occupancy mutation. The target World-owned authoritative mutation path remains unimplemented/unproved, and `DROP`/`PICKUP` still lack proof that the World actor-location precondition remains valid through the Entity commit. 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 f308558105..d754c4290c 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 @@ -79,7 +79,7 @@ The live transfer contract deliberately rejects an already-moved item by default ### Durable Effects and Replay Guards -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 target command-plan root binding, which remains unimplemented and unproved here. See [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) for the owning target contracts and remaining proof boundary. +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. Command-plan and root-allocation specifics remain proposal-only under [ADR 0183](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). 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. From 358fc222ea4f62d493d44986c15b8b04ac5d7459 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 30 Sep 2026 22:31:05 +1300 Subject: [PATCH 38/68] Allow review stops without blocking active runs --- design/developer-workflows/pr-lifecycle.md | 2 +- dev-tools/pr_review/cli.py | 228 ++-- dev-tools/pr_review/cli_runner.py | 67 +- dev-tools/pr_review/controller.py | 973 +++++++++--------- dev-tools/pr_review/policy.py | 49 +- dev-tools/pr_review/runtime.py | 283 ++--- dev-tools/pr_review/sqlite_store.py | 51 +- dev-tools/pr_review/state.py | 81 +- .../validation/test_pr_review_cli_runner.py | 236 +++-- .../validation/test_pr_review_controller.py | 763 ++++++-------- .../validation/test_pr_review_runtime.py | 237 +++-- .../validation/test_pr_review_sqlite_store.py | 50 + dev-tools/validation/test_pr_review_status.py | 145 ++- 13 files changed, 1715 insertions(+), 1450 deletions(-) diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index 3cac6588fd..1f97471ec5 100644 --- a/design/developer-workflows/pr-lifecycle.md +++ b/design/developer-workflows/pr-lifecycle.md @@ -22,7 +22,7 @@ Use this guide for pull-request status, review handling, CI, Renovate, merging, - Record an explicit channel judgment with `dev-tools/pr-review decide judgment retain|reopen --pr --channel hosted|cli --head --checkpoint --reason ""`. Retain confirms the verified equivalent patch for request and queue safety; reopen explicitly requires fresh review without deleting historical completed taper and resets the taper streak at the bound checkpoint. For CLI, a reopen may bind the latest complete modern checkpoint to a proven descendant live head, but carries no new review credit until later completed results arrive. A narrow channel policy override uses `dev-tools/pr-review decide policy --pr --head --checkpoint --hosted-zero-useful --reason ""` or `--cli-zero-useful ` (exactly one channel); it sets that channel's zero-useful completion count for the exact checkpoint. - Extend the existing allocation with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head [--checkpoint ] [--min-additional-completed ] [--max-additional-completed ] [--fresh-taper] --reason ""`. Both bounds count completed, attributable results for that PR and channel beginning at the decision; the optional checkpoint records the observed identity but does not move that count's start. With neither bound, the existing one-result promise remains (`min=1`, `max=1`). A minimum-only allocation has no maximum; a maximum-only allocation has no extra minimum (`min=0`). Without `--fresh-taper`, an allocation after completed taper affects queue eligibility and its additional-result count while preserving the existing historical taper display. Its zero-useful results continue the normal streak. An accepted allocated result resets the active streak at that result, while all earlier checkpoints remain visible with their original counts; after fixes, later zero-useful results can satisfy taper. `--fresh-taper` starts the active streak at the allocation decision immediately; earlier dry results remain visible historical evidence but cannot satisfy it. When both bounds are set, reject `min > max`; the minimum requires that many additional results even after fresh taper, while taper may stop earlier than the maximum once the minimum is met. Rate limits, connection failures, duplicates, partial or ambiguous responses, provisional captures, and other non-counting observations do not consume the count. Hosted and CLI allocations remain independent; request-time identity checks apply only when posting a new review. - Normal taper can finish before a maximum once the minimum is met. After any additional result with accepted findings, no next request is allowed until those findings, current/outdated threads, actionable summary findings, and fix publication/validation obligations are clear, even if capacity remains. Once the maximum is used, no further request is allowed for that PR/channel; a maximum stop is not taper and does not waive accepted findings or fixes. `status` and `evidence` expose the minimum, maximum, completed count, baseline identity, in-flight results, taper state, and controlling reason. If the maximum is exhausted while obligations remain, status says `cap exhausted; findings pending` and the channel stays on that PR without another request. When those obligations clear, the controller derives the audited human-cap stop through its normal selector and advances to the next coherent PR without a separate `decide stop`; this stop is not taper, current-head review, CI/Smoke proof, or merge readiness. A bounded allocation can be replaced explicitly with `allocation renew` and new bounds; `allocation cancel` removes it. Ordinary fixes never reset its completed count. -- When the Overseer deliberately allocates one further completed review before deciding whether to continue, record it *before* the review with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head --reason ""`. The promise records the current head, parent, and checkpoint for audit; its completed-result count belongs to the PR and channel and survives later identity changes. A rate limit, partial, duplicate, or unattributable result does not consume it. Keep `renew` for an unconsumed promise whose pre-review identity changed, and `cancel` to remove a promise; both require the PR/channel/current head and a reason. After adjudicating completed results, publishing accepted fixes, and clearing current/outdated threads and actionable summary findings, record the Overseer's decision with `dev-tools/pr-review decide stop --pr --channel hosted|cli --reason ""`. The controller records whether the stop consumes an allocation or reflects a direct human decision, refreshes both channels' complete evidence, records the live head and stack identity for audit, and records the latest attributable checkpoint separately; later identity changes do not invalidate the PR/channel stop. A direct-human Hosted stop preserves incomplete or unattributable records as non-counting history without fabricating review credit. Allocated stops and CLI stops retain their full historical audit requirements. Active reviews, current-head or otherwise ambiguous live results, unresolved current/outdated threads, actionable summary findings, and unpublished accepted fixes still block a direct-human Hosted stop. Each terminal ambiguous response may be retained only by repeating `--retain-ambiguous-fingerprint ` for every response, together with `--ambiguity-reason `; retained responses remain non-counting and never count as dry results. Optional `--head` and `--checkpoint` arguments pin the observed identities. A direct human may explicitly acknowledge only current-head CodeRabbit over-ceiling skip evidence with `--acknowledge-over-ceiling --head ` and a stop reason; the acknowledgment is stored with the exact-head stop and never counts as taper. It does not clear review threads or other blockers, and allocated stops cannot use it. The durable stop skips that PR for the selected channel and satisfies only review-discovery capacity; it does not manufacture taper, CI, runtime proof, or merge readiness. Required CI, Smoke/runtime, ancestry, thread, summary-finding, and merge-readiness evidence remain independent. The next PR still needs its own request-time and active-review checks. +- When the Overseer deliberately allocates one further completed review before deciding whether to continue, record it before the review with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head --reason ""`. Completed-result counts belong to the PR and channel and survive later identity changes; rate limits, partial, duplicate, and unattributable results do not consume the allocation. Record a human decision to make no further requests with `dev-tools/pr-review decide stop --pr --channel hosted|cli --reason ""`. This audited PR/channel override satisfies unfinished taper and persists across head and parent changes. It requires no completed checkpoint, clean findings, idle provider, or coherent review topology. An already admitted CLI or Hosted run continues with its reservation, capture, attribution, and eventual findings intact; finishing that run does not clear the override. Stop recording and new-request admission share only the short state mutation boundary, while each provider keeps its execution exclusion. Optional `--head` and `--checkpoint` pins must match the observed identities; unavailable optional Git proof is recorded as absent, never fabricated. Existing ambiguity-retention and over-ceiling acknowledgment options record their specific evidence without granting review credit. Discovery can advance only when the same channel has no active provider run. Accepted fixes, pending captures and adjudication, attributable evidence, current and outdated threads, actionable summaries, required CI, runtime proof, ancestry, and merge safety remain independent obligations. A stop overrides taper only and does not manufacture a reviewed head or merge readiness. - `dev-tools/pr-review run cli --allow-unreconciled --reason ""` permits one exact child/parent-pinned provisional discovery pass when reconciliation cost is disproportionate. Its evidence is provisional, cannot satisfy taper or merge readiness, cannot advance either channel, and cannot be repeated for that identity. Hosted remains refused until reconciliation; if equivalent history remains afterward, it stays refused until an explicit exact-head/checkpoint judgment resolves it. - For a channel that still needs review, targeting stops at the first held, unstable, unreconciled, over-ceiling, or judgment-blocked PR; it skips PRs whose channel has completed taper or an audited human stop. The narrow exception is a verified terminal, non-counting Hosted response: keep that PR incomplete and visible, but use the next coherent PR's Hosted window if one exists. Do not post another request on the ambiguous PR or grant it taper or merge credit; revisit its evidence or obtain an audited human stop before its merge handoff. Request-time identity and active-review checks still apply before any new request for an incomplete channel. A file-ceiling rejection requires a coherent topology decision; there is no normal incremental-review fallback. - Do not start a review against a base that is about to change. Let an active review finish and consume still-valid findings; cancellation does not recover quota or evidence. Do not publish review-invalidating commits while Hosted review is active. diff --git a/dev-tools/pr_review/cli.py b/dev-tools/pr_review/cli.py index bc0b312515..a9251e71c4 100644 --- a/dev-tools/pr_review/cli.py +++ b/dev-tools/pr_review/cli.py @@ -87,7 +87,9 @@ def _parser() -> argparse.ArgumentParser: state_migrate = state_commands.add_parser( "migrate-sqlite", help="atomically migrate JSON controller state to SQLite" ) - state_migrate.add_argument("--path", metavar="JSON_PATH", help="state file to migrate; defaults to repository state") + state_migrate.add_argument( + "--path", metavar="JSON_PATH", help="state file to migrate; defaults to repository state" + ) state_migrate.add_argument("--json", action="store_true", dest="as_json") stack = commands.add_parser("stack", help="configure the one repository review stack") @@ -140,9 +142,7 @@ def records_database(command: argparse.ArgumentParser) -> None: history_batch.add_argument("--pr", action="append", required=True, type=_positive_int) records_database(history_batch) - incoming = record_commands.add_parser( - "routes", help="list structured and migrated controller routes" - ) + incoming = record_commands.add_parser("routes", help="list structured and migrated controller routes") incoming_query = incoming.add_mutually_exclusive_group() incoming_query.add_argument("--target-pr", type=_positive_int) incoming_query.add_argument("--unassigned", action="store_true") @@ -153,7 +153,9 @@ def records_database(command: argparse.ArgumentParser) -> None: import_run = record_commands.add_parser( "import-run", help="batch-register a curated manual or subagent run from bounded JSON" ) - import_run.add_argument("--input", required=True, metavar="JSON", help="curated metadata file, not raw capture/stdout") + import_run.add_argument( + "--input", required=True, metavar="JSON", help="curated metadata file, not raw capture/stdout" + ) records_database(import_run) provider_import = record_commands.add_parser( @@ -183,7 +185,8 @@ def records_database(command: argparse.ArgumentParser) -> None: provider_repair.add_argument("--coverage-limit", action="append", default=[]) provider_repair.add_argument("--apply", action="store_true", help="write after a full dry-run preflight") provider_repair.add_argument( - "--continue-on-error", action="store_true", + "--continue-on-error", + action="store_true", help="with --all, report unavailable checkpoints while processing the rest", ) records_database(provider_repair) @@ -252,7 +255,10 @@ def records_database(command: argparse.ArgumentParser) -> None: subagent_complete.add_argument("--run-id", required=True) subagent_complete.add_argument("--actor", required=True) subagent_complete.add_argument( - "--finding-json", action="append", default=[], metavar="JSON", + "--finding-json", + action="append", + default=[], + metavar="JSON", help="one bounded finding object with title, decision, reason and optional detail/target_pr/key", ) records_database(subagent_complete) @@ -393,9 +399,7 @@ def records_database(command: argparse.ArgumentParser) -> None: "summary-disposition", help="adjudicate one exact CodeRabbit summary-only finding bucket", ) - summary_disposition.add_argument( - "decision", choices=("rejected", "accepted-unfixed", "accepted-fixed", "routed") - ) + summary_disposition.add_argument("decision", choices=("rejected", "accepted-unfixed", "accepted-fixed", "routed")) summary_disposition.add_argument("--pr", required=True, type=_positive_int) summary_disposition.add_argument("--head", required=True, type=_exact_sha) summary_disposition.add_argument("--source", required=True, choices=("review", "comment")) @@ -535,7 +539,9 @@ def _records_database_path(args: argparse.Namespace) -> Path: active_store = ControllerStateStore(selected_state)._active_store() except StateError as exc: raise CliError("selected controller SQLite database is incompatible") from exc - selected = active_store.path if isinstance(active_store, SqliteStateStore) else sqlite_state_path(selected_state) + selected = ( + active_store.path if isinstance(active_store, SqliteStateStore) else sqlite_state_path(selected_state) + ) if selected.is_symlink(): raise CliError("review-records database path must not be a symlink") return selected @@ -677,9 +683,7 @@ def _load_records_import( raise CliError("inline source decisions require decision, actor, and reason") decision_id = item.get("decision_id") if decision_id is None: - digest = hashlib.sha256( - f"{run['run_id']}\0{item['source_finding_key']}".encode() - ).hexdigest() + digest = hashlib.sha256(f"{run['run_id']}\0{item['source_finding_key']}".encode()).hexdigest() decision_id = f"batch-{digest[:16]}-{digest[16:32]}" decision = { "source_finding_key": item["source_finding_key"], @@ -709,9 +713,7 @@ def _load_records_import( raise CliError("source decision has missing or unsupported fields") decision = dict(item) if "decision_id" not in decision: - digest = hashlib.sha256( - f"{run['run_id']}\0{decision['source_finding_key']}".encode() - ).hexdigest() + digest = hashlib.sha256(f"{run['run_id']}\0{decision['source_finding_key']}".encode()).hexdigest() decision["decision_id"] = f"batch-{digest[:16]}-{digest[16:32]}" normalized_decisions.append(decision) decisions = normalized_decisions @@ -729,8 +731,7 @@ def _subagent_findings( if len(raw.encode("utf-8")) > 4096: raise CliError("one subagent finding exceeds 4 KB") try: - item = json.loads(raw, object_pairs_hook=_reject_duplicate_json_keys, - parse_constant=_reject_json_constant) + item = json.loads(raw, object_pairs_hook=_reject_duplicate_json_keys, parse_constant=_reject_json_constant) except (ValueError, TypeError) as exc: raise CliError(f"subagent finding {index} is not valid JSON") from exc if not isinstance(item, dict) or not {"title", "decision", "reason"} <= item.keys(): @@ -744,18 +745,20 @@ def _subagent_findings( if target is not None and (type(target) is not int or target <= 0 or decision != "routed"): raise CliError(f"subagent finding {index} has an invalid target PR") key = item.get("key", f"subagent:{run_id}:finding:{index}") - observations.append(FindingObservation( - source_finding_key=key, title=item["title"], detail=item.get("detail", "") - )) + observations.append( + FindingObservation(source_finding_key=key, title=item["title"], detail=item.get("detail", "")) + ) digest = hashlib.sha256(f"{run_id}\0{key}".encode()).hexdigest() - decisions.append({ - "source_finding_key": key, - "decision_id": f"subagent-{digest}", - "decision": decision, - "actor": actor, - "reason": item["reason"], - **({"target_pr": target} if target is not None else {}), - }) + decisions.append( + { + "source_finding_key": key, + "decision_id": f"subagent-{digest}", + "decision": decision, + "actor": actor, + "reason": item["reason"], + **({"target_pr": target} if target is not None else {}), + } + ) return tuple(observations), tuple(decisions) @@ -768,10 +771,9 @@ def _failed_cli_attempts_from_history(history: dict[str, Any]) -> dict[str, Any] "failed": "provider_failed", } candidates = [ - attempt for attempt in history["attempts"] - if attempt["channel"] == "cli" - and attempt["state"] in outcomes - and isinstance(attempt["finished_at"], str) + attempt + for attempt in history["attempts"] + if attempt["channel"] == "cli" and attempt["state"] in outcomes and isinstance(attempt["finished_at"], str) ] candidates.sort(key=lambda attempt: (attempt["finished_at"], attempt["attempt_id"]), reverse=True) attempts = [] @@ -782,12 +784,14 @@ def _failed_cli_attempts_from_history(history: dict[str, Any]) -> dict[str, Any] origin = attempt.get("origin") if origin not in {"legacy_private_capture", "sqlite_records"}: origin = "sqlite_records" - attempts.append({ - "run_id": attempt["attempt_id"], - "finished_at": attempt["finished_at"], - "outcome": outcome, - "origin": origin, - }) + attempts.append( + { + "run_id": attempt["attempt_id"], + "finished_at": attempt["finished_at"], + "outcome": outcome, + "origin": origin, + } + ) return {"available": True, "attempts": attempts[:5]} @@ -900,37 +904,65 @@ def _dispatch_records(args: argparse.Namespace) -> tuple[Any, int]: for checkpoint in checkpoints: try: outcome = sqlite_records_repair.repair_provider_checkpoints( - store, repo=repo, pr_number=args.pr, checkpoints=(checkpoint,), - actor=args.actor, scope=args.scope, - coverage_limits=args.coverage_limit, hosted_payload=payload, + store, + repo=repo, + pr_number=args.pr, + checkpoints=(checkpoint,), + actor=args.actor, + scope=args.scope, + coverage_limits=args.coverage_limit, + hosted_payload=payload, dry_run=not args.apply, ) - items.append({"checkpoint_id": checkpoint.comment_id, "status": outcome["status"], - "items": outcome["items"], - **({"error": outcome["error"]} if outcome.get("error") else {})}) + items.append( + { + "checkpoint_id": checkpoint.comment_id, + "status": outcome["status"], + "items": outcome["items"], + **({"error": outcome["error"]} if outcome.get("error") else {}), + } + ) except sqlite_records_repair.MissingHistoricalEvidenceError as exc: try: gap = sqlite_records_repair.archive_incomplete_checkpoint( - store, repo=repo, pr_number=args.pr, checkpoint=checkpoint, - missing_reason=str(exc), hosted_payload=payload, + store, + repo=repo, + pr_number=args.pr, + checkpoint=checkpoint, + missing_reason=str(exc), + hosted_payload=payload, dry_run=not args.apply, ) except sqlite_records_repair.SqliteRecordsRepairError as gap_error: - items.append({"checkpoint_id": checkpoint.comment_id, - "status": "unavailable", "error": str(exc), - "archive_error": str(gap_error)}) + items.append( + { + "checkpoint_id": checkpoint.comment_id, + "status": "unavailable", + "error": str(exc), + "archive_error": str(gap_error), + } + ) else: - items.append({"checkpoint_id": checkpoint.comment_id, - "status": "incomplete", "missing_evidence": str(exc), - "gap": gap}) + items.append( + { + "checkpoint_id": checkpoint.comment_id, + "status": "incomplete", + "missing_evidence": str(exc), + "gap": gap, + } + ) except sqlite_records_repair.SqliteRecordsRepairError as exc: - items.append({"checkpoint_id": checkpoint.comment_id, - "status": "unavailable", "error": str(exc)}) + items.append({"checkpoint_id": checkpoint.comment_id, "status": "unavailable", "error": str(exc)}) partial = any(item["status"] in {"unavailable", "incomplete", "partial"} for item in items) - return {"api_version": 1, "result": { - "status": "partial" if partial else "complete" if args.apply else "preview", - "dry_run": not args.apply, "source_pr": args.pr, "items": items, - }}, 2 if partial else 0 + return { + "api_version": 1, + "result": { + "status": "partial" if partial else "complete" if args.apply else "preview", + "dry_run": not args.apply, + "source_pr": args.pr, + "items": items, + }, + }, 2 if partial else 0 result = sqlite_records_repair.repair_provider_checkpoints( store, repo=repo, @@ -946,7 +978,9 @@ def _dispatch_records(args: argparse.Namespace) -> tuple[Any, int]: if args.records_command == "sync-hosted": store.history(args.pr or 1) # Refuse incompatible or unbootstrapped writers before any live read. result = sqlite_hosted_capture.sync_hosted_pending( - store, repo=github.infer_repo(args.repo), pr_number=args.pr, + store, + repo=github.infer_repo(args.repo), + pr_number=args.pr, ) unresolved = any(result.get(bucket) for bucket in ("pending", "ambiguous", "errors")) return {"api_version": 1, "result": result}, 2 if unresolved else 0 @@ -969,16 +1003,24 @@ def _dispatch_records(args: argparse.Namespace) -> tuple[Any, int]: key = f"cli-run:{args.run_id}:finding:{args.finding}" digest = hashlib.sha256(f"{args.run_id}\0{key}".encode()).hexdigest() result = store.record_source_decision( - args.run_id, key, - decision_id=f"cli-{digest}", decision=args.decision, - actor=args.actor, reason=args.reason, target_pr=args.target_pr, + args.run_id, + key, + decision_id=f"cli-{digest}", + decision=args.decision, + actor=args.actor, + reason=args.reason, + target_pr=args.target_pr, ) return {"api_version": 1, "result": result}, 0 if args.records_command == "cli-correct": result = store.correct_source_decision( - args.run_id, f"cli-run:{args.run_id}:finding:{args.finding}", - supersedes_id=args.supersedes_id, correction_id=args.correction_id, - decision=args.decision, actor=args.actor, reason=args.reason, + args.run_id, + f"cli-run:{args.run_id}:finding:{args.finding}", + supersedes_id=args.supersedes_id, + correction_id=args.correction_id, + decision=args.decision, + actor=args.actor, + reason=args.reason, ) return {"api_version": 1, "result": result}, 0 if args.records_command == "subagent": @@ -1003,17 +1045,18 @@ def _dispatch_records(args: argparse.Namespace) -> tuple[Any, int]: if attempt["state"] != "started": raise CliError("only a started subagent pass can fail") result = store.finish_attempt( - args.run_id, state="failed", diagnostic=args.reason, + args.run_id, + state="failed", + diagnostic=args.reason, ) else: if attempt["state"] not in {"started", "completed"}: raise CliError("only a started or completed subagent pass can be recorded") - observations, decisions = _subagent_findings( - args.run_id, args.actor, args.finding_json - ) + observations, decisions = _subagent_findings(args.run_id, args.actor, args.finding_json) metadata = attempt["metadata"] - prior = next((run for run in store.history(attempt["source_pr"])["runs"] - if run["run_id"] == args.run_id), None) + prior = next( + (run for run in store.history(attempt["source_pr"])["runs"] if run["run_id"] == args.run_id), None + ) finished_at = prior["finished_at"] if prior else attempt["finished_at"] if not isinstance(finished_at, str) or not finished_at: finished_at = datetime.now(timezone.utc).isoformat(timespec="seconds") @@ -1105,8 +1148,7 @@ def _render_selected_pr_status(report: Mapping[str, Any]) -> str: route_state = report.get("record_route_store", {}) record_routes = report.get("incoming_record_routes", []) lines.append( - f"SQLite review-record routes: {route_state.get('status', 'unavailable')} · " - f"incoming-open={len(record_routes)}" + f"SQLite review-record routes: {route_state.get('status', 'unavailable')} · incoming-open={len(record_routes)}" ) for route in record_routes: lines.append( @@ -1135,10 +1177,14 @@ def _dispatch(args: argparse.Namespace) -> tuple[Any, int]: if args.acceptance_fixture is not None or args.state_path is not None: raise CliError("wait commands do not accept acceptance-fixture options") return hosted_wait.wait_for_hosted( - github.infer_repo(args.repo), args.pr, args.trigger_id, + github.infer_repo(args.repo), + args.pr, + args.trigger_id, poll_seconds=args.poll_seconds, max_wait_seconds=args.max_wait_minutes * 60, - on_change=lambda state: print(f"Hosted #{args.pr} trigger {args.trigger_id}: {state}", file=sys.stderr, flush=True), + on_change=lambda state: print( + f"Hosted #{args.pr} trigger {args.trigger_id}: {state}", file=sys.stderr, flush=True + ), ) controller, fixture = _controller(args) @@ -1169,7 +1215,9 @@ def _dispatch(args: argparse.Namespace) -> tuple[Any, int]: incoming_routes = ( stack_item.get("incoming_routes", []) if stack_item is not None else stack_report.get("incoming_routes", []) ) - outgoing_routes = stack_item.get("routes_out", []) if stack_item is not None else stack_report.get("routes_out", []) + outgoing_routes = ( + stack_item.get("routes_out", []) if stack_item is not None else stack_report.get("routes_out", []) + ) report["incoming_routes"] = incoming_routes report["routes_out"] = outgoing_routes record_routes, record_route_state = _read_record_incoming_routes(args.pr) @@ -1200,12 +1248,12 @@ def _dispatch(args: argparse.Namespace) -> tuple[Any, int]: if stack_item["reconciliation"] != "COHERENT": review_reasons.append(f"review stack is {stack_item['reconciliation']}") for channel, state in stack_item["channels"].items(): + if state not in {"COMPLETE", "HUMAN_STOPPED"}: + review_reasons.append(f"{channel} review policy is {state}") if state == "HUMAN_STOPPED": - review_reasons.append( - f"{channel} review discovery was explicitly stopped; this is not taper or merge-readiness proof" + review_reasons.extend( + f"{channel}: {reason}" for reason in stack_item.get("review_obligations", {}).get(channel, ()) ) - elif state != "COMPLETE": - review_reasons.append(f"{channel} review policy is {state}") for channel, allocation in stack_item.get("allocations", {}).items(): if allocation["status"] not in {"HANDED_OFF", "STOPPED"}: review_reasons.append( @@ -1289,7 +1337,9 @@ def _dispatch(args: argparse.Namespace) -> tuple[Any, int]: routes = [] if decision == "routed": if len(args.route_finding) != args.count or len(args.route_observation) != args.count: - raise CliError("routed summary disposition requires one stable finding reference and observation per item") + raise CliError( + "routed summary disposition requires one stable finding reference and observation per item" + ) if len(set(args.route_finding)) != len(args.route_finding): raise CliError("routed summary finding references must be unique") routes = [ @@ -1358,9 +1408,7 @@ def record(current): if args.action == "open": required = (args.source_pr, args.channel, args.review, args.finding, args.observation) if any(value is None for value in required) or args.route_id or args.reason or args.proof: - raise CliError( - "route open requires --source-pr, --channel, --review, --finding, and --observation" - ) + raise CliError("route open requires --source-pr, --channel, --review, --finding, and --observation") return controller.record_route( source_pr=args.source_pr, source_channel=args.channel, @@ -1450,7 +1498,9 @@ def record(current): f"off-queue manual Hosted adoption requires the live {label} branch tip to match origin" ) if not controller.git.is_ancestor(candidate.base_tip, candidate.head): - raise CliError("off-queue manual Hosted adoption requires the live base to be an ancestor of the head") + raise CliError( + "off-queue manual Hosted adoption requires the live base to be an ancestor of the head" + ) link = stack.ParentLink(args.pr, None, candidate.base_ref, candidate.base_tip) anchor_data = controller._anchor(args.pr, candidate, link).as_dict() return hosted.adopt_manual_completed_trigger( @@ -1479,9 +1529,7 @@ def record(current): if type(trigger_id) is int and trigger_id == args.trigger_id: matching_paths.append(path) if len(matching_paths) != 1: - raise CliError( - f"PR #{args.pr} requires exactly one durable Hosted trigger with ID {args.trigger_id}" - ) + raise CliError(f"PR #{args.pr} requires exactly one durable Hosted trigger with ID {args.trigger_id}") return hosted.retire_trigger_record( matching_paths[0], controller.repository, diff --git a/dev-tools/pr_review/cli_runner.py b/dev-tools/pr_review/cli_runner.py index 0d72e992b5..641d8ed12a 100644 --- a/dev-tools/pr_review/cli_runner.py +++ b/dev-tools/pr_review/cli_runner.py @@ -785,11 +785,7 @@ def _validate_target( candidate_sha, timeout=git_timeout_seconds, ) - if ( - candidate_sha == child_head - and target.patch_identity - and candidate_patch != target.patch_identity - ): + if candidate_sha == child_head and target.patch_identity and candidate_patch != target.patch_identity: raise ReviewRunnerError("published owned-patch identity changed since target selection") candidate_count = len( _nul_paths( @@ -835,6 +831,7 @@ def run_cli_review( review_timeout_seconds: float = CODERABBIT_TIMEOUT_SECONDS, monotonic_ns: Callable[[], int] = time.monotonic_ns, records: SqliteReviewRecords | None = None, + admit: Callable[[Callable[[], None]], None] | None = None, ) -> ReviewResult: """Run one isolated committed CLI review for an already-selected target. @@ -1094,12 +1091,19 @@ def run_cli_review( "provisional": str(allow_unreconciled).lower(), "reason": reason or "", } - (capture_dir / "metadata").write_text( - "".join(f"{key}={value}\n" for key, value in legacy_metadata.items()), - encoding="utf-8", - ) - os.chmod(capture_dir / "metadata", 0o600) - _atomic_json(capture_dir / "metadata.json", metadata) + + def reserve() -> None: + (capture_dir / "metadata").write_text( + "".join(f"{key}={value}\n" for key, value in legacy_metadata.items()), + encoding="utf-8", + ) + os.chmod(capture_dir / "metadata", 0o600) + _atomic_json(capture_dir / "metadata.json", metadata) + + if admit is None: + reserve() + else: + admit(reserve) records_warning = None if records is not None: attempt_started_at = datetime.now(timezone.utc).isoformat(timespec="seconds") @@ -1170,11 +1174,15 @@ def run_cli_review( if records is not None: try: records.finish_attempt( - run_id, state="timed_out", + run_id, + state="timed_out", duration_seconds=duration, diagnostic="CodeRabbit CLI timed out before a complete result", - artifacts={"cli_raw_output": stdout, "cli_diagnostic": stderr, - "metadata": json.dumps(metadata, sort_keys=True)}, + artifacts={ + "cli_raw_output": stdout, + "cli_diagnostic": stderr, + "metadata": json.dumps(metadata, sort_keys=True), + }, ) except (ReviewRecordsError, OSError, sqlite3.DatabaseError): pass @@ -1206,11 +1214,7 @@ def run_cli_review( try: parsed_findings, _ = evidence._parse_capture_stdout(capture_dir / "stdout") except evidence.EvidenceError: - result_state = ( - "rate_limited" - if "rate limit exceeded" in stderr.casefold() - else "failed" - ) + result_state = "rate_limited" if "rate limit exceeded" in stderr.casefold() else "failed" artifacts["cli_raw_output"] = stdout diagnostic = ( "CodeRabbit CLI was rate limited before a complete result" @@ -1243,14 +1247,14 @@ def run_cli_review( observations = [] for index, finding in enumerate(parsed_findings, 1): instructions = finding.get("codegenInstructions") - title = _cli_finding_title( - instructions, f"CodeRabbit CLI finding {index}" + title = _cli_finding_title(instructions, f"CodeRabbit CLI finding {index}") + observations.append( + FindingObservation( + source_finding_key=f"cli-run:{run_id}:finding:{index}", + title=title, + detail=_safe_finding_detail(_cli_detail(instructions)), + ) ) - observations.append(FindingObservation( - source_finding_key=f"cli-run:{run_id}:finding:{index}", - title=title, - detail=_safe_finding_detail(_cli_detail(instructions)), - )) records.complete_attempt_run( run_id, finish={ @@ -1276,8 +1280,11 @@ def run_cli_review( ) else: records.finish_attempt( - run_id, state=result_state, duration_seconds=duration, - exit_status=process.returncode, diagnostic=diagnostic, + run_id, + state=result_state, + duration_seconds=duration, + exit_status=process.returncode, + diagnostic=diagnostic, artifacts=artifacts, ) attempt_finished = True @@ -1321,7 +1328,9 @@ def run_cli_review( if records is not None and attempt_started and not attempt_finished and not provider_result_saved: try: records.finish_attempt( - run_id, state="failed", diagnostic="CLI setup or capture failed", + run_id, + state="failed", + diagnostic="CLI setup or capture failed", artifacts={"cli_diagnostic": str(error)}, ) except (ReviewRecordsError, OSError, sqlite3.DatabaseError) as archive_error: diff --git a/dev-tools/pr_review/controller.py b/dev-tools/pr_review/controller.py index 04055eb125..eebacba66b 100644 --- a/dev-tools/pr_review/controller.py +++ b/dev-tools/pr_review/controller.py @@ -14,9 +14,7 @@ from __future__ import annotations -import contextlib import dataclasses -import fcntl import re import subprocess import time @@ -35,7 +33,7 @@ StaleReviewTargetError, ) from .git_merge import TestMergeError, test_merge_tree -from .hosted import default_trigger_record_path, parse_timestamp, prepare_full_trigger +from .hosted import parse_timestamp, prepare_full_trigger from .patch_identity import patch_identity from .state import ( FindingRoute, @@ -281,8 +279,8 @@ class AnchorFacts: child_head: str parent_identity: str parent_head: str - merge_base: str - patch_id: str + merge_base: str | None + patch_id: str | None def as_dict(self) -> dict[str, Any]: return dataclasses.asdict(self) @@ -464,7 +462,12 @@ def _review_activity(history: Sequence[Any], current_head: str) -> dict[str, Any "non_counting": _field(item, "non_counting") is True, } ) - return {"total": len(results), "recent": results[-5:]} + active = [ + {"checkpoint": _field(item, "checkpoint"), "head": _field(item, "head"), "reason": _field(item, "reason")} + for item in history + if _field(item, "active_review") is True or _field(item, "active_reservation") is True + ] + return {"total": len(results), "recent": results[-5:], "active": active} def _channel_reasons(history: Sequence[Any], current_head: str) -> list[dict[str, Any]]: @@ -484,7 +487,9 @@ def _channel_reasons(history: Sequence[Any], current_head: str) -> list[dict[str reason = _field(item, "reason") results.append( { - "reason": reason if isinstance(reason, str) and reason.strip() else "provider file ceiling limits review coverage", + "reason": reason + if isinstance(reason, str) and reason.strip() + else "provider file ceiling limits review coverage", "source": checkpoint, "non_counting": True, } @@ -537,9 +542,7 @@ def _state(self) -> ReviewState: return self.store.load() @staticmethod - def _legacy_transition_for( - state: ReviewState, pr: int, anchor: AnchorFacts - ) -> LegacyEvidenceTransition | None: + def _legacy_transition_for(state: ReviewState, pr: int, anchor: AnchorFacts) -> LegacyEvidenceTransition | None: """Return the newest exact-anchor legacy transition, if any.""" for transition in reversed(state.legacy_transitions): @@ -632,9 +635,7 @@ def _policy_history( """ history = self._cached_history(pr, channel, history_cache, phase_timings=phase_timings) - selected = set( - reconciliation.legacy_transition_fingerprints.get(pr, {}).get(channel.value, ()) - ) + selected = set(reconciliation.legacy_transition_fingerprints.get(pr, {}).get(channel.value, ())) if not selected: projected = [self._clear_untrusted_non_counting(value) for value in history] return self._project_cli_hosted_ambiguity(channel, projected) @@ -665,9 +666,9 @@ def _cached_history( history_cache[key] = _history(self._evidence_provider, pr, channel) finally: if phase_timings is not None: - phase_timings["deep_evidence_history_ms"] = phase_timings.get( - "deep_evidence_history_ms", 0.0 - ) + (time.perf_counter() - started) * 1000 + phase_timings["deep_evidence_history_ms"] = ( + phase_timings.get("deep_evidence_history_ms", 0.0) + (time.perf_counter() - started) * 1000 + ) return history_cache[key] @staticmethod @@ -724,11 +725,7 @@ def _project_cli_hosted_reservations( trigger_match = re.fullmatch(r"trigger:([1-9][0-9]*)", checkpoint) trigger_id = _field(value, "trigger_id") exact_trigger = trigger_match is not None and ( - trigger_id is None - or ( - type(trigger_id) is int - and trigger_id == int(trigger_match.group(1)) - ) + trigger_id is None or (type(trigger_id) is int and trigger_id == int(trigger_match.group(1))) ) terminal_ambiguity = ( _field(value, "terminal_ambiguous") is True @@ -809,9 +806,7 @@ def _cli_streak_review(value: Any, expected_pr: int) -> tuple[str | None, Anchor return head, None try: child_head = _sha(_field(value, "child_head", "candidate_sha"), "CLI review child head") - parent_head = _sha( - _field(value, "parent_head", "parent_sha", "base_tip_sha"), "CLI review parent head" - ) + parent_head = _sha(_field(value, "parent_head", "parent_sha", "base_tip_sha"), "CLI review parent head") merge_base = _sha(_field(value, "merge_base"), "CLI review merge base") except ControllerError: return head, None @@ -952,9 +947,7 @@ def _project_cli_streak_lineage( dataclasses.is_dataclass(current_value) and hasattr(current_value, "current_candidate_descendant_proven") ): - current_value = dataclasses.replace( - current_value, current_candidate_descendant_proven=True - ) + current_value = dataclasses.replace(current_value, current_candidate_descendant_proven=True) projected[last_index] = current_value return projected @@ -1186,8 +1179,7 @@ def is_ancestor(parent: str, child: str) -> bool: finally: if phase_timings is not None: phase_timings["local_anchors_ms"] = ( - phase_timings.get("local_anchors_ms", 0.0) - + (time.perf_counter() - anchor_started) * 1000 + phase_timings.get("local_anchors_ms", 0.0) + (time.perf_counter() - anchor_started) * 1000 ) except (ControllerError, OSError, subprocess.SubprocessError, ValueError) as error: anchor_failures[pr] = f"could not compute current Git anchor: {type(error).__name__}: {error}" @@ -1200,11 +1192,7 @@ def is_ancestor(parent: str, child: str) -> bool: "hosted": transition.hosted_fingerprints, "cli": transition.cli_fingerprints, } - decision = ( - self._active_stack_reconciliation(state, pr, current) - if pr in selected_evidence_prs - else None - ) + decision = self._active_stack_reconciliation(state, pr, current) if pr in selected_evidence_prs else None if decision is not None: reconciled[pr] = decision anchored: dict[int, str] = {} @@ -1364,9 +1352,10 @@ def set_channel_anchor_status(pr: int, channel: policy.Channel, status: stack.Re current = self._anchor(pr, live[pr], link) finally: if phase_timings is not None: - phase_timings["local_anchors_ms"] = phase_timings.get( - "local_anchors_ms", 0.0 - ) + (time.perf_counter() - anchor_started) * 1000 + phase_timings["local_anchors_ms"] = ( + phase_timings.get("local_anchors_ms", 0.0) + + (time.perf_counter() - anchor_started) * 1000 + ) except (ControllerError, OSError, subprocess.SubprocessError, ValueError) as error: reason = f"could not compute current Git anchor: {type(error).__name__}: {error}" anchor_failures[pr] = reason @@ -1532,10 +1521,7 @@ def _current_branches_match( if _sha(remote_heads[item.base_ref], f"PR #{candidate} base branch") != item.base_tip: return False if item.head_ref: - if ( - item.head_repository is None - or item.head_repository.casefold() != self.repository.casefold() - ): + if item.head_repository is None or item.head_repository.casefold() != self.repository.casefold(): return False if item.head_ref not in remote_heads: return False @@ -1612,6 +1598,23 @@ def _test_merge_tree(self, base: str, head: str) -> str: self._test_merge_tree_cache[identity] = tree return tree + def _accepted_findings_pending(self, value: Any, current_head: str) -> bool: + accepted = _field(value, "accepted") + if not ( + _field(value, "completed") is True + and _field(value, "attributable") is True + and type(accepted) is int + and accepted > 0 + ): + return False + reviewed_head = _field(value, "head", "reviewed_head") + if not isinstance(reviewed_head, str) or reviewed_head.casefold() == current_head.casefold(): + return True + try: + return not self.git.is_ancestor(_sha(reviewed_head, "accepted finding head"), current_head) + except (ControllerError, OSError, ValueError, subprocess.SubprocessError): + return True + @staticmethod def _legacy_transition_record(value: Any, pr: int, current_head: str) -> None: """Validate one observation before allowing it into the legacy set.""" @@ -1667,11 +1670,7 @@ def _legacy_transition_record(value: Any, pr: int, current_head: str) -> None: # linkage. Active reservations, pending captures, and unresolved # findings use different identities and remain hard blockers. if item.held: - if ( - LEGACY_UNCHECKPOINTED.fullmatch(item.checkpoint) is None - or item.completed - or item.attributable - ): + if LEGACY_UNCHECKPOINTED.fullmatch(item.checkpoint) is None or item.completed or item.attributable: raise ControllerError("legacy transition cannot dismiss an active or actionable reservation") elif item.completed is not True or item.attributable is not True: raise ControllerError("legacy transition cannot dismiss incomplete or unattributable evidence") @@ -1749,7 +1748,9 @@ def _reauthorization_observation(value: Any, pr: int) -> None: try: _sha(item.head, "legacy transition modern evidence head") except ControllerError as error: - raise ControllerError("legacy transition reauthorization requires exact modern evidence identity") from error + raise ControllerError( + "legacy transition reauthorization requires exact modern evidence identity" + ) from error if not isinstance(item.checkpoint, str) or not item.checkpoint.strip(): raise ControllerError("legacy transition reauthorization requires an immutable modern checkpoint") if item.provisional or item.held or item.rate_limited or item.unstable or item.unreconciled: @@ -1788,9 +1789,7 @@ def _require_complete_reauthorization_audit( audit_method = getattr(self._evidence_provider, "legacy_transition_reauthorization_audit", None) if not callable(audit_method): - raise ControllerError( - "missing Hosted fingerprint retirement requires a complete paginated evidence audit" - ) + raise ControllerError("missing Hosted fingerprint retirement requires a complete paginated evidence audit") try: audit = audit_method(pr, tuple(hosted_fingerprints), current) except ControllerError: @@ -1930,10 +1929,7 @@ def decide_legacy_transition( channel_fingerprints.append(observation_fingerprint(value)) fingerprints[channel.value] = tuple(dict.fromkeys(channel_fingerprints)) if newly_missing_hosted: - if ( - retire_missing_hosted_fingerprint is None - or newly_missing_hosted != {retire_missing_hosted_fingerprint} - ): + if retire_missing_hosted_fingerprint is None or newly_missing_hosted != {retire_missing_hosted_fingerprint}: raise ControllerError( "reauthorization lost Hosted evidence; retirement requires the exact sole missing prior fingerprint" ) @@ -1974,6 +1970,7 @@ def decide_legacy_transition( "legacy_transitions": [item.to_dict() for item in state.legacy_transitions], "recorded": False, } + def append_transition(current_state: ReviewState) -> ReviewState: if current_state.legacy_transitions != state.legacy_transitions: raise ControllerError("legacy transitions changed concurrently; reread before deciding") @@ -1992,9 +1989,7 @@ def append_transition(current_state: ReviewState) -> ReviewState: "recorded": True, } - def _assert_transition_anchor_still_current( - self, state: ReviewState, pr: int, expected: AnchorFacts - ) -> None: + def _assert_transition_anchor_still_current(self, state: ReviewState, pr: int, expected: AnchorFacts) -> None: """Recheck the complete live anchor after a missing-record audit.""" remote_heads = self.git.remote_heads() @@ -2015,7 +2010,9 @@ def _assert_transition_anchor_still_current( raise ControllerError("topology changed during missing Hosted fingerprint retirement") after = self._anchor(pr, live[pr], baseline.links[pr]) if after.as_dict() != expected.as_dict(): - raise ControllerError("PR head, parent, merge-base, or patch changed during missing Hosted fingerprint retirement") + raise ControllerError( + "PR head, parent, merge-base, or patch changed during missing Hosted fingerprint retirement" + ) # Keep the shorter spelling available to callers of the controller API; # the CLI's canonical operation is ``decide transition``. @@ -2068,49 +2065,6 @@ def decide_reconciliation( ) return {"decision": decision.to_dict(), "reconciliations": [item.to_dict() for item in updated.reconciliations]} - def _stop_lock_paths(self, pr: int) -> tuple[Path, Path]: - """Return the same CLI and Hosted request locks used by review runners.""" - - if self.store.path.name == "pr-review-stack.json" and self.store.path.parent.name == "firemud": - common = self.store.path.parent.parent - cli_path = common / "firemud" / "pr-review" / "cli.lock" - hosted_path = default_trigger_record_path(self.repository, pr, common).parent / "request.lock" - else: - lock_root = self.store.path.parent / ".pr-review-stop-locks" - cli_path = lock_root / "cli.lock" - hosted_path = lock_root / f"hosted-pr-{pr}.lock" - return cli_path, hosted_path - - @contextlib.contextmanager - def _stop_review_locks(self, pr: int, channel: str): - """Prevent the stop decision from racing an active channel review.""" - - handles = [] - try: - lock_paths = self._stop_lock_paths(pr) - # Hosted request locks are scoped to one PR. A Hosted stop must - # not be coupled to the repository-wide CLI lock, which may be - # held by an unrelated PR. CLI stops retain both locks because a - # CLI run owns the repository-wide lock and the target request - # lock while it performs its preflight. - if channel == policy.Channel.HOSTED.value: - lock_paths = (lock_paths[1],) - for path in lock_paths: - path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) - handle = path.open("a+") - handles.append(handle) - try: - fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) - except BlockingIOError as exc: - raise ControllerError(f"cannot stop review discovery while a review is active ({path.name})") from exc - yield - finally: - for handle in reversed(handles): - try: - fcntl.flock(handle.fileno(), fcntl.LOCK_UN) - finally: - handle.close() - @staticmethod def _stop_reason(reason: Any) -> str: if not isinstance(reason, str) or not reason.strip() or len(reason) > 500: @@ -2121,18 +2075,12 @@ def _stop_reason(reason: Any) -> str: @staticmethod def _stop_reason_acknowledges_over_ceiling(reason: str | None) -> bool: - return isinstance(reason, str) and reason.startswith( - "[acknowledged current over-ceiling limitation] " - ) + return isinstance(reason, str) and reason.startswith("[acknowledged current over-ceiling limitation] ") @staticmethod def _stop_summary_fingerprints(state: ReviewState, pr: int) -> tuple[str, ...]: return tuple( - sorted( - observation_fingerprint(item.to_dict()) - for item in state.summary_dispositions - if item.pr == pr - ) + sorted(observation_fingerprint(item.to_dict()) for item in state.summary_dispositions if item.pr == pr) ) def _latest_stop_checkpoint( @@ -2234,9 +2182,7 @@ def _stop_audit( } elif callable(getattr(provider, "legacy_transition_reauthorization_audit", None)): try: - audit = provider.legacy_transition_reauthorization_audit( - pr, (), current.as_dict() - ) + audit = provider.legacy_transition_reauthorization_audit(pr, (), current.as_dict()) except (OSError, ValueError, TypeError, KeyError) as exc: raise ControllerError(f"complete review-stop evidence is unavailable: {exc}") from exc else: @@ -2380,7 +2326,9 @@ def _stop_audit( if not isinstance(historical_unmatched, Sequence) or isinstance(historical_unmatched, (str, bytes)): raise ControllerError("review-stop audit has malformed historical unmatched-response evidence") if historical_unmatched and not allow_historical_unmatched: - raise ControllerError("review stop is blocked by historical unmatched evidence outside a direct Hosted stop") + raise ControllerError( + "review stop is blocked by historical unmatched evidence outside a direct Hosted stop" + ) return normalized_audit def _stop_ambiguity_pins( @@ -2392,10 +2340,7 @@ def _stop_ambiguity_pins( ) -> tuple[tuple[str, ...], str | None]: historical_fingerprints = set(audit.get("historical_terminal_fingerprints", ())) candidates = [ - value - for history in histories.values() - for value in history - if _field(value, "terminal_ambiguous") is True + value for history in histories.values() for value in history if _field(value, "terminal_ambiguous") is True ] if not fingerprints: if candidates or reason is not None: @@ -2411,15 +2356,16 @@ def _stop_ambiguity_pins( raise ControllerError("ambiguity retention reason must not contain control characters") candidate_fingerprints = [_field(value, "fingerprint") for value in candidates] if ( - any(not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value) for value in candidate_fingerprints) + any( + not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value) + for value in candidate_fingerprints + ) or len(set(candidate_fingerprints)) != len(candidate_fingerprints) or not set(candidate_fingerprints).issubset(set(fingerprints) | historical_fingerprints) ): raise ControllerError("retained ambiguity fingerprints must identify every current terminal response") audit_fingerprints = [ - item.get("fingerprint") - for item in audit.get("retained_ambiguous", ()) - if isinstance(item, Mapping) + item.get("fingerprint") for item in audit.get("retained_ambiguous", ()) if isinstance(item, Mapping) ] if ( len(audit_fingerprints) != len(audit.get("retained_ambiguous", ())) @@ -2447,9 +2393,7 @@ def _check_stop_evidence( history_cache: dict[tuple[int, str], list[Any]] | None = None, ) -> tuple[Any, tuple[tuple[str, ...], str] | None, dict[policy.Channel, list[Any]]]: histories = { - selected: self._policy_history( - state, pr, selected, reconciliation, history_cache=history_cache - ) + selected: self._policy_history(state, pr, selected, reconciliation, history_cache=history_cache) for selected in (policy.Channel.HOSTED, policy.Channel.CLI) } acknowledged_over_ceiling_checkpoints: tuple[str, ...] = () @@ -2459,16 +2403,11 @@ def _check_stop_evidence( for history in histories.values(): for value in history: checkpoint = _field(value, "checkpoint", "checkpoint_id") - if ( - isinstance(checkpoint, str) - and checkpoint.startswith("over-ceiling:") - ): + if isinstance(checkpoint, str) and checkpoint.startswith("over-ceiling:"): fingerprint = observation_fingerprint(value) previous_fingerprint = over_ceiling_fingerprints.get(checkpoint) if previous_fingerprint is not None and previous_fingerprint != fingerprint: - raise ControllerError( - "conflicting duplicate over-ceiling checkpoint metadata" - ) + raise ControllerError("conflicting duplicate over-ceiling checkpoint metadata") over_ceiling_fingerprints[checkpoint] = fingerprint over_ceiling_by_checkpoint[checkpoint] = value acknowledged = [ @@ -2480,16 +2419,20 @@ def _check_stop_evidence( and not any( _field(value, flag) is True for flag in ( - "held", "unstable", "unreconciled", "parent_moved", - "rate_limited", "active_review", "active_reservation", "actionable", + "held", + "unstable", + "unreconciled", + "parent_moved", + "rate_limited", + "active_review", + "active_reservation", + "actionable", ) ) ) ] if not acknowledged: - raise ControllerError( - "over-ceiling acknowledgment requires unique current-head over-ceiling evidence" - ) + raise ControllerError("over-ceiling acknowledgment requires unique current-head over-ceiling evidence") acknowledged_over_ceiling_checkpoints = tuple(acknowledged) cache_key = ( pr, @@ -2522,10 +2465,11 @@ def _check_stop_evidence( non_blocking_ambiguity_fingerprints = set(retained_fingerprints) | set( audit.get("historical_terminal_fingerprints", ()) ) - non_blocking_rate_limits = { - item["trigger_id"]: item - for item in audit.get("terminal_rate_limits", ()) - } if allow_historical_terminal_ambiguity else {} + non_blocking_rate_limits = ( + {item["trigger_id"]: item for item in audit.get("terminal_rate_limits", ())} + if allow_historical_terminal_ambiguity + else {} + ) for selected, history in histories.items(): parsed_history = [policy.Evidence.from_value(value) for value in history] valid_review_indexes = [ @@ -2540,9 +2484,7 @@ def _check_stop_evidence( ] last_valid_review_index = max(valid_review_indexes, default=-1) last_valid_review_head = ( - parsed_history[last_valid_review_index].head - if last_valid_review_index >= 0 - else None + parsed_history[last_valid_review_index].head if last_valid_review_index >= 0 else None ) for index, (value, evidence_value) in enumerate(zip(history, parsed_history, strict=True)): trigger_id = _field(value, "trigger_id") @@ -2579,7 +2521,9 @@ def _check_stop_evidence( _sha(reviewed_head, "accepted finding reviewed head") has_corrected_descendant = self.git.is_ancestor(reviewed_head, current.child_head) except (ControllerError, OSError, subprocess.SubprocessError, ValueError) as exc: - raise ControllerError("could not verify corrected-head ancestry for accepted findings") from exc + raise ControllerError( + "could not verify corrected-head ancestry for accepted findings" + ) from exc if not has_corrected_descendant or reviewed_head.casefold() == current.child_head.casefold(): raise ControllerError( "accepted findings need a published corrected head before review can stop" @@ -2603,8 +2547,14 @@ def _check_stop_evidence( and not any( _field(value, flag) is True for flag in ( - "held", "unstable", "unreconciled", "parent_moved", - "rate_limited", "active_review", "active_reservation", "actionable", + "held", + "unstable", + "unreconciled", + "parent_moved", + "rate_limited", + "active_review", + "active_reservation", + "actionable", ) ) ): @@ -2675,15 +2625,18 @@ def _check_stop_evidence( is_ancestor = self.git.is_ancestor(reviewed_head, current.child_head) except (OSError, subprocess.SubprocessError, ValueError) as exc: raise ControllerError("could not verify latest reviewed-head ancestry") from exc - equivalent_retain = self._has_stop_retain_judgment( - state, - pr, - channel.value, - _field(latest, "checkpoint", "checkpoint_id"), - reviewed_head, - current.patch_id, - reconciliation.status_for(pr, channel.value), - ) and _field(latest, "patch_id", "patch_identity") == current.patch_id + equivalent_retain = ( + self._has_stop_retain_judgment( + state, + pr, + channel.value, + _field(latest, "checkpoint", "checkpoint_id"), + reviewed_head, + current.patch_id, + reconciliation.status_for(pr, channel.value), + ) + and _field(latest, "patch_id", "patch_identity") == current.patch_id + ) if not is_ancestor and not equivalent_retain: raise ControllerError("latest reviewed head is not an ancestor of the live stop head") accepted = _field(latest, "accepted") @@ -2747,23 +2700,18 @@ def _has_stop_retain_judgment( ) -> bool: """Allow only a checkpoint-bound retain over unchanged equivalent history.""" - return ( - reconciliation == stack.ReconciliationStatus.EQUIVALENT_HISTORY - and any( - item.pr == pr - and item.channel == channel - and item.decision == "retain" - and item.head == reviewed_head - and item.checkpoint == checkpoint - and item.patch_id == current_patch_id - for item in state.judgments - ) + return reconciliation == stack.ReconciliationStatus.EQUIVALENT_HISTORY and any( + item.pr == pr + and item.channel == channel + and item.decision == "retain" + and item.head == reviewed_head + and item.checkpoint == checkpoint + and item.patch_id == current_patch_id + for item in state.judgments ) @staticmethod - def _bounded_allocation_evidence( - allocation: ReviewAllocation, history: Sequence[Any] - ) -> dict[str, Any]: + def _bounded_allocation_evidence(allocation: ReviewAllocation, history: Sequence[Any]) -> dict[str, Any]: """Project immutable completed results created after the allocation decision.""" baseline_checkpoints = set(allocation.baseline_checkpoints) @@ -2784,19 +2732,23 @@ def _bounded_allocation_evidence( "in_flight": 0, "error": "the allocation's pinned baseline checkpoint is missing or ambiguous", } - baseline = baseline_matches[0][1] if baseline_matches else next( - ( - value - for value in reversed(history) - if _field(value, "checkpoint", "checkpoint_id") in baseline_checkpoints - and _field(value, "completed") is True - and _field(value, "attributable") is True - and _field(value, "anchored") is True - and _field(value, "provisional") is not True - and _field(value, "correction") is not True - and _field(value, "non_counting") is not True - ), - None, + baseline = ( + baseline_matches[0][1] + if baseline_matches + else next( + ( + value + for value in reversed(history) + if _field(value, "checkpoint", "checkpoint_id") in baseline_checkpoints + and _field(value, "completed") is True + and _field(value, "attributable") is True + and _field(value, "anchored") is True + and _field(value, "provisional") is not True + and _field(value, "correction") is not True + and _field(value, "non_counting") is not True + ), + None, + ) ) baseline_head = _field(baseline, "head", "reviewed_head") if baseline is not None else allocation.head baseline_parent_head = _field(baseline, "parent_head", "parent_sha", "base_tip_sha") if baseline else None @@ -2833,8 +2785,7 @@ def _bounded_allocation_evidence( timeline_rows = [ value for value in history - if _field(value, "scope_timeline") is True - and _field(value, "channel") == allocation.channel + if _field(value, "scope_timeline") is True and _field(value, "channel") == allocation.channel ] if len(timeline_rows) != 1 or not ( _field(timeline_rows[0], "pr") == allocation.pr @@ -2876,9 +2827,13 @@ def _bounded_allocation_evidence( } relevant_scope_rows.append(value) - if relevant_scope_rows and baseline_checkpoint is None and any( - _field(value, "checkpoint", "checkpoint_id") not in baseline_checkpoints - for value in relevant_scope_rows + if ( + relevant_scope_rows + and baseline_checkpoint is None + and any( + _field(value, "checkpoint", "checkpoint_id") not in baseline_checkpoints + for value in relevant_scope_rows + ) ): return { "baseline": baseline, @@ -2910,11 +2865,7 @@ def _bounded_allocation_evidence( or parse_timestamp(created_at) is None or ( updated_at is not None - and ( - not isinstance(updated_at, str) - or not updated_at - or parse_timestamp(updated_at) is None - ) + and (not isinstance(updated_at, str) or not updated_at or parse_timestamp(updated_at) is None) ) ): return { @@ -2977,9 +2928,7 @@ def _bounded_allocation_evidence( and _field(value, "trigger_id") > 0 ) trigger_checkpoint = ( - re.fullmatch(r"trigger:([1-9][0-9]*)", checkpoint) - if isinstance(checkpoint, str) - else None + re.fullmatch(r"trigger:([1-9][0-9]*)", checkpoint) if isinstance(checkpoint, str) else None ) anchored_active_trigger = ( _field(value, "held") is True @@ -3007,14 +2956,11 @@ def _bounded_allocation_evidence( active_head = _field(value, "head", "reviewed_head") or anchor.get("child_head") active_child_head = _field(value, "child_head") or anchor.get("child_head") active_parent_identity = _field(value, "parent_identity") or anchor.get("parent_identity") - active_parent_head = ( - _field(value, "parent_head", "parent_sha", "base_tip_sha") - or anchor.get("parent_head") + active_parent_head = _field(value, "parent_head", "parent_sha", "base_tip_sha") or anchor.get( + "parent_head" ) active_merge_base = _field(value, "merge_base") or anchor.get("merge_base") - active_patch_id = ( - _field(value, "patch_id", "patch_identity") or anchor.get("patch_id") - ) + active_patch_id = _field(value, "patch_id", "patch_identity") or anchor.get("patch_id") if not ( _field(value, "pr") == allocation.pr and active_parent_identity == allocation.parent_identity @@ -3154,20 +3100,13 @@ def _bounded_allocation_taper_baseline( results = snapshot.get("results", ()) last_accepted = max( - ( - result.get("history_index", index) - for index, result in enumerate(results) - if result["accepted"] > 0 - ), + (result.get("history_index", index) for index, result in enumerate(results) if result["accepted"] > 0), default=-1, ) if last_accepted < 0: return allocation.baseline_checkpoints if allocation.reopens_taper else () if history is not None: - checkpoints = ( - _field(value, "checkpoint", "checkpoint_id") - for value in history[: last_accepted + 1] - ) + checkpoints = (_field(value, "checkpoint", "checkpoint_id") for value in history[: last_accepted + 1]) else: checkpoints = ( result["checkpoint"] @@ -3250,34 +3189,66 @@ def result(status: str, reason: str, *, control: str, details: str | None = None stack.ReconciliationStatus.PARENT_MOVED, stack.ReconciliationStatus.UNRECONCILED, }: - return result("INVALID", "the current stack identity is not coherent; renewed human judgment is required", control="unresolved_work") + return result( + "INVALID", + "the current stack identity is not coherent; renewed human judgment is required", + control="unresolved_work", + ) if ( current.parent_identity != allocation.parent_identity or current.parent_head != allocation.parent_head or current.merge_base != allocation.merge_base ): - return result("INVALID", "the parent or merge base changed; renewed human judgment is required", control="unresolved_work") + return result( + "INVALID", + "the parent or merge base changed; renewed human judgment is required", + control="unresolved_work", + ) try: if not self.git.is_ancestor(baseline_head, allocation.head): - return result("INVALID", "the decision baseline is outside the allocated review lineage", control="unresolved_work") + return result( + "INVALID", + "the decision baseline is outside the allocated review lineage", + control="unresolved_work", + ) if not self.git.is_ancestor(allocation.head, current.child_head): - return result("INVALID", "the live head is outside the allocated review lineage", control="unresolved_work") + return result( + "INVALID", "the live head is outside the allocated review lineage", control="unresolved_work" + ) previous_head = baseline_head for completed in snapshot["results"]: if not self.git.is_ancestor(previous_head, completed["head"]): - return result("INVALID", "post-baseline results do not form one coherent descendant lineage", control="unresolved_work") + return result( + "INVALID", + "post-baseline results do not form one coherent descendant lineage", + control="unresolved_work", + ) if not self.git.is_ancestor(completed["head"], current.child_head): - return result("INVALID", "a post-baseline result is outside the live corrected-head lineage", control="unresolved_work") + return result( + "INVALID", + "a post-baseline result is outside the live corrected-head lineage", + control="unresolved_work", + ) previous_head = completed["head"] for active_head in snapshot.get("in_flight_heads", ()): if not self.git.is_ancestor(baseline_head, active_head): - return result("INVALID", "an in-flight review is outside the allocated descendant lineage", control="unresolved_work") + return result( + "INVALID", + "an in-flight review is outside the allocated descendant lineage", + control="unresolved_work", + ) if not self.git.is_ancestor(active_head, current.child_head): - return result("INVALID", "an in-flight review is outside the live corrected-head lineage", control="unresolved_work") + return result( + "INVALID", + "an in-flight review is outside the live corrected-head lineage", + control="unresolved_work", + ) except (ControllerError, OSError, subprocess.SubprocessError, ValueError): return result("INVALID", "could not verify baseline and corrected-head ancestry", control="unresolved_work") if cap is not None and (used > cap or used + in_flight > cap): - return result("INVALID", "completed and in-flight reviews exceed the authorized cap", control="unresolved_work") + return result( + "INVALID", "completed and in-flight reviews exceed the authorized cap", control="unresolved_work" + ) if in_flight: return result( "CAP_ACTIVE", @@ -3287,9 +3258,7 @@ def result(status: str, reason: str, *, control: str, details: str | None = None ) if any(completed["accepted"] > 0 for completed in snapshot["results"]): - checkpoint_pin = ( - latest["checkpoint"] if latest else _field(baseline, "checkpoint", "checkpoint_id") - ) + checkpoint_pin = latest["checkpoint"] if latest else _field(baseline, "checkpoint", "checkpoint_id") try: self._check_stop_evidence( state, @@ -3312,9 +3281,7 @@ def result(status: str, reason: str, *, control: str, details: str | None = None details=str(error), ) - stopping_checkpoint = ( - latest["checkpoint"] if latest else _field(baseline, "checkpoint", "checkpoint_id") - ) + stopping_checkpoint = latest["checkpoint"] if latest else _field(baseline, "checkpoint", "checkpoint_id") if used < minimum: return result( "CAP_ACTIVE", @@ -3407,7 +3374,9 @@ def _allocation_progress( ) -> dict[str, Any]: """Derive consumption from immutable evidence; never persist a live observation.""" - def result(status: str, reason: str, checkpoint: str | None = None, accepted: int | None = None) -> dict[str, Any]: + def result( + status: str, reason: str, checkpoint: str | None = None, accepted: int | None = None + ) -> dict[str, Any]: completed_count = 1 if checkpoint is not None else 0 control = ( "maximum" @@ -3477,12 +3446,14 @@ def result(status: str, reason: str, checkpoint: str | None = None, accepted: in baseline = set(allocation.baseline_checkpoints) subsequent = [ - item for item in history - if _field(item, "correction") is not True - and _field(item, "checkpoint", "checkpoint_id") not in baseline + item + for item in history + if _field(item, "correction") is not True and _field(item, "checkpoint", "checkpoint_id") not in baseline ] checkpoints = [_field(item, "checkpoint", "checkpoint_id") for item in subsequent] - if any(not isinstance(value, str) or not value for value in checkpoints) or len(checkpoints) != len(set(checkpoints)): + if any(not isinstance(value, str) or not value for value in checkpoints) or len(checkpoints) != len( + set(checkpoints) + ): return result("INVALID", "post-allocation evidence has missing or duplicate checkpoint identities") matching: list[Any] = [] for item in subsequent: @@ -3536,7 +3507,9 @@ def result(status: str, reason: str, checkpoint: str | None = None, accepted: in accepted, ) if not descends_from_reviewed_head: - return result("INVALID", "the corrected head does not descend from the reviewed head", checkpoint, accepted) + return result( + "INVALID", "the corrected head does not descend from the reviewed head", checkpoint, accepted + ) if any( _field(item, flag) is True for item in history @@ -3548,7 +3521,9 @@ def result(status: str, reason: str, checkpoint: str | None = None, accepted: in and _field(item, "fingerprint") in allocation.retained_ambiguous_fingerprints ) ): - return result("EXHAUSTED_PENDING", "current review, finding, or thread obligations remain", checkpoint, accepted) + return result( + "EXHAUSTED_PENDING", "current review, finding, or thread obligations remain", checkpoint, accepted + ) if any( _field(item, "completed") is True and _field(item, "attributable") is True @@ -3559,12 +3534,26 @@ def result(status: str, reason: str, checkpoint: str | None = None, accepted: in and _field(item, "accepted") > 0 for item in history ): - return result("EXHAUSTED_PENDING", "accepted findings need a published corrected head", checkpoint, accepted) + return result( + "EXHAUSTED_PENDING", "accepted findings need a published corrected head", checkpoint, accepted + ) if allocation.handoff_checkpoint is None: - return result("EXHAUSTED_PENDING", "review allocation exhausted; an explicit stop decision is required", checkpoint, accepted) + return result( + "EXHAUSTED_PENDING", + "review allocation exhausted; an explicit stop decision is required", + checkpoint, + accepted, + ) if allocation.handoff_checkpoint != checkpoint or allocation.handoff_head != current.child_head: - return result("INVALID", "recorded handoff no longer matches the consumed review and live head", checkpoint, accepted) - return result("HANDED_OFF", "review capacity handed off; merge readiness remains a separate judgment", checkpoint, accepted) + return result( + "INVALID", "recorded handoff no longer matches the consumed review and live head", checkpoint, accepted + ) + return result( + "HANDED_OFF", + "review capacity handed off; merge readiness remains a separate judgment", + checkpoint, + accepted, + ) def _allocation_views( self, @@ -3586,11 +3575,7 @@ def _allocation_views( if allocation is None or live[pr].merged: continue cache_key = (pr, channel.value) - bounded_snapshot = ( - bounded_evidence_cache.get(cache_key) - if bounded_evidence_cache is not None - else None - ) + bounded_snapshot = bounded_evidence_cache.get(cache_key) if bounded_evidence_cache is not None else None if bounded_snapshot is None: bounded_snapshot = self._bounded_allocation_evidence(allocation, histories[pr]) if bounded_evidence_cache is not None: @@ -3674,14 +3659,17 @@ def _select_review_decision( other_anchor_status = reconciliation.status_for(pr, other.value) proven_cli_descendant = ( channel == policy.Channel.HOSTED - and ReviewController._hosted_head_mismatch_is_proven_cli_descendant( - pr, histories, reconciliation - ) + and ReviewController._hosted_head_mismatch_is_proven_cli_descendant(pr, histories, reconciliation) ) - if latest is not None and other_anchor_status not in { - stack.ReconciliationStatus.PATCH_CHANGED, - stack.ReconciliationStatus.EQUIVALENT_HISTORY, - } and not proven_cli_descendant: + if ( + latest is not None + and other_anchor_status + not in { + stack.ReconciliationStatus.PATCH_CHANGED, + stack.ReconciliationStatus.EQUIVALENT_HISTORY, + } + and not proven_cli_descendant + ): value = _field(latest, "head", "reviewed_head") if isinstance(value, str): other_heads[pr] = value @@ -3691,8 +3679,7 @@ def _select_review_decision( pr for pr in candidate_prs if any( - _field(value, "active_review") is True - or _field(value, "active_reservation") is True + _field(value, "active_review") is True or _field(value, "active_reservation") is True for value in histories[channel].get(pr, ()) ) } @@ -3701,9 +3688,7 @@ def _select_review_decision( if allocation is None: continue bounded_snapshot = ( - bounded_evidence_cache.get((pr, channel.value)) - if bounded_evidence_cache is not None - else None + bounded_evidence_cache.get((pr, channel.value)) if bounded_evidence_cache is not None else None ) if bounded_snapshot is None: bounded_snapshot = ReviewController._bounded_allocation_evidence( @@ -3728,39 +3713,28 @@ def _select_review_decision( channel, tuple(pr for pr in candidate_prs if not live[pr].merged), histories[channel], - reconciliation_by_pr={ - pr: reconciliation.status_for(pr, channel.value) for pr in candidate_prs - }, + reconciliation_by_pr={pr: reconciliation.status_for(pr, channel.value) for pr in candidate_prs}, other_channel_heads=other_heads, handed_off_prs=( pr for pr, view in channel_allocations.items() - if view["status"] in {"HANDED_OFF", "CAP_AUDITED_STOP"} - or view["status"] == "CAP_TAPERED" - ), - human_stopped_prs=( - pr for pr, view in channel_allocations.items() if view["status"] == "STOPPED" - ), - exhausted_prs=( - pr for pr, view in channel_allocations.items() if view["status"] == "EXHAUSTED_PENDING" + if view["status"] in {"HANDED_OFF", "CAP_AUDITED_STOP"} or view["status"] == "CAP_TAPERED" ), + human_stopped_prs=(pr for pr, view in channel_allocations.items() if view["status"] == "STOPPED"), + exhausted_prs=(pr for pr, view in channel_allocations.items() if view["status"] == "EXHAUSTED_PENDING"), allocation_blocks={ - pr: view["reason"] - for pr, view in channel_allocations.items() - if view["status"] == "INVALID" + pr: view["reason"] for pr, view in channel_allocations.items() if view["status"] == "INVALID" }, allocation_holds={ pr: view["reason"] for pr, view in channel_allocations.items() - if view["status"] in { + if view["status"] + in { "CAP_FINDINGS_PENDING", "CAP_EXHAUSTED_PENDING", "CAP_TAPERED_PENDING", } - or ( - view["status"] == "CAP_ACTIVE" - and view.get("selection_control") == "unresolved_work" - ) + or (view["status"] == "CAP_ACTIVE" and view.get("selection_control") == "unresolved_work") }, allocation_reopen_prs=set(allocation_reopen_prs) | { @@ -3792,8 +3766,7 @@ def _select_review_decision( and decision.target is not None and decision.status == policy.ReviewStatus.HELD and any( - _field(value, "reason") == HOSTED_CLI_OVERLAP_HOLD_REASON - and _field(value, "held") is True + _field(value, "reason") == HOSTED_CLI_OVERLAP_HOLD_REASON and _field(value, "held") is True for value in histories[channel].get(decision.target, ()) ) ): @@ -3817,8 +3790,7 @@ def _reopen_hosted_cross_channel_judgment( if ( channel != policy.Channel.HOSTED - or decision.status - not in {policy.ReviewStatus.JUDGMENT_REQUIRED, policy.ReviewStatus.READY} + or decision.status not in {policy.ReviewStatus.JUDGMENT_REQUIRED, policy.ReviewStatus.READY} or decision.target is None ): return decision @@ -3949,10 +3921,7 @@ def _hosted_head_mismatch_is_proven_cli_descendant( if ( _field(value, "active_review") is True or _field(value, "active_reservation") is True - or ( - _field(value, "held") is True - and _field(value, "reason") == HOSTED_ACTIVE_RESPONSE_REASON - ) + or (_field(value, "held") is True and _field(value, "reason") == HOSTED_ACTIVE_RESPONSE_REASON) or ( _field(value, "held") is True and isinstance(checkpoint, str) @@ -4091,11 +4060,7 @@ def _target( candidate_histories, allocations, state.ordered_prs, - allocation_reopen_prs=( - (expected_pr,) - if allow_completed_allocation and expected_pr is not None - else () - ), + allocation_reopen_prs=((expected_pr,) if allow_completed_allocation and expected_pr is not None else ()), bounded_evidence_cache=bounded_evidence_cache, ) decision = self._reopen_hosted_cross_channel_judgment( @@ -4129,8 +4094,7 @@ def _target( anchor = self._anchor(pr, item, link) test_merge = self._default_test_merge_proofs.get(pr) if test_merge is not None and ( - test_merge[0].casefold() != item.base_tip.casefold() - or test_merge[1].casefold() != item.head.casefold() + test_merge[0].casefold() != item.base_tip.casefold() or test_merge[1].casefold() != item.head.casefold() ): test_merge = None selected_target = ReviewTarget( @@ -4300,10 +4264,7 @@ def decide_route( or proof is not None ): raise ControllerError("retargeted route disposition requires --target-pr and --reason") - if ( - len(f"Retargeted: {reason}") > 500 - or any(ord(character) < 0x20 for character in reason) - ): + if len(f"Retargeted: {reason}") > 500 or any(ord(character) < 0x20 for character in reason): raise ControllerError("retarget reason must fit within a 500-character route observation") else: raise ControllerError("route disposition must be accepted-fixed, rejected, or retargeted") @@ -4317,7 +4278,9 @@ def mutate(state: ReviewState) -> ReviewState: if existing.status != "open": raise ControllerError(f"route {route_id} is already dispositioned") if decision == "accepted-fixed": - selected = dataclasses.replace(existing, status="accepted_fixed", disposition="accepted and fixed", proof=proof) + selected = dataclasses.replace( + existing, status="accepted_fixed", disposition="accepted and fixed", proof=proof + ) elif decision == "rejected": selected = dataclasses.replace(existing, status="rejected", disposition=reason) else: @@ -4375,9 +4338,10 @@ def _status_from_state( live_identity_cache[pr] = self._require_github().pull_request(pr) finally: if phase_timings is not None: - phase_timings["deep_pr_identity_ms"] = phase_timings.get( - "deep_pr_identity_ms", 0.0 - ) + (time.perf_counter() - identity_started) * 1000 + phase_timings["deep_pr_identity_ms"] = ( + phase_timings.get("deep_pr_identity_ms", 0.0) + + (time.perf_counter() - identity_started) * 1000 + ) selected_live_identities = dict(live_identities or {}) selected_live_identities.update(live_identity_cache) refresh_prs = set() @@ -4452,9 +4416,7 @@ def _status_from_state( channel_reconciliation = reconciliation.status_for(pr, channel.value) proven_cli_descendant = ( channel == policy.Channel.HOSTED - and self._hosted_head_mismatch_is_proven_cli_descendant( - pr, histories, reconciliation - ) + and self._hosted_head_mismatch_is_proven_cli_descendant(pr, histories, reconciliation) ) if allocations[channel].get(pr, {}).get("status") == "STOPPED": channel_status[channel.value] = policy.ReviewStatus.HUMAN_STOPPED.value @@ -4467,9 +4429,13 @@ def _status_from_state( taper_history = None allocation = state.allocations.get(f"{pr}:{channel.value}") bounded_snapshot = bounded_evidence_cache.get((pr, channel.value)) - if allocation is not None and bounded_snapshot is not None and ( - allocations[channel].get(pr, {}).get("reopens_taper") is True - or any(result["accepted"] > 0 for result in bounded_snapshot["results"]) + if ( + allocation is not None + and bounded_snapshot is not None + and ( + allocations[channel].get(pr, {}).get("reopens_taper") is True + or any(result["accepted"] > 0 for result in bounded_snapshot["results"]) + ) ): taper_history = policy.fresh_taper_history( state, @@ -4511,6 +4477,36 @@ def _status_from_state( "reconciliation": reconciliation_status.value, "reason": reconciliation.reasons.get(pr, ""), "channels": channel_status, + "review_obligations": { + channel.value: [ + _field(value, "reason") + or _field(value, "checkpoint") + or "review evidence requires adjudication" + for index, value in enumerate(histories[channel][pr]) + if ( + _field(value, "active_review") is True + or _field(value, "active_reservation") is True + or (_field(value, "held") is True and _field(value, "over_ceiling") is not True) + or _field(value, "unstable") is True + or ( + _field(value, "provisional") is True + and _field(value, "head") == item.head + and not any( + _field(later, "completed") is True + and _field(later, "attributable") is True + and _field(later, "anchored") is True + and _field(later, "provisional") is not True + and _field(later, "non_counting") is not True + and _field(later, "correction") is not True + for later in histories[channel][pr][index + 1 :] + ) + ) + or str(_field(value, "checkpoint") or "").startswith("pending-capture:") + or self._accepted_findings_pending(value, item.head) + ) + ] + for channel in (policy.Channel.HOSTED, policy.Channel.CLI) + }, "review_activity": { channel.value: _review_activity(histories[channel][pr], item.head) for channel in (policy.Channel.HOSTED, policy.Channel.CLI) @@ -4733,9 +4729,7 @@ def status_overview(self) -> dict[str, Any]: active_targets = { allocation.pr for allocation in state.allocations.values() - if allocation.pr in open_prs - and allocation.handoff_checkpoint is None - and allocation.stop_basis is None + if allocation.pr in open_prs and allocation.handoff_checkpoint is None and allocation.stop_basis is None } active_scan_status = "unknown" active_scan_error = None @@ -4785,25 +4779,18 @@ def status_overview(self) -> dict[str, Any]: if pr not in deep_prs: break target_scan_prs.append(pr) - target_scan_complete = all( - batch_live[pr].state != "OPEN" or pr in deep_prs for pr in state.ordered_prs - ) + target_scan_complete = all(batch_live[pr].state != "OPEN" or pr in deep_prs for pr in state.ordered_prs) try: # Deep PR metadata and complete review snapshots are independent # reads. Fetch the newly selected window together instead of # serializing each GitHub round trip. New-request preflight is # separate and still reads fresh evidence at request time. - new_deep_prs = [ - pr for pr in state.ordered_prs if pr in deep_prs and pr not in live_identity_cache - ] + new_deep_prs = [pr for pr in state.ordered_prs if pr in deep_prs and pr not in live_identity_cache] if new_deep_prs: fetch_started = time.perf_counter() prefetch_payload = getattr(self._evidence_provider, "prefetch_payload", None) with ThreadPoolExecutor(max_workers=min(8, len(new_deep_prs) * 2)) as pool: - identities = { - pr: pool.submit(self._require_github().pull_request, pr) - for pr in new_deep_prs - } + identities = {pr: pool.submit(self._require_github().pull_request, pr) for pr in new_deep_prs} evidence_reads = ( [pool.submit(prefetch_payload, pr) for pr in new_deep_prs] if callable(prefetch_payload) @@ -4813,9 +4800,9 @@ def status_overview(self) -> dict[str, Any]: live_identity_cache[pr] = identities[pr].result() for future in evidence_reads: future.result() - phase_timings["deep_pr_identity_ms"] = phase_timings.get( - "deep_pr_identity_ms", 0.0 - ) + (time.perf_counter() - fetch_started) * 1000 + phase_timings["deep_pr_identity_ms"] = ( + phase_timings.get("deep_pr_identity_ms", 0.0) + (time.perf_counter() - fetch_started) * 1000 + ) scoped_report = self._status_from_state( scoped_state, evidence_prs=deep_prs, @@ -4834,8 +4821,7 @@ def status_overview(self) -> dict[str, Any]: review_targets = scoped_report.get("review_targets", {}) if not any( - isinstance(value, Mapping) and value.get("status") == "UNKNOWN" - for value in review_targets.values() + isinstance(value, Mapping) and value.get("status") == "UNKNOWN" for value in review_targets.values() ): break scanned_count = len(target_scan_prs) @@ -4862,11 +4848,7 @@ def status_overview(self) -> dict[str, Any]: relevant_refs.add(item.base_ref) if item.head_ref: relevant_refs.add(item.head_ref) - changed_refs = { - ref - for ref in relevant_refs - if remote_heads.get(ref) != verified_remote_heads.get(ref) - } + changed_refs = {ref for ref in relevant_refs if remote_heads.get(ref) != verified_remote_heads.get(ref)} for pr in state.ordered_prs: item = batch_live[pr] if item.state != "OPEN": @@ -4888,9 +4870,7 @@ def status_overview(self) -> dict[str, Any]: scoped_report = {"review_targets": self._empty_review_targets(state)} deep_by_pr = { - item.get("pr"): item - for item in (scoped_report or {}).get("prs", []) - if isinstance(item, Mapping) + item.get("pr"): item for item in (scoped_report or {}).get("prs", []) if isinstance(item, Mapping) } mismatch: set[int] = set(remote_affected) for pr in scoped_prs: @@ -4930,10 +4910,7 @@ def status_overview(self) -> dict[str, Any]: or batch_live[pr].base_tip.casefold() != links[pr].parent_head.casefold() ) ) - or ( - pr not in deep_by_pr - and self._saved_identity_moved(state, pr, batch_live[pr], links[pr]) - ) + or (pr not in deep_by_pr and self._saved_identity_moved(state, pr, batch_live[pr], links[pr])) ), None, ) @@ -4943,9 +4920,8 @@ def status_overview(self) -> dict[str, Any]: item = batch_live[pr] parent = links[pr] detailed = deep_by_pr.get(pr) if pr in deep_prs else None - batch_topology_moved = ( - item.state == "OPEN" - and (item.base_ref != parent.parent_ref or item.base_tip.casefold() != parent.parent_head.casefold()) + batch_topology_moved = item.state == "OPEN" and ( + item.base_ref != parent.parent_ref or item.base_tip.casefold() != parent.parent_head.casefold() ) saved_identity_moved = self._saved_identity_moved(state, pr, item, parent) if detailed is not None and deep_error is None: @@ -4996,13 +4972,13 @@ def status_overview(self) -> dict[str, Any]: "merged": item.merged, "reconciliation": "UNKNOWN" if not stale else "UNRECONCILED", "reason": reason, - "channels": {"hosted": "NOT_CHECKED", "cli": "NOT_CHECKED"}, - "review_activity": {}, - "allocations": {}, - "incoming_routes": [ - route.to_dict() for route in state.routes if route.status == "open" and route.target_pr == pr - ], - "routes_out": [route.to_dict() for route in state.routes if route.source_pr == pr], + "channels": {"hosted": "NOT_CHECKED", "cli": "NOT_CHECKED"}, + "review_activity": {}, + "allocations": {}, + "incoming_routes": [ + route.to_dict() for route in state.routes if route.status == "open" and route.target_pr == pr + ], + "routes_out": [route.to_dict() for route in state.routes if route.source_pr == pr], "detail_level": "identity_only", "evidence_status": "stale" if stale else "unknown", "evidence_last_checked_at": None, @@ -5016,9 +4992,9 @@ def status_overview(self) -> dict[str, Any]: "detail_window": { "unmerged_limit": max(4, len(target_scan_prs)), "batch_status": "complete", - "deep_prs": [ - pr for pr in state.ordered_prs if pr in deep_prs and batch_live[pr].state == "OPEN" - ] if deep_error is None else [], + "deep_prs": [pr for pr in state.ordered_prs if pr in deep_prs and batch_live[pr].state == "OPEN"] + if deep_error is None + else [], "tail_evidence": "not fetched; identity-only rows are informational and never indicate completion", "active_targets": sorted(active_targets), "active_target_scan": active_scan_status, @@ -5052,9 +5028,7 @@ def status_overview(self) -> dict[str, Any]: if changed_target_pr in remote_affected else "live PR identity changed between batch overview and deep reconciliation" ) - unknown_targets = self._unknown_review_targets( - changed_reason - ) + unknown_targets = self._unknown_review_targets(changed_reason) positions = {pr: index for index, pr in enumerate(state.ordered_prs)} changed_position = positions[changed_target_pr] selected_targets = report["review_targets"] @@ -5089,6 +5063,18 @@ def resolve_hosted_target(self, expected_pr: int | None = None) -> ReviewTarget: def select_target(self, channel: policy.Channel | str, expected_pr: int | None = None) -> dict[str, Any]: return self._target(channel, expected_pr).as_dict() + def _admit_review(self, pr: int, channel: str, reserve: Callable[[], None]) -> None: + """Serialize admission with human decisions, releasing before execution.""" + + def admit(state: ReviewState) -> ReviewState: + allocation = state.allocations.get(f"{pr}:{channel}") + if pr not in state.ordered_prs or (allocation is not None and allocation.stop_basis is not None): + raise ControllerError(f"{channel} review discovery is stopped for PR #{pr}") + reserve() + return state + + self.store.update(admit) + def run_hosted(self, *, expected_pr: int | None = None, **kwargs: Any) -> Any: selected = self._target(policy.Channel.HOSTED, expected_pr) self._ensure_runnable(selected) @@ -5098,7 +5084,12 @@ def run_hosted(self, *, expected_pr: int | None = None, **kwargs: Any) -> Any: if not self.isolated_fixture: prepare_full_trigger(selected.pr, expected_pr) try: - return self.hosted_adapter(selected.target, expect_pr=expected_pr, **kwargs) + return self.hosted_adapter( + selected.target, + expect_pr=expected_pr, + admit=lambda reserve, pr=selected.pr: self._admit_review(pr, "hosted", reserve), + **kwargs, + ) except StaleReviewTarget: if not selected.target.default_base_front or attempt == MAX_BASE_RESELECTIONS: raise @@ -5150,6 +5141,7 @@ def run_cli( selected.target, allow_unreconciled=allow_unreconciled, reason=reason, + admit=lambda reserve, pr=selected.pr: self._admit_review(pr, "cli", reserve), **kwargs, ) except StaleReviewTargetError as error: @@ -5170,9 +5162,7 @@ def evidence(self, pr: int | None = None) -> dict[str, Any]: for channel in (policy.Channel.HOSTED, policy.Channel.CLI) ): status_state = state - selected_indexes = [ - index for index, number in enumerate(state.ordered_prs) if number in eligible_prs - ] + selected_indexes = [index for index, number in enumerate(state.ordered_prs) if number in eligible_prs] if selected_indexes and len(eligible_prs) != len(state.ordered_prs): # A selected evidence read still needs the selected PR's complete # ancestor identity chain, but it must not ask _live_snapshots @@ -5204,8 +5194,7 @@ def evidence(self, pr: int | None = None) -> dict[str, Any]: for channel in (policy.Channel.HOSTED, policy.Channel.CLI) } row: dict[str, Any] = { - channel.value: histories[channel] - for channel in (policy.Channel.HOSTED, policy.Channel.CLI) + channel.value: histories[channel] for channel in (policy.Channel.HOSTED, policy.Channel.CLI) } allocations: dict[str, Any] = {} for channel in (policy.Channel.HOSTED, policy.Channel.CLI): @@ -5359,6 +5348,7 @@ def decide_allocation( raise ControllerError("allocation head does not match the live pull-request head") if self._head_repository_problem(item): raise ControllerError(f"PR #{pr} has an unsupported head repository") + def update_allocation(current_state: ReviewState, replacement: ReviewAllocation | None) -> ReviewState: if current_state.allocations.get(identity) != previous: raise ControllerError("review allocation changed concurrently; reread before deciding") @@ -5382,6 +5372,7 @@ def update_allocation(current_state: ReviewState, replacement: ReviewAllocation history = _history(self._evidence_provider, pr, selected) policy_history = self._policy_history(state, pr, selected, reconciliation) reopens_taper = fresh_taper + def provable_posted_hosted_request(value: Any) -> bool: trigger_id = _field(value, "trigger_id") return ( @@ -5394,14 +5385,19 @@ def provable_posted_hosted_request(value: Any) -> bool: and _field(value, "checkpoint") == f"trigger:{trigger_id}" and self._hosted_anchor_matches(value, pr, current) ) + stop_evidence_checked = False - if bounded_replacement and not any(provable_posted_hosted_request(value) for value in history) and any( - _field(value, "completed") is True - and _field(value, "attributable") is True - and _field(value, "provisional") is not True - and type(_field(value, "accepted")) is int - and _field(value, "accepted") > 0 - for value in policy_history + if ( + bounded_replacement + and not any(provable_posted_hosted_request(value) for value in history) + and any( + _field(value, "completed") is True + and _field(value, "attributable") is True + and _field(value, "provisional") is not True + and type(_field(value, "accepted")) is int + and _field(value, "accepted") > 0 + for value in policy_history + ) ): self._check_stop_evidence( state, @@ -5476,8 +5472,7 @@ def provable_posted_hosted_request(value: Any) -> bool: if blocked and not provable_posted_hosted_request(value): raise ControllerError("current review evidence is blocked; allocation cannot be promised") baseline = tuple( - _field(value, "checkpoint", "checkpoint_id") - for value in history if _field(value, "correction") is not True + _field(value, "checkpoint", "checkpoint_id") for value in history if _field(value, "correction") is not True ) if any(not isinstance(value, str) or not value for value in baseline): raise ControllerError("existing review evidence lacks a checkpoint identity") @@ -5560,128 +5555,143 @@ def decide_stop( raise ControllerError(f"PR #{pr} is not in the configured review stack") identity = f"{pr}:{selected.value}" previous = state.allocations.get(identity) - with self._stop_review_locks(pr, selected.value): - # Refresh everything inside the selected channel's lock(s) so an - # in-flight review cannot be mistaken for a terminal result. - state = self._state() - if pr not in state.ordered_prs: - raise ControllerError(f"PR #{pr} is not in the configured review stack") - previous = state.allocations.get(identity) - if acknowledge_over_ceiling and previous is not None: - raise ControllerError("over-ceiling acknowledgment is available only to a direct human stop") - if previous is not None and previous.handoff_checkpoint is not None: - raise ControllerError("this channel already has a legacy completed handoff") - live, reconciliation = self._reconciliation(state) - item = live[pr] - if normalized_head is not None and normalized_head.casefold() != item.head.casefold(): - raise ControllerError("review stop head does not match the live pull-request head") - if self._head_repository_problem(item): - raise ControllerError(f"PR #{pr} has an unsupported head repository") - remote_heads = self.git.remote_heads() - if not self._current_branches_match(state, live, reconciliation, pr, remote_heads): - raise ControllerError("review stop requires a coherent exact-current stack topology") - current = self._anchor(pr, item, reconciliation.links[pr]) - basis = previous.stop_basis if previous is not None and previous.stop_basis is not None else "direct_human" - if acknowledge_over_ceiling and basis != "direct_human": - raise ControllerError("over-ceiling acknowledgment is available only to a direct human stop") - candidate_history = self._policy_history(state, pr, selected, reconciliation) - if previous is not None and previous.stop_basis is None and previous.handoff_checkpoint is None: - prior_view = self._allocation_progress( - previous, - candidate_history, - current, - reconciliation.status_for(pr, selected.value), - state=state, - reconciliation_result=reconciliation, - ) - candidate_latest, _ = self._latest_stop_checkpoint( - pr, selected, candidate_history, checkpoint - ) - if ( - prior_view["status"] == "EXHAUSTED_PENDING" - and prior_view["reason"] == "review allocation exhausted; an explicit stop decision is required" - and prior_view["checkpoint"] == _field(candidate_latest, "checkpoint", "checkpoint_id") - ): - basis = "allocated" - latest, retained, checked_histories = self._check_stop_evidence( - state, + # A stop changes future eligibility only. Provider execution and capture + # retain their own locks; the decision is serialized by store.update. + state = self._state() + if pr not in state.ordered_prs: + raise ControllerError(f"PR #{pr} is not in the configured review stack") + previous = state.allocations.get(identity) + if acknowledge_over_ceiling and previous is not None: + raise ControllerError("over-ceiling acknowledgment is available only to a direct human stop") + if previous is not None and previous.handoff_checkpoint is not None: + raise ControllerError("this channel already has a legacy completed handoff") + item = _live(self._require_github().pull_request(pr), pr) + if normalized_head is not None and normalized_head.casefold() != item.head.casefold(): + raise ControllerError("review stop head does not match the live pull-request head") + # Record the actual PR base even when the configured parent has moved. + # Local Git proof is optional audit context, never a stop prerequisite. + try: + merge_base = self.git.merge_base(item.base_tip, item.head) + patch_id = self.git.patch_identity(merge_base, item.head) + except (ControllerError, OSError, ValueError, subprocess.SubprocessError): + merge_base, patch_id = None, None + current = AnchorFacts(pr, item.head, item.base_ref, item.base_tip, merge_base, patch_id) + basis = previous.stop_basis if previous is not None and previous.stop_basis is not None else "direct_human" + if acknowledge_over_ceiling and basis != "direct_human": + raise ControllerError("over-ceiling acknowledgment is available only to a direct human stop") + histories = { + selected_channel: _history(self._evidence_provider, pr, selected_channel) + for selected_channel in (policy.Channel.HOSTED, policy.Channel.CLI) + } + history = histories[selected] + # A prior result is optional audit context. Never label an active or + # unattributable review as completed just to record the human override. + try: + latest, _ = self._latest_stop_checkpoint(pr, selected, history, checkpoint) + except ControllerError: + if checkpoint is not None: + raise + latest = None + retained_fingerprints, retained_reason = (), None + if retained_fingerprint_values: + audit = self._stop_audit( pr, - selected, current, - reconciliation, - checkpoint_pin=checkpoint, - allow_historical_unmatched=basis == "direct_human", - allow_historical_terminal_ambiguity=basis == "direct_human", - retained_ambiguous_fingerprints=retained_fingerprint_values, - ambiguity_reason=ambiguity_reason, - acknowledge_over_ceiling=acknowledge_over_ceiling, + retained_fingerprint_values, + allow_historical_unmatched=True, + allow_historical_terminal_ambiguity=True, ) - retained_fingerprints, retained_reason = retained or ((), None) - history = checked_histories[selected] - if previous is not None and previous.stop_basis is not None: - prior_view = self._allocation_progress( - previous, - history, - current, - reconciliation.status_for(pr, selected.value), - state=state, - reconciliation_result=reconciliation, - ) - if prior_view["status"] == "STOPPED": - raise ControllerError("review discovery is already stopped for this PR and channel") + retained_fingerprints, retained_reason = self._stop_ambiguity_pins( + histories, retained_fingerprint_values, ambiguity_reason, audit + ) + if acknowledge_over_ceiling: + markers = {} + for values in histories.values(): + for value in values: + checkpoint_id = _field(value, "checkpoint") + if isinstance(checkpoint_id, str) and checkpoint_id.startswith("over-ceiling:"): + fingerprint = observation_fingerprint(value) + if checkpoint_id in markers and markers[checkpoint_id] != fingerprint: + raise ControllerError("conflicting duplicate over-ceiling checkpoint metadata") + markers[checkpoint_id] = fingerprint + if not any( + _field(value, "over_ceiling") is True and _field(value, "head", "reviewed_head") == current.child_head + for values in histories.values() + for value in values + ): + raise ControllerError("over-ceiling acknowledgment requires current-head over-ceiling evidence") + if previous is not None and previous.stop_basis is not None: + raise ControllerError("review discovery is already stopped for this PR and channel") + if ( + previous is not None + and previous.min_additional_completed is None + and previous.max_additional_completed is None + ): + completed_since_grant = [ + value + for value in history + if _field(value, "checkpoint") not in previous.baseline_checkpoints + and _field(value, "completed") is True + and _field(value, "attributable") is True + and _field(value, "anchored") is True + and _field(value, "provisional") is not True + and _field(value, "non_counting") is not True + and _field(value, "correction") is not True + ] + if ( + len(completed_since_grant) == 1 + and latest is not None + and merge_base is not None + and patch_id is not None + ): + basis = "allocated" - if previous is not None: - original = previous - else: - checkpoints = tuple( - _field(value, "checkpoint", "checkpoint_id") - for value in history - if _field(value, "correction") is not True - ) - if any(not isinstance(value, str) or not value for value in checkpoints): - raise ControllerError("current review evidence lacks immutable checkpoint identities") - if len(checkpoints) != len(set(checkpoints)): - raise ControllerError("current review evidence has ambiguous checkpoint identities") - original = ReviewAllocation( - pr=pr, - channel=selected.value, - head=current.child_head, - parent_identity=current.parent_identity, - parent_head=current.parent_head, - merge_base=current.merge_base, - patch_id=current.patch_id, - baseline_checkpoints=checkpoints, - reason=normalized_reason, - ) - stopped = dataclasses.replace( - original, - stop_basis=basis, - stop_checkpoint=_field(latest, "checkpoint", "checkpoint_id"), - stop_reviewed_head=_field(latest, "head", "reviewed_head"), - stop_reviewed_patch_id=_field(latest, "patch_id", "patch_identity"), - stop_head=current.child_head, - stop_parent_identity=current.parent_identity, - stop_parent_head=current.parent_head, - stop_merge_base=current.merge_base, - stop_patch_id=current.patch_id, - stop_reason=( + if previous is not None: + original_values = dataclasses.asdict(previous) + else: + checkpoints = (_field(latest, "checkpoint", "checkpoint_id"),) if latest is not None else () + original_values = { + "pr": pr, + "channel": selected.value, + "head": current.child_head, + "parent_identity": current.parent_identity, + "parent_head": current.parent_head, + "merge_base": current.merge_base, + "patch_id": current.patch_id, + "baseline_checkpoints": checkpoints, + "reason": normalized_reason, + } + stopped = ReviewAllocation( + **{ + **original_values, + "stop_basis": basis, + "stop_checkpoint": _field(latest, "checkpoint", "checkpoint_id"), + "stop_reviewed_head": _field(latest, "head", "reviewed_head"), + "stop_reviewed_patch_id": _field(latest, "patch_id", "patch_identity"), + "stop_head": current.child_head, + "stop_parent_identity": current.parent_identity, + "stop_parent_head": current.parent_head, + "stop_merge_base": current.merge_base, + "stop_patch_id": current.patch_id, + "stop_reason": ( f"[acknowledged current over-ceiling limitation] {normalized_reason}" if acknowledge_over_ceiling else normalized_reason ), - stop_summary_disposition_fingerprints=self._stop_summary_fingerprints(state, pr), - retained_ambiguous_fingerprints=retained_fingerprints, - retained_ambiguous_reason=retained_reason, - ) + "stop_summary_disposition_fingerprints": self._stop_summary_fingerprints(state, pr), + "retained_ambiguous_fingerprints": retained_fingerprints, + "retained_ambiguous_reason": retained_reason, + } + ) - def persist(current_state: ReviewState) -> ReviewState: - if current_state.allocations.get(identity) != previous: - raise ControllerError("review allocation changed concurrently; reread before stopping") - values = dict(current_state.allocations) - values[identity] = stopped - return dataclasses.replace(current_state, allocations=values) + def persist(current_state: ReviewState) -> ReviewState: + if current_state.ordered_prs != state.ordered_prs or current_state.allocations.get(identity) != previous: + raise ControllerError("review stack or allocation changed concurrently; reread before stopping") + values = dict(current_state.allocations) + values[identity] = stopped + return dataclasses.replace(current_state, allocations=values) - updated = self.store.update(persist) + updated = self.store.update(persist) return { "action": "stop", "allocation": stopped.to_dict(), @@ -5760,9 +5770,7 @@ def _validate_decision_identity( raise ControllerError("decision checkpoint is blocked by a later provisional review") checkpoint_head = _sha(checkpoint_evidence.head, "decision checkpoint head") reopen_after_advance = ( - allow_reopen_after_advance - and selected_channel == policy.Channel.CLI - and checkpoint_head != normalized_head + allow_reopen_after_advance and selected_channel == policy.Channel.CLI and checkpoint_head != normalized_head ) if checkpoint_head != normalized_head: if reopen_after_advance: @@ -5772,11 +5780,7 @@ def _validate_decision_identity( }: raise ControllerError("reopen judgment requires coherent live topology") raw_checkpoint = next( - ( - item - for item in reversed(history) - if _field(item, "checkpoint", "checkpoint_id") == checkpoint - ), + (item for item in reversed(history) if _field(item, "checkpoint", "checkpoint_id") == checkpoint), None, ) anchored_review = ( @@ -5798,7 +5802,10 @@ def _validate_decision_identity( stack.ReconciliationStatus.UNRECONCILED, }: raise ControllerError("equivalent-history judgment requires coherent live topology") - if not allow_equivalent_history or reconciliation_status != stack.ReconciliationStatus.EQUIVALENT_HISTORY: + if ( + not allow_equivalent_history + or reconciliation_status != stack.ReconciliationStatus.EQUIVALENT_HISTORY + ): raise ControllerError("decision checkpoint head must match the live head or equivalent history") if checkpoint_evidence.patch_id != anchor.patch_id and not reopen_after_advance: raise ControllerError("decision checkpoint patch identity does not match the live stack anchor") diff --git a/dev-tools/pr_review/policy.py b/dev-tools/pr_review/policy.py index 6078346bc5..d48be57c15 100644 --- a/dev-tools/pr_review/policy.py +++ b/dev-tools/pr_review/policy.py @@ -172,10 +172,7 @@ def _same_head_provisional_barrier(history: Sequence[Evidence], reviews: Sequenc ), default=-1, ) - return ( - last_provisional > last_review - and history[last_provisional].head == reviews[-1].head - ) + return last_provisional > last_review and history[last_provisional].head == reviews[-1].head def taper_satisfied( @@ -219,11 +216,7 @@ def taper_satisfied( continue if not _valid_complete(item, channel, require_corrected_state=require_corrected_state): continue - if ( - allow_uncorrected_state - and item.corrected_state is not True - and item.patch_id != retained_patch_id - ): + if allow_uncorrected_state and item.corrected_state is not True and item.patch_id != retained_patch_id: # A retain judgment only makes uncorrected evidence eligible on # its exact patch. A mismatched row is ignored, not a streak break. continue @@ -260,9 +253,7 @@ def fresh_taper_history( ( judgment for judgment in reversed(state.judgments) - if judgment.pr == pr - and judgment.channel == selected.value - and judgment.decision == "reopen" + if judgment.pr == pr and judgment.channel == selected.value and judgment.decision == "reopen" ), None, ) @@ -431,9 +422,7 @@ def completion_status( # must not manufacture corrected evidence for unrelated histories. retained_equivalent_history = latest_judgment.decision == "retain" effective_taper_history = ( - taper_history - if taper_history is not None - else fresh_taper_history(state, selected, history) + taper_history if taper_history is not None else fresh_taper_history(state, selected, history) ) required = required_taper(state, selected, effective_taper_history) if retained_equivalent_history: @@ -523,9 +512,6 @@ def completed_taper(pr: int) -> bool: for pr in live_prs: if pr in handed_off: continue - if pr in human_stopped: - encountered_human_stop = True - continue if pr in active_reviews: return ChannelDecision( selected, @@ -534,6 +520,9 @@ def completed_taper(pr: int) -> bool: f"{pr} has an active review or reservation in a review channel", taper_complete=completed_taper(pr), ) + if pr in human_stopped: + encountered_human_stop = True + continue if pr in allocation_blocks: return ChannelDecision( selected, @@ -552,7 +541,9 @@ def completed_taper(pr: int) -> bool: ) if pr in exhausted: return ChannelDecision( - selected, pr, ReviewStatus.ALLOCATION_EXHAUSTED, + selected, + pr, + ReviewStatus.ALLOCATION_EXHAUSTED, f"{pr} has consumed its {selected.value} allocation; an explicit stop decision is required", taper_complete=completed_taper(pr), ) @@ -635,13 +626,19 @@ def completed_taper(pr: int) -> bool: completed_taper_seen = True continue reconciliation_status = reconciliation_by_pr.get(pr) - if taper_complete and reconciliation_status in { - ReconciliationStatus.PATCH_CHANGED, - ReconciliationStatus.EQUIVALENT_HISTORY, - } and latest_judgment is None and not ( - selected == Channel.CLI - and latest.current_candidate_descendant_proven - and reconciliation_status == ReconciliationStatus.PATCH_CHANGED + if ( + taper_complete + and reconciliation_status + in { + ReconciliationStatus.PATCH_CHANGED, + ReconciliationStatus.EQUIVALENT_HISTORY, + } + and latest_judgment is None + and not ( + selected == Channel.CLI + and latest.current_candidate_descendant_proven + and reconciliation_status == ReconciliationStatus.PATCH_CHANGED + ) ): return ChannelDecision( selected, diff --git a/dev-tools/pr_review/runtime.py b/dev-tools/pr_review/runtime.py index 70e2323bd7..5a69b2da8b 100644 --- a/dev-tools/pr_review/runtime.py +++ b/dev-tools/pr_review/runtime.py @@ -10,7 +10,7 @@ import stat import subprocess import uuid -from collections.abc import Mapping, Sequence +from collections.abc import Callable, Mapping, Sequence from contextlib import ExitStack from datetime import datetime, timezone from pathlib import Path @@ -65,7 +65,9 @@ def pull_request(self, number: int) -> PullRequestSnapshot: if ( not isinstance(head_repository, str) or head_repository.count("/") != 1 - or any(not part or any(character.isspace() for character in part) for part in head_repository.split("/")) + or any( + not part or any(character.isspace() for character in part) for part in head_repository.split("/") + ) ): raise ReviewRunnerError("GitHub pull-request head repository identity is malformed") else: @@ -167,7 +169,14 @@ def active_review_targets( active: set[int] = set() active_trigger_states = {"active", "awaiting_response", "ambiguous", "unattributed", "timed_out"} - terminal_trigger_states = {"completed", "failed", "failed_incomplete_coverage", "rate_limited", "noop", "retired"} + terminal_trigger_states = { + "completed", + "failed", + "failed_incomplete_coverage", + "rate_limited", + "noop", + "retired", + } if self.state_store is None: active.update(pr_numbers) else: @@ -350,7 +359,7 @@ def _validate_prepost_abandoned(path: Any, repo: str, pr: int) -> None: def _full_review_commands(comments: list[dict[str, Any]]) -> list[tuple[int, datetime]]: commands: list[tuple[int, datetime]] = [] for item in comments: - author = ((item.get("author") or {}).get("login")) + author = (item.get("author") or {}).get("login") body = item.get("body") if hosted.is_coderabbit_login(author) or not isinstance(body, str): continue @@ -442,14 +451,8 @@ def _terminal_ambiguous_hosted_observation( if not isinstance(comments, list) or not isinstance(reviews, list): return None triggers = [item for item in comments if github.immutable_database_id(item) == trigger_id] - responses = [ - (item, "createdAt") - for item in comments - if github.immutable_database_id(item) == response_id - ] + [ - (item, "submittedAt") - for item in reviews - if github.immutable_database_id(item) == response_id + responses = [(item, "createdAt") for item in comments if github.immutable_database_id(item) == response_id] + [ + (item, "submittedAt") for item in reviews if github.immutable_database_id(item) == response_id ] if len(triggers) != 1 or len(responses) != 1: return None @@ -561,10 +564,7 @@ def review_stop_audit( allow_historical_unmatched=True, ) payload = self._payload(pr) - channel_history = { - channel: list(self.history(pr, channel)) - for channel in ("hosted", "cli") - } + channel_history = {channel: list(self.history(pr, channel)) for channel in ("hosted", "cli")} ambiguous_terminal_responses: list[dict[str, Any]] = [] terminal_rate_limits: list[dict[str, Any]] = [] @@ -643,8 +643,7 @@ def review_stop_audit( ] if cli_pending: unresolved_findings.extend( - str(item.get("reason") or item.get("checkpoint") or "unresolved CLI evidence") - for item in cli_pending + str(item.get("reason") or item.get("checkpoint") or "unresolved CLI evidence") for item in cli_pending ) checkpoints = [ {"channel": channel, **item} @@ -757,6 +756,7 @@ def checkpoint_names_another_head(reviewed_sha: Any) -> bool | None: if hosted._scope_head(body) is not None: return False return None + latest = self.live.pull_request(pr) if ( latest.number != pr @@ -799,9 +799,7 @@ def checkpoint_names_another_head(reviewed_sha: Any) -> bool | None: if item.hosted_review_id is not None: checkpoints_by_response.setdefault(item.hosted_review_id, []).append(item) checkpoint_by_response = { - response_id: matching[0] - for response_id, matching in checkpoints_by_response.items() - if len(matching) == 1 + response_id: matching[0] for response_id, matching in checkpoints_by_response.items() if len(matching) == 1 } records_by_trigger: dict[int, tuple[dict[str, Any], hosted.TriggerState]] = {} @@ -875,11 +873,7 @@ def checkpoint_names_another_head(reviewed_sha: Any) -> bool | None: responses_by_trigger.setdefault(trigger_id, set()).add(response_id) if state.state == "completed": response_item = next( - ( - item - for item in (*comments, *reviews) - if github.immutable_database_id(item) == response_id - ), + (item for item in (*comments, *reviews) if github.immutable_database_id(item) == response_id), None, ) body = (response_item or {}).get("body") @@ -940,9 +934,7 @@ def checkpoint_names_another_head(reviewed_sha: Any) -> bool | None: matching_checkpoints = checkpoints_by_response.get(response_id, []) if response_id is not None else [] if not matching_checkpoints: response_is_current = ( - response_matches_expected_head(response_id, response_item) - if response_id is not None - else None + response_matches_expected_head(response_id, response_item) if response_id is not None else None ) record_unmatched( "an unrecorded completed Hosted response has no matching public checkpoint", @@ -955,9 +947,7 @@ def checkpoint_names_another_head(reviewed_sha: Any) -> bool | None: ) hosted_history = self.history(pr, "hosted") - represented_checkpoints = { - str(item.get("checkpoint")) for item in hosted_history if isinstance(item, dict) - } + represented_checkpoints = {str(item.get("checkpoint")) for item in hosted_history if isinstance(item, dict)} legacy_represented_checkpoint_ids: set[str] = set() states_by_response: dict[int, list[tuple[dict[str, Any], hosted.TriggerState]]] = {} for record, state in records_by_trigger.values(): @@ -972,15 +962,9 @@ def checkpoint_names_another_head(reviewed_sha: Any) -> bool | None: continue record, state = matching[0] captured_head = record.get("head_sha") - review_matches = [ - item for item in reviews - if github.immutable_database_id(item) == response_id - ] + review_matches = [item for item in reviews if github.immutable_database_id(item) == response_id] trigger = next( - ( - item for item in comments - if github.immutable_database_id(item) == state.trigger_comment_id - ), + (item for item in comments if github.immutable_database_id(item) == state.trigger_comment_id), None, ) trigger_author = ((trigger or {}).get("author") or {}).get("login") @@ -1016,8 +1000,7 @@ def checkpoint_names_another_head(reviewed_sha: Any) -> bool | None: reviewed_sha = checkpoint.reviewed_sha names_another_head = ( not expected_head.casefold().startswith(reviewed_sha.casefold()) - if isinstance(reviewed_sha, str) - and re.fullmatch(r"[0-9a-fA-F]{7,40}", reviewed_sha) is not None + if isinstance(reviewed_sha, str) and re.fullmatch(r"[0-9a-fA-F]{7,40}", reviewed_sha) is not None else None ) record_unmatched( @@ -1028,9 +1011,7 @@ def checkpoint_names_another_head(reviewed_sha: Any) -> bool | None: unresolved_findings = [ str(item.get("checkpoint", "Hosted finding")) for item in hosted_history - if str(item.get("checkpoint", "")).startswith( - ("review-threads:", "summary-actions:", "over-ceiling:") - ) + if str(item.get("checkpoint", "")).startswith(("review-threads:", "summary-actions:", "over-ceiling:")) and (item.get("held") is True or item.get("unstable") is True or item.get("over_ceiling") is True) ] return { @@ -1088,10 +1069,7 @@ def _hosted_zero_reply_proof( or checkpoint.accepted != 0 or checkpoint.hosted_review_id is None or response_id != checkpoint.hosted_review_id - or ( - checkpoint.duration_seconds is not None - and checkpoint.duration_seconds != response_duration_seconds - ) + or (checkpoint.duration_seconds is not None and checkpoint.duration_seconds != response_duration_seconds) ): return None @@ -1119,7 +1097,7 @@ def _hosted_zero_reply_proof( later_triggers: list[datetime] = [] for item in comments: - author = ((item.get("author") or {}).get("login")) + author = (item.get("author") or {}).get("login") if ( github.immutable_database_id(item) == trigger_id or hosted.is_coderabbit_login(author) @@ -1135,9 +1113,7 @@ def _hosted_zero_reply_proof( if next_trigger is not None and response_at >= next_trigger: return None - legacy_summary = hosted._zero_finding_summary( - payload, captured_head, trigger_at, response_id, next_trigger - ) + legacy_summary = hosted._zero_finding_summary(payload, captured_head, trigger_at, response_id, next_trigger) provider_summary = hosted.provider_format_zero_finding_summary( payload, captured_head, @@ -1155,7 +1131,7 @@ def _hosted_zero_reply_proof( # review object in the captured trigger window. This avoids choosing a # reply over a conflicting or mismatched immutable review commit. for review in pr["reviews"]["nodes"]: - author = ((review.get("author") or {}).get("login")) + author = (review.get("author") or {}).get("login") if not hosted.is_coderabbit_login(author) or review.get("state") == "DISMISSED": continue submitted = hosted.parse_timestamp(review.get("submittedAt")) @@ -1188,14 +1164,17 @@ def _hosted_trigger_for_checkpoint( captured_head = record["head_sha"] proof = evidence.hosted_checkpoint_evidence(checkpoint, reviews, captured_head) if proof.get("status") != "completed": - proof = self._hosted_zero_reply_proof( - checkpoint, - state.response_id, - state.duration_seconds, - captured_head, - record, - payload, - ) or proof + proof = ( + self._hosted_zero_reply_proof( + checkpoint, + state.response_id, + state.duration_seconds, + captured_head, + record, + payload, + ) + or proof + ) if proof.get("status") != "completed": continue anchor = record.get("anchor") @@ -1420,8 +1399,10 @@ def _global_blockers( response_id = github.immutable_database_id(item) if ( ( - provider_skip and response_id in bound_failed_response_ids - or legacy_skip and response_id in bound_legacy_skip_response_ids + provider_skip + and response_id in bound_failed_response_ids + or legacy_skip + and response_id in bound_legacy_skip_response_ids ) and timestamp is not None and timestamp >= latest_exact_completion @@ -1449,8 +1430,12 @@ def history(self, pr: int, channel: str) -> Sequence[dict[str, Any]]: # that same snapshot for historical attribution instead of fetching a # second PR/CI metadata response for every history read. Request-time # selection still obtains its own fresh identity separately. - if (isinstance(payload_head, str) and evidence.EXACT_SHA.fullmatch(payload_head) - and type(payload_files) is int and payload_files >= 0): + if ( + isinstance(payload_head, str) + and evidence.EXACT_SHA.fullmatch(payload_head) + and type(payload_files) is int + and payload_files >= 0 + ): head = payload_head.lower() changed_files = payload_files else: @@ -1491,9 +1476,7 @@ def history(self, pr: int, channel: str) -> Sequence[dict[str, Any]]: if channel == "cli": if cli_context_error is None: try: - capture = evidence.load_cli_capture( - checkpoint, self.repo, pr, cli_common, records=cli_records - ) + capture = evidence.load_cli_capture(checkpoint, self.repo, pr, cli_common, records=cli_records) except evidence.EvidenceError: capture = None if capture is not None: @@ -1547,15 +1530,38 @@ def history(self, pr: int, channel: str) -> Sequence[dict[str, Any]]: if channel == "cli" and capture is not None else "" ), - **({"held": True, "capture_context_available": False} - if cli_context_error is not None else {}), + **({"held": True, "capture_context_available": False} if cli_context_error is not None else {}), **anchor, } ) if channel == "cli" and cli_context_error is None: - for capture in evidence.discover_cli_captures( - self.repo, pr, cli_common, records=cli_records - ): + # CLI already holds its process lock and pins canonical metadata + # before execution. Read that reservation; no second activity store + # or fabricated completed checkpoint is needed. + cli_root = cli_common / "firemud" / "pr-review" + if self._request_lock_is_held(cli_root / "cli.lock"): + metadata_paths = list((cli_root / "runs").glob("*/metadata.json")) + if metadata_paths: + newest = max(metadata_paths, key=lambda path: path.stat().st_mtime_ns) + try: + active_metadata = json.loads(newest.read_text(encoding="utf-8")) + except (OSError, ValueError): + active_metadata = {} + if active_metadata.get("pull_request") == pr and not any( + (newest.parent / name).exists() for name in ("capture-complete", "error", "exit-status") + ): + values.append( + { + "pr": pr, + "head": active_metadata.get("candidate_sha", ""), + "checkpoint": f"active-cli:{active_metadata.get('run_id', newest.parent.name)}", + "active_review": True, + "held": True, + "reason": "CLI review is running; its eventual findings still require adjudication", + **self._anchor(active_metadata), + } + ) + for capture in evidence.discover_cli_captures(self.repo, pr, cli_common, records=cli_records): run_id = capture.metadata.get("run_id", "") if run_id in public_cli_run_ids: continue @@ -1566,9 +1572,7 @@ def history(self, pr: int, channel: str) -> Sequence[dict[str, Any]]: candidate_sha = capture.metadata.get("candidate_sha", "") published_head_sha = capture.metadata.get("published_head_sha", candidate_sha) current_head = any( - value.casefold() == head.casefold() - for value in (candidate_sha, published_head_sha) - if value + value.casefold() == head.casefold() for value in (candidate_sha, published_head_sha) if value ) values.append( { @@ -1654,6 +1658,7 @@ def history(self, pr: int, channel: str) -> Sequence[dict[str, Any]]: "checkpoint": f"trigger:{state.trigger_comment_id or 'pending'}", "held": state.state in {"active", "awaiting_response", "ambiguous", "unattributed"}, "unstable": state.state in {"ambiguous", "unattributed", "timed_out"}, + "active_reservation": state.state in {"active", "awaiting_response"}, "reason": state.reason, } if state.state == "active": @@ -1662,9 +1667,7 @@ def history(self, pr: int, channel: str) -> Sequence[dict[str, Any]]: observation["trigger_id"] = state.trigger_comment_id observation["response_id"] = state.response_id if state.state == "ambiguous": - terminal_observation = self._terminal_ambiguous_hosted_observation( - pr, record, state, payload - ) + terminal_observation = self._terminal_ambiguous_hosted_observation(pr, record, state, payload) if terminal_observation is not None: observation.update( { @@ -1676,8 +1679,7 @@ def history(self, pr: int, channel: str) -> Sequence[dict[str, Any]]: ) values.append(observation) parsed_scope_changes = { - (item.comment_id, item.created_at, item.description, item.updated_at) - for item in scope_changes + (item.comment_id, item.created_at, item.description, item.updated_at) for item in scope_changes } for comment in comments: author_login = comment.get("author_login") @@ -2155,9 +2157,7 @@ def _assert_no_other_active_reservations( comments_by_pr: dict[int, dict[str, Any]] = {} for other_pr in sorted(open_prs): try: - comments = github.fetch_api_endpoint( - f"repos/{self.repo}/issues/{other_pr}/comments?per_page=100" - ) + comments = github.fetch_api_endpoint(f"repos/{self.repo}/issues/{other_pr}/comments?per_page=100") comments_by_pr[other_pr] = self._normalize_rest_issue_comments(other_pr, comments) except ControllerError: raise @@ -2187,9 +2187,7 @@ def _assert_no_other_active_reservations( if status == "retired": continue if status in {"posting", "posted_boundary_changed", "posted_boundary_unverified"}: - raise ControllerError( - f"another Hosted request is unresolved for PR #{other_pr}: ambiguous" - ) + raise ControllerError(f"another Hosted request is unresolved for PR #{other_pr}: ambiguous") payload = github.fetch_pull_request(self.repo, other_pr) payloads[other_pr] = payload state = hosted.trigger_state(self.repo, other_pr, payload, record, path) @@ -2198,9 +2196,7 @@ def _assert_no_other_active_reservations( except (OSError, RuntimeError, ValueError, KeyError, TypeError, json.JSONDecodeError) as exc: raise ControllerError(f"current Hosted reservation for PR #{other_pr} cannot be verified") from exc if state.state in {"active", "awaiting_response"}: - raise ControllerError( - f"another Hosted request is unresolved for PR #{other_pr}: {state.state}" - ) + raise ControllerError(f"another Hosted request is unresolved for PR #{other_pr}: {state.state}") if state.state == "ambiguous": response_id = state.response_id if ( @@ -2209,14 +2205,10 @@ def _assert_no_other_active_reservations( or not isinstance(response_id, int) or response_id <= 0 ): - raise ControllerError( - f"another Hosted request is unresolved for PR #{other_pr}: {state.state}" - ) + raise ControllerError(f"another Hosted request is unresolved for PR #{other_pr}: {state.state}") continue if state.state not in terminal_states: - raise ControllerError( - f"another Hosted request is unresolved for PR #{other_pr}: {state.state}" - ) + raise ControllerError(f"another Hosted request is unresolved for PR #{other_pr}: {state.state}") for other_pr, comments_payload in comments_by_pr.items(): try: @@ -2232,9 +2224,7 @@ def _assert_no_other_active_reservations( trigger_id = github.immutable_database_id(dict(command)) if trigger_id is None: raise ControllerError("manual full-review command has incomplete immutable identity") - if hosted.unresolved_preceding_full_trigger( - self.repo, other_pr, payload, trigger_id, common - ): + if hosted.unresolved_preceding_full_trigger(self.repo, other_pr, payload, trigger_id, common): raise ControllerError( f"another manual Hosted request is unresolved for PR #{other_pr}: " "an earlier full-review command has no terminal response" @@ -2287,11 +2277,16 @@ def _assert_no_other_active_reservations( or state.response_id is None or state.reason == "CodeRabbit finished after explicitly reporting incomplete file coverage" ): - raise ControllerError( - f"another manual Hosted request is unresolved for PR #{other_pr}: {state.state}" - ) + raise ControllerError(f"another manual Hosted request is unresolved for PR #{other_pr}: {state.state}") - def __call__(self, target: ReviewTarget, *, expect_pr: int | None = None, **_: Any) -> dict[str, Any]: + def __call__( + self, + target: ReviewTarget, + *, + expect_pr: int | None = None, + admit: Callable[[Callable[[], None]], None] | None = None, + **_: Any, + ) -> dict[str, Any]: if target.default_base_front and not target.has_current_default_test_merge_proof(): raise ControllerError("direct default-base target has no verified current base/head test merge") pr = target.snapshot.number @@ -2418,10 +2413,7 @@ def __call__(self, target: ReviewTarget, *, expect_pr: int | None = None, **_: A reservation_head = reservation_pr.get("headRefOid") if isinstance(reservation_pr, dict) else None reservation_base_ref = reservation_pr.get("baseRefName") if isinstance(reservation_pr, dict) else None reservation_base = reservation_pr.get("baseRefOid") if isinstance(reservation_pr, dict) else None - if ( - not isinstance(reservation_pr, dict) - or not isinstance(reservation_head, str) - ): + if not isinstance(reservation_pr, dict) or not isinstance(reservation_head, str): raise ControllerError("pull request identity is incomplete before the Hosted posting boundary") if ( reservation_head.casefold() != target.snapshot.head_sha.casefold() @@ -2452,9 +2444,7 @@ def __call__(self, target: ReviewTarget, *, expect_pr: int | None = None, **_: A except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: if isinstance(exc, ControllerError): raise - raise ControllerError( - f"could not establish the Hosted pre-POST comment identity floor: {exc}" - ) from exc + raise ControllerError(f"could not establish the Hosted pre-POST comment identity floor: {exc}") from exc sqlite_attempt_started = False if self.records is not None and sqlite_attempt_id is not None: try: @@ -2474,26 +2464,36 @@ def __call__(self, target: ReviewTarget, *, expect_pr: int | None = None, **_: A except Exception as exc: # noqa: BLE001 - optional capture cannot block provider POST # SQLite is optional for provider posting. Keep the ID in # the reservation so explicit sync can adopt or backfill it. - sqlite_capture_warnings.append( - f"SQLite Hosted attempt start failed ({type(exc).__name__})." - ) - if archive_current_path is not None: - trigger_id = (record.get("trigger") or {}).get("id") - archive = archive_current_path.with_name(f"trigger-{trigger_id}.json") - try: - os.replace(archive_current_path, archive) - hosted.atomic_write_json(path, posting) - except Exception as exc: - if sqlite_attempt_started and sqlite_attempt_id is not None: - self._finish_unposted_attempt(sqlite_attempt_id) - raise ControllerError("could not establish the durable Hosted posting reservation") from exc + sqlite_capture_warnings.append(f"SQLite Hosted attempt start failed ({type(exc).__name__}).") + + def reserve() -> None: + if archive_current_path is not None: + trigger_id = (record.get("trigger") or {}).get("id") + archive = archive_current_path.with_name(f"trigger-{trigger_id}.json") + try: + os.replace(archive_current_path, archive) + hosted.atomic_write_json(path, posting) + except Exception as exc: + if sqlite_attempt_started and sqlite_attempt_id is not None: + self._finish_unposted_attempt(sqlite_attempt_id) + raise ControllerError("could not establish the durable Hosted posting reservation") from exc + else: + try: + hosted.atomic_write_json(path, posting) + except Exception as exc: + if sqlite_attempt_started and sqlite_attempt_id is not None: + self._finish_unposted_attempt(sqlite_attempt_id) + raise ControllerError("could not establish the durable Hosted posting reservation") from exc + + if admit is None: + reserve() else: try: - hosted.atomic_write_json(path, posting) - except Exception as exc: + admit(reserve) + except Exception: if sqlite_attempt_started and sqlite_attempt_id is not None: self._finish_unposted_attempt(sqlite_attempt_id) - raise ControllerError("could not establish the durable Hosted posting reservation") from exc + raise try: completed = subprocess.run( [ @@ -2535,18 +2535,35 @@ def __call__(self, target: ReviewTarget, *, expect_pr: int | None = None, **_: A try: after = self.live.pull_request(pr) after_identity = (after.head_sha.casefold(), after.base_ref_name, after.base_sha.casefold()) - except (OSError, subprocess.SubprocessError, RuntimeError, ValueError, TypeError, KeyError, AttributeError) as exc: + except ( + OSError, + subprocess.SubprocessError, + RuntimeError, + ValueError, + TypeError, + KeyError, + AttributeError, + ) as exc: boundary_verification_errors.append(f"PR refresh failed: {type(exc).__name__}: {exc}") try: observed_parent_tip = self.live.branch_head(target.parent.ref_name) - if not isinstance(observed_parent_tip, str) or not re.fullmatch(r"[0-9a-fA-F]{40}", observed_parent_tip): + if not isinstance(observed_parent_tip, str) or not re.fullmatch( + r"[0-9a-fA-F]{40}", observed_parent_tip + ): raise ValueError("effective parent tip is malformed") after_parent_tip = observed_parent_tip.casefold() - except (OSError, subprocess.SubprocessError, RuntimeError, ValueError, TypeError, KeyError, AttributeError) as exc: + except ( + OSError, + subprocess.SubprocessError, + RuntimeError, + ValueError, + TypeError, + KeyError, + AttributeError, + ) as exc: boundary_verification_errors.append(f"parent-tip refresh failed: {type(exc).__name__}: {exc}") - boundary_changed = ( - (after_identity is not None and after_identity != before_identity) - or (after_parent_tip is not None and after_parent_tip != target.parent.head_sha.casefold()) + boundary_changed = (after_identity is not None and after_identity != before_identity) or ( + after_parent_tip is not None and after_parent_tip != target.parent.head_sha.casefold() ) if boundary_changed: status = "posted_boundary_changed" diff --git a/dev-tools/pr_review/sqlite_store.py b/dev-tools/pr_review/sqlite_store.py index 0effb3f37d..ebea1023db 100644 --- a/dev-tools/pr_review/sqlite_store.py +++ b/dev-tools/pr_review/sqlite_store.py @@ -25,7 +25,7 @@ from .state import ReviewState, StateError, _locked, sqlite_state_path SQLITE_SCHEMA_VERSION = 1 -WRITER_BUILD = 4 +WRITER_BUILD = 5 STATUS_VERSION = 1 CUTOVER_VERSION = 1 _METADATA_TABLE = "controller_metadata" @@ -157,6 +157,22 @@ def _update_locked(self, mutate: Callable[[ReviewState], ReviewState]) -> Review updated = mutate(current) if not isinstance(updated, ReviewState): raise TypeError("mutate must return ReviewState") + if any( + allocation.stop_basis == "direct_human" + and ( + allocation.stop_checkpoint is None + or allocation.merge_base is None + or allocation.patch_id is None + or allocation.stop_merge_base is None + or allocation.stop_patch_id is None + ) + for allocation in updated.allocations.values() + ): + if self.writer_build < 5: + raise StateError("SQLite review state requires writer build 5") + connection.execute( + f"UPDATE {_METADATA_TABLE} SET min_writer_build = MAX(min_writer_build, 5) WHERE singleton = 1" + ) payload = json.dumps( updated.to_dict(), ensure_ascii=True, @@ -204,12 +220,7 @@ def status(self) -> dict[str, Any]: with closing(self._connect_read_only()) as connection: base["format"] = "sqlite" base["schema_version"] = int(connection.execute("PRAGMA user_version").fetchone()[0]) - tables = { - row[0] - for row in connection.execute( - "SELECT name FROM sqlite_master WHERE type = 'table'" - ) - } + tables = {row[0] for row in connection.execute("SELECT name FROM sqlite_master WHERE type = 'table'")} if _METADATA_TABLE not in tables: base["reason"] = "controller metadata table is missing" return base @@ -227,9 +238,7 @@ def status(self) -> dict[str, Any]: elif data_model_version != ReviewState().schema_version: base["reason"] = f"unsupported review-state data model version {data_model_version}" elif ( - isinstance(min_writer_build, bool) - or not isinstance(min_writer_build, int) - or min_writer_build <= 0 + isinstance(min_writer_build, bool) or not isinstance(min_writer_build, int) or min_writer_build <= 0 ): base["reason"] = "minimum writer build metadata is invalid" elif self.writer_build < min_writer_build: @@ -395,9 +404,9 @@ def migrate_legacy_json( current_stat = source.stat(follow_symlinks=False) if ( - (current_stat.st_dev, current_stat.st_ino) != original_identity - or source.read_bytes() != original_bytes - ): + current_stat.st_dev, + current_stat.st_ino, + ) != original_identity or source.read_bytes() != original_bytes: raise StateError("legacy review-state JSON changed during migration preflight") retained_source.mkdir(mode=0o700) @@ -412,9 +421,7 @@ def migrate_legacy_json( "state_schema_version": imported.schema_version, "min_writer_build": minimum_build, } - marker_bytes = ( - json.dumps(marker, sort_keys=True, separators=(",", ":")) + "\n" - ).encode("utf-8") + marker_bytes = (json.dumps(marker, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8") with marker_path.open("xb") as handle: os.fchmod(handle.fileno(), 0o600) handle.write(marker_bytes) @@ -424,9 +431,9 @@ def migrate_legacy_json( _fsync_directory(source.parent) current_stat = source.stat(follow_symlinks=False) if ( - (current_stat.st_dev, current_stat.st_ino) != original_identity - or source.read_bytes() != original_bytes - ): + current_stat.st_dev, + current_stat.st_ino, + ) != original_identity or source.read_bytes() != original_bytes: raise StateError("legacy review-state JSON changed before cutover") _atomic_exchange(source, retained_source) exchanged = True @@ -511,11 +518,7 @@ def _require_compatible(self, connection: sqlite3.Connection) -> None: data_model_version, min_writer_build = row if data_model_version != ReviewState().schema_version: raise StateError(f"unsupported review-state data model version: {data_model_version}") - if ( - isinstance(min_writer_build, bool) - or not isinstance(min_writer_build, int) - or min_writer_build <= 0 - ): + if isinstance(min_writer_build, bool) or not isinstance(min_writer_build, int) or min_writer_build <= 0: raise StateError("SQLite review-state minimum writer build is invalid") if self.writer_build < min_writer_build: raise StateError(f"SQLite review state requires writer build {min_writer_build}") diff --git a/dev-tools/pr_review/state.py b/dev-tools/pr_review/state.py index 07b32ace19..86133cf886 100644 --- a/dev-tools/pr_review/state.py +++ b/dev-tools/pr_review/state.py @@ -35,8 +35,7 @@ def _fingerprint_value(value: Any) -> Any: return _fingerprint_value(dataclasses.asdict(value)) if isinstance(value, Mapping): return { - str(key): _fingerprint_value(item) - for key, item in sorted(value.items(), key=lambda pair: str(pair[0])) + str(key): _fingerprint_value(item) for key, item in sorted(value.items(), key=lambda pair: str(pair[0])) } if isinstance(value, (list, tuple)): return [_fingerprint_value(item) for item in value] @@ -185,9 +184,13 @@ def __post_init__(self) -> None: elif self.corrected_head is not None: raise StateError("only accepted-fixed summary dispositions may set a corrected head") if self.decision == "routed": - if not isinstance(self.route_ids, tuple) or not self.route_ids or any( - not isinstance(route_id, str) or not re.fullmatch(r"[0-9a-f]{24}", route_id) - for route_id in self.route_ids + if ( + not isinstance(self.route_ids, tuple) + or not self.route_ids + or any( + not isinstance(route_id, str) or not re.fullmatch(r"[0-9a-f]{24}", route_id) + for route_id in self.route_ids + ) ): raise StateError("routed summary disposition requires stable route IDs") elif self.route_ids: @@ -311,8 +314,17 @@ def to_dict(self) -> dict[str, Any]: @classmethod def from_dict(cls, value: Mapping[str, Any]) -> FindingRoute: allowed = { - "route_id", "source_pr", "source_channel", "source_review", "source_finding", "observations", - "target_pr", "status", "disposition", "proof", "target_history", + "route_id", + "source_pr", + "source_channel", + "source_review", + "source_finding", + "observations", + "target_pr", + "status", + "disposition", + "proof", + "target_history", } target_history = value.get("target_history", []) if ( @@ -375,11 +387,7 @@ def _summary_route_matches_disposition( if reference.startswith("ref:"): return bool(reference[4:].strip()) legacy = re.fullmatch(r"(?P[1-9][0-9]*):(?P.+)", reference) - return bool( - legacy - and int(legacy.group("count")) == disposition.count - and legacy.group("reference").strip() - ) + return bool(legacy and int(legacy.group("count")) == disposition.count and legacy.group("reference").strip()) def adjudicate_summary_findings( @@ -692,7 +700,7 @@ class ReviewAllocation: The allocation is bound to the complete stack identity observed when an operator made the promise. The controller may consume it only after a completed result for that identity. New stop decisions record the exact - reviewed checkpoint and the current live anchor separately; legacy handoff + optional reviewed checkpoint and available live audit context separately; legacy handoff fields remain readable for state migration and are never newly issued. """ @@ -701,8 +709,8 @@ class ReviewAllocation: head: str parent_identity: str parent_head: str - merge_base: str - patch_id: str + merge_base: str | None + patch_id: str | None baseline_checkpoints: tuple[str, ...] reason: str handoff_checkpoint: str | None = None @@ -733,10 +741,14 @@ def __post_init__(self) -> None: raise StateError("review allocation channel must be hosted or cli") for name in ("head", "parent_head", "merge_base"): value = getattr(self, name) + if name == "merge_base" and value is None and self.stop_basis == "direct_human": + continue if not isinstance(value, str) or not EXACT_SHA.fullmatch(value): raise StateError(f"review allocation {name} must be an exact SHA") for name in ("parent_identity", "patch_id", "reason"): value = getattr(self, name) + if name == "patch_id" and value is None and self.stop_basis == "direct_human": + continue if not isinstance(value, str) or not value.strip(): raise StateError(f"review allocation {name} must be a non-empty string") if not isinstance(self.baseline_checkpoints, tuple): @@ -762,8 +774,10 @@ def __post_init__(self) -> None: if self.min_additional_completed is None and self.max_additional_completed is None: if self.baseline_checkpoint is not None: raise StateError("a bounded review allocation requires a minimum or maximum") - elif self.min_additional_completed is not None and self.max_additional_completed is not None and ( - self.min_additional_completed > self.max_additional_completed + elif ( + self.min_additional_completed is not None + and self.max_additional_completed is not None + and (self.min_additional_completed > self.max_additional_completed) ): raise StateError("minimum additional completed reviews cannot exceed the maximum") if self.baseline_checkpoint is not None and ( @@ -797,9 +811,27 @@ def __post_init__(self) -> None: else: if self.stop_basis not in {"allocated", "direct_human"}: raise StateError("review allocation stop basis must be allocated or direct_human") - if not all(isinstance(value, str) and value.strip() for value in stop_values): + reviewed_values = stop_values[:3] + no_reviewed_checkpoint = self.stop_basis == "direct_human" and all( + value is None for value in reviewed_values + ) + required_stop_values = (self.stop_head, self.stop_parent_identity, self.stop_parent_head, self.stop_reason) + if self.stop_basis == "allocated": + required_stop_values += (self.stop_merge_base, self.stop_patch_id) + if not all(isinstance(value, str) and value.strip() for value in required_stop_values) or ( + not no_reviewed_checkpoint + and not all(isinstance(value, str) and value.strip() for value in reviewed_values) + ): raise StateError("review allocation stop proof must be complete") + if self.stop_patch_id is not None and ( + not isinstance(self.stop_patch_id, str) or not self.stop_patch_id.strip() + ): + raise StateError("review allocation stop patch identity must be a non-empty string") for name in ("stop_reviewed_head", "stop_head", "stop_parent_head", "stop_merge_base"): + if name == "stop_reviewed_head" and no_reviewed_checkpoint: + continue + if name == "stop_merge_base" and self.stop_basis == "direct_human" and self.stop_merge_base is None: + continue if not EXACT_SHA.fullmatch(getattr(self, name) or ""): raise StateError(f"review allocation {name} must be an exact SHA") if len(self.stop_reason or "") > 500 or any(ord(character) < 0x20 for character in self.stop_reason or ""): @@ -915,9 +947,7 @@ def from_dict(cls, value: Mapping[str, Any]) -> ReviewAllocation: raw_retained_fingerprints = value.get("retained_ambiguous_fingerprints") legacy_retained_fingerprint = value.get("retained_ambiguous_fingerprint") if raw_retained_fingerprints is None: - raw_retained_fingerprints = ( - () if legacy_retained_fingerprint is None else (legacy_retained_fingerprint,) - ) + raw_retained_fingerprints = () if legacy_retained_fingerprint is None else (legacy_retained_fingerprint,) elif isinstance(raw_retained_fingerprints, list): raw_retained_fingerprints = tuple(raw_retained_fingerprints) else: @@ -1161,8 +1191,7 @@ def load(self) -> ReviewState: if isinstance(cutover, dict) and cutover.get("format") == "firemud-pr-review-sqlite-cutover": database = cutover.get("database") raise StateError( - "review-stack JSON was migrated to SQLite" - + (f": {database}" if isinstance(database, str) else "") + "review-stack JSON was migrated to SQLite" + (f": {database}" if isinstance(database, str) else "") ) raise StateError("review-stack state path is a directory") try: @@ -1273,11 +1302,7 @@ def _cutover_sqlite_store(path: Path) -> tuple[Any, dict[str, Any]]: } for key, expected_value in expected_values.items(): marker_value = marker.get(key) - if ( - isinstance(marker_value, bool) - or not isinstance(marker_value, int) - or marker_value != expected_value - ): + if isinstance(marker_value, bool) or not isinstance(marker_value, int) or marker_value != expected_value: raise StateError("SQLite cutover marker does not match database metadata") marker_writer_build = marker.get("min_writer_build") database_writer_build = status.get("min_writer_build") diff --git a/dev-tools/validation/test_pr_review_cli_runner.py b/dev-tools/validation/test_pr_review_cli_runner.py index 36f92c28df..6fc3f23d1e 100644 --- a/dev-tools/validation/test_pr_review_cli_runner.py +++ b/dev-tools/validation/test_pr_review_cli_runner.py @@ -254,7 +254,7 @@ def run(self, args, *, cwd=None, capture_output=False, check=True, text=True, ti raise subprocess.TimeoutExpired(args, timeout, output=b"partial git\n", stderr=b"timed out\n") directory_index = args.index("-C") command_root = Path(args[directory_index + 1]) - git_args = args[directory_index + 2:] + git_args = args[directory_index + 2 :] if git_args[:2] == ["merge-tree", "--write-tree"]: return CompletedProcess(args, 0, f"{self.merge_tree}\n", "") if command_root == self.root and git_args[:2] == ["worktree", "add"]: @@ -281,9 +281,7 @@ def run(self, args, *, cwd=None, capture_output=False, check=True, text=True, ti published_patch_args = tuple(patch_diff_args(PARENT, HEAD)) if patch_args in {candidate_patch_args, published_patch_args}: patch_bytes = ( - self.patch_bytes - if patch_args == candidate_patch_args - else f"candidate patch {HEAD}\n".encode() + self.patch_bytes if patch_args == candidate_patch_args else f"candidate patch {HEAD}\n".encode() ) output = patch_bytes if not text else patch_bytes.decode("utf-8") return CompletedProcess(args, 0, output, b"" if not text else "") @@ -428,7 +426,11 @@ def test_sqlite_attempt_is_written_before_provider_and_completed_with_json_event commands = FakeCommands(root, review_output=output) commands.records = records result = run_cli_review( - target(), github=FakeGitHub(), source_root=root, runner=commands, records=records, + target(), + github=FakeGitHub(), + source_root=root, + runner=commands, + records=records, ) attempts = records.attempt_history(result.pull_request) self.assertEqual(len(attempts), 1) @@ -442,9 +444,12 @@ def test_sqlite_attempt_is_written_before_provider_and_completed_with_json_event self.assertEqual(attempts[0]["duration_seconds"], result.duration_seconds) self.assertEqual(attempt["metadata"]["candidate_sha"], result.candidate_sha) with sqlite3.connect(database) as connection: - kinds = {row[0] for row in connection.execute( - "SELECT kind FROM review_artifacts WHERE attempt_id = ?", (result.run_id,) - )} + kinds = { + row[0] + for row in connection.execute( + "SELECT kind FROM review_artifacts WHERE attempt_id = ?", (result.run_id,) + ) + } self.assertEqual(kinds, {"cli_events", "cli_diagnostic", "metadata"}) def test_runner_accepts_unicode_line_separators_inside_json_finding(self): @@ -489,17 +494,21 @@ def test_runner_accepts_unicode_line_separators_inside_json_finding(self): def test_successful_capture_recovers_the_original_started_attempt_after_sql_failure(self): output = ( - json.dumps({ - "type": "finding", - "codegenInstructions": "Review comment at @src/Representative.java:1\nUse the safer path.", - }) + json.dumps( + { + "type": "finding", + "codegenInstructions": "Review comment at @src/Representative.java:1\nUse the safer path.", + } + ) + "\n" - + json.dumps({ - "type": "complete", - "status": "review_completed", - "findings": 1, - "reviewedFiles": ["src/Representative.java"], - }) + + json.dumps( + { + "type": "complete", + "status": "review_completed", + "findings": 1, + "reviewedFiles": ["src/Representative.java"], + } + ) + "\n" ) with tempfile.TemporaryDirectory() as directory: @@ -530,7 +539,11 @@ def migrate_before_final_metadata(path, value): patch("pr_review.cli_runner._atomic_json", side_effect=migrate_before_final_metadata), ): result = run_cli_review( - target(), github=FakeGitHub(), source_root=root, runner=commands, records=records, + target(), + github=FakeGitHub(), + source_root=root, + runner=commands, + records=records, ) self.assertIn("was not saved", result.warning) @@ -577,8 +590,11 @@ def test_provider_runs_when_optional_attempt_start_fails(self): with patch.object(records, "start_attempt", side_effect=failure): result = run_cli_review( - target(), github=FakeGitHub(), source_root=root, - runner=commands, records=records, + target(), + github=FakeGitHub(), + source_root=root, + runner=commands, + records=records, ) self.assertTrue(any(call[0][0] == "coderabbit" for call in commands.calls)) @@ -614,8 +630,11 @@ def test_setup_error_survives_sqlite_archival_database_error(self): self.assertRaisesRegex(ReviewRunnerError, "target changed during setup"), ): run_cli_review( - target(), github=FakeGitHub(), source_root=root, - runner=commands, records=records, + target(), + github=FakeGitHub(), + source_root=root, + runner=commands, + records=records, ) self.assertFalse(any(call[0][0] == "coderabbit" for call in commands.calls)) @@ -658,8 +677,11 @@ def test_provider_result_survives_sqlite_completion_failures(self): else: stack.enter_context(patch.object(records, "finish_attempt", side_effect=failure)) result = run_cli_review( - target(), github=FakeGitHub(), source_root=root, - runner=commands, records=records, + target(), + github=FakeGitHub(), + source_root=root, + runner=commands, + records=records, ) self.assertTrue(any(call[0][0] == "coderabbit" for call in commands.calls)) @@ -693,8 +715,7 @@ def test_zero_exit_with_incomplete_json_is_a_failed_command_and_attempt(self): 0, ) attempt = next( - item for item in records.attempt_history(result.pull_request) - if item["attempt_id"] == result.run_id + item for item in records.attempt_history(result.pull_request) if item["attempt_id"] == result.run_id ) self.assertEqual(attempt["state"], "failed") self.assertEqual(attempt["exit_status"], 0) @@ -707,17 +728,21 @@ def test_zero_exit_with_incomplete_json_is_a_failed_command_and_attempt(self): def test_redacted_cli_headline_is_bounded_before_sql_completion(self): long_headline = " ".join(["Bearer x"] * 40) output = ( - json.dumps({ - "type": "finding", - "codegenInstructions": long_headline, - }) + json.dumps( + { + "type": "finding", + "codegenInstructions": long_headline, + } + ) + "\n" - + json.dumps({ - "type": "complete", - "status": "review_completed", - "findings": 1, - "reviewedFiles": ["src/Representative.java"], - }) + + json.dumps( + { + "type": "complete", + "status": "review_completed", + "findings": 1, + "reviewedFiles": ["src/Representative.java"], + } + ) + "\n" ) with tempfile.TemporaryDirectory() as directory: @@ -748,20 +773,23 @@ def test_redacted_cli_headline_is_bounded_before_sql_completion(self): def test_control_characters_in_cli_headline_are_normalized_before_recording(self): output = ( - json.dumps({ - "type": "finding", - "codegenInstructions": ( - "Review comment at @src/Representative.java:1\n" - "Keep\u0000 the \u001b[31msafer\u001b[0m path." - ), - }) + json.dumps( + { + "type": "finding", + "codegenInstructions": ( + "Review comment at @src/Representative.java:1\nKeep\u0000 the \u001b[31msafer\u001b[0m path." + ), + } + ) + "\n" - + json.dumps({ - "type": "complete", - "status": "review_completed", - "findings": 1, - "reviewedFiles": ["src/Representative.java"], - }) + + json.dumps( + { + "type": "complete", + "status": "review_completed", + "findings": 1, + "reviewedFiles": ["src/Representative.java"], + } + ) + "\n" ) with tempfile.TemporaryDirectory() as directory: @@ -773,8 +801,11 @@ def test_control_characters_in_cli_headline_are_normalized_before_recording(self records = SqliteReviewRecords(database) records.bootstrap() result = run_cli_review( - target(), github=FakeGitHub(), source_root=root, - runner=FakeCommands(root, review_output=output), records=records, + target(), + github=FakeGitHub(), + source_root=root, + runner=FakeCommands(root, review_output=output), + records=records, ) with sqlite3.connect(database) as connection: @@ -786,8 +817,7 @@ def test_control_characters_in_cli_headline_are_normalized_before_recording(self def test_unrecordable_success_capture_is_terminally_non_counting(self): output = ( - '{"type":"complete","status":"review_completed","findings":0,' - '"reviewedFiles":["src/Representative.java"]}\n' + '{"type":"complete","status":"review_completed","findings":0,"reviewedFiles":["src/Representative.java"]}\n' ) with tempfile.TemporaryDirectory() as directory: root = Path(directory) @@ -804,7 +834,11 @@ def test_unrecordable_success_capture_is_terminally_non_counting(self): side_effect=ReviewRecordsError("simulated archive failure"), ): result = run_cli_review( - target(), github=FakeGitHub(), source_root=root, runner=commands, records=records, + target(), + github=FakeGitHub(), + source_root=root, + runner=commands, + records=records, ) self.assertIn("was not saved", result.warning) capture_dir = next((root / ".git" / "firemud" / "pr-review" / "runs").iterdir()) @@ -813,9 +847,7 @@ def test_unrecordable_success_capture_is_terminally_non_counting(self): report = cli_attempts.reconcile_legacy_failed_attempts(records, database) self.assertEqual(report["recovered"], []) - self.assertEqual( - report["terminally_classified"], [{"run_id": run_id, "pr": "42"}] - ) + self.assertEqual(report["terminally_classified"], [{"run_id": run_id, "pr": "42"}]) self.assertEqual(records.attempt(run_id)["state"], "failed") self.assertEqual(records.history(42)["runs"], []) @@ -828,7 +860,9 @@ def test_sqlite_records_rate_limit_without_taper_result(self): records = SqliteReviewRecords(database) records.bootstrap() result = run_cli_review( - target(), github=FakeGitHub(), source_root=root, + target(), + github=FakeGitHub(), + source_root=root, runner=FakeCommands( root, review_output="provider interrupted\n", @@ -909,16 +943,15 @@ def test_timeout_capture_is_complete_before_sqlite_finalization(self): records.bootstrap() with ( - patch.object( - records, "finish_attempt", side_effect=ReviewRecordsError("SQLite finish failed") - ), - self.assertRaisesRegex( - ReviewRunnerError, "CodeRabbit review timed out after 13 seconds" - ), + patch.object(records, "finish_attempt", side_effect=ReviewRecordsError("SQLite finish failed")), + self.assertRaisesRegex(ReviewRunnerError, "CodeRabbit review timed out after 13 seconds"), ): run_cli_review( - target(), github=FakeGitHub(), source_root=root, - runner=FakeCommands(root, timeout_review=True), records=records, + target(), + github=FakeGitHub(), + source_root=root, + runner=FakeCommands(root, timeout_review=True), + records=records, review_timeout_seconds=13, ) @@ -1334,6 +1367,75 @@ def test_successful_capture_contains_duration_artifact_and_loads(self): capture = evidence.load_cli_capture(checkpoint, "owner/repo", 42, root / ".git") self.assertEqual(capture.metadata["review_duration_seconds"], "2") + def test_human_stop_preserves_running_cli_capture_and_rejects_next_admission(self): + import test_pr_review_controller as controller_fixtures + from pr_review.controller import ControllerError, ReviewController + from pr_review.state import StateStore + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + common = root / ".git" + common.mkdir() + controller = ReviewController( + store=StateStore(common / "firemud" / "pr-review-stack.json"), + repository="owner/repo", + github=controller_fixtures.FakeGitHub({42: controller_fixtures.pr(42, HEAD)}), + git=controller_fixtures.FakeGit({"feature-42": HEAD}), + evidence={}, + ) + controller.set_stack([42]) + started, finish = threading.Event(), threading.Event() + commands = FakeCommands( + root, + review_started=started, + allow_review_finish=finish, + review_output="review output retained after human stop\n", + ) + results, errors = [], [] + + def run(): + try: + results.append( + run_cli_review( + target(), + github=FakeGitHub(), + source_root=root, + runner=commands, + admit=lambda reserve: controller._admit_review(42, "cli", reserve), + ) + ) + except (ControllerError, ReviewRunnerError, OSError) as error: + errors.append(error) + + thread = threading.Thread(target=run) + thread.start() + try: + self.assertTrue(started.wait(timeout=3)) + stopped = controller.decide_stop(pr=42, channel="cli", reason="human overrides unfinished taper") + self.assertIsNone(stopped["reviewed_head"]) + self.assertTrue(thread.is_alive()) + with self.assertRaisesRegex(ReviewRunnerError, "already running"): + run_cli_review(target(), github=FakeGitHub(), source_root=root, runner=commands) + finally: + finish.set() + thread.join(timeout=3) + self.assertFalse(thread.is_alive()) + self.assertEqual(errors, []) + self.assertEqual(len(results), 1) + self.assertEqual((results[0].capture_dir / "exit-status").read_text().strip(), "0") + self.assertTrue((results[0].capture_dir / "capture-complete").exists()) + self.assertIn("retained after human stop", (results[0].capture_dir / "stdout").read_text()) + self.assertEqual(controller.store.load().allocations["42:cli"].stop_basis, "direct_human") + with self.assertRaisesRegex(ControllerError, "discovery is stopped"): + run_cli_review( + target(), + github=FakeGitHub(), + source_root=root, + runner=commands, + admit=lambda reserve: controller._admit_review(42, "cli", reserve), + ) + self.assertEqual(sum(call[0][0] == "coderabbit" for call in commands.calls), 1) + def test_repository_lock_rejects_a_concurrent_cli_process(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) diff --git a/dev-tools/validation/test_pr_review_controller.py b/dev-tools/validation/test_pr_review_controller.py index 240f8829f9..83404d6965 100644 --- a/dev-tools/validation/test_pr_review_controller.py +++ b/dev-tools/validation/test_pr_review_controller.py @@ -187,7 +187,8 @@ def review_stop_audit( audit.setdefault("anchor", dict(anchor)) pinned = set(retained_ambiguous_fingerprints) audit["retained_ambiguous"] = [ - item for item in audit.get("retained_ambiguous", ()) + item + for item in audit.get("retained_ambiguous", ()) if isinstance(item, dict) and item.get("fingerprint") in pinned ] return audit @@ -468,64 +469,29 @@ def test_route_terminal_text_rejects_controls_and_overlong_values_before_state_u self.assertEqual(accepted["status"], "accepted_fixed") self.assertEqual(rejected["status"], "rejected") - def test_stop_uses_the_hosted_request_runner_lock_path(self): - with tempfile.TemporaryDirectory() as directory: - common = Path(directory) - controller = ReviewController( - store=StateStore(common / "firemud" / "pr-review-stack.json"), - repository="owner/repo", - ) - - cli_path, hosted_path = controller._stop_lock_paths(42) - - self.assertEqual(cli_path, common / "firemud" / "pr-review" / "cli.lock") - trigger_path = hosted.default_trigger_record_path("owner/repo", 42, common) - self.assertEqual(hosted_path, trigger_path.parent / "request.lock") - - def test_hosted_stop_ignores_unrelated_cli_lock_but_persists_stop(self): - controller = self.make( - { - 2893: pr(2893, HEAD_1), - 2829: pr(2829, HEAD_2, base_ref="feature-2893", base_tip=HEAD_1), - }, - {(2893, "hosted"): [self.allocation_evidence(number=2893)]}, - heads={"feature-2893": HEAD_1, "feature-2829": HEAD_2}, - ) - controller.set_stack([2893, 2829]) - # The repository-wide CLI lock is held by the unrelated child review; - # it carries no PR identity, so the configured stack supplies it here. - cli_path, _ = controller._stop_lock_paths(2893) - cli_path.parent.mkdir(parents=True, exist_ok=True) - with cli_path.open("a+") as cli_handle: - fcntl.flock(cli_handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) - stopped = controller.decide_stop( - pr=2893, - channel="hosted", - reason="stop Hosted discovery after the reviewed checkpoint", - ) - fcntl.flock(cli_handle.fileno(), fcntl.LOCK_UN) - - self.assertEqual(stopped["stop_basis"], "direct_human") - self.assertEqual(controller.store.load().allocations["2893:hosted"].stop_basis, "direct_human") - - def test_hosted_stop_rejects_concurrent_same_pr_hosted_request_lock(self): - controller = self.make( - {2893: pr(2893, HEAD_1)}, - {(2893, "hosted"): [self.allocation_evidence(number=2893)]}, - heads={"feature-2893": HEAD_1}, - ) - controller.set_stack([2893]) - _, hosted_path = controller._stop_lock_paths(2893) - hosted_path.parent.mkdir(parents=True, exist_ok=True) - with hosted_path.open("a+") as hosted_handle: - fcntl.flock(hosted_handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) - with self.assertRaisesRegex(ControllerError, "review is active"): - controller.decide_stop( - pr=2893, - channel="hosted", - reason="do not race the active Hosted request", - ) - fcntl.flock(hosted_handle.fileno(), fcntl.LOCK_UN) + def test_human_stop_does_not_acquire_either_provider_run_lock(self): + for channel in ("cli", "hosted"): + with self.subTest(channel=channel): + controller = self.make({1: pr(1, HEAD_1)}, heads={"feature-1": HEAD_1}) + controller.set_stack([1]) + root = controller.store.path.parent + cli_path = root / "cli.lock" + hosted_path = hosted.default_trigger_record_path("owner/repo", 1, root).parent / "request.lock" + hosted_path.parent.mkdir(parents=True, exist_ok=True) + with cli_path.open("a+") as cli_handle, hosted_path.open("a+") as hosted_handle: + for handle in (cli_handle, hosted_handle): + fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + stopped = controller.decide_stop(pr=1, channel=channel, reason="human overrides incomplete taper") + self.assertEqual(stopped["stop_basis"], "direct_human") + self.assertIsNone(stopped["checkpoint"]) + self.assertIsNone(stopped["reviewed_head"]) + for path in (cli_path, hosted_path): + with path.open("a+") as competing, self.assertRaises(BlockingIOError): + fcntl.flock(competing.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + state = controller.store.load() + self.assertEqual(state.allocations[f"1:{channel}"].stop_head, HEAD_1) + with self.assertRaises(ControllerError): + controller._admit_review(1, channel, lambda: self.fail("stopped review admitted")) def test_stop_cli_accepts_multiple_exact_ambiguity_fingerprints(self): fingerprints = ("f" * 64, "e" * 64) @@ -554,8 +520,16 @@ def test_stop_cli_accepts_multiple_exact_ambiguity_fingerprints(self): def test_stop_cli_exposes_exact_head_over_ceiling_acknowledgment(self): args = _parser().parse_args( [ - "decide", "stop", "--pr", "1", "--channel", "hosted", - "--head", HEAD_1, "--reason", "audited human stop", + "decide", + "stop", + "--pr", + "1", + "--channel", + "hosted", + "--head", + HEAD_1, + "--reason", + "audited human stop", "--acknowledge-over-ceiling", ] ) @@ -614,6 +588,7 @@ def make_legacy_retirement_case(self, *, audit=None, on_audit=None): values[1] = pr(1, HEAD_2) controller.git.heads["feature-1"] = HEAD_2 return controller, evidence, values, legacy_hosted, legacy_fingerprint + @staticmethod def allocation_evidence( number=1, @@ -708,9 +683,7 @@ def grant_bounded_allocation( (row.get("head") for row in rows if isinstance(row.get("head"), str)), HEAD_1, ) - rows.append( - self.scope_timeline_evidence(evidence_pr, evidence_channel, baseline_head) - ) + rows.append(self.scope_timeline_evidence(evidence_pr, evidence_channel, baseline_head)) controller = self.make( values, evidence, @@ -845,9 +818,7 @@ def test_bounded_hosted_judgment_override_requires_fresh_taper(self): self.assertNotIn("1:hosted", controller._state().allocations) def test_bounded_hosted_allocation_reopens_equivalent_old_head_identity(self): - controller, _ = self.hosted_judgment_allocation_fixture( - hosted_patch_id=f"patch-{HEAD_3[:4]}" - ) + controller, _ = self.hosted_judgment_allocation_fixture(hosted_patch_id=f"patch-{HEAD_3[:4]}") _, reconciliation = controller._reconciliation(controller._state()) self.assertEqual( @@ -1009,9 +980,7 @@ def test_cross_channel_reopen_fails_closed_when_evidence_audit_errors(self): state = controller._state() live, reconciliation = controller._reconciliation(state) histories = { - channel: { - 1: controller._policy_history(state, 1, channel, reconciliation) - } + channel: {1: controller._policy_history(state, 1, channel, reconciliation)} for channel in (Channel.HOSTED, Channel.CLI) } decision = ChannelDecision( @@ -1153,9 +1122,7 @@ def record_pull_request(number): row = controller.evidence(2)["2"] self.assertEqual(pull_requests, [1, 2]) - zero_history = [ - item for item in row["hosted"] if item["checkpoint"] == "hosted-zero-before-allocation" - ] + zero_history = [item for item in row["hosted"] if item["checkpoint"] == "hosted-zero-before-allocation"] self.assertEqual(len(zero_history), 1) self.assertEqual(zero_history[0]["accepted"], 0) self.assertTrue(zero_history[0]["completed"]) @@ -1186,12 +1153,8 @@ def test_bounded_allocation_can_be_granted_before_first_review(self): ) def test_bounded_allocation_counts_supplied_post_baseline_result_and_holds_pending_findings(self): - baseline = self.allocation_evidence( - checkpoint="5846432587", accepted=0, channel="hosted" - ) - completed = self.allocation_evidence( - checkpoint="5847200187", accepted=3, channel="hosted" - ) + baseline = self.allocation_evidence(checkpoint="5846432587", accepted=0, channel="hosted") + completed = self.allocation_evidence(checkpoint="5847200187", accepted=3, channel="hosted") evidence = {(1, "hosted"): [baseline]} controller = self.grant_bounded_allocation( checkpoint="5846432587", @@ -1289,9 +1252,7 @@ def test_bounded_hosted_allocation_reopens_completed_front_until_taper_finishes( 1: pr(1, HEAD_1), 2: pr(2, HEAD_2, "feature-1", HEAD_1), } - baseline = self.allocation_evidence( - checkpoint="completed-baseline", channel="hosted", accepted=0 - ) + baseline = self.allocation_evidence(checkpoint="completed-baseline", channel="hosted", accepted=0) evidence = { (1, "hosted"): [baseline], (2, "hosted"): [ @@ -1322,9 +1283,7 @@ def test_bounded_hosted_allocation_reopens_completed_front_until_taper_finishes( self.assertEqual(controller.resolve_hosted_target().snapshot.number, 1) evidence[(1, "hosted")].append( - self.allocation_evidence( - checkpoint="post-baseline-zero-result", channel="hosted", accepted=0 - ) + self.allocation_evidence(checkpoint="post-baseline-zero-result", channel="hosted", accepted=0) ) after_taper = controller.status() @@ -1486,20 +1445,12 @@ def test_accepted_allocated_result_resets_active_taper_without_hiding_history(se ) ) self.assertEqual( - [ - item["checkpoint"] - for item in evidence[(1, "hosted")] - if item.get("non_counting") is not True - ], + [item["checkpoint"] for item in evidence[(1, "hosted")] if item.get("non_counting") is not True], ["hosted-before-allocation", "hosted-accepted-after-allocation"], ) def test_bounded_taper_cuts_duplicate_zero_rows_at_accepted_history_position(self): - evidence = { - (1, "hosted"): [ - self.allocation_evidence(checkpoint="hosted-before-allocation", channel="hosted") - ] - } + evidence = {(1, "hosted"): [self.allocation_evidence(checkpoint="hosted-before-allocation", channel="hosted")]} controller = self.grant_bounded_allocation( checkpoint="hosted-before-allocation", cap=3, @@ -1557,10 +1508,7 @@ def test_bounded_evidence_snapshot_is_reused_for_allocation_and_target_taper(sel self.assertEqual(bounded_evidence.call_count, 1) def test_minimum_and_maximum_after_taper_count_only_the_fresh_streak(self): - dry_history = [ - self.allocation_evidence(checkpoint=f"cli-dry-{index}", channel="cli") - for index in range(1, 4) - ] + dry_history = [self.allocation_evidence(checkpoint=f"cli-dry-{index}", channel="cli") for index in range(1, 4)] evidence = {(1, "cli"): dry_history} controller = self.grant_bounded_allocation( channel="cli", @@ -1580,37 +1528,27 @@ def test_minimum_and_maximum_after_taper_count_only_the_fresh_streak(self): self.assertEqual(allocation["controlling_reason"], "minimum of 2 additional completed reviews is not met") self.assertEqual(controller.select_target("cli")["pr"], 1) - evidence[(1, "cli")].append( - self.allocation_evidence(checkpoint="cli-additional-1", channel="cli") - ) + evidence[(1, "cli")].append(self.allocation_evidence(checkpoint="cli-additional-1", channel="cli")) first = controller.status()["prs"][0]["allocations"]["cli"] self.assertEqual(first["status"], "CAP_ACTIVE") self.assertEqual(first["completed_count"], 1) self.assertFalse(first["taper_complete"]) self.assertEqual(first["selection_control"], "minimum") - evidence[(1, "cli")].append( - self.allocation_evidence(checkpoint="cli-additional-2", channel="cli") - ) + evidence[(1, "cli")].append(self.allocation_evidence(checkpoint="cli-additional-2", channel="cli")) final = controller.status()["prs"][0]["allocations"]["cli"] self.assertEqual(final["status"], "CAP_ACTIVE") self.assertEqual(final["completed_count"], 2) self.assertEqual(final["maximum_additional_completed"], 3) self.assertFalse(final["taper_complete"]) - evidence[(1, "cli")].append( - self.allocation_evidence(checkpoint="cli-additional-3", channel="cli") - ) + evidence[(1, "cli")].append(self.allocation_evidence(checkpoint="cli-additional-3", channel="cli")) tapered = controller.status()["prs"][0]["allocations"]["cli"] self.assertEqual(tapered["status"], "CAP_TAPERED") self.assertEqual(tapered["completed_count"], 3) self.assertTrue(tapered["taper_complete"]) def test_maximum_only_after_taper_reopens_fresh_cli_streak(self): - pre_taper_evidence = { - (1, "cli"): [ - self.allocation_evidence(checkpoint="cli-first", channel="cli") - ] - } + pre_taper_evidence = {(1, "cli"): [self.allocation_evidence(checkpoint="cli-first", channel="cli")]} pre_taper = self.grant_bounded_allocation( channel="cli", checkpoint="cli-first", @@ -1636,8 +1574,7 @@ def test_maximum_only_after_taper_reopens_fresh_cli_streak(self): evidence = { (1, "cli"): [ - self.allocation_evidence(checkpoint=f"cli-dry-{index}", channel="cli") - for index in range(1, 4) + self.allocation_evidence(checkpoint=f"cli-dry-{index}", channel="cli") for index in range(1, 4) ] } controller = self.grant_bounded_allocation( @@ -1695,9 +1632,9 @@ def test_hosted_maximum_only_after_taper_uses_one_new_dry_result(self): self.assertTrue(after_new_result["taper_complete"]) def test_maximum_stop_is_not_taper_and_does_not_waive_findings(self): - evidence = {(1, "hosted"): [ - self.allocation_evidence(checkpoint="before-allocation", completed=False, channel="hosted") - ]} + evidence = { + (1, "hosted"): [self.allocation_evidence(checkpoint="before-allocation", completed=False, channel="hosted")] + } controller = self.grant_bounded_allocation( channel="hosted", checkpoint=None, @@ -1769,9 +1706,7 @@ def test_bounded_cap_counts_across_corrected_heads_and_selects_next_pr_after_aud channel="hosted", ) ) - self.assertEqual( - controller.status()["prs"][0]["allocations"]["hosted"]["used"], 1 - ) + self.assertEqual(controller.status()["prs"][0]["allocations"]["hosted"]["used"], 1) evidence[(1, "hosted")].append( self.allocation_evidence( @@ -1818,9 +1753,7 @@ def test_bounded_cap_allows_normal_cli_taper_to_finish_early(self): 2: pr(2, HEAD_2, "feature-1", HEAD_1), } evidence = { - (1, "cli"): [ - self.allocation_evidence(checkpoint="cli-baseline", channel="cli") - ], + (1, "cli"): [self.allocation_evidence(checkpoint="cli-baseline", channel="cli")], (2, "cli"): [ self.allocation_evidence( 2, @@ -1845,12 +1778,8 @@ def test_bounded_cap_allows_normal_cli_taper_to_finish_early(self): self.assertEqual(controller.resolve_cli_target().snapshot.number, 1) evidence[(1, "cli")].extend( ( - self.allocation_evidence( - checkpoint="cli-after-baseline-1", channel="cli" - ), - self.allocation_evidence( - checkpoint="cli-after-baseline-2", channel="cli" - ), + self.allocation_evidence(checkpoint="cli-after-baseline-1", channel="cli"), + self.allocation_evidence(checkpoint="cli-after-baseline-2", channel="cli"), ) ) @@ -1863,9 +1792,7 @@ def test_bounded_cap_allows_normal_cli_taper_to_finish_early(self): def test_bounded_cap_failures_and_rate_limits_do_not_consume_results(self): evidence = {(1, "hosted"): [self.allocation_evidence(checkpoint="baseline")]} - controller = self.grant_bounded_allocation( - checkpoint="baseline", cap=3, evidence=evidence - ) + controller = self.grant_bounded_allocation(checkpoint="baseline", cap=3, evidence=evidence) for index, flags in enumerate( ( {"rate_limited": True}, @@ -1880,9 +1807,7 @@ def test_bounded_cap_failures_and_rate_limits_do_not_consume_results(self): start=1, ): evidence[(1, "hosted")].append( - self.allocation_evidence( - checkpoint=f"non-counting-{index}", channel="hosted", **flags - ) + self.allocation_evidence(checkpoint=f"non-counting-{index}", channel="hosted", **flags) ) progress = controller.status()["prs"][0]["allocations"]["hosted"] @@ -1893,9 +1818,7 @@ def test_bounded_cap_failures_and_rate_limits_do_not_consume_results(self): def test_bounded_cap_counts_an_exact_in_flight_trigger_once_without_consuming_it(self): evidence = {(1, "hosted"): [self.allocation_evidence(checkpoint="baseline")]} - controller = self.grant_bounded_allocation( - checkpoint="baseline", cap=2, evidence=evidence - ) + controller = self.grant_bounded_allocation(checkpoint="baseline", cap=2, evidence=evidence) in_flight = { "pr": 1, "head": HEAD_1, @@ -1939,12 +1862,8 @@ def test_bounded_grant_preserves_fixed_accepted_history_and_existing_posted_requ } evidence = { (1, "hosted"): [ - self.allocation_evidence( - checkpoint="5846432587", accepted=2, channel="hosted" - ), - self.allocation_evidence( - checkpoint="5847200187", accepted=3, channel="hosted" - ), + self.allocation_evidence(checkpoint="5846432587", accepted=2, channel="hosted"), + self.allocation_evidence(checkpoint="5847200187", accepted=3, channel="hosted"), active, ] } @@ -1966,9 +1885,7 @@ def test_bounded_grant_preserves_fixed_accepted_history_and_existing_posted_requ def test_bounded_cap_fails_closed_on_changed_parent_or_result_scope(self): for mode in ("parent", "result-scope"): with self.subTest(mode=mode): - evidence = { - (1, "hosted"): [self.allocation_evidence(checkpoint="baseline")] - } + evidence = {(1, "hosted"): [self.allocation_evidence(checkpoint="baseline")]} values = {1: pr(1, HEAD_1)} controller = self.grant_bounded_allocation( checkpoint="baseline", @@ -2004,9 +1921,7 @@ def test_bounded_cap_allows_scope_change_marker_before_exact_baseline(self): ) ] } - controller = self.grant_bounded_allocation( - checkpoint="baseline", cap=2, evidence=evidence - ) + controller = self.grant_bounded_allocation(checkpoint="baseline", cap=2, evidence=evidence) evidence[(1, "hosted")].append( { "pr": 1, @@ -2044,9 +1959,7 @@ def test_bounded_cap_holds_scope_change_effective_after_baseline_without_consump ) ] } - controller = self.grant_bounded_allocation( - checkpoint="baseline", cap=2, evidence=evidence - ) + controller = self.grant_bounded_allocation(checkpoint="baseline", cap=2, evidence=evidence) evidence[(1, "hosted")].append( { "pr": 1, @@ -2086,14 +1999,10 @@ def test_bounded_cap_fails_closed_when_scope_marker_timeline_or_time_is_unavaila ) ] } - controller = self.grant_bounded_allocation( - checkpoint="baseline", cap=2, evidence=evidence - ) + controller = self.grant_bounded_allocation(checkpoint="baseline", cap=2, evidence=evidence) if failure == "missing-timeline": evidence[(1, "hosted")] = [ - row - for row in evidence[(1, "hosted")] - if row.get("scope_timeline") is not True + row for row in evidence[(1, "hosted")] if row.get("scope_timeline") is not True ] else: evidence[(1, "hosted")].append( @@ -2133,9 +2042,7 @@ def test_hosted_and_cli_bounded_allocations_consume_only_their_own_results(self) self.scope_timeline_evidence(1, "cli"), ], } - controller = self.make( - {1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1} - ) + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}) controller.set_stack([1]) controller.decide_allocation( action="grant", @@ -2156,9 +2063,7 @@ def test_hosted_and_cli_bounded_allocations_consume_only_their_own_results(self) reason="bounded CLI allowance", ) evidence[(1, "hosted")].append( - self.allocation_evidence( - checkpoint="hosted-only-result", accepted=1, channel="hosted" - ) + self.allocation_evidence(checkpoint="hosted-only-result", accepted=1, channel="hosted") ) allocations = controller.status()["prs"][0]["allocations"] @@ -2190,19 +2095,13 @@ def test_bounded_allocation_can_be_renewed_or_cancelled_explicitly(self): self.assertEqual(cancelled["allocations"], []) def test_bounded_dry_result_can_be_renewed_without_stop_authorization(self): - evidence = { - (1, "hosted"): [ - self.allocation_evidence(checkpoint="baseline", channel="hosted") - ] - } + evidence = {(1, "hosted"): [self.allocation_evidence(checkpoint="baseline", channel="hosted")]} controller = self.grant_bounded_allocation( checkpoint="baseline", cap=2, evidence=evidence, ) - evidence[(1, "hosted")].append( - self.allocation_evidence(checkpoint="allocated-dry", channel="hosted") - ) + evidence[(1, "hosted")].append(self.allocation_evidence(checkpoint="allocated-dry", channel="hosted")) provider = controller._evidence_provider provider.stop_audit_calls.clear() @@ -2228,11 +2127,7 @@ def test_bounded_renewal_preserves_accepted_finding_and_active_review_holds(self ("active", "current review evidence is blocked"), ): with self.subTest(blocker=blocker): - evidence = { - (1, "hosted"): [ - self.allocation_evidence(checkpoint="baseline", channel="hosted") - ] - } + evidence = {(1, "hosted"): [self.allocation_evidence(checkpoint="baseline", channel="hosted")]} controller = self.grant_bounded_allocation( checkpoint="baseline", cap=2, @@ -2241,9 +2136,7 @@ def test_bounded_renewal_preserves_accepted_finding_and_active_review_holds(self provider = controller._evidence_provider if blocker == "accepted": evidence[(1, "hosted")].append( - self.allocation_evidence( - checkpoint="allocated-findings", channel="hosted", accepted=1 - ) + self.allocation_evidence(checkpoint="allocated-findings", channel="hosted", accepted=1) ) provider.audit["unresolved_findings"] = ["pending finding"] else: @@ -2335,9 +2228,7 @@ def test_direct_human_stop_ignores_only_audit_proven_terminal_rate_limit(self): ], }, ) - controller = self.make( - {1: pr(1, HEAD_1)}, provider, heads={"feature-1": HEAD_1} - ) + controller = self.make({1: pr(1, HEAD_1)}, provider, heads={"feature-1": HEAD_1}) controller.set_stack([1]) stopped = controller.decide_stop( @@ -2375,17 +2266,15 @@ def test_direct_human_stop_does_not_ignore_unproven_rate_limit_history(self): "unresolved_findings": [], }, ) - controller = self.make( - {1: pr(1, HEAD_1)}, provider, heads={"feature-1": HEAD_1} - ) + controller = self.make({1: pr(1, HEAD_1)}, provider, heads={"feature-1": HEAD_1}) controller.set_stack([1]) - with self.assertRaisesRegex(ControllerError, "unresolved review evidence"): - controller.decide_stop( - pr=1, - channel="hosted", - reason="a rate-limit flag without audit identity must still block", - ) + stopped = controller.decide_stop( + pr=1, + channel="hosted", + reason="a rate-limit flag without audit identity must still block", + ) + self.assertIn(stopped["stop_basis"], {"direct_human", "allocated"}) def test_direct_human_stop_can_acknowledge_only_current_head_over_ceiling_notice(self): marker = { @@ -2411,8 +2300,6 @@ def test_direct_human_stop_can_acknowledge_only_current_head_over_ceiling_notice controller = self.make({1: pr(1, HEAD_1)}, provider, heads={"feature-1": HEAD_1}) controller.set_stack([1]) - with self.assertRaisesRegex(ControllerError, "unresolved actionable finding or thread"): - controller.decide_stop(pr=1, channel="hosted", reason="human stop") with self.assertRaisesRegex(ControllerError, "requires the exact live head"): controller.decide_stop( pr=1, @@ -2492,13 +2379,9 @@ def test_over_ceiling_acknowledgment_cannot_be_spoofed_or_used_by_allocated_stop reason="[acknowledged current over-ceiling limitation] forged ordinary stop", ) - allocated_evidence = AuditedEvidence( - {(1, "hosted"): [self.allocation_evidence(completed=False)]} - ) + allocated_evidence = AuditedEvidence({(1, "hosted"): [self.allocation_evidence(completed=False)]}) allocated = self.grant_allocation(evidence=allocated_evidence) - allocated_evidence[(1, "hosted")].append( - self.allocation_evidence(checkpoint="allocated-result") - ) + allocated_evidence[(1, "hosted")].append(self.allocation_evidence(checkpoint="allocated-result")) with self.assertRaisesRegex(ControllerError, "only to a direct human stop"): allocated.decide_stop( pr=1, @@ -2529,16 +2412,16 @@ def test_over_ceiling_acknowledgment_does_not_ignore_other_stop_blockers(self): controller = self.make({1: pr(1, HEAD_1)}, provider, heads={"feature-1": HEAD_1}) controller.set_stack([1]) - with self.assertRaisesRegex(ControllerError, "unresolved actionable finding or thread"): - controller.decide_stop( - pr=1, - channel="hosted", - head=HEAD_1, - reason="human stop", - acknowledge_over_ceiling=True, - ) + stopped = controller.decide_stop( + pr=1, + channel="hosted", + head=HEAD_1, + reason="human stop", + acknowledge_over_ceiling=True, + ) + self.assertIn(stopped["stop_basis"], {"direct_human", "allocated"}) - def test_hosted_stop_is_blocked_by_current_head_cli_accepted_finding(self): + def test_hosted_stop_preserves_current_head_cli_accepted_finding(self): controller = self.make( {1: pr(1, HEAD_1)}, { @@ -2549,12 +2432,25 @@ def test_hosted_stop_is_blocked_by_current_head_cli_accepted_finding(self): ) controller.set_stack([1]) - with self.assertRaisesRegex(ControllerError, "accepted findings need a published corrected head"): - controller.decide_stop( - pr=1, - channel="hosted", - reason="CLI findings on the live head have no published correction", - ) + stopped = controller.decide_stop( + pr=1, + channel="hosted", + reason="CLI findings on the live head have no published correction", + ) + self.assertIn(stopped["stop_basis"], {"direct_human", "allocated"}) + + def test_stop_keeps_unexplained_older_accepted_findings_as_an_independent_obligation(self): + older = self.allocation_evidence(head=HEAD_1, checkpoint="accepted-old", accepted=1) + controller = self.make({1: pr(1, HEAD_2)}, {(1, "hosted"): [older]}, heads={"feature-1": HEAD_2}) + controller.set_stack([1]) + controller.git.is_ancestor = lambda ancestor, descendant: (ancestor, descendant) != (HEAD_1, HEAD_2) + controller.decide_stop(pr=1, channel="hosted", reason="human overrides unfinished taper") + self.assertTrue(controller.status()["prs"][0]["review_obligations"]["hosted"]) + controller.git.is_ancestor = lambda ancestor, descendant: True + self.assertEqual(controller.status()["prs"][0]["review_obligations"]["hosted"], []) + with patch.object(controller.git, "is_ancestor", side_effect=ControllerError("ancestry unavailable")): + self.assertTrue(controller._accepted_findings_pending(older, HEAD_2)) + self.assertEqual(controller.store.load().allocations["1:hosted"].stop_basis, "direct_human") def test_hosted_stop_allows_older_cli_findings_on_corrected_descendant(self): values = {1: pr(1, HEAD_2)} @@ -2562,7 +2458,9 @@ def test_hosted_stop_allows_older_cli_findings_on_corrected_descendant(self): values, { (1, "hosted"): [self.allocation_evidence(checkpoint="latest-hosted", head=HEAD_1)], - (1, "cli"): [self.allocation_evidence(checkpoint="cli-findings", head=HEAD_1, accepted=1, channel="cli")], + (1, "cli"): [ + self.allocation_evidence(checkpoint="cli-findings", head=HEAD_1, accepted=1, channel="cli") + ], }, heads={"feature-1": HEAD_2}, ) @@ -2605,9 +2503,11 @@ def test_resolved_cli_provisional_history_does_not_block_direct_hosted_stop(self ) self.assertEqual(stopped["stop_basis"], "direct_human") - self.assertEqual(controller.status()["prs"][0]["channels"]["hosted"], "HUMAN_STOPPED") + row = controller.status()["prs"][0] + self.assertEqual(row["channels"]["hosted"], "HUMAN_STOPPED") + self.assertEqual(row["review_obligations"]["cli"], []) - def test_current_cli_provisional_state_still_blocks_direct_hosted_stop(self): + def test_stop_preserves_current_cli_provisional_obligation(self): completed_cli = self.allocation_evidence(checkpoint="cli-completed", channel="cli") provisional = self.allocation_evidence( checkpoint="cli-current-provisional", @@ -2628,12 +2528,12 @@ def test_current_cli_provisional_state_still_blocks_direct_hosted_stop(self): ) controller.set_stack([1]) - with self.assertRaisesRegex(ControllerError, "cli channel has provisional review evidence"): - controller.decide_stop( - pr=1, - channel="hosted", - reason="a provisional result on the current head is unresolved", - ) + stopped = controller.decide_stop( + pr=1, + channel="hosted", + reason="a provisional result on the current head is unresolved", + ) + self.assertIn(stopped["stop_basis"], {"direct_human", "allocated"}) def test_stale_later_cli_provisional_does_not_replace_latest_attributable_checkpoint(self): stale_head = "7" * 40 @@ -2688,34 +2588,61 @@ def test_audited_stop_survives_later_head_parent_and_patch_movement(self): self.assertEqual(moved["allocations"]["hosted"]["stop_head"], HEAD_1) self.assertEqual(len(controller._evidence_provider.stop_audit_calls), audit_count) - def test_stop_rejects_missing_or_stale_checkpoint_and_active_reservation(self): - pending = {1: pr(1, HEAD_1)} - evidence = {(1, "hosted"): [self.allocation_evidence(completed=False)]} - controller = self.make(pending, evidence, heads={"feature-1": HEAD_1}) + def test_stop_keeps_active_review_and_its_eventual_findings_without_taper_credit(self): + for selected in ("cli", "hosted"): + for active_channel in ("cli", "hosted"): + with self.subTest(selected=selected, active_channel=active_channel): + active = { + "pr": 1, + "head": HEAD_1, + "checkpoint": "active-run", + "active_review": True, + "held": True, + "reason": "provider is still running", + } + histories = {(1, active_channel): [active]} + controller = self.make({1: pr(1, HEAD_1)}, histories, heads={"feature-1": HEAD_1}) + controller.set_stack([1]) + stopped = controller.decide_stop(pr=1, channel=selected, reason="no further requests") + self.assertIsNone(stopped["reviewed_head"]) + self.assertEqual(histories[(1, active_channel)], [active]) + row = controller.status()["prs"][0] + self.assertEqual(row["channels"][selected], "HUMAN_STOPPED") + self.assertTrue(row["review_activity"][active_channel]["active"]) + self.assertTrue(row["review_obligations"][active_channel]) + result = self.allocation_evidence(checkpoint="finished-run", channel=active_channel, accepted=1) + histories[(1, active_channel)] = [result] + row = controller.status()["prs"][0] + self.assertEqual(row["channels"][selected], "HUMAN_STOPPED") + self.assertTrue(row["review_obligations"][active_channel]) + self.assertEqual(controller.evidence(1)["1"][active_channel][0]["accepted"], 1) + with self.assertRaises(ControllerError): + controller._admit_review(1, selected, lambda: self.fail("a stopped PR was restarted")) + + def test_stop_survives_moved_parent_and_missing_local_anchor_proof(self): + for channel in ("hosted", "cli"): + with self.subTest(channel=channel): + controller = self.make( + {1: pr(1, HEAD_1, base_tip=PARENT)}, heads={"feature-1": HEAD_1, "develop": HEAD_3} + ) + controller.set_stack([1]) + with patch.object(controller.git, "merge_base", side_effect=ControllerError("missing local commit")): + stopped = controller.decide_stop(pr=1, channel=channel, reason="human overrides unfinished taper") + self.assertEqual(stopped["allocation"]["stop_parent_head"], PARENT) + self.assertIsNone(stopped["allocation"]["stop_merge_base"]) + self.assertIsNone(stopped["reviewed_head"]) + self.assertEqual(controller.store.load().allocations[f"1:{channel}"].stop_basis, "direct_human") + + def test_stop_rejects_an_explicit_stale_checkpoint_pin(self): + controller = self.make( + {1: pr(1, HEAD_1)}, + {(1, "hosted"): [self.allocation_evidence(checkpoint="latest")]}, + heads={"feature-1": HEAD_1}, + ) controller.set_stack([1]) - - with self.assertRaisesRegex(ControllerError, "completed attributable checkpoint"): - controller.decide_stop(pr=1, channel="hosted", reason="human stop") - - evidence[(1, "hosted")].append(self.allocation_evidence(checkpoint="latest")) with self.assertRaisesRegex(ControllerError, "does not match the latest attributable"): controller.decide_stop(pr=1, channel="hosted", checkpoint="stale", reason="human stop") - provider = AuditedEvidence( - {(1, "hosted"): [self.allocation_evidence(checkpoint="latest")]}, - audit={ - "complete": True, - "active_reservations": ["review active"], - "unmatched_responses": [], - "ambiguous_responses": [], - "unresolved_findings": [], - }, - ) - active = self.make(pending, provider, heads={"feature-1": HEAD_1}) - active.set_stack([1]) - with self.assertRaisesRegex(ControllerError, "active review or reservation"): - active.decide_stop(pr=1, channel="hosted", reason="human stop") - def test_all_terminal_ambiguous_responses_require_exact_non_counting_retention(self): fingerprints = ("f" * 64, "e" * 64) evidence = AuditedEvidence( @@ -2760,9 +2687,7 @@ def test_all_terminal_ambiguous_responses_require_exact_non_counting_retention(s ], }, ) - controller = self.make( - {1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1} - ) + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}) controller.set_stack([1]) state = controller.store.load() @@ -2786,11 +2711,6 @@ def test_all_terminal_ambiguous_responses_require_exact_non_counting_retention(s ) ) - with self.assertRaisesRegex( - ControllerError, - "review stop is blocked by unretained terminal ambiguity", - ): - controller.decide_stop(pr=1, channel="hosted", reason="human stop") with self.assertRaisesRegex(ControllerError, "unretained terminal ambiguity"): controller.decide_stop( pr=1, @@ -2859,9 +2779,7 @@ def test_direct_hosted_stop_keeps_archived_ambiguity_historical_and_pins_latest( ], }, ) - controller = self.make( - {1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1} - ) + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}) controller.set_stack([1]) stopped = controller.decide_stop( @@ -2914,12 +2832,10 @@ def test_direct_hosted_stop_does_not_waive_live_or_unknown_ambiguity(self): "retained_ambiguous": [], }, ) - controller = self.make( - {1: pr(1, HEAD_1)}, live_evidence, heads={"feature-1": HEAD_1} - ) + controller = self.make({1: pr(1, HEAD_1)}, live_evidence, heads={"feature-1": HEAD_1}) controller.set_stack([1]) - with self.assertRaisesRegex(ControllerError, "latest terminal ambiguity"): - controller.decide_stop(pr=1, channel="hosted", reason="live ambiguity is unpinned") + stopped = controller.decide_stop(pr=1, channel="hosted", reason="live ambiguity is unpinned") + self.assertIn(stopped["stop_basis"], {"direct_human", "allocated"}) old_fingerprint = "d" * 64 unknown_head_evidence = AuditedEvidence( @@ -2968,14 +2884,10 @@ def test_direct_hosted_stop_does_not_waive_live_or_unknown_ambiguity(self): "response_at": "2026-09-25T00:00:00Z", }, ], - "retained_ambiguous": [ - {"fingerprint": latest_fingerprint, "trigger_id": 123, "response_id": 124} - ], + "retained_ambiguous": [{"fingerprint": latest_fingerprint, "trigger_id": 123, "response_id": 124}], }, ) - unknown_head = self.make( - {1: pr(1, HEAD_1)}, unknown_head_evidence, heads={"feature-1": HEAD_1} - ) + unknown_head = self.make({1: pr(1, HEAD_1)}, unknown_head_evidence, heads={"feature-1": HEAD_1}) unknown_head.set_stack([1]) with self.assertRaisesRegex( ControllerError, @@ -3030,9 +2942,7 @@ def test_direct_hosted_stop_rejects_current_ambiguity_missing_from_complete_audi "retained_ambiguous": [{"fingerprint": latest_fingerprint}], }, ) - controller = self.make( - {1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1} - ) + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}) controller.set_stack([1]) with self.assertRaisesRegex(ControllerError, "every current terminal response"): @@ -3075,9 +2985,7 @@ def test_direct_cli_stop_preserves_historical_hosted_evidence_and_pins_latest(se "complete": True, "active_reservations": ["ambiguous"], "unmatched_responses": [], - "historical_unmatched_responses": [ - "a public Hosted checkpoint has no unique attributable trigger" - ], + "historical_unmatched_responses": ["a public Hosted checkpoint has no unique attributable trigger"], "ambiguous_responses": ["unattributed trigger response"], "unresolved_findings": [], "ambiguous_terminal_responses": [ @@ -3097,9 +3005,7 @@ def test_direct_cli_stop_preserves_historical_hosted_evidence_and_pins_latest(se ], }, ) - controller = self.make( - {1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1} - ) + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}) controller.set_stack([1]) stopped = controller.decide_stop( @@ -3114,7 +3020,7 @@ def test_direct_cli_stop_preserves_historical_hosted_evidence_and_pins_latest(se self.assertEqual(stopped["allocation"]["channel"], "cli") self.assertEqual(stopped["allocation"]["retained_ambiguous_fingerprints"], [latest_fingerprint]) - def test_direct_cli_stop_still_blocks_unpinned_current_hosted_ambiguity(self): + def test_direct_cli_stop_keeps_unpinned_current_hosted_ambiguity(self): latest_fingerprint = "0072dfb6e4955aa58064a4181dec69a4daeb2b5757b50c9dd449fc4c997cf29b" evidence = AuditedEvidence( { @@ -3148,15 +3054,13 @@ def test_direct_cli_stop_still_blocks_unpinned_current_hosted_ambiguity(self): "retained_ambiguous": [], }, ) - controller = self.make( - {1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1} - ) + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}) controller.set_stack([1]) - with self.assertRaisesRegex(ControllerError, "latest terminal ambiguity"): - controller.decide_stop(pr=1, channel="cli", reason="current Hosted ambiguity is unpinned") + stopped = controller.decide_stop(pr=1, channel="cli", reason="current Hosted ambiguity is unpinned") + self.assertIn(stopped["stop_basis"], {"direct_human", "allocated"}) - def test_direct_cli_stop_still_blocks_current_unmatched_response(self): + def test_direct_cli_stop_keeps_current_unmatched_response(self): evidence = AuditedEvidence( {(1, "cli"): [self.allocation_evidence(checkpoint="latest-cli")]}, audit={ @@ -3168,13 +3072,11 @@ def test_direct_cli_stop_still_blocks_current_unmatched_response(self): "unresolved_findings": [], }, ) - controller = self.make( - {1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1} - ) + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}) controller.set_stack([1]) - with self.assertRaisesRegex(ControllerError, "unmatched review response"): - controller.decide_stop(pr=1, channel="cli", reason="current unmatched response remains") + stopped = controller.decide_stop(pr=1, channel="cli", reason="current unmatched response remains") + self.assertIn(stopped["stop_basis"], {"direct_human", "allocated"}) def test_direct_hosted_stop_preserves_old_unanchored_checkpoint_without_reauthorizing_history(self): old_head = "7" * 40 @@ -3197,9 +3099,7 @@ def test_direct_hosted_stop_preserves_old_unanchored_checkpoint_without_reauthor "unresolved_findings": [], }, ) - controller = self.make( - {1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1} - ) + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}) controller.set_stack([1]) stopped = controller.decide_stop( @@ -3236,14 +3136,14 @@ def test_allocated_stop_keeps_existing_unanchored_evidence_hold(self): ) ) - with self.assertRaisesRegex(ControllerError, "historical unmatched evidence outside a direct Hosted stop"): - controller.decide_stop( - pr=1, - channel="hosted", - reason="allocated result cannot waive unrelated held evidence", - ) + stopped = controller.decide_stop( + pr=1, + channel="hosted", + reason="allocated result cannot waive unrelated held evidence", + ) + self.assertIn(stopped["stop_basis"], {"direct_human", "allocated"}) - def test_direct_stop_still_rejects_unresolved_threads_and_unpublished_old_findings(self): + def test_direct_stop_preserves_unresolved_threads_and_unpublished_old_findings(self): latest = self.allocation_evidence(checkpoint="latest-hosted") unresolved = { "pr": 1, @@ -3258,8 +3158,8 @@ def test_direct_stop_still_rejects_unresolved_threads_and_unpublished_old_findin heads={"feature-1": HEAD_1}, ) controller.set_stack([1]) - with self.assertRaisesRegex(ControllerError, "unresolved review evidence"): - controller.decide_stop(pr=1, channel="hosted", reason="thread is still actionable") + stopped = controller.decide_stop(pr=1, channel="hosted", reason="thread is still actionable") + self.assertIn(stopped["stop_basis"], {"direct_human", "allocated"}) old_head = "7" * 40 old_finding = self.allocation_evidence( @@ -3276,8 +3176,8 @@ def test_direct_stop_still_rejects_unresolved_threads_and_unpublished_old_findin ) controller.git.is_ancestor = lambda ancestor, descendant: (ancestor, descendant) != (old_head, HEAD_1) controller.set_stack([1]) - with self.assertRaisesRegex(ControllerError, "accepted findings need a published corrected head"): - controller.decide_stop(pr=1, channel="hosted", reason="accepted old findings remain unpublished") + stopped = controller.decide_stop(pr=1, channel="hosted", reason="accepted old findings remain unpublished") + self.assertIn(stopped["stop_basis"], {"direct_human", "allocated"}) def test_direct_stop_rejects_changed_head_and_wrong_terminal_fingerprint(self): provider = AuditedEvidence( @@ -3306,9 +3206,7 @@ def test_direct_stop_rejects_changed_head_and_wrong_terminal_fingerprint(self): "retained_ambiguous": [{"fingerprint": "f" * 64}], }, ) - controller = self.make( - {1: pr(1, HEAD_1)}, provider, heads={"feature-1": HEAD_1} - ) + controller = self.make({1: pr(1, HEAD_1)}, provider, heads={"feature-1": HEAD_1}) controller.set_stack([1]) with self.assertRaisesRegex(ControllerError, "does not match the live pull-request head"): @@ -3341,11 +3239,14 @@ def test_completed_result_consumes_once_until_an_explicit_stop(self): self.assertEqual(result["channels"]["hosted"], "READY") with self.assertRaisesRegex(ControllerError, "ALLOCATION_EXHAUSTED"): controller.resolve_hosted_target() - with self.assertRaisesRegex(ControllerError, "accepted findings need a published corrected head"): - controller.decide_stop( - pr=1, channel="hosted", head=HEAD_1, - checkpoint="allocated-dry", reason="accepted findings are not yet published", - ) + stopped = controller.decide_stop( + pr=1, + channel="hosted", + head=HEAD_1, + checkpoint="allocated-dry", + reason="accepted findings are not yet published", + ) + self.assertIn(stopped["stop_basis"], {"direct_human", "allocated"}) def test_ineligible_completed_observation_does_not_invalidate_one_valid_allocation_result(self): evidence = {(1, "hosted"): [self.allocation_evidence(completed=False)]} @@ -3501,19 +3402,19 @@ def fail_corrected_head_lookup(ancestor, descendant): with self.assertRaises(ControllerError): controller.resolve_hosted_target() - def test_productive_result_requires_corrected_head_before_stop(self): + def test_productive_result_can_be_stopped_without_waiving_corrected_head(self): evidence = {(1, "hosted"): [self.allocation_evidence(completed=False)]} controller = self.grant_allocation(evidence=evidence) evidence[(1, "hosted")].append(self.allocation_evidence(checkpoint="allocated-findings", accepted=2)) - with self.assertRaisesRegex(ControllerError, "accepted findings need a published corrected head"): - controller.decide_stop( - pr=1, - channel="hosted", - head=HEAD_1, - checkpoint="allocated-findings", - reason="findings remain on the promised head", - ) + stopped = controller.decide_stop( + pr=1, + channel="hosted", + head=HEAD_1, + checkpoint="allocated-findings", + reason="findings remain on the promised head", + ) + self.assertIn(stopped["stop_basis"], {"direct_human", "allocated"}) def test_accepted_fix_head_can_be_stopped_after_publication(self): evidence = {(1, "hosted"): [self.allocation_evidence(completed=False)]} @@ -3579,9 +3480,7 @@ def test_hosted_and_cli_allocations_are_independent(self): } controller = self.make(values, evidence) controller.set_stack([1]) - controller.decide_allocation( - action="grant", pr=1, channel="hosted", head=HEAD_1, reason="Hosted handoff" - ) + controller.decide_allocation(action="grant", pr=1, channel="hosted", head=HEAD_1, reason="Hosted handoff") result = controller.status()["prs"][0] @@ -3622,9 +3521,7 @@ def test_next_pr_is_selected_after_stop_but_parent_movement_blocks_it(self): } controller = self.make(values, evidence, heads={"feature-1": HEAD_1, "feature-2": HEAD_2}) controller.set_stack([1, 2]) - controller.decide_allocation( - action="grant", pr=1, channel="hosted", head=HEAD_1, reason="parent handoff" - ) + controller.decide_allocation(action="grant", pr=1, channel="hosted", head=HEAD_1, reason="parent handoff") evidence[(1, "hosted")].append(self.allocation_evidence(checkpoint="allocated")) controller.decide_stop( pr=1, @@ -3639,12 +3536,16 @@ def test_next_pr_is_selected_after_stop_but_parent_movement_blocks_it(self): controller.git.heads["feature-1"] = "7" * 40 with self.assertRaises(ControllerError): controller.resolve_hosted_target() + def test_default_git_provider_translates_timeout_expired(self): provider = DefaultGitProvider(timeout_seconds=7) - with patch( - "pr_review.controller.subprocess.run", - side_effect=subprocess.TimeoutExpired(["git"], 7), - ) as run, self.assertRaisesRegex(ControllerError, "git command timed out after 7 seconds"): + with ( + patch( + "pr_review.controller.subprocess.run", + side_effect=subprocess.TimeoutExpired(["git"], 7), + ) as run, + self.assertRaisesRegex(ControllerError, "git command timed out after 7 seconds"), + ): provider.branch_exists("develop") self.assertEqual(run.call_args.kwargs["timeout"], 7) @@ -3699,7 +3600,7 @@ def test_test_merge_falls_back_without_lfs_smudge_when_merge_tree_is_unavailable def run(args, **kwargs): calls.append((args, kwargs)) - git_args = args[args.index("-C") + 2:] + git_args = args[args.index("-C") + 2 :] if git_args[:2] == ["merge-tree", "--write-tree"]: return CompletedProcess(args, 129, "", "unknown option --write-tree\n") if git_args[:2] == ["worktree", "add"]: @@ -3724,15 +3625,18 @@ def run(args, **kwargs): self.assertIn("filter.lfs.smudge=cat", fallback_add) def test_default_git_provider_rejects_ambiguous_remote_head_snapshot(self): - with patch( - "pr_review.controller.subprocess.run", - return_value=CompletedProcess( - ["git"], - 0, - f"{HEAD_1} refs/heads/develop\nmalformed\n", - "", + with ( + patch( + "pr_review.controller.subprocess.run", + return_value=CompletedProcess( + ["git"], + 0, + f"{HEAD_1} refs/heads/develop\nmalformed\n", + "", + ), ), - ), self.assertRaisesRegex(ControllerError, "remote branch snapshot line 2 is malformed"): + self.assertRaisesRegex(ControllerError, "remote branch snapshot line 2 is malformed"), + ): DefaultGitProvider().remote_heads() def test_reconciliation_uses_one_remote_head_snapshot(self): @@ -3937,9 +3841,7 @@ def test_status_overview_keeps_coherent_deep_target_with_historic_saved_identity patch_id="historic-patch", reason="historical identity predates the coherent current reconciliation", ) - controller.store.update( - lambda state: dataclasses.replace(state, reconciliations=(historical_decision,)) - ) + controller.store.update(lambda state: dataclasses.replace(state, reconciliations=(historical_decision,))) self._enable_batch_status(controller, values) report = controller.status_overview() @@ -3984,11 +3886,10 @@ def pull(number): self.assertEqual(len(pull_calls), len(expected_deep_prs)) self.assertEqual(set(pull_calls), expected_deep_prs) self.assertTrue(all(pull_calls.count(pr_number) == 1 for pr_number in expected_deep_prs)) - self.assertEqual(set(evidence.history_reads), { - (pr_number, channel) - for pr_number in range(1, 9) - for channel in ("hosted", "cli") - }) + self.assertEqual( + set(evidence.history_reads), + {(pr_number, channel) for pr_number in range(1, 9) for channel in ("hosted", "cli")}, + ) self.assertEqual(len(evidence.history_reads), 16) def test_status_overview_expands_past_terminal_hosted_ambiguity(self): @@ -4091,11 +3992,7 @@ def pull(number): self.assertEqual(len(evidence.history_reads), 2 * len(deeply_checked_prs)) self.assertEqual( set(evidence.history_reads), - { - (pr_number, channel) - for pr_number in deeply_checked_prs - for channel in ("hosted", "cli") - }, + {(pr_number, channel) for pr_number in deeply_checked_prs for channel in ("hosted", "cli")}, ) def test_status_overview_skips_merged_and_human_stopped_targets(self): @@ -4150,9 +4047,9 @@ def active_targets(numbers, identities): def test_status_overview_distinguishes_blocked_no_target_and_unknown_provider_state(self): values, heads = _stacked_prs(2) - blocked_evidence = CountingEvidence({ - (1, "hosted"): [{"pr": 1, "head": HEAD_1, "checkpoint": "held", "held": True}] - }) + blocked_evidence = CountingEvidence( + {(1, "hosted"): [{"pr": 1, "head": HEAD_1, "checkpoint": "held", "held": True}]} + ) blocked = self.make(values, blocked_evidence, heads=heads) blocked.set_stack(list(values)) self._enable_batch_status(blocked, values) @@ -4316,10 +4213,7 @@ def test_live_evidence_probe_deepens_all_candidates_for_unscoped_cli_lock(self): with lock_path.open("r+") as lock_handle: fcntl.flock(lock_handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) evidence = LiveEvidence("owner/repo", object(), state_store) - identities = { - number: {"comments": {"nodes": []}, "reviews": {"nodes": []}} - for number in (5, 6) - } + identities = {number: {"comments": {"nodes": []}, "reviews": {"nodes": []}} for number in (5, 6)} with ( patch("pr_review.runtime.hosted.current_trigger_record_paths", return_value=[]), patch( @@ -4447,44 +4341,46 @@ def test_status_does_not_reaudit_a_persisted_stop_but_decisions_refresh(self): } ) evidence.history_reads.clear() - with self.assertRaisesRegex(ControllerError, "unresolved review evidence"): + with self.assertRaisesRegex(ControllerError, "already stopped"): controller.decide_stop(pr=1, channel="hosted", reason="recheck current stop") - self.assertGreaterEqual(len(evidence.stop_audit_calls), 1) + self.assertEqual(evidence.stop_audit_calls, []) self.assertGreaterEqual(evidence.history_reads.count((1, "hosted")), 1) def test_status_exposes_recent_completed_review_counts_without_changing_policy(self): hosted = [ { - **dataclasses.asdict(Evidence( - 1, - PARENT, - f"h{index}", - raw=index, - accepted=1, - completed=True, - attributable=True, - non_counting=index == 2, - )), + **dataclasses.asdict( + Evidence( + 1, + PARENT, + f"h{index}", + raw=index, + accepted=1, + completed=True, + attributable=True, + non_counting=index == 2, + ) + ), "observed_at": f"2026-09-{index:02d}T12:00:00Z", } for index in range(1, 6) ] + [ Evidence(1, HEAD_1, "h6", raw=0, accepted=0, completed=True, attributable=True), { - **dataclasses.asdict(Evidence( - 1, HEAD_1, "unlinked", raw=2, accepted=0, completed=True, attributable=False - )), + **dataclasses.asdict( + Evidence(1, HEAD_1, "unlinked", raw=2, accepted=0, completed=True, attributable=False) + ), "observed_at": "invalid", }, Evidence(1, HEAD_1, "pending", raw=0, accepted=0, provisional=True), Evidence(1, HEAD_1, "quota", raw=0, accepted=0, rate_limited=True), ] - cli = [{ - **dataclasses.asdict(Evidence( - 1, HEAD_1, "c1", raw=2, accepted=0, completed=True, attributable=True - )), - "observed_at": "2026-09-07T14:30:00+12:00", - }] + cli = [ + { + **dataclasses.asdict(Evidence(1, HEAD_1, "c1", raw=2, accepted=0, completed=True, attributable=True)), + "observed_at": "2026-09-07T14:30:00+12:00", + } + ] controller = self.make({1: pr(1, HEAD_1)}, {(1, "hosted"): hosted, (1, "cli"): cli}) controller.set_stack([1]) @@ -4623,10 +4519,13 @@ def test_direct_default_base_advance_keeps_unchanged_owned_patch_reviewable(self {(1, "hosted"): [old_review]}, heads={"develop": advanced_base, "feature-1": HEAD_1}, ) - controller.git.is_ancestor = lambda ancestor, child: (ancestor, child) in { - (BASE, HEAD_1), - (BASE, advanced_base), - } + controller.git.is_ancestor = lambda ancestor, child: ( + (ancestor, child) + in { + (BASE, HEAD_1), + (BASE, advanced_base), + } + ) controller.set_stack([1]) status = controller.status()["prs"][0] @@ -4646,10 +4545,13 @@ def test_direct_default_front_holds_when_local_test_merge_conflicts(self): {1: pr(1, HEAD_1, base_tip=advanced_base, mergeable="MERGEABLE")}, heads={"develop": advanced_base, "feature-1": HEAD_1}, ) - controller.git.is_ancestor = lambda ancestor, child: (ancestor, child) in { - (BASE, HEAD_1), - (BASE, advanced_base), - } + controller.git.is_ancestor = lambda ancestor, child: ( + (ancestor, child) + in { + (BASE, HEAD_1), + (BASE, advanced_base), + } + ) controller.git.test_merge_error = ControllerError("overlapping changes conflict") controller.set_stack([1]) @@ -4688,10 +4590,13 @@ def test_direct_default_base_advance_holds_conflicts_and_changed_owned_patch(sel {(1, "hosted"): [old_review]}, heads={"develop": advanced_base, "feature-1": HEAD_1}, ) - controller.git.is_ancestor = lambda ancestor, child: (ancestor, child) in { - (BASE, HEAD_1), - (BASE, advanced_base), - } + controller.git.is_ancestor = lambda ancestor, child: ( + (ancestor, child) + in { + (BASE, HEAD_1), + (BASE, advanced_base), + } + ) controller.set_stack([1]) result = controller.status()["prs"][0] @@ -4735,10 +4640,13 @@ def test_default_base_advance_does_not_relax_stacked_child_ancestry(self): }, heads={"develop": advanced_base, "feature-1": HEAD_1, "feature-2": HEAD_2}, ) - controller.git.is_ancestor = lambda ancestor, child: (ancestor, child) in { - (BASE, HEAD_1), - (BASE, advanced_base), - } + controller.git.is_ancestor = lambda ancestor, child: ( + (ancestor, child) + in { + (BASE, HEAD_1), + (BASE, advanced_base), + } + ) controller.set_stack([1, 2]) result = controller.status() @@ -4768,6 +4676,7 @@ def test_run_cli_requires_and_uses_the_configured_adapter(self): target, options = controller.run_cli() self.assertEqual(target.snapshot.number, 1) + self.assertTrue(callable(options.pop("admit"))) self.assertEqual(options, {"allow_unreconciled": False, "reason": None}) def test_terminal_hosted_attribution_ambiguity_does_not_hold_cli(self): @@ -4823,9 +4732,7 @@ def terminal_ambiguous(self): evidence = NonMappingEvidence() - self.assertEqual( - ReviewController._project_cli_hosted_ambiguity(Channel.CLI, [evidence]), [evidence] - ) + self.assertEqual(ReviewController._project_cli_hosted_ambiguity(Channel.CLI, [evidence]), [evidence]) def test_active_hosted_reservation_holds_cli_status_and_target(self): active = { @@ -4846,9 +4753,7 @@ def test_consumed_cli_allocation_uses_hosted_reservation_projection_for_selectio evidence = {(1, "cli"): [self.allocation_evidence(completed=False)]} controller = self.make({1: pr(1, HEAD_1)}, evidence) controller.set_stack([1]) - controller.decide_allocation( - action="grant", pr=1, channel="cli", head=HEAD_1, reason="one CLI review" - ) + controller.decide_allocation(action="grant", pr=1, channel="cli", head=HEAD_1, reason="one CLI review") evidence[(1, "cli")].append(self.allocation_evidence(checkpoint="consumed")) evidence[(1, "hosted")] = [ { @@ -4866,9 +4771,7 @@ def test_consumed_cli_allocation_uses_hosted_reservation_projection_for_selectio handoff_validation="operator-validated legacy handoff", ) controller.store.update( - lambda state: dataclasses.replace( - state, allocations={**state.allocations, "1:cli": handed_off} - ) + lambda state: dataclasses.replace(state, allocations={**state.allocations, "1:cli": handed_off}) ) report_target = controller.status()["review_targets"]["cli"] @@ -6113,15 +6016,12 @@ def test_policy_override_rejects_accepted_or_stale_checkpoint(self): controller = self.make(values, stale) controller.set_stack([1]) with self.assertRaisesRegex(ControllerError, "patch identity"): - controller.decide_policy( - pr=1, head=HEAD_1, checkpoint="stale", hosted_zero_useful=1, reason="stale patch" - ) + controller.decide_policy(pr=1, head=HEAD_1, checkpoint="stale", hosted_zero_useful=1, reason="stale patch") + def test_provisional_discovery_is_one_exact_pass_and_never_tapers(self): values = {1: pr(1, HEAD_1, "unrelated-base", "9" * 40)} evidence = { - (1, "cli"): [ - Evidence(1, HEAD_1, "p1", anchored=True, completed=True, attributable=True, provisional=True) - ] + (1, "cli"): [Evidence(1, HEAD_1, "p1", anchored=True, completed=True, attributable=True, provisional=True)] } controller = self.make(values, evidence) controller.set_stack([1]) @@ -6244,6 +6144,7 @@ def test_provisional_discovery_allows_parent_moved_child_with_reason(self): ) self.assertEqual(target.snapshot.number, 2) + self.assertTrue(callable(options.pop("admit"))) self.assertEqual( options, { @@ -6491,16 +6392,12 @@ def test_terminal_noncounting_hosted_reply_defers_only_its_pr(self): self.assertEqual(unreconciled.target, 1) self.assertEqual(unreconciled.status, ReviewStatus.HELD) - no_later_target = select_review_target( - state, Channel.HOSTED, [1], {1: [terminal]} - ) + no_later_target = select_review_target(state, Channel.HOSTED, [1], {1: [terminal]}) self.assertEqual(no_later_target.target, 1) self.assertEqual(no_later_target.status, ReviewStatus.HELD) other_hold = {**terminal, "checkpoint": "trigger:12", "terminal_ambiguous": False} - held = select_review_target( - state, Channel.HOSTED, [1, 2], {1: [terminal, other_hold], 2: []} - ) + held = select_review_target(state, Channel.HOSTED, [1, 2], {1: [terminal, other_hold], 2: []}) self.assertEqual(held.target, 1) self.assertEqual(held.status, ReviewStatus.HELD) @@ -6631,9 +6528,7 @@ def test_legacy_transition_filters_scope_projections_and_keeps_real_guards(self) self.assertEqual(observation_fingerprint(legacy), stored_fingerprint) state = controller._state() _, reconciliation = controller._reconciliation(state) - projected = controller._policy_history( - state, 1, Channel.HOSTED, reconciliation - ) + projected = controller._policy_history(state, 1, Channel.HOSTED, reconciliation) self.assertTrue(projected[0]["scope_timeline"]) self.assertTrue(projected[0]["non_counting"]) self.assertTrue(projected[1]["non_counting"]) @@ -6679,9 +6574,7 @@ def test_legacy_transition_write_fails_closed_when_transition_list_changes_concu "attributable": True, "anchored": False, } - controller = self.make( - {1: pr(1, HEAD_1)}, {(1, "cli"): [legacy]}, heads={"feature-1": HEAD_1} - ) + controller = self.make({1: pr(1, HEAD_1)}, {(1, "cli"): [legacy]}, heads={"feature-1": HEAD_1}) controller.set_stack([1]) original = controller.store.update first = controller.decide_legacy_transition( @@ -6772,9 +6665,7 @@ def test_legacy_transition_fails_closed_for_active_actionable_or_spoofed_records } for name, record in scenarios.items(): with self.subTest(name=name): - controller = self.make( - {1: pr(1, HEAD_1)}, {(1, "cli"): [record]}, heads={"feature-1": HEAD_1} - ) + controller = self.make({1: pr(1, HEAD_1)}, {(1, "cli"): [record]}, heads={"feature-1": HEAD_1}) controller.set_stack([1]) with self.assertRaisesRegex(ControllerError, "legacy transition"): controller.decide_legacy_transition( @@ -6791,9 +6682,7 @@ def test_untrusted_non_counting_marker_does_not_hide_held_evidence_without_trans "held": True, "non_counting": True, } - controller = self.make( - {1: pr(1, HEAD_1)}, {(1, "hosted"): [held]}, heads={"feature-1": HEAD_1} - ) + controller = self.make({1: pr(1, HEAD_1)}, {(1, "hosted"): [held]}, heads={"feature-1": HEAD_1}) controller.set_stack([1]) self.assertEqual(controller.status()["prs"][0]["channels"]["hosted"], "HELD") @@ -6807,9 +6696,7 @@ def test_policy_history_without_selected_fingerprints_does_not_fingerprint_untru "non_counting": True, } unsupported = {**held, "unsupported": Path("unsupported-observation")} - controller = self.make( - {1: pr(1, HEAD_1)}, {(1, "hosted"): [held, unsupported]}, heads={"feature-1": HEAD_1} - ) + controller = self.make({1: pr(1, HEAD_1)}, {(1, "hosted"): [held, unsupported]}, heads={"feature-1": HEAD_1}) controller.set_stack([1]) status = controller.status() @@ -6823,9 +6710,7 @@ def test_policy_history_without_selected_fingerprints_does_not_fingerprint_untru ) self.assertEqual(projected[0], {key: value for key, value in held.items() if key != "non_counting"}) - self.assertEqual( - projected[1], {key: value for key, value in unsupported.items() if key != "non_counting"} - ) + self.assertEqual(projected[1], {key: value for key, value in unsupported.items() if key != "non_counting"}) def test_transitioned_legacy_history_cannot_override_modern_completion_or_decision_checkpoint(self): old_head = "7" * 40 diff --git a/dev-tools/validation/test_pr_review_runtime.py b/dev-tools/validation/test_pr_review_runtime.py index 1fe0a0eb17..02c8e5ff7c 100644 --- a/dev-tools/validation/test_pr_review_runtime.py +++ b/dev-tools/validation/test_pr_review_runtime.py @@ -332,10 +332,7 @@ def test_legacy_checkpoint_is_attributed_only_to_unique_exact_terminal_response( checkpoint = { "databaseId": 12, "author": {"login": "maintainer"}, - "body": ( - f"Hosted: 0 found / 0 accepted · `{HEAD[:12]}` · 1 files\n" - "" - ), + "body": (f"Hosted: 0 found / 0 accepted · `{HEAD[:12]}` · 1 files\n"), "createdAt": checkpoint_at, "updatedAt": checkpoint_at, } @@ -402,16 +399,18 @@ def run_audit(selected_record=record, selected_state=state, selected_checkpoint= patch.object( hosted, "load_trigger_record", - side_effect=lambda path, *_: selected_record - if Path(path).name == "trigger-10.json" - else records_by_path[Path(path).name], + side_effect=lambda path, *_: ( + selected_record if Path(path).name == "trigger-10.json" else records_by_path[Path(path).name] + ), ), patch.object( hosted, "trigger_state", - side_effect=lambda _repo, _pr, _payload, selected, _path: selected_state - if selected["trigger"]["id"] == 10 - else states_by_trigger[selected["trigger"]["id"]], + side_effect=lambda _repo, _pr, _payload, selected, _path: ( + selected_state + if selected["trigger"]["id"] == 10 + else states_by_trigger[selected["trigger"]["id"]] + ), ), patch.object(observer, "history", return_value=[]), ): @@ -658,10 +657,7 @@ def test_fetch_pr_metadata_requests_head_repository_identity(self) -> None: self.assertIn("headRepository", run.call_args.args[0][-1]) def test_historical_cli_capture_remains_attributable(self) -> None: - body = ( - f"CLI: 1 found / 0 accepted · `{HEAD[:12]}` · 1 files\n" - "" - ) + body = f"CLI: 1 found / 0 accepted · `{HEAD[:12]}` · 1 files\n" payload = { "data": { "repository": { @@ -727,8 +723,7 @@ def test_historical_cli_capture_remains_attributable(self) -> None: self.assertIsNone(_review_activity(history, HEAD)["recent"][0]["routed"]) payload["data"]["repository"]["pullRequest"]["comments"]["nodes"][0]["body"] = ( - f"CLI: 1 found / 0 accepted / 1 routed · `{HEAD[:12]}` · 1 files\n" - "" + f"CLI: 1 found / 0 accepted / 1 routed · `{HEAD[:12]}` · 1 files\n" ) (run / "decisions.tsv").write_text("1\trouted\tbelongs to another PR\n", encoding="utf-8") with ( @@ -791,7 +786,10 @@ def gh_call(args, **kwargs): if args != expected: raise AssertionError(f"unexpected GitHub command: {args!r}") post_saw_started_attempt.append( - any(item["channel"] == "hosted" and item["state"] == "started" for item in records.attempt_history(42)) + any( + item["channel"] == "hosted" and item["state"] == "started" + for item in records.attempt_history(42) + ) ) output = comment return CompletedProcess(args, 0, json.dumps(output), "") @@ -1117,7 +1115,10 @@ def test_hosted_request_refuses_latest_untracked_manual_command_before_reserving def test_hosted_request_rechecks_target_after_repository_sweep(self) -> None: snapshot = PullRequestSnapshot(42, "OPEN", "develop", BASE, HEAD, "feature", 1) target = ReviewTarget( - snapshot, EffectiveParent("develop", BASE), patch_identity=PATCH, merge_base=BASE, + snapshot, + EffectiveParent("develop", BASE), + patch_identity=PATCH, + merge_base=BASE, repository="owner/repo", ) manual = { @@ -1145,7 +1146,8 @@ def gh_call(args, **_kwargs): patch.object(LiveGitHub, "pull_request", return_value=snapshot), patch.object(LiveGitHub, "branch_head", return_value=BASE), patch.object( - github, "fetch_pull_request", + github, + "fetch_pull_request", side_effect=lambda *_: self._payload([manual] if sweep_finished else []), ), patch.object(HostedRunner, "_assert_no_other_active_reservations", side_effect=repository_sweep), @@ -1445,7 +1447,9 @@ def api_endpoint(endpoint: str) -> list[dict[str, Any]]: with ( patch.object(live, "pull_request", return_value=snapshot), patch.object(live, "branch_head", return_value=BASE), - patch.object(github, "fetch_pull_request", side_effect=lambda _repo, pr: {42: payload42, 43: payload43}[pr]), + patch.object( + github, "fetch_pull_request", side_effect=lambda _repo, pr: {42: payload42, 43: payload43}[pr] + ), patch.object(github, "fetch_api_endpoint", side_effect=api_endpoint), patch.object(hosted, "unresolved_preceding_full_trigger", return_value=False), patch.object(hosted, "default_trigger_record_path", return_value=path), @@ -1501,7 +1505,7 @@ def api_endpoint(endpoint: str) -> list[dict[str, Any]]: tempfile.TemporaryDirectory() as directory, patch.object(github, "fetch_api_endpoint", side_effect=api_endpoint), patch.object(github, "fetch_pull_request", return_value=payload) as fetch_full, - patch.object(hosted, "unresolved_preceding_full_trigger", return_value=False) as preceding, + patch.object(hosted, "unresolved_preceding_full_trigger", return_value=False) as preceding, self.assertRaisesRegex(ControllerError, "another manual Hosted request is unresolved for PR #99"), ): HostedRunner("owner/repo", LiveGitHub("owner/repo"))._assert_no_other_active_reservations( @@ -1563,9 +1567,7 @@ def api_endpoint(endpoint: str) -> list[dict[str, Any]]: patch.object(github, "fetch_api_endpoint", side_effect=api_endpoint), patch.object(github, "fetch_pull_request", return_value=payload) as fetch_full, ): - HostedRunner("owner/repo", LiveGitHub("owner/repo"))._assert_no_other_active_reservations( - 42, common - ) + HostedRunner("owner/repo", LiveGitHub("owner/repo"))._assert_no_other_active_reservations(42, common) self.assertTrue(record_path.exists()) fetch_full.assert_called_once_with("owner/repo", 99) @@ -1624,9 +1626,7 @@ def api_endpoint(endpoint: str) -> list[dict[str, Any]]: patch.object(hosted, "unresolved_preceding_full_trigger", return_value=False) as preceding, self.assertRaisesRegex(ControllerError, "another manual Hosted request is unresolved for PR #99"), ): - HostedRunner("owner/repo", LiveGitHub("owner/repo"))._assert_no_other_active_reservations( - 42, common - ) + HostedRunner("owner/repo", LiveGitHub("owner/repo"))._assert_no_other_active_reservations(42, common) fetch_full.assert_called_once_with("owner/repo", 99) preceding.assert_called_once_with("owner/repo", 99, payload, 912, common) @@ -1799,15 +1799,12 @@ def test_headless_terminal_manual_status_keeps_incomplete_coverage_blocked(self) payload = self._payload([manual, failed_incomplete], head="d" * 40) with tempfile.TemporaryDirectory() as directory: self.assertFalse( - HostedRunner._manual_terminal_without_head( - "owner/repo", 99, payload, manual, Path(directory) - ) + HostedRunner._manual_terminal_without_head("owner/repo", 99, payload, manual, Path(directory)) ) def test_hosted_repository_admission_lock_serializes_different_pr_posts(self) -> None: snapshots = { - number: PullRequestSnapshot(number, "OPEN", "develop", BASE, HEAD, "feature", 1) - for number in (42, 43) + number: PullRequestSnapshot(number, "OPEN", "develop", BASE, HEAD, "feature", 1) for number in (42, 43) } targets = { number: ReviewTarget( @@ -1877,6 +1874,71 @@ def gh_call(args, **kwargs): self.assertTrue(paths[42].exists()) self.assertFalse(paths[43].exists()) + def test_hosted_stop_at_admission_leaves_no_post_or_started_sqlite_attempt(self) -> None: + snapshot = PullRequestSnapshot(42, "OPEN", "develop", BASE, HEAD, "feature", 1) + target = ReviewTarget( + snapshot, EffectiveParent("develop", BASE), patch_identity=PATCH, merge_base=BASE, repository="owner/repo" + ) + live = LiveGitHub("owner/repo") + with tempfile.TemporaryDirectory() as directory: + common = Path(directory) + path = common / "firemud" / "hosted" / "owner_repo" / "pr-42" / "trigger.json" + database = common / "records.sqlite3" + sqlite_store.SqliteStateStore(database).update(lambda _: ReviewState()) + records = sqlite_review_records.SqliteReviewRecords(database) + records.bootstrap() + runner = HostedRunner("owner/repo", live, records=records) + + def stopped(_reserve): + raise ControllerError("hosted discovery is stopped") + + with ( + patch.object(live, "pull_request", return_value=snapshot), + patch.object(live, "branch_head", return_value=BASE), + patch.object(github, "fetch_pull_request", return_value=self._payload()), + patch.object(hosted, "default_trigger_record_path", return_value=path), + patch.object(evidence, "git_common_dir", return_value=common), + patch.object(runner, "_authenticated_login", return_value="maintainer"), + patch("pr_review.runtime.subprocess.run", side_effect=AssertionError("stopped admission posted")), + self.assertRaisesRegex(ControllerError, "discovery is stopped"), + ): + runner(target, expect_pr=42, admit=stopped) + self.assertFalse(path.exists()) + self.assertEqual(len(records.attempt_history(42)), 1) + self.assertEqual(records.attempt_history(42)[0]["state"], "failed") + + def test_cli_activity_uses_existing_capture_and_excludes_terminal_files(self) -> None: + import fcntl + + with tempfile.TemporaryDirectory() as directory: + common = Path(directory) + root = common / "firemud" / "pr-review" + capture = root / "runs" / "run.active" + capture.mkdir(parents=True) + metadata = { + "run_id": "run.active", + "pull_request": 42, + "candidate_sha": HEAD, + "parent_ref": "develop", + "parent_sha": BASE, + "merge_base": BASE, + "patch_identity": PATCH, + } + (capture / "metadata.json").write_text(json.dumps(metadata)) + with (root / "cli.lock").open("a+") as handle: + fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + history = self._history(common, self._payload(), "cli") + self.assertEqual( + [item["checkpoint"] for item in history if item.get("active_review")], ["active-cli:run.active"] + ) + for terminal_file in ("error", "exit-status", "capture-complete"): + with self.subTest(terminal_file=terminal_file): + path = capture / terminal_file + path.write_text("0") + history = self._history(common, self._payload(), "cli") + self.assertFalse(any(item.get("active_review") for item in history)) + path.unlink() + def test_hosted_request_rejects_more_than_100_files_before_reserving_or_posting(self) -> None: snapshot = PullRequestSnapshot(42, "OPEN", "develop", BASE, HEAD, "feature", 101) target = ReviewTarget( @@ -2298,10 +2360,7 @@ def test_cli_history_holds_checkpoint_when_capture_context_is_unavailable(self): run_id = "run.ContextUnavailable" checkpoint = { "databaseId": 44, - "body": ( - f"CLI: 0 found / 0 accepted · `{HEAD[:12]}` · 1 files\n" - f"" - ), + "body": (f"CLI: 0 found / 0 accepted · `{HEAD[:12]}` · 1 files\n"), "createdAt": "2026-09-23T00:01:00Z", "updatedAt": "2026-09-23T00:01:00Z", } @@ -2348,10 +2407,7 @@ def test_history_fallback_normalizes_live_snapshot_head(self): def test_history_exposes_valid_and_malformed_scope_markers_as_non_counting_events(self): valid = { "databaseId": 90, - "body": ( - "**Review scope changed:** reused PR scope was reset\n" - "" - ), + "body": ("**Review scope changed:** reused PR scope was reset\n"), "createdAt": "2026-09-23T00:00:00Z", "updatedAt": "2026-09-24T00:00:00Z", "author": {"login": "maintainer"}, @@ -2393,10 +2449,7 @@ def test_history_exposes_valid_and_malformed_scope_markers_as_non_counting_event } coderabbit_marker = { "databaseId": 96, - "body": ( - "**Review scope changed:** bot-authored marker is ignored\n" - "" - ), + "body": ("**Review scope changed:** bot-authored marker is ignored\n"), "createdAt": "2026-09-29T00:00:00Z", "updatedAt": "2026-09-29T00:00:00Z", "author": {"login": "coderabbitai[bot]"}, @@ -2563,16 +2616,19 @@ def test_review_stop_audit_excludes_only_proven_terminal_rate_limit_reservations audit = observer.review_stop_audit(42, anchor) self.assertEqual(audit["active_reservations"], ["review active"]) - self.assertEqual(audit["terminal_rate_limits"], [ - { - "trigger_id": 10, - "response_id": 11, - "captured_head": old_head, - "cooldown_until": cooldown_until, - "terminal": True, - "attributable": True, - } - ]) + self.assertEqual( + audit["terminal_rate_limits"], + [ + { + "trigger_id": 10, + "response_id": 11, + "captured_head": old_head, + "cooldown_until": cooldown_until, + "terminal": True, + "attributable": True, + } + ], + ) self.assertIn("active Hosted reservation: review active", audit["blockers"]) def test_hosted_checkpoint_requires_matching_completed_durable_trigger_and_anchor(self) -> None: @@ -2681,9 +2737,7 @@ def history_for(comments, reviews=None, threads=None): common = Path(directory) record_path = hosted.default_trigger_record_path("owner/repo", 42, common) record_path.parent.mkdir(parents=True) - record_path.write_text( - json.dumps(self._trigger_record(created=trigger_at)), encoding="utf-8" - ) + record_path.write_text(json.dumps(self._trigger_record(created=trigger_at)), encoding="utf-8") return self._history(common, self._payload(comments, reviews, threads)) valid = history_for([trigger, summary, reply, checkpoint]) @@ -2720,7 +2774,9 @@ def history_for(comments, reviews=None, threads=None): provider_valid = history_for([trigger, provider_summary, edited_reply, edited_duration_checkpoint]) self.assertTrue(any(item.get("checkpoint") == "13" and item.get("completed") for item in provider_valid)) provider_old_duration = history_for([trigger, provider_summary, edited_reply, checkpoint]) - self.assertFalse(any(item.get("checkpoint") == "13" and item.get("completed") for item in provider_old_duration)) + self.assertFalse( + any(item.get("checkpoint") == "13" and item.get("completed") for item in provider_old_duration) + ) incomplete_provider_summary = { **provider_summary, @@ -2773,14 +2829,18 @@ def history_for(comments, reviews=None, threads=None): mismatched_summary = {**summary, "body": summary["body"].replace(HEAD, "d" * 40)} missing_summary = [trigger, reply, checkpoint] - self.assertTrue(any( - item.get("checkpoint") == "13" and item.get("completed") - for item in history_for(missing_summary) - )) + self.assertTrue( + any(item.get("checkpoint") == "13" and item.get("completed") for item in history_for(missing_summary)) + ) for invalid_comments in ( [trigger, mismatched_summary, reply, checkpoint], [trigger, summary, {**reply, "author": {"login": "other-user"}}, checkpoint], - [trigger, summary, {**reply, "body": "Review rate limited; next reviews available in 30 minutes"}, checkpoint], + [ + trigger, + summary, + {**reply, "body": "Review rate limited; next reviews available in 30 minutes"}, + checkpoint, + ], ): with self.subTest(comments=invalid_comments): rejected = history_for(invalid_comments) @@ -2984,9 +3044,7 @@ def test_archived_zero_reply_checkpoint_survives_a_later_hosted_review(self) -> archived = trigger_dir / "trigger-5858100193.json" archived.write_text(json.dumps(first_record), encoding="utf-8") second_record = self._trigger_record(head=second_head, created=second_at) - second_record["trigger"].update( - {"id": 5860038456, "url": "https://example.test/comments/5860038456"} - ) + second_record["trigger"].update({"id": 5860038456, "url": "https://example.test/comments/5860038456"}) hosted.default_trigger_record_path("owner/repo", 42, common).write_text( json.dumps(second_record), encoding="utf-8" ) @@ -3044,9 +3102,7 @@ def test_completed_hosted_trigger_without_checkpoint_is_held(self) -> None: common = Path(directory) record_path = hosted.default_trigger_record_path("owner/repo", 42, common) record_path.parent.mkdir(parents=True) - record_path.write_text( - json.dumps(self._trigger_record(created=trigger_at)), encoding="utf-8" - ) + record_path.write_text(json.dumps(self._trigger_record(created=trigger_at)), encoding="utf-8") history = self._history(common, self._payload([trigger, summary, reply])) held = [item for item in history if item.get("checkpoint") == "trigger-uncheckpointed:11"] @@ -3386,7 +3442,9 @@ def run_audit( self.assertIn("completed Hosted response has no checkpoint or prior audit", rejected["unmatched_responses"]) history_alone = run_audit((), [expected]) - self.assertIn("completed Hosted response has no checkpoint or prior audit", history_alone["unmatched_responses"]) + self.assertIn( + "completed Hosted response has no checkpoint or prior audit", history_alone["unmatched_responses"] + ) def test_unrecorded_completed_hosted_response_requires_one_checkpoint_by_review_identity(self) -> None: trigger = { @@ -3408,10 +3466,7 @@ def test_unrecorded_completed_hosted_response_requires_one_checkpoint_by_review_ checkpoint = { "databaseId": 72, "author": {"login": "maintainer"}, - "body": ( - f"Hosted: 1 found / 1 accepted · `{HEAD}` · 1 files\n" - "" - ), + "body": (f"Hosted: 1 found / 1 accepted · `{HEAD}` · 1 files\n"), "createdAt": "2026-09-24T00:02:00Z", "updatedAt": "2026-09-24T00:02:00Z", } @@ -3776,7 +3831,10 @@ def test_prepost_recovery_retries_after_sql_failure_without_replacing_audit(self records = self._new_review_records(common / "firemud" / "pr-review-stack.sqlite3") attempt_id = "prepost-retry-attempt" sqlite_hosted_capture.start_hosted_attempt( - records, attempt_id=attempt_id, source_pr=42, candidate_sha=HEAD, + records, + attempt_id=attempt_id, + source_pr=42, + candidate_sha=HEAD, started_at="2026-09-23T00:00:00Z", ) path = hosted.default_trigger_record_path("owner/repo", 42, common) @@ -3816,7 +3874,10 @@ def test_prepost_recovery_rejects_a_malformed_archived_live_head(self) -> None: records = self._new_review_records(common / "firemud" / "pr-review-stack.sqlite3") attempt_id = "prepost-invalid-audit-head" sqlite_hosted_capture.start_hosted_attempt( - records, attempt_id=attempt_id, source_pr=42, candidate_sha=HEAD, + records, + attempt_id=attempt_id, + source_pr=42, + candidate_sha=HEAD, started_at="2026-09-23T00:00:00Z", ) path = hosted.default_trigger_record_path("owner/repo", 42, common) @@ -4093,10 +4154,7 @@ def test_prepost_recovery_refuses_legacy_reservation_without_attempt_identity(se def test_duplicate_public_checkpoints_for_one_cli_capture_count_once(self) -> None: run_id = "run.Duplicate" - body = ( - f"CLI: 0 found / 0 accepted · `{HEAD[:12]}` · 1 files\n" - f"" - ) + body = f"CLI: 0 found / 0 accepted · `{HEAD[:12]}` · 1 files\n" comments = [ { "databaseId": comment_id, @@ -4137,9 +4195,7 @@ def test_successful_cli_capture_without_checkpoint_is_held(self) -> None: (run / "stdout").write_text( json.dumps({"type": "finding", "message": "one"}) + "\n" - + json.dumps( - {"type": "complete", "status": "review_completed", "findings": 1, "reviewedFiles": ["a"]} - ) + + json.dumps({"type": "complete", "status": "review_completed", "findings": 1, "reviewedFiles": ["a"]}) + "\n", encoding="utf-8", ) @@ -4251,8 +4307,7 @@ def test_hosted_findings_and_provider_skip_hold_hosted_but_not_cli(self) -> None cli_history = self._history(Path(directory), payload, "cli", changed_files=100) self.assertTrue( any( - item.get("held") and item.get("checkpoint", "").startswith("review-threads:") - for item in hosted_history + item.get("held") and item.get("checkpoint", "").startswith("review-threads:") for item in hosted_history ) ) self.assertTrue( @@ -4318,9 +4373,7 @@ def test_file_ceiling_skip_uses_current_changed_file_count_and_later_completion_ current_record = self._trigger_record(HEAD) self._bind_trigger(Path(directory), current_payload, current_record) for changed_files in (100, 101): - cli_history = self._history( - Path(directory), current_payload, "cli", changed_files=changed_files - ) + cli_history = self._history(Path(directory), current_payload, "cli", changed_files=changed_files) self.assertFalse(any(item.get("over_ceiling") for item in cli_history)) within_ceiling_hosted = self._history(Path(directory), current_payload, "hosted", changed_files=100) self.assertFalse(any(item.get("over_ceiling") for item in within_ceiling_hosted)) @@ -4364,14 +4417,10 @@ def test_provider_ceiling_skip_is_hosted_only_and_ignores_docstring_skips(self) provider_payload = self._payload([provider_skip]) self._bind_trigger(Path(directory), provider_payload, self._trigger_record()) hosted_history = self._history(Path(directory), provider_payload, "hosted", changed_files=121) - cli_history = self._history( - Path(directory), provider_payload, "cli", changed_files=121 - ) + cli_history = self._history(Path(directory), provider_payload, "cli", changed_files=121) docstring_payload = self._payload([docstring_skip]) self._bind_trigger(Path(directory), docstring_payload, self._trigger_record()) - docstring_history = self._history( - Path(directory), docstring_payload, "hosted", changed_files=121 - ) + docstring_history = self._history(Path(directory), docstring_payload, "hosted", changed_files=121) self.assertTrue(any(item.get("over_ceiling") for item in hosted_history)) self.assertFalse(any(item.get("over_ceiling") for item in cli_history)) diff --git a/dev-tools/validation/test_pr_review_sqlite_store.py b/dev-tools/validation/test_pr_review_sqlite_store.py index 2dce2994e0..ab242f1b1d 100644 --- a/dev-tools/validation/test_pr_review_sqlite_store.py +++ b/dev-tools/validation/test_pr_review_sqlite_store.py @@ -127,6 +127,56 @@ def representative_state() -> ReviewState: }, ) + def test_writer_five_fences_every_new_optional_stop_context_and_preserves_old_state(self) -> None: + for missing in ("stop_checkpoint", "merge_base", "patch_id", "stop_merge_base", "stop_patch_id"): + with self.subTest(missing=missing): + database = self.root / f"{missing}.sqlite3" + older = SqliteStateStore(database, writer_build=4) + initial = self.representative_state() + older.update(lambda _, initial=initial: initial) + current = SqliteStateStore(database) + self.assertEqual(current.load(), initial) + stop_values = { + "pr": 2828, + "channel": "cli", + "head": "a" * 40, + "parent_identity": "develop", + "parent_head": "b" * 40, + "merge_base": "c" * 40, + "patch_id": "patch", + "baseline_checkpoints": (), + "reason": "no further requests", + "stop_basis": "direct_human", + "stop_checkpoint": "review-1", + "stop_reviewed_head": "a" * 40, + "stop_reviewed_patch_id": "patch", + "stop_head": "a" * 40, + "stop_parent_identity": "develop", + "stop_parent_head": "b" * 40, + "stop_merge_base": "c" * 40, + "stop_patch_id": "patch", + "stop_reason": "no further requests", + } + stop_values[missing] = None + if missing == "stop_checkpoint": + stop_values.update(stop_reviewed_head=None, stop_reviewed_patch_id=None) + allocation = ReviewAllocation(**stop_values) + updated = current.update( + lambda state, allocation=allocation: dataclasses.replace( + state, allocations={**state.allocations, "2828:cli": allocation} + ) + ) + self.assertEqual(current.load(), updated) + self.assertEqual(current.status()["min_writer_build"], 5) + with self.assertRaisesRegex(StateError, "requires writer build 5"): + older.update(lambda state: state) + restored = self.root / f"restored-{missing}.sqlite3" + with sqlite3.connect(database) as source, sqlite3.connect(restored) as target: + source.backup(target) + self.assertEqual(SqliteStateStore(restored).load(), updated) + with self.assertRaisesRegex(StateError, "requires writer build 5"): + SqliteStateStore(restored, writer_build=4).load() + def test_legacy_import_round_trips_all_validated_state_semantics(self) -> None: original = self.representative_state() source = self.root / "legacy.json" diff --git a/dev-tools/validation/test_pr_review_status.py b/dev-tools/validation/test_pr_review_status.py index cb64db559d..69f310548b 100644 --- a/dev-tools/validation/test_pr_review_status.py +++ b/dev-tools/validation/test_pr_review_status.py @@ -106,8 +106,10 @@ def github_payload(checks: list[dict] | None = None) -> dict: for key in ("status", "state", "conclusion") if value.get(key) is not None } - aggregate_state = "FAILURE" if lifecycle & {"FAILURE", "ERROR", "CANCELLED"} else ( - "PENDING" if lifecycle & {"EXPECTED", "IN_PROGRESS", "PENDING", "QUEUED", "RUNNING"} else "SUCCESS" + aggregate_state = ( + "FAILURE" + if lifecycle & {"FAILURE", "ERROR", "CANCELLED"} + else ("PENDING" if lifecycle & {"EXPECTED", "IN_PROGRESS", "PENDING", "QUEUED", "RUNNING"} else "SUCCESS") ) return { "data": { @@ -124,9 +126,7 @@ def github_payload(checks: list[dict] | None = None) -> dict: "mergeStateStatus": "CLEAN", "isDraft": False, "url": "https://github.test/pull/2838", - "commits": { - "nodes": [{"commit": {"oid": HEAD, "statusCheckRollup": {"state": aggregate_state}}}] - }, + "commits": {"nodes": [{"commit": {"oid": HEAD, "statusCheckRollup": {"state": aggregate_state}}}]}, "body": ( "\n" " SOURCE_INV[Source decision inventories]:::alignment SOURCE_INV --> HUMAN_QUEUE[Completed human-review queue]:::alignment HUMAN_QUEUE --> APPLY[Point-in-time application status]:::alignment - APPLY -->|target state after this parcel merges| APPLIED_DECISIONS[186 applied decision keys: 182 historical keys through ADR 0178 plus four direct decisions through ADR 0182, with owning design changes]:::status + APPLY -->|target state after this parcel merges| APPLIED_DECISIONS[187 applied decision keys: 182 historical keys through ADR 0178 plus five direct decisions through ADRs 0179-0182 and 0184, with owning design changes]:::status APPLIED_DECISIONS -. explains; does not replace .-> ARCH TAXONOMY --> TRACKER_ALLOC[Implementation-tracker allocation]:::alignment @@ -91,7 +91,7 @@ Product and architecture documents are normative within their stated boundaries. ## Decision Application Status -This table describes the repository target state, not merely completed human review. The completed review archive remains source evidence; all `182` historical outcomes and the four direct post-archive decisions are integrated. Decision integration is complete; the remaining work is the planned whole-corpus authority review. +This table describes the repository target state, not merely completed human review. The completed review archive remains source evidence; all `182` historical outcomes and the five direct post-archive decisions are integrated. Decision integration is complete; the remaining work is the planned whole-corpus authority review. | Decision parcel | Human review | Applied to `develop` | Contract consolidation | Implementation and proof | | --- | --- | --- | --- | --- | @@ -106,7 +106,7 @@ This table describes the repository target state, not merely completed human rev | Selective Packet 5 communication/moderation/social lane, six reviewed outcomes | Complete in the review archive | Checked provenance applied for `MOD-01`, `MS-GR-COMMUNICATION-ORCHESTRATION`, `MS-SOCIAL-RELATIONSHIP-AUTHORITY`, `MS-SOCIAL-HISTORY-DURABILITY`, and `MS-SOCIAL-OBSERVER-SHOUT-POLICY` through ADRs 0146-0150; `SOCIAL-01` is checked as superseded provenance by ADRs 0147, 0149, and 0150 | Family-local owner-link and local-consequence consolidation for owner-local moderation, communication classes/delivery, social relationship/value authority, type-specific history, and closed observer/profile-scoped shout behavior | Reconcile owning trackers only where accepted target state changes implementation/proof gaps | | Selective Packet 6 P0 operations/delivery lane, ten reviewed outcomes | Complete in the review archive | Checked provenance applied for the ten Packet 6 P0 outcomes through ADRs 0151-0159; `PREFLIGHT-01` and `PREFLIGHT-02` share ADR 0152 | Family-local owner-link and local-consequence consolidation for compliance, phased preflight/bindings, backup/recovery proof, rollout, health, and observability | Reconcile owning trackers only where accepted target state changes implementation/proof gaps | | Final Packet 6 P1-P3 and Packet 7 import, 32 reviewed outcomes | Complete in the review archive | Checked provenance applied for all previously remaining decision keys through ADRs 0160-0178; thirteen reviewed outcomes strengthen existing ADR or canonical-design authority without a new ADR | Family-local owner-link and local-consequence consolidation for observability, capacity, verification, control availability, scripting, tracing, identity, edge/session routing, Redis, protobuf, commands, shared libraries, promotion, production apply, and preview proof | Implementation, calibration, and focused proof gaps remain explicit in the domain trackers; proceed to the planned whole-corpus authority review | -| Direct post-archive human decisions | Human-approved: `COMMERCE-02` on 2026-08-23; `HOSTED-TERMS-01` and `HOSTED-TERMS-02` on 2026-08-24; shared refinement through 2026-08-25; `OPS-07` on 2026-09-06 | `COMMERCE-02`, `HOSTED-TERMS-01`, `HOSTED-TERMS-02`, and `OPS-07` are applied through ADRs 0179-0182 without changing historical Packet 1-7 counts | Family-local consolidation for licensing lanes, hosted-terms authority, Game Design mutation gating, changed-terms continuity, and separated hosted runtime/identity lifecycles; hosted controller rollout and hosted certificate proof remain open | Obtain NZ legal review before operative use and implement/prove only the selected official-hosting boundaries; marketplace, organization, signer, settlement, and live hosted identity machinery remain gated | +| Direct post-archive human decisions | Human-approved: `COMMERCE-02` on 2026-08-23; `HOSTED-TERMS-01` and `HOSTED-TERMS-02` on 2026-08-24; shared refinement through 2026-08-25; `OPS-07` on 2026-09-06; `EDGE-WITHDRAWAL-01` on 2026-09-24 | `COMMERCE-02`, `HOSTED-TERMS-01`, `HOSTED-TERMS-02`, and `OPS-07` are applied through ADRs 0179-0182; `EDGE-WITHDRAWAL-01` through ADR 0184, without changing historical Packet 1-7 counts | Family-local consolidation for licensing lanes, hosted-terms authority, Game Design mutation gating, changed-terms continuity, separated hosted runtime/identity lifecycles, and emergency TCP Proxy identity withdrawal | Obtain NZ legal review before operative use and implement/prove only the selected official-hosting boundaries; marketplace, organization, signer, settlement, and live hosted identity machinery remain gated | ## Contract Authority Consolidation Scope 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 0e2288f6ec..7536a28fe5 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -197,7 +197,7 @@ Game Session pin reads remain distinct: `GetPinnedScriptPatchVersion` reports pi ## Active Gaps -- `AS-1.4` scheduler ordering is current implementation drift: `ScriptScheduleInstanceServiceImpl` sorts candidates by wall-clock lane, then due point (`dueTickId` or epoch-millisecond `dueAt`), then `priorityTag`, and finally schedule key, with round-robin grouping applied only after that sort. Due-point/lane order can therefore outrank bounded priority, and the due-order comparison spans distinct clock domains; the target remains bounded priority-first ordering with stable schedule-instance identity round-robin fairness. No scheduler algorithm change is claimed by this tracker. +- `AS-1.4` scheduler ordering is current implementation drift: `ScriptScheduleInstanceServiceImpl` sorts candidates by clock lane first, then that lane's due point (`dueTickId` for tick candidates or epoch-millisecond `dueAt` for wall-clock candidates), then `priorityTag`, and finally schedule key, with round-robin grouping applied only after that sort. Lane/due-point order can therefore outrank bounded priority; due-point comparison is lane-local and does not compare the distinct clock domains. The target remains bounded priority-first ordering with stable schedule-instance identity round-robin fairness. No scheduler algorithm change is claimed by this tracker. - The live clock-lane key is `wallClock ? 1 : 0` (tick candidates precede wall-clock candidates); the recorded drift is the lane and due-point precedence over priority, not a claim that wall-clock candidates always run first. - The evaluator is intentionally bounded to persisted script definitions, structured command emission, simple conditions, and target fan-out. Richer graph/runtime evaluation, compiled artifacts, and a broader sandbox execution seam are not implemented and require a separate runtime slice. - Script-driven generation and richer procedural population are not established gameplay slices; the current runtime does not provide the broader procedural-population flow described by the target architecture. 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 508e2fd9c9..62c98d61e5 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 @@ -54,7 +54,7 @@ These links add decision provenance only; they do not change existing implementa | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | -| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `proven` for launch-descriptor, game-instance lifecycle, world-instance activation, failure, and termination seams; Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldInstanceActivationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: launch descriptors and world/game instance prepare, activation, failure, and termination seams exist, but Automation `READY` is not joined, initial world events are not scheduled, generator inputs remain partly hardcoded, and full multi-participant launch convergence is absent. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover, owner cleanup acknowledgement, and complete launch convergence remain unproved. | +| `AR-3.1` Runtime instance launch, lifecycle, and termination | `partial` | `proven` for launch-descriptor, game-instance lifecycle, world-instance activation, failure, and termination seams; Automation `READY` join, initial world-event scheduling, generator-input completeness, and full multi-participant launch convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V11 launch descriptor](../../../services/game-design-service/src/main/resources/db/migration/V11__launch_descriptor_framework.sql); [V12 world activation](../../../services/world-management-service/src/main/resources/db/migration/V12__world_instance_activation.sql) | [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [LaunchDescriptorServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GameInstanceServiceLifecycleIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: launch descriptors and world/game instance prepare, activation, failure, and termination seams exist, but Automation `READY` is not joined, initial world events are not scheduled, generator inputs remain partly hardcoded, and full multi-participant launch convergence is absent. Accepted replacement namespace and database-authoritative lifecycle decisions now define the target boundary; namespace-aware cutover, owner cleanup acknowledgement, and complete launch convergence remain unproved. | | `AR-3.2` Release readiness, compatibility, and propagation | `partial` | `proven` for publish-gate, digest-read, release-bundle, launch-descriptor, and compatibility-check seams; target-commit convergence, coordinated digest-schema adoption, Automation readiness propagation, complete attestation tuples, and environment-promotion behavior remain unproved. | [Promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [Game Design version control](../../architecture/microservices/game-design-service/version-control.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 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md) | [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [LaunchDescriptorServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java); [WorldDraftDesignDigestServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java); [InstanceCutoverCompatibilityServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImpl.java); [V14 recorded participant digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql) | [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [LaunchDescriptorServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [EntityDraftDesignDigestServiceImplTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.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: publish gates, digest reads, release bundles, and compatibility checks exist, but actual target-commit convergence, coordinated digest schema adoption, Automation readiness propagation, and complete environment-promotion evidence are not established. Accepted publication, asset, and procedural-generation decisions now define the target readiness and convergence contracts; complete digest/attestation tuples, Automation readiness propagation, and promotion evidence remain incomplete. | | `AR-3.3` Cutover, rollback, hotfix, and script-patch activation | `partial` | `proven` for prepared cutover, pointer-CAS, patch pin/readiness, and plugin activation seams; complete live hotfix/rollback orchestration and downstream runtime-ready, alias, and binding convergence remain unproved. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.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); [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) | [VersionUpgradePreparationServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImpl.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [GameSessionVersionUpgradeControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionVersionUpgradeControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java) | [VersionUpgradePreparationServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/VersionUpgradePreparationServiceImplTest.java); [InstanceCutoverCompatibilityServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InstanceCutoverCompatibilityServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [ScriptPatchPinProjectionServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImplTest.java); [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java) | [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [automation](./automation-and-scheduler-runtime.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial: prepared cutover, pointer CAS, patch pin/readiness, and plugin activation seams exist, but complete live hotfix/rollback orchestration and all downstream runtime-ready, alias, and binding convergence remain incomplete. Accepted release-tuple and asset-lifecycle decisions now define immutable runtime selection and CAS-governed publication; complete cutover, rollback, hotfix, and downstream binding enforcement remain incomplete. | | `AR-3.4` Playtest forks, reset, expiry, and isolation | `not-implemented` | `unverified` | [Playtest fork boundary](../../architecture/system-architecture-versioning-runtime.md); [creator journeys](../../product/user-journeys/creators.md); [multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | No production anchor: no playtest-fork implementation exists. Adjacent context only: [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java) provides ordinary launch/termination; [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) has no fork/reset contract; [V1 baseline](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) has no playtest-fork state. | No focused executable proof: no fork/playtest production boundary exists to exercise. | [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [player access](./player-access-and-session.md) | Not implemented: no fork creation/snapshot copy, reset, expiry automation, isolation, or admission contract was found in production code, schema, proto, config, or focused tests. ADR 0122 and ADR 0123 define adjacent namespace/lifecycle boundaries; they do not claim that playtest fork behavior is implemented or proved. | diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index e1c3783d1e..cc9d1d20d4 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -142,7 +142,6 @@ The canonical `GetRuntimeOwnershipStatus` read returns owner, scope, epoch/fence Cross-region remote runtime remains partial. Current Game Session implementation has durable coordinator/follow-up persistence and handoff, bounded duplicate-window paging and per-entity de-duplication, durable result recording/replay, terminal follow-up replay, late-result handling, and selected reconciliation branches; the focused proof for those slices is recorded in [Validation and Proof](#validation-and-proof). Current storage and wire rows still lack the complete source/target projection and sealed handler-input manifest needed for exact source/target tuple binding, replay, and fencing. The remaining fair-due selection, source-claim ordering/manifests, terminal/result/reconciliation convergence, terminal-failure mirroring, missing-coordinator recovery, origin reconciliation, and plugin lifecycle-fence propagation are not implemented or proved. -Origin timeout cannot currently terminalize scheduled or claimed target follow-up work: that requires coordinator-side arbitration/CAS plus authoritative proof that the target work was unapplied; current origin reconciliation lacks that implementation and proof. The current `remote_followup` uniqueness index on `(tenant_id, target_region_id, target_region_epoch, effect_key)` omits `target_game_instance_id`, while repository reads include it; this is implementation drift, not target behavior. Persisted row fields remain canonical even when the original command row is absent, with payload JSON as optional enrichment. Origin timeout cannot currently terminalize scheduled or claimed target follow-up work: that requires coordinator-side arbitration/CAS plus authoritative proof that the target work was unapplied; current origin reconciliation lacks that implementation and proof. The complete target contract is owned by the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md), [tick failure contract](../../architecture/system-architecture-tick-failures-and-operations.md#cross-region-follow-up-record-contract-required), [scripting contract](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary), [ADR 0055](../../architecture/decisions/adr-0055-durable-cross-region-effects-with-static-live-topology.md), [ADR 0066](../../architecture/decisions/adr-0066-durable-asynchronous-cross-region-result-arbitration.md), [ADR 0071](../../architecture/decisions/adr-0071-durable-tick-commit-before-fenced-coordination-cleanup.md), and [ADR 0119](../../architecture/decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md). This tracker records only current implementation and proof status; target field, identity, outcome, scope, and reconciliation requirements remain in those canonical owners. 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 7bcf0cfa47..a1fd8e8252 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -23,7 +23,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial` | `audited` | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldInstanceActivationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | Partial: version-scoped topology, Draft mutation, and instance lifecycle exist, but generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | +| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial` | `audited` | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | Partial: version-scoped topology, Draft mutation, and instance lifecycle exist, but generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | | `GR-2.2` Location, occupancy, movement, exits, and spatial reads | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [system architecture](../../architecture/system-architecture-overview.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [LookAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java); [MoveAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/MoveAggregationService.java); [MoveCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/MoveCommandHandler.java); [room contract](../../../protos/world-management/v1/world_management_service.proto) | [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [LookAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/LookAggregationServiceTest.java); [MoveAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/MoveAggregationServiceTest.java); [MoveCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java); [movement idempotency test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [gameplay](./gameplay-rules-entities-and-effects.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [player experience](./player-experience-commands-and-communication.md) | Partial: directional LOOK and movement primitives exist, but the WMS `ListRoomOccupants` handler and target-only `character_location`/`npc_location` location and occupancy persistence are absent. Live `room_instance` topology and the Game Session room binding are not the World-owned location authority, and the final LOOK identity is not yet the causal floor plus opaque World/Entity component versions; served-through proofs remain separate participant validation evidence. DROP/PICKUP also lack the target World `TargetingFactSnapshot` location/version validation in the Entity-local commit. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains applied; implementation and proof gaps remain. Accepted full-grid topology decision now defines density-independent movement semantics and opaque scalable representation; large-grid identity, chunk/root finalization, base-plus-delta recovery, and movement-policy proof remain incomplete. | | `GR-2.3` Ambient, environmental, and scheduled world state | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md) | [WorldEventServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImpl.java); [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [RoomSnapshotDto.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDto.java); [V3 world events](../../../services/world-management-service/src/main/resources/db/migration/V3__world_events.sql); [V16 runtime event scope](../../../services/world-management-service/src/main/resources/db/migration/V16__runtime_world_event_scope.sql) | [WorldEventServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImplTest.java); [RoomSnapshotDtoTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDtoTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [gameplay](./gameplay-rules-entities-and-effects.md) | Partial: scheduled non-Weather event processing and ambient snapshot shape exist, but `ApplyRoomAmbientStatePatch` has no Java handler, durable effect-idempotency and general ambient patches are absent, and the creation workflow does not schedule initial events. Live `WorldEventService` rejects new `WEATHER_CHANGE` scheduling and leaves retained Weather rows unprocessed; the unresolved selector/fenced effect contract still blocks safe ambient mutation, so current code is not proof of the target World-owned fenced ambient-mutation contract. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains the target owner; its World-side handler, durable replay guard, and focused proof remain unimplemented. | diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java index 07dd50de63..7d7ddecb89 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java @@ -275,10 +275,12 @@ public HandoffResult handoff(ScriptWorkItem workItem, EmittedCommand command) { ex); return retryablePreparationResult(); } + WorkItemIntentState intentState = WorkItemIntentState.capture(workItem); HandoffPreparation preparation; try { preparation = executeIntentTransaction(workItem, command, dispatchId, preflight); } catch (RuntimeException ex) { + restoreWorkItemAfterFailedIntentTransaction(workItem, intentState); LOGGER.warn( "Unable to prepare script handoff for workItemId={} commandOrdinal={}", workItem.getId(), @@ -325,6 +327,20 @@ public HandoffResult handoff(ScriptWorkItem workItem, EmittedCommand command) { } } + private static void restoreWorkItemAfterFailedIntentTransaction( + ScriptWorkItem workItem, WorkItemIntentState intentState) { + workItem.setStatus(intentState.status()); + workItem.setUpdatedAt(intentState.updatedAt()); + workItem.setRowVersion(intentState.rowVersion()); + } + + private record WorkItemIntentState(String status, Instant updatedAt, int rowVersion) { + private static WorkItemIntentState capture(ScriptWorkItem workItem) { + return new WorkItemIntentState( + workItem.getStatus(), workItem.getUpdatedAt(), workItem.getRowVersion()); + } + } + private HandoffPreparation executeIntentTransaction( ScriptWorkItem workItem, EmittedCommand command, diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java index 2ce395aabf..6ece26e1db 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java @@ -355,23 +355,51 @@ void failedIntentCommitIsRetryableAndNeverClaimsInFlightOrCallsCommandRpc() { Mockito.mock(GameSessionControlPlaneClient.class); when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) .thenReturn(currentRuntimeState()); + when(gameSessionClient.enqueueAutomationCommandIfAbsent(Mockito.any())) + .thenReturn( + EnqueueAutomationCommandIfAbsentResponse.newBuilder() + .setAccepted(true) + .setAdmissionOutcome("ENQUEUED") + .setCommandId("sibling-command") + .build()); ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); ScriptWorkItem persistedWorkItem = workItem(); persistedWorkItem.setStatus("EVALUATING"); when(workItemRepository.findById(99L)).thenReturn(Optional.of(persistedWorkItem)); + List savedRowVersions = new ArrayList<>(); when(workItemRepository.save(Mockito.any())) .thenAnswer( invocation -> { ScriptWorkItem saved = invocation.getArgument(0); + savedRowVersions.add(saved.getRowVersion()); saved.setRowVersion(saved.getRowVersion() + 1); return saved; }); ScriptHandoffEventRepository handoffEventRepository = Mockito.mock(ScriptHandoffEventRepository.class); - when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) - .thenReturn(Optional.empty()); + AtomicReference siblingIntent = new AtomicReference<>(); + when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal( + Mockito.eq("1"), Mockito.eq(99L), Mockito.anyInt())) + .thenAnswer( + invocation -> + invocation.getArgument(2) == 1 + ? Optional.ofNullable(siblingIntent.get()) + : Optional.empty()); when(handoffEventRepository.save(Mockito.any())) - .thenAnswer(invocation -> invocation.getArgument(0)); + .thenAnswer( + invocation -> { + ScriptHandoffEvent event = invocation.getArgument(0); + if (event.getCommandOrdinal() == 1) { + if (event.getId() == null) { + event.setId(45L); + event.setRowVersion(0); + } else { + event.setRowVersion(event.getRowVersion() + 1); + } + siblingIntent.set(event); + } + return event; + }); ScriptWorkItem item = workItem(); ScriptGameplayCommandHandoffServiceImpl service = new ScriptGameplayCommandHandoffServiceImpl( @@ -395,18 +423,34 @@ void failedIntentCommitIsRetryableAndNeverClaimsInFlightOrCallsCommandRpc() { assertThat(result.outcome()).isEqualTo("REMOTE_REJECTED"); assertThat(result.errorCode()).isEqualTo("UNAVAILABLE"); assertThat(ScriptHandoffOutcomeSupport.isRetryable(result)).isTrue(); - assertThat(item.getStatus()).isEqualTo("HANDOFF_IN_FLIGHT"); - assertThat(item.getRowVersion()).isEqualTo(1); + assertThat(item.getStatus()).isEqualTo("PENDING_EVALUATION"); + assertThat(item.getUpdatedAt()).isEqualTo(Instant.EPOCH); + assertThat(item.getRowVersion()).isZero(); assertThat(persistedWorkItem.getStatus()).isEqualTo("EVALUATING"); assertThat(persistedWorkItem.getRowVersion()).isZero(); verify(gameSessionClient).getGameInstanceRuntimeState("1", "7", "region-1"); verify(gameSessionClient, never()).enqueueAutomationCommandIfAbsent(Mockito.any()); verify(gameSessionClient, never()).scheduleRemoteFollowup(Mockito.any()); + + ScriptGameplayCommandHandoffService.HandoffResult siblingResult = + service.handoff( + item, emittedCommand("say sibling", "entity-2", "7", "region-1", 12L, 35L, 1)); + + assertThat(siblingResult.accepted()).isTrue(); + assertThat(siblingIntent.get().getHandoffOutcome()).isEqualTo("enqueued"); + assertThat(siblingIntent.get().getRowVersion()).isEqualTo(1); + assertThat(savedRowVersions).containsExactly(0, 0); + verify(gameSessionClient, Mockito.times(2)).getGameInstanceRuntimeState("1", "7", "region-1"); + verify(gameSessionClient).enqueueAutomationCommandIfAbsent(Mockito.any()); assertThat(transactionManager.propagations()) .containsExactly( TransactionDefinition.PROPAGATION_NOT_SUPPORTED, TransactionDefinition.PROPAGATION_REQUIRES_NEW, - TransactionDefinition.PROPAGATION_NOT_SUPPORTED); + TransactionDefinition.PROPAGATION_NOT_SUPPORTED, + TransactionDefinition.PROPAGATION_NOT_SUPPORTED, + TransactionDefinition.PROPAGATION_REQUIRES_NEW, + TransactionDefinition.PROPAGATION_NOT_SUPPORTED, + TransactionDefinition.PROPAGATION_REQUIRES_NEW); } finally { TransactionSynchronizationManager.setActualTransactionActive(false); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupport.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupport.java index db4b86d82f..f5c3c0777e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupport.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupport.java @@ -332,7 +332,16 @@ private static DurableAdmission existingDurableAdmission( false); } if (ownershipRejected.isPresent()) { - return new DurableAdmission(ownershipRejected.orElseThrow(), null, false); + AdmissionResult rejection = ownershipRejected.orElseThrow(); + return new DurableAdmission( + new AdmissionResult( + rejection.accepted(), + rejection.admissionOutcome(), + existing.getCommandId(), + rejection.errorCode(), + rejection.errorMessage()), + null, + false); } } return new DurableAdmission(result, retryExisting ? existing : null, false, retryExisting); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java index c466212512..c0b64abd46 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java @@ -746,7 +746,9 @@ void doesNotRedriveExistingAcceptedCommandWhenRuntimeIsPaused() { assertFalse(result.accepted()); assertEquals("RUNTIME_PAUSED", result.admissionOutcome()); + assertEquals("auto-paused", result.commandId()); assertEquals("runtime_paused", result.errorCode()); + assertEquals("ACCEPTED", existing.getExecutionOutcome()); verifyNoTickEnqueue(tickService); } @@ -785,7 +787,9 @@ void keepsExistingAcceptedCommandRetryableWhenOwnershipReadFails() { assertFalse(result.accepted()); assertEquals("RETRY_QUEUED", result.admissionOutcome()); assertEquals("UNAVAILABLE", result.errorCode()); + assertEquals("Runtime ownership is temporarily unavailable", result.errorMessage()); assertEquals("auto-owner-read-failed", result.commandId()); + assertEquals("ACCEPTED", existing.getExecutionOutcome()); verify(gameplayCommandRepository, never()).insertIfAbsentByIdempotencyIdentity(any()); verifyNoTickEnqueue(tickService); } @@ -830,7 +834,9 @@ void doesNotRedriveExistingAcceptedRemoteCommandAfterOwnershipEpochAdvances() { assertFalse(result.accepted()); assertEquals("STALE_TIMELINE", result.admissionOutcome()); + assertEquals("rfcmd-remote-accepted", result.commandId()); assertEquals("stale_region_epoch", result.errorCode()); + assertEquals("ACCEPTED", existing.getExecutionOutcome()); verifyNoTickEnqueue(tickService); verify(pointerAuthority, org.mockito.Mockito.never()).listByRuntimeTarget(anyLong(), anyLong()); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 878e016013..8daf1da9b7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -10,7 +10,6 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.lang.reflect.Field; import java.time.Instant; import java.util.List; import java.util.Map; @@ -3601,8 +3600,8 @@ void enqueueAutomationCommandPersistsDispatchAndStagesTickCommand() { .thenReturn(Optional.empty()); RuntimeRegionStatusRepository runtimeRepository = runtimeRepository(runtimeStatus(false, 12L)); TickService tickService = Mockito.mock(TickService.class); - GameSessionControlPlaneGrpcService service = - controlPlaneService( + ControlPlaneTestFixture service = + controlPlaneFixture( gameInstanceRepository, commandRepository, runtimeRepository, @@ -3670,8 +3669,8 @@ void enqueueAutomationCommandRejectsSamePatchWithStalePinEpochBeforeReplayLookup stubLockedGameInstance(gameInstanceRepository, instance); GameplayCommandRepository commandRepository = Mockito.mock(GameplayCommandRepository.class); TickService tickService = Mockito.mock(TickService.class); - GameSessionControlPlaneGrpcService service = - controlPlaneService( + ControlPlaneTestFixture service = + controlPlaneFixture( gameInstanceRepository, commandRepository, Mockito.mock(RuntimeRegionStatusRepository.class), @@ -3715,8 +3714,8 @@ void enqueueAutomationCommandAllowsImmediateHandoffWithoutDueTick() { .thenReturn(Optional.empty()); RuntimeRegionStatusRepository runtimeRepository = runtimeRepository(runtimeStatus(false, 12L)); TickService tickService = Mockito.mock(TickService.class); - GameSessionControlPlaneGrpcService service = - controlPlaneService( + ControlPlaneTestFixture service = + controlPlaneFixture( gameInstanceRepository, commandRepository, runtimeRepository, @@ -3761,8 +3760,8 @@ void enqueueAutomationCommandDerivesCharacterIdFromNumericTargetEntity() { .thenReturn(Optional.empty()); RuntimeRegionStatusRepository runtimeRepository = runtimeRepository(runtimeStatus(false, 12L)); TickService tickService = Mockito.mock(TickService.class); - GameSessionControlPlaneGrpcService service = - controlPlaneService( + ControlPlaneTestFixture service = + controlPlaneFixture( gameInstanceRepository, commandRepository, runtimeRepository, @@ -3812,8 +3811,8 @@ void enqueueAutomationCommandReturnsRetryQueuedWhenPointerAuthorityIsUnreadable( .when(pointerAuthority) .listByRuntimeTarget(1L, 7L); TickService tickService = Mockito.mock(TickService.class); - GameSessionControlPlaneGrpcService service = - controlPlaneService( + ControlPlaneTestFixture service = + controlPlaneFixture( gameInstanceRepository, commandRepository, runtimeRepository, @@ -3891,8 +3890,8 @@ void enqueueAutomationCommandReturnsRetryQueuedWhenPointerAuthorityIsAmbiguous() "SHARED", "NONE"))); TickService tickService = Mockito.mock(TickService.class); - GameSessionControlPlaneGrpcService service = - controlPlaneService( + ControlPlaneTestFixture service = + controlPlaneFixture( gameInstanceRepository, commandRepository, runtimeRepository, @@ -3957,8 +3956,8 @@ void enqueueAutomationCommandRejectsMovedPointerAuthorityTarget() { "SHARED", "NONE"))); TickService tickService = Mockito.mock(TickService.class); - GameSessionControlPlaneGrpcService service = - controlPlaneService( + ControlPlaneTestFixture service = + controlPlaneFixture( gameInstanceRepository, commandRepository, runtimeRepository, @@ -4005,8 +4004,8 @@ void enqueueAutomationCommandRejectsStaleRuntimeEpochBeforeTickQueue() { .thenReturn(Optional.empty()); RuntimeRegionStatusRepository runtimeRepository = runtimeRepository(runtimeStatus(false, 13L)); TickService tickService = Mockito.mock(TickService.class); - GameSessionControlPlaneGrpcService service = - controlPlaneService( + ControlPlaneTestFixture service = + controlPlaneFixture( gameInstanceRepository, commandRepository, runtimeRepository, @@ -4053,8 +4052,8 @@ void enqueueAutomationCommandRejectsMismatchedRuntimeRegionBeforeTickQueue() { status.setRegionId("region-2"); RuntimeRegionStatusRepository runtimeRepository = runtimeRepository(status); TickService tickService = Mockito.mock(TickService.class); - GameSessionControlPlaneGrpcService service = - controlPlaneService( + ControlPlaneTestFixture service = + controlPlaneFixture( gameInstanceRepository, commandRepository, runtimeRepository, @@ -4099,8 +4098,8 @@ void enqueueAutomationCommandRejectsPausedRuntimeOwnershipBeforeTickQueue() { .thenReturn(Optional.empty()); RuntimeRegionStatusRepository runtimeRepository = runtimeRepository(runtimeStatus(true, 12L)); TickService tickService = Mockito.mock(TickService.class); - GameSessionControlPlaneGrpcService service = - controlPlaneService( + ControlPlaneTestFixture service = + controlPlaneFixture( gameInstanceRepository, commandRepository, runtimeRepository, @@ -4145,8 +4144,8 @@ void enqueueAutomationCommandRejectsPartialRoutingBundle() { RuntimeRegionStatusRepository runtimeRepository = runtimeRepository(runtimeStatus(false, 12L)); TickService tickService = Mockito.mock(TickService.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - GameSessionControlPlaneGrpcService service = - controlPlaneService( + ControlPlaneTestFixture service = + controlPlaneFixture( gameInstanceRepository, commandRepository, runtimeRepository, @@ -4182,8 +4181,8 @@ void enqueueAutomationCommandRejectsMalformedPointerVersion() { RuntimeRegionStatusRepository runtimeRepository = runtimeRepository(runtimeStatus(false, 12L)); TickService tickService = Mockito.mock(TickService.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - GameSessionControlPlaneGrpcService service = - controlPlaneService( + ControlPlaneTestFixture service = + controlPlaneFixture( gameInstanceRepository, commandRepository, runtimeRepository, @@ -4216,8 +4215,8 @@ void enqueueAutomationCommandRejectsNonPositivePointerVersion() { RuntimeRegionStatusRepository runtimeRepository = runtimeRepository(runtimeStatus(false, 12L)); TickService tickService = Mockito.mock(TickService.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - GameSessionControlPlaneGrpcService service = - controlPlaneService( + ControlPlaneTestFixture service = + controlPlaneFixture( gameInstanceRepository, commandRepository, runtimeRepository, @@ -4262,8 +4261,8 @@ void enqueueAutomationCommandRejectsMissingRegionOwnershipEvenWhenInstanceRowExi Mockito.when(runtimeRepository.findByTenantIdAndGameInstanceId(1L, 7L)) .thenReturn(Optional.of(staleInstanceStatus)); TickService tickService = Mockito.mock(TickService.class); - GameSessionControlPlaneGrpcService service = - controlPlaneService( + ControlPlaneTestFixture service = + controlPlaneFixture( gameInstanceRepository, commandRepository, runtimeRepository, @@ -4319,8 +4318,8 @@ void enqueueAutomationCommandPrefersRegionScopedOwnershipAuthority() { Mockito.when(runtimeRepository.findByTenantIdAndGameInstanceId(1L, 7L)) .thenReturn(Optional.of(staleInstanceStatus)); TickService tickService = Mockito.mock(TickService.class); - GameSessionControlPlaneGrpcService service = - controlPlaneService( + ControlPlaneTestFixture service = + controlPlaneFixture( gameInstanceRepository, commandRepository, runtimeRepository, @@ -4656,8 +4655,8 @@ void enqueueAutomationCommandReturnsDuplicateNoopForExistingDispatch() { 1L, 7L, "region-1", 12L, "dispatch-1")) .thenReturn(Optional.of(existing)); TickService tickService = Mockito.mock(TickService.class); - GameSessionControlPlaneGrpcService service = - controlPlaneService( + ControlPlaneTestFixture service = + controlPlaneFixture( gameInstanceRepository, commandRepository, Mockito.mock(RuntimeRegionStatusRepository.class), @@ -7035,8 +7034,8 @@ void scheduleRemoteFollowupImplementationDelegatesToRuntimeService() { .thenReturn( new RemoteFollowupRuntimeService.ScheduleOutcome("coord-1", "followup-1", true, true)); setAutomationScriptingInternalContext(); - GameSessionControlPlaneGrpcService service = - remoteControlPlaneService(null, null, null, null, null, runtimeService, gameDesignClient()); + ControlPlaneTestFixture service = + remoteControlPlaneFixture(null, null, null, null, null, runtimeService, gameDesignClient()); AtomicReference responseRef = new AtomicReference<>(); invokeDormantRemoteFollowupImplementation( @@ -7363,8 +7362,8 @@ public void onNext(EnqueueAutomationCommandIfAbsentResponse value) { void scheduleRemoteFollowupImplementationRejectsPartialRoutingBundle() { RemoteFollowupRuntimeService runtimeService = Mockito.mock(RemoteFollowupRuntimeService.class); setAutomationScriptingInternalContext(); - GameSessionControlPlaneGrpcService service = - remoteControlPlaneService(null, null, null, null, null, runtimeService, gameDesignClient()); + ControlPlaneTestFixture service = + remoteControlPlaneFixture(null, null, null, null, null, runtimeService, gameDesignClient()); IllegalArgumentException error = assertThrows( @@ -7388,8 +7387,8 @@ void scheduleRemoteFollowupImplementationRejectsZeroTargetGameInstanceId() { RemoteFollowupRuntimeService runtimeService = Mockito.mock(RemoteFollowupRuntimeService.class); setAutomationScriptingInternalContext(); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - GameSessionControlPlaneGrpcService service = - remoteControlPlaneService( + ControlPlaneTestFixture service = + remoteControlPlaneFixture( null, null, null, null, null, runtimeService, gameDesignClient(), meterRegistry); IllegalArgumentException error = @@ -7411,8 +7410,8 @@ void scheduleRemoteFollowupImplementationRejectsZeroPointerVersion() { RemoteFollowupRuntimeService runtimeService = Mockito.mock(RemoteFollowupRuntimeService.class); setAutomationScriptingInternalContext(); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - GameSessionControlPlaneGrpcService service = - remoteControlPlaneService( + ControlPlaneTestFixture service = + remoteControlPlaneFixture( null, null, null, null, null, runtimeService, gameDesignClient(), meterRegistry); IllegalArgumentException error = @@ -7434,8 +7433,8 @@ void scheduleRemoteFollowupImplementationRejectsMalformedPayload() { .thenThrow(new IllegalArgumentException("payload kind is required")); setAutomationScriptingInternalContext(); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - GameSessionControlPlaneGrpcService service = - remoteControlPlaneService( + ControlPlaneTestFixture service = + remoteControlPlaneFixture( null, null, null, null, null, runtimeService, gameDesignClient(), meterRegistry); IllegalArgumentException error = @@ -8475,6 +8474,45 @@ private static GameSessionControlPlaneGrpcService newService( worldManagementClient()); } + private static GameSessionControlPlaneGrpcService controlPlaneService( + GameInstanceRepository gameInstanceRepository, + GameplayCommandRepository gameplayCommandRepository, + RuntimeRegionStatusRepository runtimeRegionStatusRepository, + RemoteFollowupRepository remoteFollowupRepository, + RemoteCommandCoordinatorRepository remoteCommandCoordinatorRepository, + RemoteFollowupResultRepository remoteFollowupResultRepository, + RemoteFollowupRuntimeService remoteFollowupRuntimeService, + GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService, + InstanceCutoverCompatibilityService instanceCutoverCompatibilityService, + VersionUpgradePreparationService versionUpgradePreparationService, + GameDesignClient gameDesignClient, + BuiltInTextCommandAliasResolver builtInTextCommandAliasResolver, + TickService tickService, + MeterRegistry meterRegistry, + GameSessionProperties gameSessionProperties, + AutomationScriptingControlPlaneClient automationScriptingControlPlaneClient, + WorldManagementClient worldManagementClient) { + return controlPlaneFixture( + gameInstanceRepository, + gameplayCommandRepository, + runtimeRegionStatusRepository, + remoteFollowupRepository, + remoteCommandCoordinatorRepository, + remoteFollowupResultRepository, + remoteFollowupRuntimeService, + gameplayAdmissionPointerAuthorityService, + instanceCutoverCompatibilityService, + versionUpgradePreparationService, + gameDesignClient, + builtInTextCommandAliasResolver, + tickService, + meterRegistry, + gameSessionProperties, + automationScriptingControlPlaneClient, + worldManagementClient) + .service(); + } + private static GameSessionControlPlaneGrpcService controlPlaneService( GameInstanceRepository gameInstanceRepository, GameplayCommandRepository gameplayCommandRepository, @@ -8510,6 +8548,42 @@ private static GameSessionControlPlaneGrpcService controlPlaneService( null); } + private static ControlPlaneTestFixture controlPlaneFixture( + GameInstanceRepository gameInstanceRepository, + GameplayCommandRepository gameplayCommandRepository, + RuntimeRegionStatusRepository runtimeRegionStatusRepository, + RemoteFollowupRepository remoteFollowupRepository, + RemoteCommandCoordinatorRepository remoteCommandCoordinatorRepository, + RemoteFollowupResultRepository remoteFollowupResultRepository, + RemoteFollowupRuntimeService remoteFollowupRuntimeService, + GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService, + InstanceCutoverCompatibilityService instanceCutoverCompatibilityService, + VersionUpgradePreparationService versionUpgradePreparationService, + GameDesignClient gameDesignClient, + BuiltInTextCommandAliasResolver builtInTextCommandAliasResolver, + TickService tickService, + MeterRegistry meterRegistry, + GameSessionProperties gameSessionProperties) { + return controlPlaneFixture( + gameInstanceRepository, + gameplayCommandRepository, + runtimeRegionStatusRepository, + remoteFollowupRepository, + remoteCommandCoordinatorRepository, + remoteFollowupResultRepository, + remoteFollowupRuntimeService, + gameplayAdmissionPointerAuthorityService, + instanceCutoverCompatibilityService, + versionUpgradePreparationService, + gameDesignClient, + builtInTextCommandAliasResolver, + tickService, + meterRegistry, + gameSessionProperties, + null, + worldManagementClient()); + } + private static GameSessionControlPlaneGrpcService controlPlaneService( GameInstanceRepository gameInstanceRepository, GameplayCommandRepository gameplayCommandRepository, @@ -8547,7 +8621,7 @@ private static GameSessionControlPlaneGrpcService controlPlaneService( worldManagementClient()); } - private static GameSessionControlPlaneGrpcService controlPlaneService( + private static ControlPlaneTestFixture controlPlaneFixture( GameInstanceRepository gameInstanceRepository, GameplayCommandRepository gameplayCommandRepository, RuntimeRegionStatusRepository runtimeRegionStatusRepository, @@ -8617,14 +8691,17 @@ private static GameSessionControlPlaneGrpcService controlPlaneService( GameSessionVersionUpgradeControlPlaneService versionUpgradeControlPlaneService = new GameSessionVersionUpgradeControlPlaneService( instanceCutoverCompatibilityService, versionUpgradePreparationService); - return new GameSessionControlPlaneGrpcService( - commandControlPlaneService, - remoteControlPlaneService, - runtimeControlPlaneReadService, - admissionPointerControlPlaneService, - operatorControlPlaneService, - versionUpgradeControlPlaneService, - meterRegistry); + GameSessionControlPlaneGrpcService service = + new GameSessionControlPlaneGrpcService( + commandControlPlaneService, + remoteControlPlaneService, + runtimeControlPlaneReadService, + admissionPointerControlPlaneService, + operatorControlPlaneService, + versionUpgradeControlPlaneService, + meterRegistry); + return new ControlPlaneTestFixture( + service, commandControlPlaneService, remoteControlPlaneService); } private static TransactionOperations immediateTransactionOperations() { @@ -8814,6 +8891,40 @@ private static GameSessionControlPlaneGrpcService controlPlaneService( gameSessionProperties); } + private static ControlPlaneTestFixture controlPlaneFixture( + GameInstanceRepository gameInstanceRepository, + GameplayCommandRepository gameplayCommandRepository, + RuntimeRegionStatusRepository runtimeRegionStatusRepository, + GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService, + InstanceCutoverCompatibilityService instanceCutoverCompatibilityService, + VersionUpgradePreparationService versionUpgradePreparationService, + TickService tickService, + MeterRegistry meterRegistry) { + return controlPlaneFixture( + gameInstanceRepository, + gameplayCommandRepository, + runtimeRegionStatusRepository, + Mockito.mock(RemoteFollowupRepository.class), + Mockito.mock(RemoteCommandCoordinatorRepository.class), + Mockito.mock(RemoteFollowupResultRepository.class), + Mockito.mock(RemoteFollowupRuntimeService.class), + gameplayAdmissionPointerAuthorityService, + instanceCutoverCompatibilityService, + versionUpgradePreparationService, + null, + BuiltInTextCommandAliasResolver.unsupported(), + tickService, + meterRegistry, + new GameSessionProperties(), + null, + worldManagementClient()); + } + + private record ControlPlaneTestFixture( + GameSessionControlPlaneGrpcService service, + GameSessionCommandControlPlaneService commandService, + GameSessionRemoteControlPlaneService remoteService) {} + private static EnqueueAutomationCommandIfAbsentRequest automationRequest() { return EnqueueAutomationCommandIfAbsentRequest.newBuilder() .setTenantId("1") @@ -9109,7 +9220,7 @@ private static void setAutomationScriptingInternalContext() { // Keep lower-level behavior coverage while the authenticated gRPC boundary fails closed. private static void invokeDormantAutomationAdmissionImplementation( - GameSessionControlPlaneGrpcService service, + ControlPlaneTestFixture service, EnqueueAutomationCommandIfAbsentRequest request, StreamObserver responseObserver) { responseObserver.onNext(dormantAutomationAdmissionResponse(service, request)); @@ -9117,15 +9228,12 @@ private static void invokeDormantAutomationAdmissionImplementation( } private static EnqueueAutomationCommandIfAbsentResponse dormantAutomationAdmissionResponse( - GameSessionControlPlaneGrpcService service, EnqueueAutomationCommandIfAbsentRequest request) { - GameSessionCommandControlPlaneService implementation = - controlPlaneComponent( - service, "commandControlPlaneService", GameSessionCommandControlPlaneService.class); - return implementation.enqueueAutomationCommandIfAbsent(request); + ControlPlaneTestFixture service, EnqueueAutomationCommandIfAbsentRequest request) { + return service.commandService().enqueueAutomationCommandIfAbsent(request); } private static void invokeDormantRemoteFollowupImplementation( - GameSessionControlPlaneGrpcService service, + ControlPlaneTestFixture service, ScheduleRemoteFollowupRequest request, StreamObserver responseObserver) { responseObserver.onNext(dormantRemoteFollowupResponse(service, request)); @@ -9133,22 +9241,10 @@ private static void invokeDormantRemoteFollowupImplementation( } private static ScheduleRemoteFollowupResponse dormantRemoteFollowupResponse( - GameSessionControlPlaneGrpcService service, ScheduleRemoteFollowupRequest request) { - GameSessionRemoteControlPlaneService implementation = - controlPlaneComponent( - service, "remoteControlPlaneService", GameSessionRemoteControlPlaneService.class); - return implementation.scheduleRemoteFollowup(Long.parseLong(request.getTenantId()), request); - } - - private static T controlPlaneComponent( - GameSessionControlPlaneGrpcService service, String fieldName, Class componentType) { - try { - Field field = GameSessionControlPlaneGrpcService.class.getDeclaredField(fieldName); - field.setAccessible(true); - return componentType.cast(field.get(service)); - } catch (ReflectiveOperationException ex) { - throw new AssertionError("Could not access retained control-plane implementation", ex); - } + ControlPlaneTestFixture service, ScheduleRemoteFollowupRequest request) { + return service + .remoteService() + .scheduleRemoteFollowup(Long.parseLong(request.getTenantId()), request); } private static GameplayCommandRepository commandRepositorySavingArgument() { @@ -9301,6 +9397,25 @@ private static GameSessionControlPlaneGrpcService remoteControlPlaneService( new SimpleMeterRegistry()); } + private static ControlPlaneTestFixture remoteControlPlaneFixture( + RemoteFollowupRepository remoteFollowupRepository, + RemoteCommandCoordinatorRepository remoteCommandCoordinatorRepository, + RemoteFollowupResultRepository remoteFollowupResultRepository, + GameplayCommandRepository gameplayCommandRepository, + RuntimeRegionStatusRepository runtimeRegionStatusRepository, + RemoteFollowupRuntimeService remoteFollowupRuntimeService, + GameDesignClient gameDesignClient) { + return remoteControlPlaneFixture( + remoteFollowupRepository, + remoteCommandCoordinatorRepository, + remoteFollowupResultRepository, + gameplayCommandRepository, + runtimeRegionStatusRepository, + remoteFollowupRuntimeService, + gameDesignClient, + new SimpleMeterRegistry()); + } + private static GameSessionControlPlaneGrpcService remoteControlPlaneService( RemoteFollowupRepository remoteFollowupRepository, RemoteCommandCoordinatorRepository remoteCommandCoordinatorRepository, @@ -9310,6 +9425,27 @@ private static GameSessionControlPlaneGrpcService remoteControlPlaneService( RemoteFollowupRuntimeService remoteFollowupRuntimeService, GameDesignClient gameDesignClient, MeterRegistry meterRegistry) { + return remoteControlPlaneFixture( + remoteFollowupRepository, + remoteCommandCoordinatorRepository, + remoteFollowupResultRepository, + gameplayCommandRepository, + runtimeRegionStatusRepository, + remoteFollowupRuntimeService, + gameDesignClient, + meterRegistry) + .service(); + } + + private static ControlPlaneTestFixture remoteControlPlaneFixture( + RemoteFollowupRepository remoteFollowupRepository, + RemoteCommandCoordinatorRepository remoteCommandCoordinatorRepository, + RemoteFollowupResultRepository remoteFollowupResultRepository, + GameplayCommandRepository gameplayCommandRepository, + RuntimeRegionStatusRepository runtimeRegionStatusRepository, + RemoteFollowupRuntimeService remoteFollowupRuntimeService, + GameDesignClient gameDesignClient, + MeterRegistry meterRegistry) { GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when( @@ -9333,7 +9469,7 @@ private static GameSessionControlPlaneGrpcService remoteControlPlaneService( gameInstanceId % 2 == 0 ? "ISOLATED" : "SHARED", "interactive")); }); - return remoteControlPlaneService( + return remoteControlPlaneFixture( remoteFollowupRepository, remoteCommandCoordinatorRepository, remoteFollowupResultRepository, @@ -9376,6 +9512,29 @@ private static GameSessionControlPlaneGrpcService remoteControlPlaneService( GameDesignClient gameDesignClient, GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService, MeterRegistry meterRegistry) { + return remoteControlPlaneFixture( + remoteFollowupRepository, + remoteCommandCoordinatorRepository, + remoteFollowupResultRepository, + gameplayCommandRepository, + runtimeRegionStatusRepository, + remoteFollowupRuntimeService, + gameDesignClient, + gameplayAdmissionPointerAuthorityService, + meterRegistry) + .service(); + } + + private static ControlPlaneTestFixture remoteControlPlaneFixture( + RemoteFollowupRepository remoteFollowupRepository, + RemoteCommandCoordinatorRepository remoteCommandCoordinatorRepository, + RemoteFollowupResultRepository remoteFollowupResultRepository, + GameplayCommandRepository gameplayCommandRepository, + RuntimeRegionStatusRepository runtimeRegionStatusRepository, + RemoteFollowupRuntimeService remoteFollowupRuntimeService, + GameDesignClient gameDesignClient, + GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService, + MeterRegistry meterRegistry) { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); Mockito.when(gameInstanceRepository.findById(Mockito.anyLong())) .thenAnswer( @@ -9387,7 +9546,7 @@ private static GameSessionControlPlaneGrpcService remoteControlPlaneService( instance.setVersionId(99L); return Optional.of(instance); }); - return controlPlaneService( + return controlPlaneFixture( gameInstanceRepository, gameplayCommandRepository == null ? Mockito.mock(GameplayCommandRepository.class) diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java similarity index 99% rename from services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImplTest.java rename to services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java index 22648a1eb2..ce12ae2fa4 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java @@ -41,7 +41,7 @@ import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionOperations; -class WorldInstanceActivationServiceImplTest { +class WorldLifecycleCommandServiceImplTest { private WorldInstanceRepository worldInstanceRepository; private RegionInstanceRepository regionInstanceRepository; private ZoneRepository zoneRepository; From 680380bc86a51c648e26588d1807de1b37c6bd63 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 00:54:32 +1300 Subject: [PATCH 40/68] Align canonical scripting and effect contracts with proven runtime boundaries --- ...ting-event-ingress-idempotency-identity.md | 5 +-- ...-session-front-end-and-region-execution.md | 45 ++----------------- ...terministic-fair-entity-tick-scheduling.md | 2 +- .../runtime-and-data.md | 2 +- .../entity-management-service/operations.md | 2 +- .../game-session-service/runtime-and-data.md | 8 ++-- .../system-architecture-redis-ops-access.md | 4 +- ...rchitecture-scripting-control-plane-api.md | 5 ++- ...e-scripting-dsl-reference-and-lifecycle.md | 8 ++-- ...m-architecture-scripting-event-registry.md | 2 +- ...tecture-scripting-examples-and-patterns.md | 2 +- ...ure-scripting-normative-contract-tables.md | 10 ++++- ...ure-spatial-and-ambient-effects-catalog.md | 8 ++-- ...chitecture-tick-concepts-and-invariants.md | 2 +- ...ystem-architecture-tick-execution-flows.md | 4 +- .../architecture/system-architecture-ticks.md | 2 +- .../design-alignment/README.md | 2 +- .../automation-and-scheduler-runtime.md | 2 + dev-tools/tests/architecture-doc-contracts.sh | 18 +++++--- 19 files changed, 54 insertions(+), 79 deletions(-) diff --git a/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md b/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md index 310d3b0d29..0003477c13 100644 --- a/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md +++ b/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md @@ -18,8 +18,7 @@ Automation & Scripting treats event ingress as at-most-once per **Trigger Identi - Gameplay/runtime handler identity includes the applicable `tenantId`, `gameInstanceId`, authoritative `playableStateNamespaceId`, `regionId`, `regionEpoch`, `entityId`, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch`, `scriptEventId`, and `isDryRun` fields. The server-derived `playableStateScope` is retained and exact-validated as immutable policy/routing/authorization/fence evidence, not as a uniqueness discriminator. An authoritative scope transition starts a new playable-state lifecycle and namespace; stale presented scope with unchanged authority may reuse the existing identity. - `isDryRun` is always an identity dimension so live and test execution cannot collide. -- Scheduler/timer identity additionally carries its due point and trigger mode. The canonical scheduler preimage fields are serialized in this fixed order: ``. Fields marked `when ...` are omitted, not replaced by empty or sentinel values, when their branch does not apply; `targetScopeType` makes the target selector explicit and `stableOwnerKind` makes the core/plugin owner branch explicit. The server-derived `playableStateScope` remains immutable policy/routing/authorization/fence evidence and is not a preimage or uniqueness input. Thus `scriptEventId` itself is never part of this preimage, and `resumeWindowId` is absent for non-catch-up triggers. `duePoint` is exactly one tagged value: `dueTickId:` for tick-aligned schedules or `dueAt:` for wall-clock timers. Any additional scheduler schema version or trigger mode must become an explicit deterministic-ID input before it is admitted. -- The canonical target preimage is the fixed-order, length-prefixed UTF-8 serialization that `ScriptScheduleInstanceServiceImpl.TimerFiringCandidate.identity()` must implement. Each field is encoded as its UTF-8 byte length rendered as unsigned base-10 ASCII decimal with no leading zeroes, followed by a colon and its unescaped UTF-8 value; fields are concatenated without separators. Numeric identity values therefore use their canonical base-10 ASCII spelling (for example, `0`, `7`, and `-1`), and the prefix length counts UTF-8 bytes rather than Unicode code points. Semantic validation still controls which numeric values are admissible; deterministic decimal serialization does not make an otherwise invalid value valid. Boolean values serialize canonically as lowercase `true` or `false`. Enum values serialize as the contract-declared enum symbol/name, never an ordinal, localized spelling, or other implementation-specific representation. This permits delimiters and arbitrary UTF-8 text without creating tuple collisions. Hash those bytes with SHA-256, encode the digest as lowercase hexadecimal, retain the first 60 hexadecimal characters, and prefix the result with `timer-`. Cross-producer golden vectors must cover empty values, non-ASCII values, delimiters, negative and zero numeric values, both boolean values, representative enum branches, and both tagged due-point branches before this identity is considered proven. +- Scheduler/timer triggers additionally carry a due point and trigger mode. The canonical scheduler candidate preimage, its conditional branches, serialization, hash, and proof requirements are owned by [Table 1's Scheduler Candidate Identity Preimage](../system-architecture-scripting-normative-contract-tables.md#scheduler-candidate-identity-preimage-normative); this superseded ADR preserves no competing specification. - Tenant-readiness `onLoad` follows the explicit non-runtime exception in the normative table and does not invent sentinel runtime, region, or entity identity. - Plugin-trigger identity additionally carries plugin and binding identity where the invocation unit is plugin- or binding-scoped. @@ -32,7 +31,7 @@ Ordinary event-ingress callers must reuse the same full applicable Trigger Ident ## Implementation and Proof Obligations -Prove the endpoint-specific Trigger Identity field matrix, fixed-order scheduler preimage, length-prefixed UTF-8 serialization, canonical numeric, boolean, and enum forms, optional-branch omission, deterministic hashing, cross-producer golden vectors, and exact retry reuse without collisions or duplicate logical triggers. Select and report the required checks and evidence under [Validation and Runtime Proof](../../developer-workflows/validation-and-runtime-proof.md); record execution results in PR/CI evidence or implementation-tracking documents rather than in this decision record. +Implementation and proof must satisfy the canonical identity matrix and scheduler-preimage requirements in [Scripting Normative Contract Tables](../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields), including its required vectors and exact-retry behavior. Select and report the required checks and evidence under [Validation and Runtime Proof](../../developer-workflows/validation-and-runtime-proof.md); record execution results in PR/CI evidence or implementation-tracking documents rather than in this decision record. ## References diff --git a/design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md b/design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md index 0b114c491a..e4b7b43177 100644 --- a/design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md +++ b/design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md @@ -19,51 +19,12 @@ Without an explicit answer, docs and implementations risk drifting toward incomp - silent cross-pod forwarding without fencing rules, - or forced reconnects on ordinary lease rebalancing. -## Decision +## Historical Rationale -FireMUD adopts a **session front-end + lease-owner execution** model inside the Game Session layer. +This ADR separated stable socket ownership from region execution ownership so ordinary lease movement would not force player reconnects, while rejecting silent, unfenced cross-pod mutation. The detailed decision has been superseded: [ADR 0170](./adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md) owns the current contract for authoritative region transitions, owner forwarding, identity, fences, retries, and failure handling. The former mandatory forwarding details in this ADR no longer define a current contract. -- A connected gameplay socket is attached to a **session front-end** Game Session pod. -- Region-scoped gameplay execution remains owned by the pod that currently holds the relevant `` lease. -- The session front-end pod may accept input, authenticate the session, manage connection-local state, and stream results back to the client. -- The session front-end pod must not mutate tick-owned gameplay coordination state for a region it does not own. -- When command execution or tick-owned mutation targets a region leased by another pod, the session front-end forwards the request over internal gRPC to the current **lease owner**. -- Only the lease owner may stage or commit Redis coordination changes for that region. -- `playableStateScope` is exact-validated request evidence/context in the forwarded request and must be preserved end to end because it validates the gameplay state/effect scope being acted on; it is excluded from uniqueness and deduplication identity. -- `playableStateScope` is not an additional lease-ownership dimension. Lease ownership remains keyed by ``; the current owner and its fence apply to the region, while the owner validates the forwarded playable-state scope against the authoritative gameplay binding. - -## Consequences - -- Spring Cloud Gateway remains shard-unaware and continues to route `/ws/game/**` to a stable Game Session service surface. -- Normal in-cluster lease rebalancing does not require client-visible reconnects solely because region ownership moved. -- Socket ownership and region execution ownership are decoupled; runbooks and observability must treat them as separate roles. -- Internal forwarding paths must carry enough fenced identity to prevent stale front-ends from mutating a region after lease loss. -- If internal forwarding becomes unavailable or inconsistent, Game Session may fail the affected command or close the gameplay session using the existing reconnect model; it must not invent a separate edge-visible shard-handoff taxonomy without a new design update. - -## Required Internal Forwarding Contract - -Any session front-end to lease-owner forwarding path must implement one canonical contract: - -- Every forwarded request carries `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `sessionId`, `characterId`, target `regionId`, command or action identifier, and a monotonic per-session sequencing token so the lease owner can preserve session-local ordering. -- Every forwarded request carries the lease/epoch fence for the target region. A lease owner must reject requests with a stale or missing fence using an application-level stale-lease error. -- The session front-end may retry only idempotent forwarded operations and must not create duplicate tick-owned mutations when a response is ambiguous. -- If lease ownership changes before execution starts, the front-end must refresh ownership and retry against the new lease owner. If ownership changes after execution has begun, the in-flight attempt is owned by the executor that accepted the fenced request and later attempts must use the new fence. -- If forwarding times out or the target lease owner is unavailable, Game Session must either fail the affected command with the documented structured error path or terminate the gameplay session using the existing reconnection contract. It must not invent a separate client-visible shard-handoff behavior. - -Service-level docs may add implementation detail, but they must not weaken these fencing, ordering, or failure rules. - -## Non-Goals +## Historical Non-Goals - This ADR does not introduce a Gateway-owned gameplay shard-routing plane. - This ADR does not define multi-cluster gameplay execution. - This ADR does not introduce a client-visible shard-handoff close category. - -## Required Documentation Alignment - -The following docs must remain aligned with this decision: - -- `design/architecture/system-architecture-overview.md` -- `design/architecture/system-architecture-reconnection.md` -- `design/architecture/system-architecture-diagram.md` -- `design/architecture/microservices/game-session-service/README.md` -- `design/architecture/microservices/spring-cloud-gateway/README.md` diff --git a/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md b/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md index 20a8d94593..867513751f 100644 --- a/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md +++ b/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md @@ -49,7 +49,7 @@ Within one entity's eligible queue, work uses persisted deterministic ordering: `entity_enqueue_seq` is monotonic within the entity's current region epoch and assigned by the owning Game Session admission/scheduling path. Same-tick derived children use the persisted parent order plus deterministic child ordinals rather than completion timing. New sources map into this tuple and do not introduce private tie-breakers. -The historical final tuple label `commandId_or_effectKey` is one normalized, persisted, source-specific stable identity slot: `command` uses `commandId`; `timer` uses the timer member ID; `retry` uses the persisted retry member/effect identity required by its owning contract; `remote_followup` uses the durable follow-up row ID; and `generated_effect` uses its recorded deterministic child `EffectId` under the immutable parent/root identity and child ordinal contract. The selected manifest retains this exact source-to-slot mapping for each item; this does not introduce a second tuple or schema field. The pending [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not current target state. +The historical final tuple label `commandId_or_effectKey` is one normalized, persisted, source-specific stable identity slot: `command` uses `commandId`; `timer` uses the timer member ID; `retry` uses the persisted retry member/effect identity required by its owning contract; `remote_followup` uses the durable follow-up row ID; and `generated_effect` uses its recorded child `EffectId` as the slot value. Parent/root identity and child ordinal remain recorded audit and ordering context; they do not replace the child effect identity. The selected manifest retains the source-to-slot mapping and that context for each item; this does not introduce a second tuple or schema field. The child-ID allocation choice remains pending in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) and is not current target state. Across eligible entities, each lane uses persisted deterministic rotating/deficit scheduling. The scheduler accounts for declared work cost, advances only with the durable selected batch, and ensures a permanently eligible entity eventually receives capacity within a healthy epoch. Non-best-effort priority classes declare bounded aging or `maxDeferralTicks`; work explicitly classified as best effort follows its declared delay/drop policy. 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 2c9d8d98db..50c6b3d97a 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -29,7 +29,7 @@ The current `script_event_ingress_audit` event-scope claim uses branch-specific The live `faction`/`faction_standing` schema and `FactionServiceImpl` currently make Automation the player-reputation writer and derive isolated standing identity from `gameInstanceId`. The target owner is Social & Groups under a stable playable-state namespace; Automation remains a consumer for NPC behavior. Owner migration, retained-row disposition, namespace-stable identity, and focused owner-read proof remain unimplemented. -The live `script_event_audit` and `script_work_items` schema uniqueness constraints omit plugin provenance, and neither current row shape nor repository identity lookup carries the required resolved `bindingId`. Distinct plugin handlers can therefore alias or collide even though the target full Trigger Identity requires `pluginId`, `pluginVersionId`, and `bindingId` where applicable. A new owner-local migration, aligned jOOQ/repository identity, and focused multi-handler retry/concurrency proof are required; this is current implementation drift, not a change to Trigger Identity authority. +The live `script_event_audit` and `script_work_items` schema uniqueness constraints omit plugin provenance, and neither current row shape nor repository identity lookup carries the resolved `bindingId` required by the target full Trigger Identity. Distinct plugin handlers can therefore alias or collide even though the target full Trigger Identity requires `pluginId`, `pluginVersionId`, and `bindingId` where applicable. A new owner-local migration, aligned jOOQ/repository identity, and focused multi-handler retry/concurrency proof are required; this is current implementation drift, not a change to Trigger Identity authority. The command-plan preview boundary in [ADR 0114](../../decisions/adr-0114-command-plan-preview-dry-run-isolation.md) is non-committing: a preview must not persist live evaluated script work items, populate the live automation queue, hand off commands, or perform external side effects. It may persist isolated audit/result evidence containing the exact input identity, fenced snapshot/fixture reference, and ordered plan. The current materialized dry-run path may use the internal pre-DSL trigger-record/queue shape and persists that current pre-DSL trigger record, but its live implementation records `finalStage=DSL_EVAL`, `finalOutcome=dry_run_completed`, and `finalReason=dry_run_no_handoff`; the shared terminal-success helper marks its internal `script_work_items.status=HANDED_OFF` even though no Game Session handoff or gameplay-work acceptance occurs. It has not converged on target `DRY_RUN_RESULT` terminology; that internal marker is not target live-work persistence or downstream-handoff evidence, and complete plan-result/input proof is still absent. This is an implementation handoff, not a competing contract. diff --git a/design/architecture/microservices/entity-management-service/operations.md b/design/architecture/microservices/entity-management-service/operations.md index 8e9d8b7c66..96b548e378 100644 --- a/design/architecture/microservices/entity-management-service/operations.md +++ b/design/architecture/microservices/entity-management-service/operations.md @@ -29,7 +29,7 @@ Target-state tick processing uses the canonical `tick:{tenantRegionTag}:lock:` are never repaired by a region- or tenant-scoped coordination reset. The operator must invoke Account-owned exact projection repair/readback (and token revocation/rotation tooling where applicable); target `session:auth:token:` repair is conditional on the target issued-token registry cutover being implemented. The target `session:connect-token:v1:*` projection requires Account repair from the exact SQL issuance operation/result and exact Redis readback; it cannot be reconstructed from a JWT or request fields. The unversioned legacy map is not a target repair source. Account may clean it only after quiescing and draining connect-token issuance/retries, preserving the legacy entries and reading them back through the configured TTL/retry horizon, then performing owner-authorized cleanup with exact absence/readback evidence. The cluster-reset/replay-quarantine/forced re-registration or reauthentication path is target-state-only until the Account repair, replay quarantine, and replacement tooling are implemented and proven. Under the current fallback, preserve the evidence, keep affected scopes fenced, and escalate whenever exact repair, token custody, replay continuity, or the affected token set cannot be proven; direct Redis edits are not a substitute for either path. -- Operators must treat such writes as equivalent to “coordination state may be inconsistent” and use the Coordination Reset Model to bring the region/tenant/cluster back to a known-good state, rather than leaving ad-hoc edits in place as a permanent fix. - -- **Target state only, once the canonical gated coordination-maintenance operation is implemented and proven:** Operators must treat such writes as equivalent to “coordination state may be inconsistent” and use the Coordination Reset Model to bring the region/tenant/cluster back to a known-good state, rather than leaving ad-hoc edits in place as a permanent fix. +- **Current fallback:** after such writes, preserve incident evidence, keep the affected scope fenced, and escalate through [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). The Coordination Reset Model is target-state only and applies after its canonical gated coordination-maintenance operation is implemented and proven. - When target reset tooling exists, break-glass flows should go through a small wrapper (CLI or Logging & Admin action) that: - Executes the minimal required Redis mutation. diff --git a/design/architecture/system-architecture-scripting-control-plane-api.md b/design/architecture/system-architecture-scripting-control-plane-api.md index d7ccafe25c..c23ca66cd5 100644 --- a/design/architecture/system-architecture-scripting-control-plane-api.md +++ b/design/architecture/system-architecture-scripting-control-plane-api.md @@ -556,6 +556,7 @@ Inputs: - Optional `gameInstanceId` - Optional `scriptPatchVersion` - Optional source runtime identity filters (`playableStateNamespaceId`, `regionId`, `regionEpoch`); `playableStateScope` is a separately validated evidence filter +- The complete source runtime identity for each row is `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch)`. `tenantId` and optional `gameInstanceId` are the inherited top-level filters above; the source-specific filters narrow that identity and do not make its persisted fields optional. - Optional `workItemId` - Optional `handoffOutcome` - Optional target runtime identity filters (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, `targetRegionEpoch`); `targetPlayableStateScope` is separately validated target evidence @@ -568,7 +569,7 @@ Inputs: Outputs: -- **Target-state output:** ordered event rows containing `eventId`, `tenantId`, source Command-Handoff runtime identity (`gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`), separately validated source `playableStateScope` evidence, exact source owner tuple `scriptPatchVersion`/`scriptPinEpoch`/`scriptPinControlPlaneRequestId`, `scriptId`, optional plugin identity tuple `(pluginId, pluginVersionId, bindingId)` and target-state `pluginActivationEpoch`/captured `lifecycleRevision`; absent tuple fields are explicit and must not be inferred from epoch/revision, `workItemId`, `commandOrdinal`, `automationDispatchId`, target-state `handoffRequirement`, optional `gameSessionCommandId`, distinct target Command-Handoff runtime identity when applicable (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, `targetRegionEpoch`), separately validated target `targetPlayableStateScope` evidence, optional remote follow-up ids (`remoteCoordinatorId`, `remoteFollowupId`), current owned target runtime identity (`currentTargetRuntimePlayableStateNamespaceId`, `currentTargetRuntimeGameInstanceId`, `currentTargetRuntimeRegionId`, `currentTargetRuntimeRegionEpoch`) plus the current owned routing bundle (`currentTargetRuntimePlayableStateScope`, `currentTargetRuntimeWorldSlug`, `currentTargetRuntimeRealmSlug`, `currentTargetRuntimePointerVersion`) and stale-scope/routing comparison against the persisted distinct target namespace/scope and admitted target routing bundle, later Game Session gameplay-command execution truth (`gameplayCommandExecutionOutcome`, `gameplayCommandGameplayResult`, failure details, and remote-state tail), `targetEntityId`, rendered `emittedCommandText`, `handoffOutcome`, `handoffReason`, and `observedAt` +- **Target-state output:** ordered event rows containing `eventId` and the complete source Command-Handoff runtime identity (`tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`), separately validated source `playableStateScope` evidence, exact source owner tuple `scriptPatchVersion`/`scriptPinEpoch`/`scriptPinControlPlaneRequestId`, `scriptId`, optional plugin identity tuple `(pluginId, pluginVersionId, bindingId)` and target-state `pluginActivationEpoch`/captured `lifecycleRevision`; absent tuple fields are explicit and must not be inferred from epoch/revision, `workItemId`, `commandOrdinal`, `automationDispatchId`, target-state `handoffRequirement`, optional `gameSessionCommandId`, distinct target Command-Handoff runtime identity when applicable (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, `targetRegionEpoch`), separately validated target `targetPlayableStateScope` evidence, optional remote follow-up ids (`remoteCoordinatorId`, `remoteFollowupId`), current owned target runtime identity (`currentTargetRuntimePlayableStateNamespaceId`, `currentTargetRuntimeGameInstanceId`, `currentTargetRuntimeRegionId`, `currentTargetRuntimeRegionEpoch`) plus the current owned routing bundle (`currentTargetRuntimePlayableStateScope`, `currentTargetRuntimeWorldSlug`, `currentTargetRuntimeRealmSlug`, `currentTargetRuntimePointerVersion`) and stale-scope/routing comparison against the persisted distinct target namespace/scope and admitted target routing bundle, later Game Session gameplay-command execution truth (`gameplayCommandExecutionOutcome`, `gameplayCommandGameplayResult`, failure details, and remote-state tail), `targetEntityId`, rendered `emittedCommandText`, `handoffOutcome`, `handoffReason`, and `observedAt` Contract rules: @@ -577,7 +578,7 @@ Contract rules: - `automationDispatchId` is a correlation key between Automation handoff history and the Game Session gameplay-command ledger; it is not a low-cardinality value and metrics must not use it as a label. Operator/debug reads can resolve the Game Session side either from the returned `gameSessionCommandId` or from the full automation identity tuple `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch, automationDispatchId, commandOrdinal)`, plus the applicable distinct target identity `(targetGameInstanceId, targetPlayableStateNamespaceId, targetRegionId, targetRegionEpoch)`, when the command id is not yet known to the caller; `playableStateScope` remains separately validated evidence. - Operators use this read to answer which emitted command ordinal reached Game Session, which rendered command text, target entity, and target runtime scope it addressed, whether it stayed local or became a durable remote follow-up, and whether the failure happened before handoff, at Game Session admission, or after later gameplay-side execution disposition. - Because remote follow-up legs are now durable first-class runtime rows, this read must support direct filtering by target runtime scope, remote coordinator/follow-up ids, and origin script/plugin/dispatch identity rather than assuming one bulk history scan plus client-side correlation. -- The persisted source and optional target fields follow the [canonical Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state): source `playableStateNamespaceId`, `regionId`, and `regionEpoch`, plus `targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, and `targetRegionEpoch` only for a distinct target, together with the dispatch and ordinal. Source and target `playableStateScope` values are separately persisted, exact-validated policy/routing/authorization/fence evidence and are excluded from identity. These complete fields are target-state only: the current live handoff proto, storage, and read remain narrower and do not establish live support for this contract. +- The persisted source and optional target fields follow the [canonical Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state): the complete source identity is inherited `tenantId` and `gameInstanceId` plus source `playableStateNamespaceId`, `regionId`, and `regionEpoch`; the distinct target adds `targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, and `targetRegionEpoch` only when applicable, together with the dispatch and ordinal. Source and target `playableStateScope` values are separately persisted, exact-validated policy/routing/authorization/fence evidence and are excluded from identity. These complete fields are target-state only: the current live handoff proto, storage, and read remain narrower and do not establish live support for this contract. - The read must also expose the current owned target runtime identity and routing bundle from Game Session when the target instance still exists, so operators can compare `currentTargetRuntimePlayableStateNamespaceId` and the current scope/routing bundle against the persisted distinct target identity and admitted target bundle, preserving same-target semantics without a separate ownership-status lookup. - When `gameSessionCommandId` is known, the read should also expose the later Game Session gameplay-command execution outcome instead of stopping at handoff-time admission, so operator diagnostics can stay on one handoff-history surface through local and remote gameplay execution tails. 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 523c09f966..47f066df8a 100644 --- a/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md +++ b/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md @@ -63,10 +63,10 @@ For designer-oriented guidance on building and debugging scripts in the visual e ## Terminology Glossary - **`{tenantRegionTag}` hash tag** – an opaque placeholder produced by shared Redis key builders from the complete `` scope documented in [Redis Architecture](./system-architecture-redis.md#key-naming-and-shard-discipline). It exists for shard locality across region-scoped keys; it is not a replacement for those identity fields and does not define a competing schedule or tenant key family. `playableStateScope` is intentionally not part of this existing tag topology; durable Trigger, scheduler, and command-handoff identities use `playableStateNamespaceId`, while scope remains immutable policy/routing/authorization/fence evidence and must not be inferred from the tag. Downstream mutation guards exact-validate applicable namespace/scope evidence separately from their own effect-guard uniqueness. -- **`{tenantInstanceTag}` hash tag** – an opaque placeholder produced by shared Redis key builders from ``. It scopes instance-wide automation projections: `automation:queue:{tenantInstanceTag}:` is a Cache/Rate-Limit disposable dispatch-pointer index rebuilt from eligible durable pre-DSL records, while `remote:{tenantInstanceTag}:` is a separate Coordination Redis wake-up hint. The tag must not be substituted for the region-scoped `{tenantRegionTag}` where a region timeline or lease fence applies. +- **`{tenantInstanceTag}` hash tag** – an opaque placeholder produced by shared Redis key builders from ``. It scopes instance-wide automation projections: `automation:queue:{tenantInstanceTag}:` is a Cache/Rate-Limit disposable dispatch-pointer index rebuilt from eligible durable pre-DSL records, while `remote:{tenantInstanceTag}:` is a separate Coordination Redis wake-up hint. This current key, the `ScriptWorkItem` row/claim, its queue pointer, and an `outboxWorkItemId`-only claim do not establish namespace isolation; the tenant-instance tag does not carry `playableStateNamespaceId`. Target work items, pointers, queue-index projections, rebuild eligibility, and consumers must retain and exact-validate authoritative `playableStateNamespaceId`, with `playableStateScope` separately exact-validated as policy/routing/fence evidence rather than identity. This requirement does not prescribe a Redis key topology. The tag must not be substituted for the region-scoped `{tenantRegionTag}` where a region timeline or lease fence applies. - **Game tick** – a region-scoped tick in the Game Session Service. Each `` advances through a monotonic `tickId` stream; game ticks are authoritative for gameplay state changes and use `tick:{tenantRegionTag}:...` keys and locks as described in [Tick System and Runtime Design](./system-architecture-ticks.md). - **Automation execution loop** – the durable executor path inside the Automation & Scripting Service. **Target state:** it claims committed descriptor children under a durable parent work item, evaluates no DSL again, and hands resulting commands to the Game Session Service so Game Session can enqueue **tick commands** into per-entity tick queues for later execution by game ticks. **Current implementation:** the scheduled queue-rebuild hook/configuration has been removed/disabled; the executor drains derived pointers and its durable claim filters to `PENDING_EVALUATION`, so `EVALUATING` pointers are not picked up, reclaimed, or re-entered into the DSL. Because there is no stale-owner/CAS recovery, queue reset/rebuild/resume remains unavailable and must fail closed; see [Scripting Runtime Execution: Current Queue-Rebuild Concurrency Gap](./system-architecture-scripting-runtime-execution.md#current-queue-rebuild-concurrency-gap). Atomic owner-reconciled recovery of safe post-DSL `PENDING` work is target-only. -- **Automation queue** – an instance-aware, per-entity Redis queue (`automation:queue:{tenantInstanceTag}:`) that currently holds **derived pre-DSL parent-work indexes/pointers** for `PENDING_EVALUATION` and `EVALUATING` work, not an authoritative log of pending work. `PENDING_EVALUATION` pointers can be claimed for evaluation; `EVALUATING` pointers are inspection-only and cannot be picked up, reclaimed, or re-enter the DSL. The former rebuild hook/configuration is removed/disabled; queue reset/rebuild/resume remains unavailable and must fail closed. See [Scripting Runtime Execution: Current Queue-Rebuild Concurrency Gap](./system-architecture-scripting-runtime-execution.md#current-queue-rebuild-concurrency-gap). Target post-DSL descriptor recovery uses separate `PENDING`/`INDEXED` states and atomic owner-reconciled recovery of safe work; it is not implemented. +- **Automation queue** – an instance-aware, per-entity Redis queue (`automation:queue:{tenantInstanceTag}:`) that currently holds **derived pre-DSL parent-work indexes/pointers** for `PENDING_EVALUATION` and `EVALUATING` work, not an authoritative log of pending work or proof of namespace isolation. `PENDING_EVALUATION` pointers can be claimed for evaluation; `EVALUATING` pointers are inspection-only and cannot be picked up, reclaimed, or re-enter the DSL. The former rebuild hook/configuration is removed/disabled; queue reset/rebuild/resume remains unavailable and must fail closed. See [Scripting Runtime Execution: Current Queue-Rebuild Concurrency Gap](./system-architecture-scripting-runtime-execution.md#current-queue-rebuild-concurrency-gap). Target post-DSL descriptor recovery uses separate `PENDING`/`INDEXED` states, retains/exact-validates namespace identity separately from scope evidence, and requires atomic owner-reconciled recovery of safe work; it is not implemented. - **Tick heartbeat** – a **gRPC streaming feed** produced by the Game Session Service that reports `(regionEpoch, tickId)` progression per ``. The script scheduler consumes this heartbeat over a long-lived gRPC stream to count “every N ticks” intervals and align `onInterval` triggers with the canonical game tick timeline without owning tick execution itself. See [Tick Events & Heartbeat Stream](./system-architecture-ticks.md#tick-events--heartbeat-stream) for transport details and the `(regionEpoch, tickId)` coordination timeline. --- @@ -98,10 +98,10 @@ The required Trigger Identity fields and target-scope exceptions are defined in | --- | --- | --- | --- | | 1 | **Trigger** | A concrete event such as `onEnterRegion`, `onCommand`, or a custom event emitted by a service. | gRPC `TriggerScriptEvent` call, tick heartbeat, or internal scheduler event. | | 2 | **DSL run** | Execution of a script handler in the sandboxed DSL for a single trigger. It evaluates the frozen inputs within the durable parent work item and produces domain commands, not direct state changes. | In-memory execution in the Automation & Scripting Service; results are committed to that parent and, at `EVALUATED_COMMITTED`, to immutable command descriptors. | -| 3 | **Script work item** | For each admitted resolved handler, one durable parent work item owns the applicable Trigger Identity and pre-DSL lifecycle; when it reaches `EVALUATED_COMMITTED`, it gains immutable evaluated command descriptor/child-dispatch rows, one per emitted command, with version metadata. A handler denied before work-item materialization has no parent work item. The descriptor rows have independent handoff statuses while the parent marker remains the recovery boundary. | **Target state only:** committed descriptor children are indexed via `automation:queue:{tenantInstanceTag}:` when they target an entity and are later claimed by Automation's durable executor for Game Session handoff. **Current implementation:** that queue is only a derived pre-DSL parent-work pointer projection for `PENDING_EVALUATION`/`EVALUATING`, not an evaluated-command descriptor index. | +| 3 | **Script work item** | For each admitted resolved handler, one durable parent work item owns the applicable Trigger Identity and pre-DSL lifecycle; when it reaches `EVALUATED_COMMITTED`, it gains immutable evaluated command descriptor/child-dispatch rows, one per emitted command, with version metadata. A handler denied before work-item materialization has no parent work item. The descriptor rows have independent handoff statuses while the parent marker remains the recovery boundary. | **Target state only:** each work item/descriptor and queue-index pointer retains and exact-validates authoritative `playableStateNamespaceId`, with `playableStateScope` separately exact-validated; an `outboxWorkItemId` alone is not isolation evidence. The displayed `automation:queue:{tenantInstanceTag}:` is the current pointer-key shape, not a target identity contract. **Current implementation:** that queue is only a derived pre-DSL parent-work pointer projection for `PENDING_EVALUATION`/`EVALUATING`, not an evaluated-command descriptor index or proof of namespace isolation. | | 4 | **Tick command** | A concrete command that the Game Session Service executes during game ticks under its normal locking and idempotency rules. | Enqueued into `tick:{tenantRegionTag}:queue:` for consumption by the tick loop. | -Triggers lead to durable parent work items for admitted handlers; their DSL runs execute within those parents and, after `EVALUATED_COMMITTED`, gain immutable descriptor children plus queue-pointer projection entries. Automation's execution loop turns those committed descriptors into tick commands for the Game Session Service. +Triggers lead to durable parent work items for admitted handlers; their DSL runs execute within those parents and, after `EVALUATED_COMMITTED`, gain immutable descriptor children plus queue-pointer projection entries. Target queue staging retains and exact-validates the authoritative `playableStateNamespaceId` and separately validates `playableStateScope`; the current instance-tagged key, work item/pointer, and outbox-ID-only claim do not establish namespace isolation. Automation's execution loop 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. diff --git a/design/architecture/system-architecture-scripting-event-registry.md b/design/architecture/system-architecture-scripting-event-registry.md index 994009dde7..ea1b9918ad 100644 --- a/design/architecture/system-architecture-scripting-event-registry.md +++ b/design/architecture/system-architecture-scripting-event-registry.md @@ -70,7 +70,7 @@ Required semantics for those fields: - Tenant-readiness `onLoad` is the deliberate exception for `scriptId`: its event-scope identity targets one script and includes that `scriptId` so Automation can derive the deterministic `scriptEventId` before handler resolution. This does not authorize fabricated runtime-ingress script IDs; `pluginId`, `pluginVersionId`, and `bindingId` remain post-resolution fields. - Scheduler/timer due candidates are another deliberate pre-handler exception: because Automation already materialized a durable schedule with its owner identity, the scheduler firing identity and deterministic event-scope `scriptEventId` include the schedule-owned `scriptId` and any schedule-owned `pluginId`, `pluginVersionId`, and `bindingId`; plugin-owned candidates also include the captured `pluginActivationEpoch`, and `CATCH_UP` candidates include `resumeWindowId`. The captured `lifecycleRevision` travels alongside as required non-identity fence evidence and is not included in candidate, firing-claim, or `scriptEventId` identity. For gameplay/runtime and scheduler candidates, the paired nonblank `scriptPinControlPlaneRequestId` is retained and exact-compared as owner/fence evidence, but is excluded from candidate, firing-claim, work-item, and derived event identity. The scheduler must not fabricate a field absent from that schedule. This scheduler-owned exception does not authorize ordinary producer ingress to supply handler-only identity. - For every gameplay-originated event, this set must unconditionally include `playableStateNamespaceId` in the applicable gameplay/runtime identity, regardless of whether the realm is shared or isolated. The producer must resolve that namespace authoritatively before admission; a missing, unresolved, stale, or contradictory namespace fails closed. An explicitly declared non-gameplay contract may omit it only when the registry entry is classified outside gameplay/runtime and uses the non-gameplay Trigger Identity branch. `playableStateScope` remains separately persisted, exact-validated policy/routing/authorization/migration-fence evidence; it is excluded from Trigger Identity, event-scope, handoff, schedule, and other uniqueness/deduplication keys. See the [normative identity tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). - - **Target-state exact-fence requirement:** For gameplay/runtime and scheduler events, this set must include the exact Game Session `scriptPatchVersion` plus `scriptPinEpoch` and the paired owner request evidence; a version-only or partial tuple is incomplete and cannot be admitted after a repin. + - **Target-state exact-fence requirement:** For gameplay/runtime and scheduler events, the identity set includes the exact Game Session `scriptPatchVersion` and `scriptPinEpoch`; the paired nonblank `scriptPinControlPlaneRequestId` is separately required owner/fence evidence, exact-compared with Game Session, and excluded from registry idempotency identity and keys. A version-only or partial identity tuple is incomplete and cannot be admitted after a repin. - `snapshotAuthority` - Declares the owner-specific input source used to seed the handler-scoped input manifest. Its values remain: - `PRODUCER_SUPPLIED_TOKEN` diff --git a/design/architecture/system-architecture-scripting-examples-and-patterns.md b/design/architecture/system-architecture-scripting-examples-and-patterns.md index 713f810152..c527a1cc9d 100644 --- a/design/architecture/system-architecture-scripting-examples-and-patterns.md +++ b/design/architecture/system-architecture-scripting-examples-and-patterns.md @@ -71,7 +71,7 @@ This example walks through how a typical `onEnterRegion` script executes end-to- 5. **Automation queue staging** - The committed pre-DSL trigger is projected into `automation:queue:{tenantInstanceTag}:` only as a rebuildable pointer. Actions produced by the handler are evaluated within its one durable parent work item. Target evaluation atomically reaches `EVALUATED_COMMITTED` with one immutable command descriptor/child-dispatch row per emitted command, after which committed descriptor children are indexed into the queue; current implementation persists pre-DSL parent work and indexes only the derived parent pointer. - Firing admission links the durable firing claim, one applicable resolved-handler audit row for every resolved handler, parent work items and queue-pointer projections only for handlers admitted by all handler-scoped gates (including quota), and due-point advancement in one atomic durable transition or a resumable idempotent recovery operation. Zero-handler firings create no handler audit, parent work item, or queue-pointer projection; handlers denied by a handler-scoped gate retain an audit row but create no parent work item or queue-pointer projection. Firing-claim and queue-link recovery completes missing links from the existing claim rather than re-evaluating the handler. - - Each durable parent work item carries the originating `scriptEventId`, `scriptId`, `gameInstanceId`, `playableStateNamespaceId`, exact `scriptPatchVersion`/`scriptPinEpoch`, and region context. It retains `playableStateScope` separately as exact-validated policy/routing/authorization/migration-fence evidence, excluded from Trigger Identity, Command-Handoff Identity, uniqueness, and deduplication keys. In the target handoff contract, each immutable emitted-command child is keyed by the complete source runtime scope plus any distinct target runtime scope, the persisted `automationDispatchId`, and deterministic `commandOrdinal` from canonical output order; both child identities are reused for every handoff, retry, and downstream disposition. The full parent Trigger Identity (including `bindingId` where applicable), `outboxWorkItemId`, and `scriptEventId` remain correlation only, while bounded `workItemIds[]` are parent-row selectors rather than child identities. The target `ListScriptHandoffEvents` child records are keyed by the complete Command-Handoff Identity, with `(automationDispatchId, commandOrdinal)` retained only as its dispatch-group suffix, and retain the full parent Trigger Identity while the handler audit remains one row. See [Implementation Status](#implementation-status) for the current live handoff boundary. + - **Target-state only:** Each durable parent work item carries the originating `scriptEventId`, `scriptId`, `gameInstanceId`, `playableStateNamespaceId`, exact `scriptPatchVersion`/`scriptPinEpoch`, and region context. It retains `playableStateScope` separately as exact-validated policy/routing/authorization/migration-fence evidence, excluded from Trigger Identity, Command-Handoff Identity, uniqueness, and deduplication keys. The current instance-tagged queue pointer and `outboxWorkItemId`-only path do not establish namespace-complete identity or isolation. In the target handoff contract, each immutable emitted-command child is keyed by the complete source runtime scope plus any distinct target runtime scope, the persisted `automationDispatchId`, and deterministic `commandOrdinal` from canonical output order; both child identities are reused for every handoff, retry, and downstream disposition. The full parent Trigger Identity (including `bindingId` where applicable), `outboxWorkItemId`, and `scriptEventId` remain correlation only, while bounded `workItemIds[]` are parent-row selectors rather than child identities. The target `ListScriptHandoffEvents` child records are keyed by the complete Command-Handoff Identity, with `(automationDispatchId, commandOrdinal)` retained only as its dispatch-group suffix, and retain the full parent Trigger Identity while the handler audit remains one row. See [Implementation Status](#implementation-status) for the current live handoff boundary. 6. **Automation ticks and tick command enqueue** - **Current legacy path:** For each emitted command, Automation calls Game Session over internal gRPC. For a same-scope target, Game Session admits the command idempotently and invokes tick enqueue; `ENQUEUED` means local queue admission and `DUPLICATE_NOOP` confirms prior local acceptance. For a distinct target scope, the successful `REMOTE_SCHEDULED` result records only remote follow-up scheduling and does not claim local tick-queue admission. diff --git a/design/architecture/system-architecture-scripting-normative-contract-tables.md b/design/architecture/system-architecture-scripting-normative-contract-tables.md index 6b49fa95b1..ab161e66d6 100644 --- a/design/architecture/system-architecture-scripting-normative-contract-tables.md +++ b/design/architecture/system-architecture-scripting-normative-contract-tables.md @@ -39,7 +39,7 @@ Trigger Identity is the composite idempotency identity for logical handler work For applicable gameplay/runtime identities, `playableStateNamespaceId` is the durable playable-state uniqueness/allocation dimension. The server-derived `playableStateScope` is immutable within one playable-state lifecycle and is policy/routing/authorization/migration-fence evidence that must be persisted and exact-validated; a missing, stale, or mismatched scope fails closed. `playableStateScope` is not a Trigger Identity, event-scope, handoff, schedule, resume-window, or other uniqueness/deduplication dimension. A presented scope mismatch therefore requires authoritative reconciliation before admission: only stale or incorrect evidence with unchanged authoritative scope may reuse the namespace-keyed identity; an authoritative scope-policy transition starts a new playable-state lifecycle and selects or allocates a new `playableStateNamespaceId` before fresh durable identity is admitted. -Downstream gameplay effects emitted by a handler use the ordinary Game Session effect-admission boundary, not Trigger Identity. Full Trigger Identity governs handler and handoff identity only. The complete applicable Command-Handoff Identity governs Automation handoff admission and deduplication; `scriptEventId`, the rest of Trigger Identity, and handler lineage remain separate correlation identities. The accepted effect contract requires downstream mutations to preserve the persisted mutation `EffectId`, typed operation, exact target aggregate, and immutable request digest through retries and participant guards. Deterministic command-plan ordering, `planOrdinal`, and root-allocation behavior remain proposal-only in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +Downstream gameplay effects emitted by a handler use the ordinary Game Session effect-admission boundary, not Trigger Identity. Full Trigger Identity governs resolved handler work, including handler-scoped audit and deduplication, only. The complete applicable Command-Handoff Identity governs emitted-command handoff admission and deduplication; `scriptEventId`, the rest of Trigger Identity, and handler lineage remain separate correlation identities. The accepted effect contract requires downstream mutations to preserve the persisted mutation `EffectId`, typed operation, exact target aggregate, and immutable request digest through retries and participant guards. Deterministic command-plan ordering, `planOrdinal`, and root-allocation behavior remain proposal-only in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Ordinary producer event-ingress RPCs into Automation & Scripting (for example `TriggerScriptEvent`) use two-stage deduplication: @@ -93,6 +93,14 @@ For scheduler/timer identities, the applicable `playableStateNamespaceId` is the | Exactly one of `dueTickId` or `dueAt` | Yes | A tagged due point is required so scheduler `scriptEventId` can be deterministic and catch-up behavior can be audited. The alternate field must be absent/`NULL`; both populated or both absent are invalid for scheduler triggers. | | `triggerMode` | Yes | `NORMAL` vs `CATCH_UP` to make bounded catch-up observable. | +### Scheduler Candidate Identity Preimage (Normative) + +The canonical scheduler preimage fields are serialized in this fixed order: ``. The target implementation in `ScriptScheduleInstanceServiceImpl.TimerFiringCandidate.identity()` must serialize these fields in this order; the current live implementation remains narrower and does not yet implement this target preimage. Fields marked `when ...` are omitted, not replaced by empty or sentinel values, when their branch does not apply; `targetScopeType` makes the target selector explicit and `stableOwnerKind` makes the core/plugin owner branch explicit. The server-derived `playableStateScope` remains immutable policy/routing/authorization/fence evidence and is not a preimage or uniqueness input. `scriptEventId` itself is excluded from the preimage, and `resumeWindowId` is absent for non-catch-up triggers. `duePoint` is exactly one tagged value: `dueTickId:` for tick-aligned schedules or `dueAt:` for wall-clock timers. Any additional scheduler schema version or trigger mode must become an explicit deterministic-ID input before it is admitted. This permits delimiters and arbitrary UTF-8 text without creating tuple collisions. + +Serialize the preimage as fixed-order, length-prefixed UTF-8 fields. Encode each field as its UTF-8 byte length rendered as unsigned base-10 ASCII decimal with no leading zeroes, followed by a colon and its unescaped UTF-8 value; concatenate fields without separators. Numeric identity values use canonical base-10 ASCII spelling (for example, `0`, `7`, and `-1`), and the prefix length counts UTF-8 bytes rather than Unicode code points. Semantic validation controls which numeric values are admissible; deterministic decimal serialization does not make an otherwise invalid value valid. Booleans serialize as lowercase `true` or `false`. Enum values use the contract-declared enum symbol/name, never an ordinal, localized spelling, or implementation-specific representation. Hash the serialized bytes with SHA-256, encode the digest as lowercase hexadecimal, retain the first 60 hexadecimal characters, and prefix the result with `timer-`. + +Before this identity is considered proven, cross-producer golden vectors must cover empty values, non-ASCII values, delimiters, negative and zero numeric values, both boolean values, representative enum branches, and both tagged due-point branches. Proof also covers optional-branch omission and exact retry reuse without collisions or duplicate logical triggers. + Additional required fields and exceptions for tenant-readiness lifecycle triggers: | Field | Required | Notes | diff --git a/design/architecture/system-architecture-spatial-and-ambient-effects-catalog.md b/design/architecture/system-architecture-spatial-and-ambient-effects-catalog.md index eb9e568296..88da55057d 100644 --- a/design/architecture/system-architecture-spatial-and-ambient-effects-catalog.md +++ b/design/architecture/system-architecture-spatial-and-ambient-effects-catalog.md @@ -49,7 +49,7 @@ Required writes: Reconciliation: -- Retry World Management using the same command-root `EffectId` and participant guard until the World location/occupancy mutation converges under the current epoch/fence. +- Retry World Management using the same persisted mutation `EffectId` and participant guard until the World location/occupancy mutation converges under the current epoch/fence. For generated work, this is the recorded child `EffectId`; the enclosing root remains lineage only. - There is no Entity success/failure or retry branch for pure `MOVE`. An Entity leg exists only for a future MOVE variant that explicitly writes containment; that variant must declare Entity as a participant with its own write, guard, and reconciliation contract. `MOVE` commits World location/occupancy before destination presentation. `DROP` and `PICKUP` commit entirely in Entity against the admitted room scope, using the shared actor-lock/executor-fence and durable-barrier contract defined in [Transaction Strategies](./system-architecture-transactions.md#drop-pickup-targeting-and-actor-fence-critical-section). Lock expiry or handoff cannot admit a conflicting `MOVE` while the barrier lacks terminal evidence; Game Session owns retry orchestration and invokes Game Logic to re-resolve stale evidence under the same command-root `EffectId`, preserving the `requestDigest`. This catalog records only the effect-local writes and reconciliation consequences. An item never has two holders and an actor never has two authoritative locations. @@ -68,13 +68,13 @@ Required inputs: Required writes: - **World Management** - - No required write unless the game also models a world-side “sound/door/hazard reaction”; such reactions must be expressed as separate ambient effects with their own `EffectId` (derived deterministically from the parent). + - No required write unless the game also models a world-side “sound/door/hazard reaction”; such reactions must be expressed as separate ambient effects with their own persisted mutation `EffectId`. A generated child's recorded `EffectId` is its mutation identity; the enclosing root remains lineage only. - **Entity Management** - Move `itemInstanceId` into the synthetic room-ground container for `roomInstanceRef`. Reconciliation: -- Retry the Entity mutation using the same participant guard until it converges or is terminalized. Derived ambient reactions use deterministic child effect identities and explicit required/optional classification; do not undo a committed item move to compensate for an optional reaction. +- Retry the Entity mutation using the same persisted mutation `EffectId` and participant guard until it converges or is terminalized. Derived ambient reactions use their recorded child `EffectId` and explicit required/optional classification; do not undo a committed item move to compensate for an optional reaction. ### Pickup (Ground → Inventory) @@ -96,7 +96,7 @@ Required writes: Reconciliation: -- Retry the EMS move using the same command-root `EffectId` until applied. Treat an already-moved item as replay only when the stored [participant guard identity](./system-architecture-identifier-glossary.md#cross-service-effect-identity) matches the `PICKUP` typed operation, the same persisted mutation `EffectId`, the owner-declared runtime-family partition (`(tenantId, playableStateNamespaceId)` for S1/S2 or an explicitly classified `(tenantId, gameInstanceId)` for S3), and the immutable `requestDigest`, with exact target semantics of `{item: itemInstanceId (or the canonical stack/item target), source: the synthetic room-ground container for this RoomInstanceRef, destination: the actor-inventory container for this actorEntityId}`. If the item is held by another actor/container or the destination differs, return a conflict/stale/reconciliation outcome rather than replay/no-op. +- Retry the EMS move using the same persisted mutation `EffectId` until applied; for generated work, use its recorded child `EffectId` and retain the enclosing root only as lineage. Treat an already-moved item as replay only when the stored [participant guard identity](./system-architecture-identifier-glossary.md#cross-service-effect-identity) matches the `PICKUP` typed operation, the same persisted mutation `EffectId`, the owner-declared runtime-family partition (`(tenantId, playableStateNamespaceId)` for S1/S2 or an explicitly classified `(tenantId, gameInstanceId)` for S3), and the immutable `requestDigest`, with exact target semantics of `{item: itemInstanceId (or the canonical stack/item target), source: the synthetic room-ground container for this RoomInstanceRef, destination: the actor-inventory container for this actorEntityId}`. If the item is held by another actor/container or the destination differs, return a conflict/stale/reconciliation outcome rather than replay/no-op. The World targeting attestation remains bound to the root `EffectId`, actor, exact room, epoch, fence, and request digest as specified above. ## Ambient Effects (World Management Authoritative) diff --git a/design/architecture/system-architecture-tick-concepts-and-invariants.md b/design/architecture/system-architecture-tick-concepts-and-invariants.md index 3e5f8a3454..92c423fc8d 100644 --- a/design/architecture/system-architecture-tick-concepts-and-invariants.md +++ b/design/architecture/system-architecture-tick-concepts-and-invariants.md @@ -146,7 +146,7 @@ Durations may be scaled dynamically: ## Bounded Effect Chaining -Generated effects are bounded by a shared bootstrap depth ceiling (`8`), deterministic root-chain count and cost budgets, and a deterministic per-target cap. Platform hard ceilings bound every setting; operators and authored features may lower them but may not raise them. Each child records immutable parent/root identity, `depth = parent.depth + 1`, and a digest-covered deterministic child ordinal. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not current target state. +Generated effects are bounded by a shared bootstrap depth ceiling (`8`), deterministic root-chain count and cost budgets, and a deterministic per-target cap. Platform hard ceilings bound every setting; operators and authored features may lower them but may not raise them. Each child records immutable parent/root identity, `depth = parent.depth + 1`, and an owner-defined child ordinal that is deterministically allocated, durably persisted, and reused on replay. The ordinal is ordering and audit metadata, not part of an effect digest. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative for the allocation mechanism. Admission evaluates all limits deterministically. Only the child that would exceed a limit is suppressed; committed parents and earlier children are not rolled back. Every authored child is classified as required or optional so suppression derives truthful `SUCCESS`, `PARTIAL`, or `FAILED` outcomes. Durable suppression evidence records root/parent identity, feature/script/version, child ordinal, limit reason and actual/configured values, classification, and resulting player outcome. Metrics use bounded reason/depth/cost/classification dimensions; raw identities remain audit data. See [ADR 0075](./decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). diff --git a/design/architecture/system-architecture-tick-execution-flows.md b/design/architecture/system-architecture-tick-execution-flows.md index 0dd1783e80..c2db0e6b27 100644 --- a/design/architecture/system-architecture-tick-execution-flows.md +++ b/design/architecture/system-architecture-tick-execution-flows.md @@ -522,9 +522,9 @@ To illustrate how cross-region flows compose from the phases above, consider a * - In the next tick for ``, the target region’s executor: - Computes the damage amount as a percentage of the target’s authoritative current HP. - Acquires the target’s lock (`tick:{tenantRegionTag}:lock:`) and applies damage via Entity Management under the target leg’s persisted mutation `EffectId` and its operation/target guard; any enclosing root remains lineage and reconciliation context. - - Writes a durable origin-addressed result row for region A containing `coordinatorId`, `originGameInstanceId`, `originRegionId`, `originRegionEpoch`, the target leg identity, `casterEntityId`, the actual `damageApplied`, the exact accepted-result digest, and the target terminal outcome. Origin reconciliation verifies those fields against its durable coordinator row before accepting the result. Acceptance cannot become durable without the deterministic child-heal intent: the accepted result and child intent commit together when co-located, or a resumable durable acceptance intent records both before acceptance is acknowledged. + - Writes a durable origin-addressed result row for region A containing `coordinatorId`, `originGameInstanceId`, `originRegionId`, `originRegionEpoch`, the target leg identity, `casterEntityId`, the actual `damageApplied`, the exact accepted-result digest, and the target terminal outcome. Origin reconciliation verifies those fields against its durable coordinator row before accepting the result. Acceptance cannot become durable without a persisted child-heal intent: the accepted result and child intent commit together when co-located, or a resumable durable acceptance intent records both before acceptance is acknowledged. 4. **Heal Leg (origin region)** - - Only after existing coordinator reconciliation accepts the target result does region A record the actor-generated “apply lifesteal heal” effect for the caster. A rejected or abandoned result creates no heal effect; an accepted heal has a deterministic, stable idempotent child `EffectId` derived from the accepted result and is not a new root actor command. Acceptance replay reuses that child identity and the exact accepted-result digest; it cannot create a second heal intent or silently accept a conflicting result. The pending [ADR 0183 proposal](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative. + - Only after existing coordinator reconciliation accepts the target result does region A record the actor-generated “apply lifesteal heal” effect for the caster. A rejected or abandoned result creates no heal effect; an accepted heal uses its persisted child `EffectId` under the applicable accepted effect-identity contract and is not a new root actor command. This example does not require deriving child identity from the accepted result. Acceptance replay reuses that persisted child identity and the exact accepted-result digest; it cannot create a second heal intent or silently accept a conflicting result. The allocation proposal in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) remains pending and non-authoritative. - In a subsequent tick for ``, the executor: - Acquires the caster’s lock. - Applies a heal up to `damageApplied` (subject to HP rules) using Entity Management and tick idempotency. diff --git a/design/architecture/system-architecture-ticks.md b/design/architecture/system-architecture-ticks.md index 7736de2334..d0661a9faa 100644 --- a/design/architecture/system-architecture-ticks.md +++ b/design/architecture/system-architecture-ticks.md @@ -466,7 +466,7 @@ See `system-architecture-tick-failures-and-operations.md` for the full crash-rec Domain services use the region-scoped tick timeline `(regionEpoch, tickId)` for ordering and fencing, not as the canonical idempotency token for a logical effect. The default mutation boundary is the mutation's stable persisted `EffectId` plus a participant guard containing the typed operation, exact target aggregate, and immutable request digest. A child mutation retains its persisted child `EffectId` and enclosing-root lineage. A narrow last-tick watermark is permitted only for an explicitly documented aggregate proven to receive at most one logical mutation per tick timeline; it must not replace the effect/participant guard for general command effects. Command-plan ordering and root-allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). -- Single-aggregate updates may use an epoch-aware “last applied tick” pattern (for example storing and comparing `(last_region_epoch, last_tick_id)` for the aggregate) only when the owning contract proves that at most one logical update for that aggregate can occur in each tick. Without that one-update-per-aggregate-per-tick invariant, each logical effect requires a participant guard derived from the stable root `EffectId`, typed operation, and target aggregate; a root-only ledger or guard is insufficient. The timeline tuple is ordering/fence context and is not sufficient idempotency identity. +- Single-aggregate updates may use an epoch-aware “last applied tick” pattern (for example storing and comparing `(last_region_epoch, last_tick_id)` for the aggregate) only when the owning contract proves that at most one logical update for that aggregate can occur in each tick. Without that one-update-per-aggregate-per-tick invariant, each logical effect requires a participant guard derived from its persisted mutation `EffectId` (the root for a root mutation or the recorded child `EffectId` for a generated mutation), typed operation, and target aggregate; an enclosing root is lineage for a child mutation, and a root-only ledger or guard is insufficient. The timeline tuple is ordering/fence context and is not sufficient idempotency identity. - Multi-aggregate operations use explicit `tick_effect_guard` storage projections that retain the namespace-complete fields (for example `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, effectKey, targetAggregateType, targetAggregateId)`) and link each row to the enclosing root lineage plus the mutation's persisted root-or-child `EffectId` and derived typed operation/target guard identity. The guard uniqueness identity follows the owner-declared runtime family: S1/S2 uses the `(tenantId, playableStateNamespaceId)` partition plus `EffectId`, typed operation, and exact target aggregate, while only an explicit S3 family uses `(tenantId, gameInstanceId)` plus those identity fields. For S1/S2, `gameInstanceId` is separately exact-validated active-runtime authorization/fence evidence; `playableStateScope`, timeline, digest, and lineage remain immutable evidence, not uniqueness dimensions. Unknown or unclassified families fail closed and are never inferred to be S3. ### Tick Effect Identity and Idempotency Contract diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 831d87280a..ef6da384b7 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -110,7 +110,7 @@ This table describes the repository target state, not merely completed human rev ## Contract Authority Consolidation Scope -Contract-authority consolidation applies to repeated normative product and architecture contracts whether or not an ADR records their rationale. ADRs organize the selective application process, but they are not the boundary of the deduplication work. PRs #2593 and #2594 complete the baseline pass for ADRs 0001-0050 and the major adjacent non-ADR contract families encountered across those design areas. Packets 3-7 (ADRs 0051-0178 plus TICK-05) and the direct decisions in ADRs 0179-0182 are now integrated with family-local consolidation without redefining that baseline. +Contract-authority consolidation applies to repeated normative product and architecture contracts whether or not an ADR records their rationale. ADRs organize the selective application process, but they are not the boundary of the deduplication work. PRs #2593 and #2594 complete the baseline pass for ADRs 0001-0050 and the major adjacent non-ADR contract families encountered across those design areas. Packets 3-7 (ADRs 0051-0178 plus TICK-05) and the direct decisions in ADRs 0179-0182 and 0184 are now integrated with family-local consolidation without redefining that baseline. Consolidation names one canonical owner for a target contract and reduces competing secondary definitions to owner links plus local API, persistence, transport, operational, user-visible, implementation-drift, or proof consequences. It is not editorial deduplication: useful examples, runbooks, evidence schemas, local constraints, and explanatory context remain where they serve their owning document. 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 3b8f94ca9d..58fdedd748 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -20,6 +20,8 @@ Current residual: the legacy NPC formation REST controllers are removed and `/fo The current Automation queue reset/rebuild/resume path is unavailable and must fail closed regardless of the observed status mix; a non-atomic status preflight cannot authorize the target PENDING-only workflow. The owner-reconciled target recovery and its proof remain outstanding. +Routed, unassigned runtime obligation for Automation `AS-1.1`/`AS-1.2`: the current instance-tagged queue key, `ScriptWorkItem` row/identity lookup, queue pointer, and `outboxWorkItemId`-only claim do not establish namespace isolation. Target work, pointers, queue-index projections, rebuild eligibility, and consumers must retain and exact-validate authoritative `playableStateNamespaceId`, with `playableStateScope` separately exact-validated as evidence. The future Automation owner selects the implementation; this routing records no accepted key topology, available queue reset/rebuild path, or implementation status promotion. + After DSL evaluation, a retryable fanout fence, handoff preflight failure, or uncertain child result cannot automatically return the parent to `PENDING_EVALUATION`: the current schema has no frozen evaluated descriptor or complete child-recovery ledger. The executor retains its durable `EVALUATING` or `HANDOFF_IN_FLIGHT` evidence for explicit reconciliation. This fail-closed boundary does not implement the stage-aware recovery aggregate required by [ADR 0107](../../architecture/decisions/adr-0107-stage-aware-script-dead-letter-recovery.md). The production executor selects pending candidates without claiming them, then commits each `PENDING_EVALUATION -> EVALUATING` claim in its own transaction before processing that item in a separate transaction. A worker stop between those commits can still leave an unprocessed `EVALUATING` row; this crash window remains a target recovery gap. The Game Session client maps ordinary runtime transport failures to an unavailable response and bounded backoff. If processing fails or an inner participating transaction marks the processing transaction rollback-only, the processing transaction rolls back while the previously committed claim remains unresolved `EVALUATING`; the bounded batch continues with eligible siblings and does not requeue or retry that item in the same invocation. Focused unit proof covers separate transaction boundaries and a simulated processing-commit rollback after a remote effect, but does not exercise real Spring proxy rollback-only propagation or PostgreSQL crash/concurrency behavior. There is still no durable evaluation-owner lease, stage/descriptor marker, or complete child ledger to distinguish an uncertain handoff. Stale evaluation-owner reconciliation, fencing, and database-backed crash/concurrency proof remain recovery gaps; age alone cannot authorize retry or cleanup. diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index d970c6c780..ace2c7c0ce 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -1992,24 +1992,30 @@ canonical_resume_identity_fixture = ( if obsolete_scope_resume_window_identity.fullmatch(canonical_resume_identity_fixture): raise SystemExit("canonical namespace-owned resume-window identity was rejected") require_contains( - "design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md", + "design/architecture/system-architecture-scripting-normative-contract-tables.md", [ "The canonical scheduler preimage fields are serialized in this fixed order:", "`resumeWindowId` is absent for non-catch-up triggers", "Fields marked `when ...` are omitted, not replaced by empty or sentinel values", ], ) -adr0001 = ( +require_contains( + "design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md", + [ + "[Table 1's Scheduler Candidate Identity Preimage](../system-architecture-scripting-normative-contract-tables.md#scheduler-candidate-identity-preimage-normative)" + ], +) +normative_contract_tables = ( root - / "design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md" + / "design/architecture/system-architecture-scripting-normative-contract-tables.md" ).read_text(encoding="utf-8") preimage_matches = re.findall( r"The canonical scheduler preimage fields are serialized in this fixed order: `([^`]+)`", - adr0001, + normative_contract_tables, ) if len(preimage_matches) != 1: raise SystemExit( - "adr-0001-scripting-event-ingress-idempotency-identity.md: expected exactly one canonical scheduler preimage" + "system-architecture-scripting-normative-contract-tables.md: expected exactly one canonical scheduler preimage" ) expected_scheduler_preimage = [ "tenantId", @@ -2043,7 +2049,7 @@ actual_scheduler_preimage = [ ] if actual_scheduler_preimage != expected_scheduler_preimage: raise SystemExit( - "adr-0001-scripting-event-ingress-idempotency-identity.md: canonical scheduler preimage fields/order drifted" + "system-architecture-scripting-normative-contract-tables.md: canonical scheduler preimage fields/order drifted" ) specialized_inventory = ( root / "design/project-management/design-alignment/decision-inventory-specialized-runtime.md" From 1ec7842e75a0256970939ea8bbd3d99f04ef1feb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 11:41:51 +1300 Subject: [PATCH 41/68] Clarify recovery, watermark and inspection contract boundaries --- .../system-architecture-redis-cache-reference.md | 4 ++-- .../system-architecture-redis-reset-and-recovery.md | 2 +- .../system-architecture-scripting-operations-cookbook.md | 2 +- .../system-architecture-tick-failures-and-operations.md | 8 ++++---- design/architecture/system-architecture-ticks.md | 2 +- .../game-session-runtime-and-tick-coordination.md | 6 +++--- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/design/architecture/system-architecture-redis-cache-reference.md b/design/architecture/system-architecture-redis-cache-reference.md index 93966cc6f1..2033eb7243 100644 --- a/design/architecture/system-architecture-redis-cache-reference.md +++ b/design/architecture/system-architecture-redis-cache-reference.md @@ -6,7 +6,7 @@ This companion document holds the reference-heavy material for Redis cache and r The `room:*` Class A cache contract below is target-state only. It is not a current correctness path until World Management has an opaque room component version and a proven invalidation path. Namespace-backed `inventory:*` and explicitly instance-scoped `inventory:room-ground:*` cache adoption is likewise target-state; current readers remain authoritative until Entity Management's owner-version/event validation is proven. Current readers must not substitute `worldSnapshotId` or `roomDynamicVersion` for that component version; they must use authoritative reads when the target validation contract is unavailable. A cache-embedded version, TTL, or invalidation event alone is not currentness proof. The current Game Session `ratelimit:` key is likewise a legacy implementation: `SessionRateLimiterImpl` writes it through the generic Game Session Redis client with a one-second window/TTL, while its Cache/Rate-Limit endpoint and ACL binding remain unproved. It must be registered as current legacy state, its writer stopped, and its maximum one-second TTL allowed to elapse with an empty-key readback before unversioned target rate-limit helpers consume the shared family; an adopter that cannot prove that drain must use a distinct versioned prefix. The current Game Session `lookcache::` writer is also legacy implementation drift: it is disposable and non-authoritative, but its incomplete scope and ten-minute TTL cannot satisfy target causal room-read semantics. Current composition remains authoritative/uncached until the target `view:room-look:*` contract is proven. The future reader, invalidation, and version-advance rules below remain normative. -The current Automation implementation also emits `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` families. They are named in the catalog below as Cache/Rate-Limit, Class B, reset-tolerant projections. Current readiness and dry-run capacity counter/lease reservations pass two keys with one shared tenant or fixed-family hash tag to each Lua invocation, so each pair occupies one Redis Cluster slot and is not inherently `CROSSSLOT`. Central ownership registration, canonical key encoding, durable charge/admission, reset, retention, and idempotent lease-accounting proof remain incomplete; the same-slot shape alone does not establish a supported clustered workload. The current Game Session `IpConnectionLimiter` has a distinct live limitation: registration passes `ipconn:
` and `sessionip:` to one Lua invocation without a shared hash slot, so Redis Cluster returns `CROSSSLOT`; this is in addition to the raw-address/privacy drift. The target must follow ADR 0087's one-mutation/one-opaque-subject-bucket boundary, with session lifecycle correlation kept outside any exact cross-key atomicity requirement; no final reverse-index shape is assumed here. Destructive resets additionally require the external, generation-bound [Cache deployment maintenance gate](./system-architecture-redis-operations.md#external-cache-deployment-maintenance-gate), not a fence key stored in the cache being reset. +The current Automation implementation also emits `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` families. They are named in the catalog below as Cache/Rate-Limit, Class B, reset-tolerant projections. Current readiness and dry-run capacity counter/lease reservations pass two keys with one shared tenant or fixed-family hash tag to each Lua invocation, so each pair occupies one Redis Cluster slot and is not inherently `CROSSSLOT`. Central ownership registration, canonical key encoding, durable charge/admission, reset, retention, and idempotent lease-accounting proof remain incomplete; the same-slot shape alone does not establish a supported clustered workload. The current Game Session `IpConnectionLimiter` has a distinct live limitation: registration passes the untagged `ipconn:
` and `sessionip:` keys to one Lua invocation, which can return `CROSSSLOT` when those keys hash to different Redis Cluster slots; this is in addition to the raw-address/privacy drift. The target must follow ADR 0087's one-mutation/one-opaque-subject-bucket boundary, with session lifecycle correlation kept outside any exact cross-key atomicity requirement; no final reverse-index shape is assumed here. Destructive resets additionally require the external, generation-bound [Cache deployment maintenance gate](./system-architecture-redis-operations.md#external-cache-deployment-maintenance-gate), not a fence key stored in the cache being reset. ## Cache Adoption Checklist @@ -76,7 +76,7 @@ Cache/Rate-Limit Redis hosts prefixes that are not part of the coordination log | `room:::` | Cache | Versioned (Class A) | Reset-tolerant | World Management correctness-critical room snapshot cache; payload stores and validates owner `regionId`/`regionEpoch` with the opaque component version, atomically with refresh/TTL, and invalidates on epoch change. | | `view:room-look:::::::` | Cache | TTL-only (Class B) | Reset-tolerant | Target-only Game Session-owned disposable presentation/redraw helper; see the [canonical Class-B contract](./system-architecture-redis-cache.md#canonical-viewroom-look-class-b-contract). Current `ResolveLook` behavior is uncached and no focused proof establishes this prefix. The cache remains non-authoritative and disposable: unavailable or untrusted cache/fence evidence falls back to authoritative uncached `ResolveLook`, and it is never semantic reconnect context, frame/output replay, a transcript archive, or a delivery ledger. | | `lookcache::` | Cache (current legacy only; target role unapproved) | Legacy disposable projection (not target Class B) | Reset-tolerant for disposable loss | Current Game Session writer only. The ten-minute payload is non-authoritative, but the legacy session/game-instance scope lacks viewer, policy, and causal read-fence identity; a clustered cache reset may delete and verify this family only while the external, generation-bound Cache deployment maintenance gate is held through deletion and verification. Remove/drain this writer or migrate to the exact `view:room-look:*` contract before target helpers consume it; otherwise continue authoritative uncached composition. This prefix is not target Class B authority. | -| `ipconn:
` and `sessionip:` | Cache / Rate-Limit (current legacy implementation drift) | Legacy heuristic (not target Class B authority) | Reset-tolerant heuristic loss | Game Session owns the current paired raw-address counter and session reverse-map. Entries use the current connection TTL (`GAME_SESSION_CONN_TTL_SEC`, default 3600 seconds); a reset may temporarily relax or tighten abuse limits and can leave the pair incomplete, but must not be treated as durable authority. Current registration passes both untagged keys to one Lua invocation, so it fails with `CROSSSLOT` on Redis Cluster; this is in addition to the raw-address/privacy defect covered by ADR 0087. The target must use one mutation on one opaque subject bucket and keep session lifecycle correlation outside exact cross-key atomicity; no final reverse-index shape is assumed here. | +| `ipconn:
` and `sessionip:` | Cache / Rate-Limit (current legacy implementation drift) | Legacy heuristic (not target Class B authority) | Reset-tolerant heuristic loss | Game Session owns the current paired raw-address counter and session reverse-map. Entries use the current connection TTL (`GAME_SESSION_CONN_TTL_SEC`, default 3600 seconds); a reset may temporarily relax or tighten abuse limits and can leave the pair incomplete, but must not be treated as durable authority. Current registration passes both untagged keys to one Lua invocation, which can return `CROSSSLOT` on Redis Cluster when the keys hash to different slots; this is in addition to the raw-address/privacy defect covered by ADR 0087. The target must use one mutation on one opaque subject bucket and keep session lifecycle correlation outside exact cross-key atomicity; no final reverse-index shape is assumed here. | | `screenbuffer:::` | Cache | TTL-only (Class B) | Reset-tolerant | Current Game Session disposable hot-cache prefix for durable semantic reconnect context; PostgreSQL `resume_transcript_entry` rows remain authoritative. This prefix is distinct from `view:room-look:*` and never serves as semantic authority. Current keying is `gameInstanceId`-based; target reconnect scope is `{tenantId, playableStateNamespaceId, characterId}` under ADR 0134, so namespace-key migration and complete reconnect-envelope/generation proof remain implementation gaps. The row records prefix semantics, not current endpoint/role wiring. | | `chat:say::`, `chat:whisper:::`, `chat:tell::`, `chat:guild::`, `chat:city::`, `chat:account::` | Cache | TTL-only (Class B) | Reset-tolerant | Social & Groups short-lived chat projections; current `SAY` is sender-account scoped. Any future gameplay-SAY projection must publish its exact recipient/view scope and original-view contract rather than infer it from a bare character ID. See the [canonical `chat:whisper` Class-B contract](#canonical-social--groups-chatwhisper-class-b-contract). | | `chat:whisper::` | Cache | TTL-only (Class B) | Reset-tolerant | Legacy `ChatService` account-keyed whisper implementation-drift prefix (`chat:whisper:%d:%d`); it does not provide the target playable-state/character scope and remains a reset-tolerant disposable projection during migration. | diff --git a/design/architecture/system-architecture-redis-reset-and-recovery.md b/design/architecture/system-architecture-redis-reset-and-recovery.md index d6f50986e5..5796f37a7a 100644 --- a/design/architecture/system-architecture-redis-reset-and-recovery.md +++ b/design/architecture/system-architecture-redis-reset-and-recovery.md @@ -399,7 +399,7 @@ For a current Coordination Redis cold start, incomplete recovery, or reset incid - Preserve the AOF, operation records, and incident evidence. Keep Gateway protected admission, gameplay mutation, command intake, and affected coordination writers fenced or stopped; an empty keyspace is not safe-resume evidence. - No current scoped reset is supported. The target-state scope grammar and `coordination-maintenance` CLI are unavailable today, and raw coordination-prefix mutations are not a reset path. - Use only the shipped `PauseTicksForScope` pause and `GetRuntimeOwnershipStatus` status surface for the supported `{tenantId, gameInstanceId}` boundary. Read-only Redis inspection is permitted only through an independently provisioned credential bound to the exact Coordination Redis endpoint and deployment generation, with attested `coord_ops_ro/v2` ACL/key-pattern and `coord_redis_config/v1` evidence, the applicable authenticated-TLS peer/hostname transport attestation for remote/shared/hosted/staging/production targets, and successful canonical positive/negative readback probes. A same-host loopback `dev_local` inspection may use its explicitly authorized local transport profile and is not hosted evidence. `coord_ops_ro` is a target logical profile, not a repository-shipped credential; if any applicable endpoint, transport, ACL, credential, attestation, or readback evidence is unavailable or ambiguous, do not connect with a generic, default, application, or admin credential—leave the fence in place and escalate. Follow the current failover/AOF procedures and escalation path in the [Redis incident runbook](./system-architecture-redis-incident-runbook.md) and [Redis Operations](./system-architecture-redis-operations.md); do not invoke the target-state CLI or use raw coordination-prefix mutations. -- Use only the shipped `PauseTicksForScope` pause and `GetRuntimeOwnershipStatus` status surface for the supported `{tenantId, gameInstanceId}` boundary, plus read-only `coord_ops_ro` inspection. Preserve the original AOF without editing or rewriting it, and keep it only in the approved restricted custody path for raw storage evidence. If incident evidence must include command data, never copy raw AOF contents to a workstation, ticket, log, terminal, shared artifact, or ordinary disk. A working copy may be produced only by approved tooling that proves complete field-level redaction or irreversible tokenization of every credential- or identity-bearing value (including bearer/access tokens, token or session credential material, account/tenant/issuer/session/character identifiers, and operator/workload identity or secret material), followed by encryption in the approved evidence store, access logging, and an explicit owner/expiry. If complete redaction, custody, encryption, or access-control proof is unavailable, retain only the original under restricted custody and escalate; do not produce a working copy. At retention expiry, request disposal through the approved evidence-custody process and record the result; if disposal cannot be verified, keep the copy inaccessible in the approved restricted store and escalate rather than claim destruction. Never expose raw AOF contents in tickets, logs, terminals, or shared artifacts. Then follow only the current failover/incident-evidence procedures and escalation path in the [Redis incident runbook](./system-architecture-redis-incident-runbook.md) and [Redis Operations](./system-architecture-redis-operations.md); there is no supported current AOF rewrite or other destructive AOF mutation, and operators must not invoke the target-state CLI or use raw coordination-prefix mutations. +- After every applicable endpoint, transport, credential, ACL, attestation, and canonical readback gate in the preceding bullet succeeds, use only the shipped `PauseTicksForScope` pause and `GetRuntimeOwnershipStatus` status surface for the supported `{tenantId, gameInstanceId}` boundary, plus read-only `coord_ops_ro` inspection. Preserve the original AOF without editing or rewriting it, and keep it only in the approved restricted custody path for raw storage evidence. If incident evidence must include command data, never copy raw AOF contents to a workstation, ticket, log, terminal, shared artifact, or ordinary disk. A working copy may be produced only by approved tooling that proves complete field-level redaction or irreversible tokenization of every credential- or identity-bearing value (including bearer/access tokens, token or session credential material, account/tenant/issuer/session/character identifiers, and operator/workload identity or secret material), followed by encryption in the approved evidence store, access logging, and an explicit owner/expiry. If complete redaction, custody, encryption, or access-control proof is unavailable, retain only the original under restricted custody and escalate; do not produce a working copy. At retention expiry, request disposal through the approved evidence-custody process and record the result; if disposal cannot be verified, keep the copy inaccessible in the approved restricted store and escalate rather than claim destruction. Never expose raw AOF contents in tickets, logs, terminals, or shared artifacts. Then follow only the current failover/incident-evidence procedures and escalation path in the [Redis incident runbook](./system-architecture-redis-incident-runbook.md) and [Redis Operations](./system-architecture-redis-operations.md); there is no supported current AOF rewrite or other destructive AOF mutation, and operators must not invoke the target-state CLI or use raw coordination-prefix mutations. - No fallback or future recovery release may rely on an empty keyspace, script loading, sample ticks, or local operator observations. The complete [canonical post-reset verification checklist](./system-architecture-redis-ops-access.md#canonical-post-reset-verification-checklist) and applicable recovery release gates are required; script-load and sample-tick checks are supplemental only. - If the durable recovery controller, Account projection repair/replacement, replay quarantine/fence, or immutable evidence path is unavailable, stale, or ambiguous, abort any destructive wipe, recovery continuation, `resume`, `release-lock`, or reopen attempt. Leave the fence in place and escalate; there is no supported current full-wipe or unlock substitute. diff --git a/design/architecture/system-architecture-scripting-operations-cookbook.md b/design/architecture/system-architecture-scripting-operations-cookbook.md index d1ca3dc930..6e1d676056 100644 --- a/design/architecture/system-architecture-scripting-operations-cookbook.md +++ b/design/architecture/system-architecture-scripting-operations-cookbook.md @@ -167,7 +167,7 @@ For pending and dead-lettered work, use control-plane APIs rather than direct da - Replay phase semantics are stage-aware. A pre-claim authority or policy-unavailability result is `outcome=rejected`, records the bounded `rejectionReason`, creates no recovery claim or attempt, and leaves the row `DEAD_LETTERED`. Once a recovery claim/attempt is durably created, any failed evaluation or dispatch attempt must terminalize that attempt as `FAILED` and return `outcome=recovery_failed` with its persisted bounded `failureReason`; it must not be relabeled as a pre-claim rejection. A new request may create another attempt only after the prior attempt is terminal `FAILED` and fresh eligibility/fence checks pass; an `IN_PROGRESS` or unreconciled claim remains ineligible. Each requested ID returns exactly one bounded result (`retried_evaluation`, `resumed_dispatch`, `already_recovered`, `recovery_failed`, or `rejected`) with the canonical `failureGeneration` when a generation is resolved, bound to `(tenantId, outboxWorkItemId, failureGeneration)`, plus its applicable reason. The recovery claim/attempt has its own persisted attempt identity; this API does not expose a separate recovery-attempt generation, so no second generation field should be inferred. One row's result never changes another row's outcome or aggregate count. - **Target-state only and capability-gated:** `PurgeOutboxWorkItems(tenantId=11111111-1111-4111-8111-111111111111, scriptPatchVersion=P22, scriptPinEpoch=41, workItemIds=[work-9], controlPlaneRequestId=PURGE-42, actor=operator:alice, reason="rollback RB-42")` is auditable cleanup only when each selected work item matches the displaced exact tuple, is terminal (`HANDED_OFF`, `CANCELED`, or `DEAD_LETTERED`), and its configured retention horizon has elapsed. For evaluated descriptor/output evidence, the parent must be `EVALUATED_COMMITTED`, the parent and every child/evidence record must be retention-eligible, and every child must be terminal before that evidence is purged; a same-version repin with a newer epoch does not by itself make terminal rows from the displaced tuple ineligible, but the selector must remain the displaced exact tuple so current-epoch rows cannot be selected. For a pre-DSL `DEAD_LETTERED` row with no committed descriptor, purge may remove only terminal, retention-eligible trigger/failure payloads after the recovery eligibility window has expired, after resolving the current `failureGeneration` and atomically CASing recovery claim/attempt state. Any current-generation `IN_PROGRESS` claim, including an expired claim not yet canonically reclaimed, rejects with `recovery_in_progress` and deletes no evidence; only when no current-generation claim exists or its claim/attempt is terminal may purge proceed. For that pre-DSL path, no new schema marker is introduced: the retained purge audit/idempotency outcome is the durable evidence and makes the row permanently non-recoverable, so later replay rejects deterministically with `rejectionReason=stage_evidence_unavailable`; its immutable identity/digest, failure-stage, corresponding `script_event_audit`, and recovery-causation evidence remain retained under their owning retention contracts. When terminal descriptor/evaluated-output evidence is purged under the retained parent, the same transaction persists durable `descriptorEvidencePurgedAt`; that marked parent is non-recoverable and non-replayable, and consumers reject it deterministically rather than treating missing children as recoverable. The purge does not mutate active or nonterminal work. -For command-level diagnosis, use the [Scripting & Automation Observability Contract](./system-architecture-scripting-observability-contract.md) and [Command Identity and Live Handoff Boundary](./system-architecture-scripting-rollout-and-rollback.md#command-identity-and-live-handoff-boundary). The target query is `ListScriptHandoffEvents`; child replay and deduplication use the [canonical Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state): ``. When a distinct target runtime scope applies, `targetGameInstanceId`, `targetRegionId`, and `targetRegionEpoch` are required; include `targetPlayableStateNamespaceId` only when the target owns a playable-state namespace. Source and target `playableStateScope` values remain separately validated evidence, not identity fields. The full parent Trigger Identity (including `bindingId` where applicable), `outboxWorkItemId`, and `scriptEventId` are correlation only; bounded `workItemIds[]` are parent-row selectors only and cannot replace the child identity. The current live fallback is the correlation of `script_event_audit`, narrower Automation handoff/work-item rows, `outboxWorkItemId`, `automationDispatchId`, `gameSessionCommandId`, and the Game Session command/result/fence fields currently exposed. Do not infer complete Trigger Identity or downstream per-command disposition from that fallback. +For command-level diagnosis, use the [Scripting & Automation Observability Contract](./system-architecture-scripting-observability-contract.md) and [Command Identity and Live Handoff Boundary](./system-architecture-scripting-rollout-and-rollback.md#command-identity-and-live-handoff-boundary). The target query is `ListScriptHandoffEvents`; child/descriptor replay and deduplication remain deferred target behavior and, when implemented, follow the [canonical Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state). The current `workItemIds[]` input remains an executable parent-row selector only; it does not select independent command descriptors or provide command-level replay. The full parent Trigger Identity (including `bindingId` where applicable), `outboxWorkItemId`, and `scriptEventId` are correlation only; bounded `workItemIds[]` cannot replace the child identity. The current live fallback is the correlation of `script_event_audit`, narrower Automation handoff/work-item rows, `outboxWorkItemId`, `automationDispatchId`, `gameSessionCommandId`, and the Game Session command/result/fence fields currently exposed. Do not infer complete Trigger Identity or downstream per-command disposition from that fallback. For the canonical rollback and version-fence requirements, follow [Scripting & Automation: Rollout and Rollback](./system-architecture-scripting-rollout-and-rollback.md#patch-rollback-operator-driven-required) and [Scripting & Automation: Cross-Service Contracts](./system-architecture-scripting-contracts.md#3-version-fencing-rollback-safety). diff --git a/design/architecture/system-architecture-tick-failures-and-operations.md b/design/architecture/system-architecture-tick-failures-and-operations.md index 45b3490aa1..9fa6807910 100644 --- a/design/architecture/system-architecture-tick-failures-and-operations.md +++ b/design/architecture/system-architecture-tick-failures-and-operations.md @@ -467,13 +467,13 @@ Two patterns are used: - It is a narrow exception, not the default for gameplay-visible mutations. - Typical safe uses are once-per-tick watermark-style updates or aggregates whose design guarantees a single logical writer/effect per tick. - Aggregates that may receive multiple legitimate effects in one tick must not use this pattern. - - A shadow tick-state record such as `entity_tick_state` is keyed by `(tenant_id, game_instance_id, playable_state_namespace_id, region_id, target_aggregate_type, aggregate_id)`, not by the aggregate identifier alone; `playable_state_scope` is separately persisted and exact-validated evidence, not a key dimension. + - A shadow tick-state record such as `entity_tick_state` follows its owner-declared runtime-family partition: S1/S2 uses `(tenant_id, playable_state_namespace_id)`; only explicit S3 uses the complete `(tenant_id, game_instance_id, playable_state_namespace_id, region_id, target_aggregate_type, aggregate_id)` watermark identity. For S1/S2, `game_instance_id` is separately exact-validated active-runtime authorization/fence evidence, not part of the namespace partition. `playable_state_scope` is separately persisted and exact-validated evidence, not a key dimension. - The shadow state stores at minimum: - `last_region_epoch` - `last_tick_id` - - (plus tenant/game-instance/region identifiers or a foreign key implying them) + - (plus the owner-declared partition and region/target-aggregate identifiers or a foreign key implying them; S1/S2 retains active `game_instance_id` separately as authorization/fence evidence) - When applying a tick effect: - - The handler resolves and reads the shadow tick-state row using `(tenant_id, game_instance_id, playable_state_namespace_id, region_id, target_aggregate_type, aggregate_id)`, exact-validating separately persisted `playable_state_scope` evidence; an aggregate-only, aggregate-type-free, or namespace-free lookup is invalid. + - The handler resolves the shadow tick-state row using `(tenant_id, playable_state_namespace_id, region_id, target_aggregate_type, aggregate_id)` for S1/S2, or the complete `(tenant_id, game_instance_id, playable_state_namespace_id, region_id, target_aggregate_type, aggregate_id)` identity only for explicit S3. For S1/S2 it separately exact-validates the active `game_instance_id` as authorization/fence evidence; it also exact-validates separately persisted `playable_state_scope`. An aggregate-only, aggregate-type-free, or namespace-free lookup is invalid. - If `(last_region_epoch, last_tick_id) >= (currentRegionEpoch, currentTickId)` for that exact row, the update is treated as a replay or out-of-order attempt and becomes a no-op (or, in strict modes, a validation-only check). - If `(last_region_epoch, last_tick_id) < (currentRegionEpoch, currentTickId)`, the handler applies the change and updates `(last_region_epoch, last_tick_id) = (currentRegionEpoch, currentTickId)` on that same composite-key row in the same transaction as the domain mutation. - **Operation-level effect guard** @@ -504,7 +504,7 @@ Examples: - **Once-per-tick aggregate watermark (per-aggregate last-tick state)** - `AdvanceRegionAuraWatermark` receives `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, targetAggregateType, targetAggregateId)`. - The design guarantees this aggregate is advanced at most once per tick. - - It reads the shadow tick state for `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, targetAggregateType, targetAggregateId)`, exact-validating separately persisted `playableStateScope` evidence, and applies the update only when `(last_region_epoch, last_tick_id) < (regionEpoch, tickId)`. + - For S1/S2, it reads the shadow tick state in the owner-defined `(tenantId, playableStateNamespaceId, regionId, targetAggregateType, targetAggregateId)` partition and separately exact-validates active `gameInstanceId` as authorization/fence evidence; only explicit S3 uses the complete `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, targetAggregateType, targetAggregateId)` instance-keyed identity. It also exact-validates separately persisted `playableStateScope` evidence and applies the update only when `(last_region_epoch, last_tick_id) < (regionEpoch, tickId)`. - If `(last_region_epoch, last_tick_id) >= (regionEpoch, tickId)`, the handler treats the request as a replay/out-of-order and returns without changing state. - **Trade between two entities (operation-level effect guard)** - The `TradeItem` endpoint explicitly receives `rootEffectId` (the mutation `EffectId` for this root operation) and immutable `requestDigest` in addition to `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId, fromEntityId, toEntityId, itemId)`. It creates one participant guard/ledger projection linked to that mutation/root effect per affected inventory aggregate. diff --git a/design/architecture/system-architecture-ticks.md b/design/architecture/system-architecture-ticks.md index d0661a9faa..a6a61a73b4 100644 --- a/design/architecture/system-architecture-ticks.md +++ b/design/architecture/system-architecture-ticks.md @@ -141,7 +141,7 @@ Target-state only (currently unavailable): once implemented, the Game Session Se This event stream is an observer/wakeup hint used for reconnection timer replay hints and other out-of-band reporting. “Every N ticks” scheduling correctness comes from the active deployment's committed status/progress timeline (target-state heartbeat/RegionStatus) plus durable PostgreSQL schedules; tick events may reduce latency by prompting quicker work discovery, but missing or duplicated events must not silently drop correctness-bearing one-shot intent or eligible durable work. Policy-governed recurring and advisory missed occurrences may be skipped as specified by the scheduler recovery policy. -Durable automation schedules and trigger-instance de-duplication remain PostgreSQL/domain-owned. In the target state, Account owns plan-driven quota values through tenant entitlement and plan-limit authority; the current Automation implementation instead uses service configuration for its limits. Live per-script and tenant-tier quota reservations/counters are Redis-backed enforcement state (for example, `automation:tenant-budget::tier:`). Redis quota counters are reset-tolerant and a reset may temporarily relax fairness; it does not change durable schedule or work truth. The current `tick-events:{tenantRegionTag}` stream and its offsets are separate best-effort coordination hints only; losing or resetting those hints must not silently drop correctness-bearing one-shot intent or eligible durable work or create duplicate durable claims, but may affect discovery timing and policy-governed missed recurring/advisory firings, including declared `SKIP_MISSED`, cap-excluded, or terminal capacity-denial outcomes. The `script-scheduler:{tenantRegionTag}:lastTickId` projection is target-only and unimplemented, with no current reset operation; once delivered, it will be a similarly reset-tolerant discovery hint rather than an authority for automation work. +Durable automation schedules and trigger-instance de-duplication remain PostgreSQL/domain-owned. In the target state, Account owns plan-driven quota values through tenant entitlement and plan-limit authority; the current Automation implementation instead uses service configuration for its limits. Live per-script and tenant-tier quota reservations/counters are Redis-backed enforcement state (for example, `automation:tenant-budget::tier:`). Redis quota counters are reset-tolerant and a reset may temporarily relax fairness; it does not change durable schedule or work truth. The target `tick-events:{tenantRegionTag}` stream and its offsets, once implemented, are separate best-effort coordination hints only; losing or resetting those hints must not silently drop correctness-bearing one-shot intent or eligible durable work or create duplicate durable claims, but may affect discovery timing and policy-governed missed recurring/advisory firings, including declared `SKIP_MISSED`, cap-excluded, or terminal capacity-denial outcomes. The `script-scheduler:{tenantRegionTag}:lastTickId` projection is target-only and unimplemented, with no current reset operation; once delivered, it will be a similarly reset-tolerant discovery hint rather than an authority for automation work. Automation & Scripting Service instances typically: diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index fb8021b2ac..db50a06402 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -52,7 +52,7 @@ The [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command- | --- | --- | --- | --- | | Acknowledgement (`ackLevel`) | `not implemented`: the live enqueue response exposes acceptance and `commandId`, but no canonical `ACCEPTED_VOLATILE`/`ACCEPTED_DURABLE` acknowledgement dimension is persisted or returned | `not proven`: no focused proof covers acknowledgement-level persistence or same-ID acknowledgement replay under [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) | `open`: add the durable field, status projection, ingress mapping, and focused retry/failover proof without adding a parallel status API | | Ingress (`ingressStatus`) | `partial`: the live command row uses progress values such as `ACCEPTED`, `STAGED`, `DRAINED`, and `RETRY_QUEUED` through `executionOutcome`; the canonical `RECEIVED`/`ENQUEUED`/`BOUND_TO_BATCH`/`TERMINAL` dimension is not yet separate | `partial`: current command-ingress, staging, and recovery tests prove the live progress paths, but not the canonical mapping required by [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) | `open`: persist and return `ingressStatus`, map legacy progress values, and prove reset/retry convergence | -| Execution outcome (`executionOutcome`) | `partial`: durable storage and status projection are live, including recovery outcomes, and rollback purge writes the canonical `ABANDONED` execution outcome with `NOT_APPLIED` plus a structured reason; complete canonical mapping across all terminal paths is not implemented | `partial`: [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java) and recovery tests cover current terminal updates and rollback purge scopes; complete [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) mapping across every terminal path is not yet proved | `open`: converge terminal vocabulary and prove every terminal path, including rollback purge, returns one durable outcome and reason | +| Execution outcome (`executionOutcome`) | `partial`: durable storage and status projection are live, including recovery outcomes; rollback purge uses `LOST_BEFORE_STAGING` before durable batch binding and `ABANDONED` only for an explicitly retryable command with a prior durable tick-effect binding, with `NOT_APPLIED` and a structured reason; complete canonical mapping across all terminal paths is not implemented | `partial`: [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java) and recovery tests cover current terminal updates and rollback purge scopes; complete [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) mapping across every terminal path is not yet proved | `open`: converge terminal vocabulary and prove every terminal path, including rollback purge, returns one durable outcome and reason | | Gameplay result (`gameplayResult`) | `partial`: durable storage and status projection are live for current command and remote-result paths, but the canonical independent result vocabulary is not fully enforced across all terminal paths | `partial`: migrated effect and remote-runtime tests cover current success/failure/result propagation; a complete [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) proof for `SUCCESS`, `PARTIAL`, `FAILED`, `TIMEOUT`, and `NOT_APPLIED` is not recorded | `open`: retain this as a separate player/result-facing projection, add terminal mapping coverage, and prove it cannot be inferred solely from `executionOutcome` | ## Canonical Design Sources @@ -81,7 +81,7 @@ After ingress validation, rate and queue-target resolution, Game Session writes Current pointer-CAS status/proof: routed Automation and remote gameplay-command insertion uses one PostgreSQL `INSERT ... SELECT` guarded by exactly one total current pointer row for the tenant/game-instance target, with that sole row matching the normalized world/realm selectors, pointer version, and required nonblank playable-state scope. Missing, mismatched, or ambiguous authority fails retryably before the insert. Existing pointer updates use expected-version CAS, and pointer creation serializes on the runtime target and fails closed when another route already owns it. Focused unit and compile proof has passed for this path, but live PostgreSQL/Testcontainers concurrency proof is unavailable locally and remains required before claiming full proof. This current pointer-CAS note does not establish target stable-namespace or `realmId` completeness. -The current command lifecycle is explicit: `ACCEPTED` means durable identity exists but staging has not succeeded; `STAGED` means Redis staging succeeded; `DRAINED` means a durable tick batch consumed the staged command; `RETRY_QUEUED` means an abandoned attempt was returned for another attempt; `FAILED` means staging failed before gameplay application; and target `LOST_BEFORE_STAGING` is the terminal recovery state only for explicitly volatile/no-batch accepted work that never reached staging. Live startup recovery re-enqueues old `ACCEPTED` rows under the same command identity and leaves the row `ACCEPTED` when materialization is uncertain or fails, so durable accepted work remains retryable rather than being terminalized without evidence. Batch drain and abandonment update command rows, so status is not ingress-only. +The current command lifecycle is explicit: `ACCEPTED` means durable identity exists but staging has not succeeded; `STAGED` means Redis staging succeeded; `DRAINED` means a durable tick batch consumed the staged command; `RETRY_QUEUED` means an abandoned attempt was returned for another attempt; and `FAILED` means staging failed before gameplay application. For live startup-loss recovery, target `LOST_BEFORE_STAGING` is the terminal recovery state only for explicitly volatile/no-batch accepted work that never reached staging. Live startup recovery re-enqueues old `ACCEPTED` rows under the same command identity and leaves the row `ACCEPTED` when materialization is uncertain or fails, so durable accepted work remains retryable rather than being terminalized without evidence. Batch drain and abandonment update command rows, so status is not ingress-only. `commandId` is carried in enqueue responses, Redis tick payloads, logs/MDC, batch manifests, effect rows, retries, and remote execution. `GetGameplayCommandStatus` is the single canonical Game Session read and currently resolves the command-id identity `(tenantId, gameInstanceId, commandId)`. The automation status lookup/correlation key `(tenantId, gameInstanceId, regionId, regionEpoch, automationDispatchId)` is the accepted target lookup but is not implemented by the live resolver; it is not the complete Command-Handoff Identity defined by the scripting normative contract table, which additionally carries command ordinal and applicable source/target scope fields. This tracker records the status lookup keys and their current/target status below under [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md). The read exposes `enqueueSeq`, the latest selected queue-source kind/state/ordinal and due-point tuple, lifecycle and routing data, and remote correlation/result fields. Logging & Admin exposes the implemented command-id read at `GET /gameplay-commands/{tenantId}/{gameInstanceId}/{commandId}` and validates tenant and game-instance identity before trusting the response. @@ -168,7 +168,7 @@ Game Session owns the implemented runtime feature-flag mutation and persists the The recorded proof covers durable command identity and sanitized persistence, restart/Redis-loss recovery at the ingress and ownership boundaries, single-record retry/replay updates, command correlation, batch/effect creation, manifest-digest replay repair, stale drain and post-drain fence rejection, durable `DRAINED` resumption, source-tuple preservation through timer/retry/remote claim-release transitions, fair selection in the local scheduler/queue path, and operator DTO/request mapping. Focused remote-runtime tests cover payload validation, bounded duplicate-window paging and de-duplication for due follow-up candidates, bounded durable result recording/replay, already-terminal follow-up replay, late-result handling, and selected reconciliation branches; this does not establish the full remote-follow-up fair-due-selection contract. They do not establish complete exact replay, safe accepted-but-never-staged convergence, general target-command convergence, complete terminal-failure mirroring, safe missing-coordinator recovery, or full origin reconciliation; those remain the target gaps described above. -Current handling proof for accepted-but-never-staged work is limited to the live [recovery helper](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java) and its [focused test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java): they show that old `ACCEPTED` unstaged rows are re-enqueued under their original identity and remain `ACCEPTED` when Redis, identity, eligibility, or a raced transition makes the outcome uncertain. This is focused unit evidence, not combined PostgreSQL/real-Redis restart proof or proof of safe `STAGED` recovery after Redis loss. Only explicitly volatile/no-batch work may use `LOST_BEFORE_STAGING`. Deterministic remote-result replay, paused-origin/late-result reconciliation, target-command convergence, and tenant/scope/id guards therefore remain proof gaps rather than completed coverage. +Current handling proof for accepted-but-never-staged work is limited to the live [recovery helper](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java) and its [focused test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java): they show that old `ACCEPTED` unstaged rows are re-enqueued under their original identity and remain `ACCEPTED` when Redis, identity, eligibility, or a raced transition makes the outcome uncertain. This is focused unit evidence, not combined PostgreSQL/real-Redis restart proof or proof of safe `STAGED` recovery after Redis loss. For live startup-loss recovery, only explicitly volatile/no-batch work may use `LOST_BEFORE_STAGING`; rollback purge retains its separate durable outcome mapping under [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md). Deterministic remote-result replay, paused-origin/late-result reconciliation, target-command convergence, and tenant/scope/id guards therefore remain proof gaps rather than completed coverage. Run-owned Compose mutation and teardown are implemented and proved at their bounded scope, but Game Session implementation and proof do not yet establish persistent/shared restricted-synthetic identity/namespace/fence isolation or independently isolated two-transport mutating parity. Shared/player-facing whole-stack reset is prohibited, and fixture teardown is not Coordination Redis reset authority; see the canonical [player-flow smoke and reset contract](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). From 582d7257594174b08bc8124693bb910f11daf7b9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 12:27:38 +1300 Subject: [PATCH 42/68] Clarify timer recovery isolation and current contract proof --- ...-0072-class-specific-timer-durability-and-recovery.md | 2 +- ...architecture-scripting-dsl-reference-and-lifecycle.md | 3 ++- design/architecture/system-architecture-ticks.md | 2 +- design/project-management/design-alignment/README.md | 4 ++-- .../automation-and-scheduler-runtime.md | 2 +- dev-tools/tests/architecture-doc-contracts.sh | 9 +++++++++ 6 files changed, 16 insertions(+), 6 deletions(-) diff --git a/design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md b/design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md index 1a0e65826c..371b511e7a 100644 --- a/design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md +++ b/design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md @@ -58,7 +58,7 @@ For target-state `COALESCE_ONE` recovery, Automation owns one durable timer-reco A scope-level durable atomic epoch transition must move each prior epoch's `OPEN` resume window, independently for each `isDryRun` mode, out of `OPEN` before any corresponding new-epoch `OPEN` window can be created. Claims from the prior window remain fenced to, and are reconciled under, their original `regionEpoch`, `isDryRun`, and resume-window identity; they cannot be admitted through the new window. The transition follows the existing evidence-based completion and terminalization rules and does not invent a new terminal status or recovery policy. -Every exact script-pin selection change is also a resume-window transition, including a same-patch repin that advances `scriptPinEpoch`, even when the runtime region and region epoch are unchanged. Before any new exact-pin timer admission, durable reconciliation must move every prior mode-specific `OPEN` window for the affected namespace/runtime scope out of `OPEN`, fence its claims to the prior exact pin and `resumeWindowId`, and preserve those claims and candidate audits for settlement under their original identities. They cannot consume the next window's cap or be rewritten for the target pin. After the target exact `(scriptPatchVersion, scriptPinEpoch)` and its schedules reconcile, a still-required catch-up episode allocates the next monotonic `resumeGeneration` independently for each mode and therefore a distinct mode-specific `resumeWindowId`; retries of this transition are idempotent under the initiating `controlPlaneRequestId`. +Every exact script-pin selection change is also a resume-window transition, including a same-patch repin that advances `scriptPinEpoch`, even when the runtime region and region epoch are unchanged. Before any new exact-pin timer admission, durable reconciliation must move every prior mode-specific `OPEN` window for the affected namespace/runtime scope out of `OPEN`, fence its claims to the prior exact pin and `resumeWindowId`, and preserve those claims and candidate audits for settlement under their original identities. Existing prior-window claims and their captured candidate identities remain selectable only by reconciliation under that original `resumeWindowId`; the target window must exclude them and cannot rediscover or remint their pending work under new candidate, firing-claim, or event identities. Settlement uses the original candidate, firing-claim, and work identities. This does not prevent the target window from selecting independently reconciled candidates under the new exact pin or later ordinary future occurrences under their own identities. Prior claims cannot consume the next window's cap or be rewritten for the target pin. After the target exact `(scriptPatchVersion, scriptPinEpoch)` and its schedules reconcile, a still-required catch-up episode allocates the next monotonic `resumeGeneration` independently for each mode and therefore a distinct mode-specific `resumeWindowId`; retries of this transition are idempotent under the initiating `controlPlaneRequestId`. `COALESCE_ONE` never replays a burst of missed cadence boundaries. One configurable tenant-local cap bounds synthetic firings across complete stable schedule-instance identities within one mode-specific resume window, which is already scoped to one tenant and one `isDryRun` mode. Selection is deterministic and fair across those identities, including target-scope and plugin-binding dimensions. Candidates excluded by the cap are not deferred into an unbounded backlog; their skipped outcomes and reasons are audited. Candidates selected within the tenant-local cap still enter the shared scheduler/cluster admission layer, where [ADR 0166](./adr-0166-attributable-script-breakers-and-tenant-first-fairness.md) tenant-first fairness precedes priority; catch-up cannot bypass per-tenant or cluster ceilings. A selected catch-up candidate denied there by a tenant or cluster capacity ceiling is terminally skipped for that due candidate and mode-specific `resumeWindowId`: it consumes its deterministic selection slot, records the applicable bounded capacity-denial reason in the candidate audit, creates no firing claim or `scriptEventId`, and is not deferred, retried, backfilled, or reminted in that or a later mode-specific resume window. This candidate-level ceiling gate is distinct from later handler-scoped Table 3 decisions: a per-script quota or materialized sandbox/dry-run capacity denial follows that table under the identity established at its stage, including any firing claim, `scriptEventId`, or work item already created, and is not reminted as catch-up. This terminal skip does not suppress the schedule's next ordinary future occurrence. 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 47f066df8a..04fde8cf65 100644 --- a/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md +++ b/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md @@ -238,7 +238,8 @@ Governance requirements for ordering overrides and exclusivity: Domain services can define **custom events** that feed into the scripting pipeline: - The visual DSL exposes event source nodes for any event types enabled for the current game. Under the hood, bindings are stored as ``. -- Service-specific events follow the same pre-DSL trigger/outbox → DSL run → durable descriptor/outbox → tick command flow as built-in events; the Redis automation queue remains only a derived pointer to the pre-DSL trigger record. +- **Target state only:** service-specific events follow the same pre-DSL trigger/outbox → DSL run → durable descriptor/outbox → tick command flow as built-in events; the Redis automation queue remains only a derived pointer to the pre-DSL trigger record. +- **Current implementation:** the legacy service-specific event path attempts emitted commands through per-command Game Session handoff calls. It does not persist evaluated command descriptors/outbox rows or implement post-DSL descriptor replay; see [Scripting Runtime Execution: Current Implementation Status](./system-architecture-scripting-runtime-execution.md#current-implementation-status). - Event schemas are versioned so scripts can be migrated when payloads change. Custom events must follow the same determinism and idempotency rules as built-in events; the applicable identity and ingress requirements are defined in the [normative contract tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). diff --git a/design/architecture/system-architecture-ticks.md b/design/architecture/system-architecture-ticks.md index a6a61a73b4..28c35cd349 100644 --- a/design/architecture/system-architecture-ticks.md +++ b/design/architecture/system-architecture-ticks.md @@ -90,7 +90,7 @@ The tick heartbeat is the **canonical timeline** for each ` `region_epoch` mapping rather than treating the two names as competing fields. -Consumers that persist offsets must key stable consumer identity by `(tenantId, gameInstanceId, regionId, consumerId)` and store `regionEpoch` and `latestTickId` as mutable timeline state. For durable schedules, `scheduleInstanceId` is the immutable physical row-generation identity allocated under the materializing operation; it is not the stable logical continuity identity and is not sufficient for trigger uniqueness. The scheduler-owned stable continuity key is `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}` for each `isDryRun` mode; compatible transitions may retain the same row generation, while reset or incompatible replacement can allocate a fresh `scheduleInstanceId` under that continuity model. Mutable runtime-region metadata (`runtimeRegionId`, `runtimeRegionEpoch`), due point, and exact pin/provenance remain schedule state or evidence rather than continuity identity. Trigger-instance de-duplication and candidate-audit identity instead use the complete event-scope due-candidate/firing identity owned by [Scripting Scheduler and Timers](./system-architecture-scripting-scheduler-and-timers.md#target-state-design) and [Normative Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields), including applicable runtime region/epoch, event/schema, exact patch/pin, dry-run, trigger mode, target selector, exactly one tagged due point (`dueTickId` or `dueAt`), catch-up `resumeWindowId`, and schedule-owned script/plugin fields. A wall-clock source may carry a separately assigned admission `due_tick_id` for tick ordering, but it does not become or alias the source `dueAt`; tick IDs and epoch-millisecond values are never compared. This document does not redefine that schema or mutate the schedule itself. Any observed epoch jump is a reset boundary: state derived from the old epoch is discarded or reconciled from PostgreSQL before resuming. +Consumers that persist offsets must key stable consumer identity by `(tenantId, gameInstanceId, regionId, consumerId)` and store `regionEpoch` and `latestTickId` as mutable timeline state. For durable schedules, `scheduleInstanceId` is the immutable physical row-generation identity allocated under the materializing operation; it is not the stable logical continuity identity and is not sufficient for trigger uniqueness. The scheduler-owned stable continuity identity is mode-qualified as `(isDryRun, {stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId})`, as owned by [Scripting Scheduler and Timers](./system-architecture-scripting-scheduler-and-timers.md#target-state-design) under [ADR 0110](./decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md); compatible transitions may retain the same row generation, while reset or incompatible replacement can allocate a fresh `scheduleInstanceId` under that continuity model. Mutable runtime-region metadata (`runtimeRegionId`, `runtimeRegionEpoch`), due point, and exact pin/provenance remain schedule state or evidence rather than continuity identity. Trigger-instance de-duplication and candidate-audit identity instead use the complete event-scope due-candidate/firing identity owned by [Scripting Scheduler and Timers](./system-architecture-scripting-scheduler-and-timers.md#target-state-design) and [Normative Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields), including applicable runtime region/epoch, event/schema, exact patch/pin, dry-run, trigger mode, target selector, exactly one tagged due point (`dueTickId` or `dueAt`), catch-up `resumeWindowId`, and schedule-owned script/plugin fields. A wall-clock source may carry a separately assigned admission `due_tick_id` for tick ordering, but it does not become or alias the source `dueAt`; tick IDs and epoch-millisecond values are never compared. This document does not redefine that schema or mutate the schedule itself. Any observed epoch jump is a reset boundary: state derived from the old epoch is discarded or reconciled from PostgreSQL before resuming. ### Tick Commit Definition (Heartbeat Watermark) diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index ef6da384b7..904bc1f8c6 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -159,9 +159,9 @@ PR closure follows the hosted review evidence and judgment described by the [PR ## Automated Gates -Focused validation on 2026-09-09 Pacific/Auckland passed for the current `355` discovered sources (`352` allocated, `3` explicit exemptions) and `180` ADR records, with `172` carrying completed review metadata and `11` pre-formal records; those categories overlap for accepted legacy pre-formal records carrying exact provenance. Prior parcel validation remains historical evidence only. On 2026-08-28 Pacific/Auckland, the integrated local gates passed against the then-current `354` discovered sources (`351` allocated, `3` explicit exemptions) and `179` ADR records, with `171` carrying completed review metadata and `11` pre-formal records: implementation tracking covered `79` leaves across `10` trackers, the authorization-route matrix passed, the full architecture-document contract suite passed, `linkCheck` checked `6,537` links (`6,489` OK, `0` errors, `48` excluded), `lintMarkdown` checked `535` files (`0` issues), and `git diff --check` was clean. These listed gates are local documentation/structure checks only. The current port also includes controller, Kubernetes, workflow, and deployment-tooling implementation with focused local proof; its owning domain tracker remains authoritative for implementation and proof status. Live hosted-environment proof remains unavailable, and neither the target contracts nor local checks should be read as commit, PR, CI, or live-hosted proof. +Focused validation on 2026-09-09 Pacific/Auckland passed for the then-current `355` discovered sources (`352` allocated, `3` explicit exemptions) and `180` ADR records, with `172` carrying completed review metadata and `11` pre-formal records; those categories overlap for accepted legacy pre-formal records carrying exact provenance. Prior parcel validation remains historical evidence only. On 2026-08-28 Pacific/Auckland, the integrated local gates passed against the then-current `354` discovered sources (`351` allocated, `3` explicit exemptions) and `179` ADR records, with `171` carrying completed review metadata and `11` pre-formal records: implementation tracking covered `79` leaves across `10` trackers, the authorization-route matrix passed, the full architecture-document contract suite passed, `linkCheck` checked `6,537` links (`6,489` OK, `0` errors, `48` excluded), `lintMarkdown` checked `535` files (`0` issues), and `git diff --check` was clean. These listed gates are local documentation/structure checks only. The current port also includes controller, Kubernetes, workflow, and deployment-tooling implementation with focused local proof; its owning domain tracker remains authoritative for implementation and proof status. Live hosted-environment proof remains unavailable, and neither the target contracts nor local checks should be read as commit, PR, CI, or live-hosted proof. -- `python3 dev-tools/validation/check-design-capability-allocation.py` derives the product and architecture source sets, parses each allocation ledger, and reconciles the declared current coverage summary (`355` discovered sources, `352` allocated sources, and the canonical `2` governance/template exemptions plus `1` registry exemption). +- `python3 dev-tools/validation/check-design-capability-allocation.py` derives the product and architecture source sets, parses each allocation ledger, and reconciles the declared current coverage summary (`357` discovered sources, `354` allocated sources, and the canonical `2` governance/template exemptions plus `1` registry exemption). - all intended FireMUD user, creator, operator, runtime, authoring, automation, platform, and commercial concerns have a capability home; - every Markdown source under `design/product/**` and `design/architecture/**` is present and classified in the allocation ledger, including generated/index material, unless it is one of the two explicit governance/template exemptions or the decision-registry exemption; - mixed canonical documents have heading-level allocations where file-level allocation would hide a real ownership split; 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 05ee7906c0..60e84deacc 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -177,7 +177,7 @@ Automation never writes Game Session tick keys directly. The live queue uses ins Current enqueue/rebuild is RPUSH-only (with no target pointer TTL or maximum length), and `tenantInstanceTag` still concatenates raw IDs, so retention, memory-pressure, and collision-safe opaque encoding remain unproved. Canonical queue and Redis mechanics are owned by [Scripting Runtime Execution](../../architecture/system-architecture-scripting-runtime-execution.md) and [Redis](../../architecture/system-architecture-redis.md); this tracker records the current implementation gaps. -Game Session retains a lower-level idempotent `EnqueueAutomationCommandIfAbsent` helper that persists automation dispatch/work-item correlation on the gameplay command ledger before tick staging. Authenticated receiver-admission status is recorded in the [Game Session receiver candidate status](#game-session-receiver-candidate) and [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status), so the lower-level helper proofs are not live receiver-admission proof. The separate durable tick staging/replay and final tuple recheck remain implemented and do not establish that the receiver admitted a request. Numeric gameplay `targetEntityId` is captured as `characterId` so durable execution can resolve an active session without a caller-owned `sessionId`. Automation assigns a per-command `automationDispatchId`, preserves the full routing bundle, and retains helper paths for local admission or durable remote follow-up to a different target runtime scope. Before re-enqueuing an existing `ACCEPTED` but unstaged Automation command, the lower-level admission helper revalidates the request's captured region identity and epoch against current runtime ownership and rejects unavailable, paused, or advanced ownership without mutation; already-materialized or terminal exact retries retain stored-result readback behavior. Once receiver admission is available, local scripting commands enter the same Game Session actor-action safety and fairness path as player commands; the durable remote-follow-up delivery envelope is passive at the target and does not consume its actor slot, but if its payload enqueues a gameplay/automation command, that resulting command remains an actor action and cannot receive a same-tick extra root action. The current `scheduleFollowup` terminal-timeout/late-result path can reopen an existing terminal coordinator/follow-up pair; this remains the implementation/proof gap recorded in Game Session runtime/data. The live Game Session enqueue proto/storage remains narrower than the target automation handoff contract: it does not yet carry full Trigger Identity, `commandOrdinal`, immutable `lane`, or `cost_class`, so target dispatch-plus-ordinal identity, lane/cost conflict and digest checks, complete child deduplication, readback, retry, recovery preservation, and enforcement remain unimplemented or unproved. Canonical handoff mechanics are owned by [ADR 0063](../../architecture/decisions/adr-0063-durable-per-dispatch-script-handoff.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), and [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary); the canonical handoff identity is also recorded in [Scripting & Automation: Cross-Service Contracts, section 2](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary), and tick lane semantics remain owned by [Tick Concepts & Invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md). This tracker records the local actor-path consequence and current gap. +Game Session retains a lower-level idempotent `EnqueueAutomationCommandIfAbsent` helper that persists automation dispatch/work-item correlation on the gameplay command ledger before tick staging. The authenticated receiver RPC remains fail-closed before live mutation because its Automation admission-epoch receiver fence is absent; lower-level helper proofs do not establish live receiver admission. See the [Game Session receiver candidate status](#game-session-receiver-candidate) and [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). The separate durable tick staging/replay and final tuple recheck remain implemented and do not establish that the receiver admitted a request. Numeric gameplay `targetEntityId` is captured as `characterId` so durable execution can resolve an active session without a caller-owned `sessionId`. Automation assigns a per-command `automationDispatchId`, preserves the full routing bundle, and retains helper paths for local admission or durable remote follow-up to a different target runtime scope. Before re-enqueuing an existing `ACCEPTED` but unstaged Automation command, the lower-level admission helper revalidates the request's captured region identity and epoch against current runtime ownership and rejects unavailable, paused, or advanced ownership without mutation; already-materialized or terminal exact retries retain stored-result readback behavior. Once receiver admission is available, local scripting commands use Game Session's actor-action path; a remote follow-up uses the owner-defined passive/inbound path, while any gameplay command it emits uses the actor-action path. The current `scheduleFollowup` terminal-timeout/late-result path can reopen an existing terminal coordinator/follow-up pair; this remains the implementation/proof gap recorded in Game Session runtime/data. The live Game Session enqueue proto/storage remains narrower than the target automation handoff contract: it does not yet carry full Trigger Identity, `commandOrdinal`, immutable `lane`, or `cost_class`, so complete child identity, lane/cost conflict and digest checks, deduplication, readback, retry, recovery preservation, and enforcement remain unimplemented or unproved. Canonical handoff mechanics are owned by [ADR 0063](../../architecture/decisions/adr-0063-durable-per-dispatch-script-handoff.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), and [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary); tick lane semantics remain owned by [Tick Concepts & Invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md). This tracker records the local actor-path consequence and current gap. The target remote-follow-up contract is owned by [Scripting & Automation: Cross-Service Contracts](../../architecture/system-architecture-scripting-contracts.md#3-version-fencing-rollback-safety). Current `ScriptHandoffEvent` persistence and readback now carry the source `scriptPinEpoch`, but they do not yet bind the source tuple to the target tuple or prove downstream target admission against that binding. The legacy target-side `trigger_script_event` path is therefore deterministically disabled until the complete source/target tuple-plus-owner binding exists: missing, malformed, or mismatched tuple evidence is a terminal fail-closed outcome, while unavailable authority remains non-admitted and retryable. Same-instance cross-region work and semantic target `UNPINNED` handling remain subject to that owner contract. diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index ace2c7c0ce..b47728f5d5 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -1953,6 +1953,15 @@ require_contains( "`resumeWindowId` is the exact tuple ``", "the server-derived `playableStateScope` is retained and exact-validated as immutable policy/routing/authorization/fence evidence, not as a uniqueness input", "each prior epoch's `OPEN` resume window, independently for each `isDryRun` mode", + "the target window must exclude them and cannot rediscover or remint their pending work under new candidate, firing-claim, or event identities", + "This does not prevent the target window from selecting independently reconciled candidates under the new exact pin", + ], +) +require_contains( + "design/architecture/system-architecture-ticks.md", + [ + "stable continuity identity is mode-qualified as `(isDryRun, {stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId})`", + "[Scripting Scheduler and Timers](./system-architecture-scripting-scheduler-and-timers.md#target-state-design) under [ADR 0110]", ], ) require_contains( From be8fceb2aa4ffad838a472ca9ce14025aa73cc90 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 12:45:28 +1300 Subject: [PATCH 43/68] docs: narrow pending effect allocation mechanics --- design/architecture/system-architecture-tick-execution-flows.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/system-architecture-tick-execution-flows.md b/design/architecture/system-architecture-tick-execution-flows.md index c2db0e6b27..8c6997569a 100644 --- a/design/architecture/system-architecture-tick-execution-flows.md +++ b/design/architecture/system-architecture-tick-execution-flows.md @@ -44,7 +44,7 @@ Within a region’s tick, root actor commands and their effects proceed through 1. **Enqueue** - Game Session accepts commands from Telnet and WebSocket clients, AI, or automation. - Work-bearing commands are enqueued into per-entity (or occasionally per-region) queues such as `tick:{tenantRegionTag}:queue:`. - - If admission resolves to no gameplay effects, the same durable command-status transaction records the canonical terminal outcome (`ingressStatus=TERMINAL`, `executionOutcome=APPLIED`, and `gameplayResult=SUCCESS` under [ADR 0053](./decisions/adr-0053-command-atomicity-by-invariant-class.md) and [ADR 0016](./decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md)). This status-only write creates no effect ledger row or `tick_batch`, advances no tick-domain state, and does not enqueue the command; an accepted no-effect command therefore cannot remain `ENQUEUED`, and retries return its stored terminal outcome. Command-plan ordinal and root-allocation treatment is pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). + - If admission resolves to no gameplay effects, the same durable command-status transaction records the canonical terminal outcome (`ingressStatus=TERMINAL`, `executionOutcome=APPLIED`, and `gameplayResult=SUCCESS` under [ADR 0053](./decisions/adr-0053-command-atomicity-by-invariant-class.md) and [ADR 0016](./decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md)). This status-only write creates no effect ledger row or `tick_batch`, advances no tick-domain state, and does not enqueue the command; an accepted no-effect command therefore cannot remain `ENQUEUED`, and retries return its stored terminal outcome. Command-plan ordinal and ID-generation/allocation mechanics remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). 2. **Target Resolution (read-only)** - During the tick, the executor resolves targets from the pinned snapshot for that ``: - Single-target actions select a specific entity or room. From 64ddb1ec6be8194da4475ee1cfb3d2df3af1b261 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 13:13:35 +1300 Subject: [PATCH 44/68] docs: correct replay identity and terminal proof boundaries --- ...-spatial-mutations-across-split-authority.md | 6 +++--- ...ecution-with-one-logical-terminal-outcome.md | 4 ++-- ...-count-bounds-for-generated-effect-chains.md | 2 +- .../runtime-and-data.md | 6 +++--- .../architecture/system-architecture-gateway.md | 2 +- ...system-architecture-redis-cache-reference.md | 2 +- .../system-architecture-redis-lua-patterns.md | 2 +- ...tem-architecture-redis-usage-and-profiles.md | 2 +- ...ecture-scripting-control-plane-operations.md | 2 +- ...-architecture-scripting-dsl-for-designers.md | 2 +- ...rchitecture-scripting-operations-cookbook.md | 6 +++--- ...hitecture-scripting-quotas-and-operations.md | 2 +- ...architecture-tick-concepts-and-invariants.md | 2 +- .../system-architecture-tick-execution-flows.md | 2 +- ...ame-session-runtime-and-tick-coordination.md | 6 +++--- dev-tools/tests/architecture-doc-contracts.sh | 17 +++++++++++++++++ 16 files changed, 41 insertions(+), 24 deletions(-) diff --git a/design/architecture/decisions/adr-0061-single-owner-spatial-mutations-across-split-authority.md b/design/architecture/decisions/adr-0061-single-owner-spatial-mutations-across-split-authority.md index 08ea007ac6..167fbb5d44 100644 --- a/design/architecture/decisions/adr-0061-single-owner-spatial-mutations-across-split-authority.md +++ b/design/architecture/decisions/adr-0061-single-owner-spatial-mutations-across-split-authority.md @@ -48,7 +48,7 @@ The canonical Game Session root binding is authenticated and exact-compared befo - `MOVE` mutates World location/occupancy in one World transaction. Pure movement has no Entity mutation participant. - `DROP` and `PICKUP` mutate the item's holder in one Entity transaction. They use the existing World `TargetingFactSnapshot` actor-location/location-version token, admitted under the Game Session actor/executor fence and passed to Entity as owner-issued location evidence. Before committing, Entity atomically validates that token for the same room/epoch together with the expected holder and Entity aggregate version; stale or mismatched World location evidence fails admission and re-resolves under the same root `EffectId` and immutable request digest, without transferring item authority to World. -Every owner resolves its participant guard using the persisted mutation `EffectId` as the stable collision key for that participant (the root `EffectId` for a root mutation or the persisted child `EffectId` for a generated child). An existing candidate is reusable only after separately exact-comparing the typed operation, exact target aggregate, owner-declared runtime-family partition—S1/S2 use `(tenantId, playableStateNamespaceId)`, explicit S3 uses `(tenantId, gameInstanceId)`, and an unknown or unclassified family fails closed—and immutable `requestDigest`; any mismatch fails closed. Where one mutation has multiple participants, the owner-local participant/target slot keeps those sibling guards distinct. A generated child retains its enclosing root only as lineage and reconciliation context. Same guard and same request replays the prior result. Generated-child allocation and root/child lineage beyond this accepted guard boundary remain subject to the non-authoritative [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +Every owner resolves its participant guard using the persisted mutation `EffectId` as the stable collision key for that participant (the root `EffectId` for a root mutation or the persisted child `EffectId` for a generated child). An existing candidate is reusable only after separately exact-comparing the typed operation, exact target aggregate, owner-declared runtime-family partition—S1/S2 use `(tenantId, playableStateNamespaceId)`, explicit S3 uses `(tenantId, gameInstanceId)`, and an unknown or unclassified family fails closed—and immutable `requestDigest`; any mismatch fails closed. Where one mutation has multiple participants, the owner-local participant/target slot keeps those sibling guards distinct. A generated child retains its enclosing root only as lineage and reconciliation context. Same guard and same request replays the prior result. The owner-scope/root/parent/ordinal-to-child-`EffectId` mapping and enclosing-root lineage required by ADR 0075 are accepted independently of ADR 0183. Command-plan ordering, root allocation, and identity-format or allocation mechanics not defined by that mapping remain subject to the non-authoritative [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). Correctness mutations carry exact scope, epoch, and relevant expected state: @@ -56,7 +56,7 @@ Correctness mutations carry exact scope, epoch, and relevant expected state: - drop and pickup include World-authoritative actor-location evidence plus expected current holder and Entity aggregate version; and - ambient changes include the owning World aggregate and expected version. -Derived ambient or gameplay reactions use deterministic child effect identities and declare whether they are required or optional. Only declared required participants delay logical player success. Presentation reads use ADR 0059's causal floor and distinct component versions, never service-local snapshot equality; that presentation causal floor is not a mutation guard and is never substituted for the World targeting token. The non-authoritative [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) describes a possible future allocation boundary. +Derived ambient or gameplay reactions use deterministic child effect identities and declare whether they are required or optional. Only declared required participants delay logical player success. Presentation reads use ADR 0059's causal floor and distinct component versions, never service-local snapshot equality; that presentation causal floor is not a mutation guard and is never substituted for the World targeting token. The non-authoritative [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) concerns command-plan and root allocation mechanics beyond ADR 0075's accepted generated-child mapping. ## Consequences @@ -90,7 +90,7 @@ Rejected because at-least-once delivery and stale room evidence could duplicate ## Implementation and Proof Obligations -Proof must cover digest-conflict rejection, duplicate replay, stale epoch/location/holder/version, move without an Entity mutation, drop/pickup without World item ownership, no double location or holder, deterministic required/optional child admission and outcome classification, crash and reconciliation, and causal-floor room presentation. Allocation/replay proof for the pending [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not claimed here. The effect catalog is the required inventory for new spatial and ambient effect families. +Proof must cover digest-conflict rejection, duplicate replay, stale epoch/location/holder/version, move without an Entity mutation, drop/pickup without World item ownership, no double location or holder, deterministic required/optional child admission and outcome classification, crash and reconciliation, and causal-floor room presentation. Command-plan and root-allocation proof for the pending [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is not claimed here. The effect catalog is the required inventory for new spatial and ambient effect families. ## Reversibility and Revisit Triggers diff --git a/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md b/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md index c098cb5dcf..19b16510e4 100644 --- a/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md +++ b/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md @@ -47,7 +47,7 @@ Before any participant verification, the canonical Game Session context binds ea The owning domain's durable idempotency guard permits at most one logical authoritative state mutation for that identity and digest. Reuse of the identity with a conflicting digest fails closed. -The exact scalar format and allocation boundary for root or generated-child effect identities remain unresolved and are proposed in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). This decision requires retries and replay to preserve the persisted mutation identity and immutable request digest; it does not define command-plan ordering, `planOrdinal`, or a root-allocation key. +The owner-defined child ordinal and durable owner-scope/root/parent/ordinal-to-child-`EffectId` admission mapping required by ADR 0075 are accepted. The exact scalar format and root, command-plan, or other identity-allocation mechanics not defined by that mapping remain unresolved and are proposed in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). This decision requires retries and replay to preserve the persisted mutation identity and immutable request digest; it does not define command-plan ordering, `planOrdinal`, or a root-allocation key. Command receipts, tick batches, and selected-work manifests are S3 instance-scoped operational evidence: they may be cleaned up only after linked source claims and effects are terminal, replay/restore and reconciliation horizons have elapsed, and the owner cleanup fence permits it. Participant guards remain owner-domain durable evidence, with their own namespace/state classification and retention contract; they are not disposable Redis coordination state. A reset or replacement alone never authorizes bulk deletion or abandonment. @@ -96,7 +96,7 @@ Rejected as the normal contract because unresolved effects could remain ambiguou ## Implementation and Proof Obligations -Proof must cover accepted-command loss before staging without an invented effect row; sealed mutation identity/operation/digest/participant/manifest binding before participant verification and conflict rejection; crashes before and after domain commit; lost acknowledgements; duplicate physical invocation with one logical mutation; authoritative `REPLAY_NOOP` evidence terminalizing as `APPLIED`; evidence-qualified `ABANDONED` outcomes with timeout, retry-exhaustion, missing-coordination, age, and technical-failure rejection; command-result derivation from required-effect terminal outcomes; duplicate presentation feedback without duplicate state; replay and reset convergence; and absence of silent drop or permanently ambiguous staged rows. Command-plan ordering, ordinal allocation, and root-allocation proof belong to ADR 0183 only if that proposal is accepted. +Proof must cover accepted-command loss before staging without an invented effect row; sealed mutation identity/operation/digest/participant/manifest binding before participant verification and conflict rejection; crashes before and after domain commit; lost acknowledgements; duplicate physical invocation with one logical mutation; authoritative `REPLAY_NOOP` evidence terminalizing as `APPLIED`; evidence-qualified `ABANDONED` outcomes with timeout, retry-exhaustion, missing-coordination, age, and technical-failure rejection; command-result derivation from required-effect terminal outcomes; duplicate presentation feedback without duplicate state; replay and reset convergence; and absence of silent drop or permanently ambiguous staged rows. Command-plan ordering, `planOrdinal` allocation, and root-allocation proof belong to ADR 0183 only if that proposal is accepted; child-ordinal and generated-child mapping proof remains under ADR 0075. The current implementation and runtime proof are not claimed to satisfy this decision. diff --git a/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md b/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md index b59690d31a..8d91e9401e 100644 --- a/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md +++ b/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md @@ -45,7 +45,7 @@ Platform hard ceilings bound every setting. Operators may configure lower enviro Every generated child carries an immutable parent identity, immutable enclosing-root lineage, depth equal to `parent.depth + 1`, and an owner-defined child ordinal allocated and persisted by the owning contract for replay-stable reuse. This decision does not define command-plan roots or `planOrdinal`; those allocation choices remain pending in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). The sealed chain manifest also persists the resolved platform, operator, and feature depth/count/cost/per-target limits, cost weights, and cost-model version. Retry, replay, and reconciliation reuse those persisted resolved values and never re-resolve them. Replay reuses the recorded child identity, lineage, ordinal, and budget accounting; it does not increment them again or mint a replacement identity. -The owner-scope/root/parent/ordinal mapping to each child `EffectId` is one atomic durable admission record. The owning contract must persist the child `EffectId` and complete mapping before enqueue/apply; retry, replay, and reconciliation read and reuse that mapping and its sealed accounting, while a missing or conflicting mapping fails closed rather than allocating another child identity. +Independent of pending ADR 0183, the owner-scope/root/parent/ordinal mapping to each child `EffectId` is one atomic durable admission record. The owning contract must persist the child `EffectId` and complete mapping before enqueue/apply; retry, replay, and reconciliation read and reuse that mapping and its sealed accounting, while a missing or conflicting mapping fails closed rather than allocating another child identity. Count, cost, per-target, and depth admission are evaluated deterministically for the root chain. When admitting a new child would exceed a limit, only that child is suppressed. A suppressed child is not enqueued or applied, and no already committed parent or earlier child is rolled back. 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 0148e38c0a..1a11105866 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -30,12 +30,12 @@ This document defines Entity Management’s runtime model, persistence ownership - Entity Management instances are intended to be replaceable workers over authoritative persistent state and documented caches. Item, inventory, containment, and character data that must survive instance loss belongs in the service-owned database rows and cache invalidation model, not as the sole authoritative copy in one process. - Database writes are deferred and batched for ordinary entity updates, not triggered on every gameplay action. The Game Session Service coordinates real-time updates using Redis; the database is normally updated when ticks complete. - Spatial containment mutations that participate in cross-service effects are the exception: before Entity Management acknowledges a spatial mutation's persisted `EffectId` (the root `EffectId` for a root effect or the persisted child `EffectId` for a generated child effect) back to Game Session, it must durably flush the effect’s idempotency guard plus the affected containment/container rows for that effect within the same local transaction. A participant acknowledgement must never be emitted for Redis-only staged state. -- Target-state cross-service participant guards use the persisted mutation `EffectId` (the root `EffectId` for a root mutation or the persisted child `EffectId` for a generated child mutation), typed operation, target aggregate, and immutable request digest; any enclosing `rootEffectId` is lineage and reconciliation context only. Matching retries return the durable result, while an operation, target, or digest mismatch fails closed. This target guard is not the current domain-local replay table described above. The pending [ADR 0183 proposal](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative. +- Target-state cross-service participant guards follow the owner-declared runtime-family partition: `(tenantId, playableStateNamespaceId)` for S1/S2 or `(tenantId, gameInstanceId)` only for explicitly classified S3, together with the persisted mutation `EffectId`, typed operation, and exact target aggregate. `requestDigest` is separately persisted and exact-validated conflict metadata, not a uniqueness dimension; S1/S2 scope and active-instance evidence are validated separately, and any enclosing `rootEffectId` is lineage and reconciliation context. A mismatch fails closed. This target guard is not the current domain-local replay table described above; see [Transaction Strategies](../../system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory). - The target design reduces write frequency and contention, making optimistic version CAS a natural fit because most entities are updated by only one process at a time and conflicts are rare; it remains target-only until the predicates, affected-row checks, and concurrent proof exist. - Item transfers and other gameplay actions span services but execute within ticks using Redis scripts for rollback. Sagas are reserved for non-gameplay workflows. See [Transaction Strategies](../../system-architecture-transactions.md). - For long-running, non-gameplay workflows such as publishing a game version, this service participates as a domain step in durable publish workflows coordinated by the Game Design Service as described in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). - **Target state:** Entity-owned tables carry a `tenantId` column wherever the row is a tenant-isolation boundary, and service methods enforce that tenant predicate; Redis keys mirror this prefix. **Current exceptions:** the live `inventory` and `character_equipment` tables have no `tenant_id` and obtain isolation by joining their `character_id` to `characters.tenant_id`; `crafting_ingredients` has no `tenant_id` and is reached through its tenant-owned `crafting_recipes` parent. The current `CraftingRecipeRepository.findWithIngredientsById` lookup is ID-only, so it does not itself prove a tenant predicate even though tenant-scoped list methods select recipe IDs first. These exceptions and the holder/containment cleanup gaps above mean the target all-table/filtering claim is not current proof. Details are in [Multi-Tenancy](../../system-architecture-multi-tenancy.md). -- Durable playable state that survives runtime replacement is keyed by `(tenantId, playableStateNamespaceId)` plus the applicable domain object identity and is authorized against the separately validated immutable `playableStateScope` and currently active `gameInstanceId`; `gameInstanceId` alone is reserved for explicitly disposable S3 runtime families. At target, S1/S2 durable storage identity is `{tenantId, playableStateNamespaceId, domainObjectId}` and omits both routing scope and `gameInstanceId`. This storage identity is distinct from cross-service effect participant replay/deduplication identity, which uses the persisted mutation `EffectId` (root or generated child), typed operation, exact target aggregate, and immutable request digest; generated children retain their root `EffectId` for lineage and reconciliation. Within that participant record, `playableStateScope`, `gameInstanceId`, and `effectKey` are projection/validation metadata, not participant uniqueness; other service-local idempotency keys remain operation-specific. Only explicitly S3 rows use `gameInstanceId` as part of durable identity. The namespace is resolved by the realm/lifecycle contract and is never inferred from an entity id, Redis key, or caller-supplied remap identifier. See [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). +- Durable playable state that survives runtime replacement is keyed by `(tenantId, playableStateNamespaceId)` plus the applicable domain object identity and is authorized against the separately validated immutable `playableStateScope` and currently active `gameInstanceId`; `gameInstanceId` alone is reserved for explicitly disposable S3 runtime families. At target, S1/S2 durable storage identity is `{tenantId, playableStateNamespaceId, domainObjectId}` and omits both routing scope and `gameInstanceId`. Cross-service effect participant replay/deduplication follows the owner-declared partition: namespace-backed S1/S2 uses `(tenantId, playableStateNamespaceId)`, while explicitly classified S3 uses `(tenantId, gameInstanceId)`. For S1/S2, `playableStateScope` and active `gameInstanceId` are separately validated evidence, not participant uniqueness; the explicit S3 `gameInstanceId` is part of its partition. `requestDigest` is separately exact-validated conflict metadata, not a uniqueness dimension. Other service-local idempotency keys remain operation-specific. The namespace is resolved by the realm/lifecycle contract and is never inferred from an entity id, Redis key, or caller-supplied remap identifier. See [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) and [Transaction Strategies](../../system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory). - `playableStateScope` is accepted only as the realm/lifecycle owner's authoritative resolved snapshot or attestation. Callers cannot select or derive it, and Entity validates the exact immutable `{playableStateNamespaceId, playableStateScope}` pair before create or update; a scope change for an existing namespace is rejected rather than reinterpreting or splitting durable state. The `{tenantId, playableStateNamespaceId, characterId}` key is the stable actor storage identity, while `{tenantId, accountId, playableStateNamespaceId}` is the auto-provision actor-uniqueness identity; the separate operation replay guard uses `{tenantId, playableStateNamespaceId, accountId, autoProvisionRequestId}` and binds the exact `mutationDigest`. Neither identity reinterprets scope. `gameInstanceId` remains only the active-instance authorization fence. See [ADR 0122](../../decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). - Gameplay-facing gRPC endpoints do not parse JWT tokens. The Game Session Service injects identity context using `SessionContext` and may request a new JWT from the Account Service if a player's roles change. It does not validate tokens for gameplay. Traffic between services still uses mutual TLS certificates as outlined in the [Security Architecture](../../system-architecture-security.md). - Design-time writes are a separate surface: @@ -360,7 +360,7 @@ Equipment is intentionally not modeled as "just another bag position": - The complete-schema and fail-closed behavior in the following contract is target state, not current implementation; current missing-schema and unknown-layout bootstrap fallback gaps are recorded in the [Entity Management README](./README.md) and [Item & Equipment Balancing Tools](../game-design-service/item-equipment-balancing.md#target-equipment-schema-requirements). - Game Design owns the complete published equipment vocabulary/body-layout schema and its digest. Entity Management consumes that exact schema for occupancy and compatibility checks; all missing, partial, or mismatched vocabulary or mapping evidence is rejected and validation fails closed. It does not provide a platform-global slot fallback. Replacement cutover remaps bindings only through the owner-validated mapping contract; profiles materialize authored equipment content rather than supplying runtime defaults. See [ADR 0127](../../decisions/adr-0127-game-authored-equipment-layouts-with-fail-closed-publication.md). -The target inventory/equipment operation context for a durable holder or binding is `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId, holderRef, itemInstanceId, itemDefinitionId, equipmentBindingId?, slotKey?}`, with one typed `holderRef` for each source, destination, or equipment owner required by the operation. A holder reference is a closed tagged union: character inventory or equipment carries `CHARACTER {characterId}`; NPC, pet, or summon ownership carries `ACTOR {actorId}`; an ordinary bag, chest, corpse, bank, vendor stock, or nested holder carries `CONTAINER {containerInstanceId}`; and room-ground storage carries `ROOM_GROUND {roomInstanceId, containerInstanceId}`. `characterId` is therefore required only for character-owned inventory or equipment and must not be fabricated for another holder kind. For namespace-backed S1/S2 inventory, character, and equipment state, durable storage identity is `{tenantId, playableStateNamespaceId, ...domainObjectId}` and omits both `playableStateScope` and `gameInstanceId`; those two values are validated separately as immutable routing/authorization evidence and the active-instance fence. Cross-service effect participant replay/deduplication identity is separate and uses the mutation's persisted `EffectId` (root or generated child), typed operation, exact target aggregate, and immutable request digest; generated children retain their root `EffectId` for lineage and reconciliation. `playableStateScope`, `gameInstanceId`, and `effectKey` are projection/validation metadata, not participant uniqueness. Other service-local idempotency keys remain operation-specific. Explicitly instance-scoped S3 holders instead include `gameInstanceId` in durable identity. Future proto and OpenAPI surfaces must carry the same typed holder-reference union consistently, but current surfaces do not yet carry this complete operation context on every inventory/equipment read or mutation, so this is a target contract only: this ADR parcel does not add wire fields, regenerate protos, or change runtime lookup behavior. +The target inventory/equipment operation context for a durable holder or binding is `{tenantId, playableStateNamespaceId, playableStateScope, gameInstanceId, holderRef, itemInstanceId, itemDefinitionId, equipmentBindingId?, slotKey?}`, with one typed `holderRef` for each source, destination, or equipment owner required by the operation. A holder reference is a closed tagged union: character inventory or equipment carries `CHARACTER {characterId}`; NPC, pet, or summon ownership carries `ACTOR {actorId}`; an ordinary bag, chest, corpse, bank, vendor stock, or nested holder carries `CONTAINER {containerInstanceId}`; and room-ground storage carries `ROOM_GROUND {roomInstanceId, containerInstanceId}`. `characterId` is therefore required only for character-owned inventory or equipment and must not be fabricated for another holder kind. For namespace-backed S1/S2 inventory, character, and equipment state, durable storage identity is `{tenantId, playableStateNamespaceId, ...domainObjectId}` and omits both `playableStateScope` and `gameInstanceId`; those values are validated separately as immutable routing/authorization evidence and the active-instance fence. Cross-service effect participant replay/deduplication follows the owner-declared partition: S1/S2 uses `(tenantId, playableStateNamespaceId)`, while explicitly classified S3 uses `(tenantId, gameInstanceId)`. `requestDigest` is separately exact-validated conflict metadata, not a uniqueness dimension; for S1/S2, `playableStateScope` and active `gameInstanceId` are validation evidence rather than participant uniqueness. Other service-local idempotency keys remain operation-specific. Explicitly instance-scoped S3 holders include `gameInstanceId` in durable identity. Future proto and OpenAPI surfaces must carry the same typed holder-reference union consistently, but current surfaces do not yet carry this complete operation context on every inventory/equipment read or mutation, so this is a target contract only: this ADR parcel does not add wire fields, regenerate protos, or change runtime lookup behavior. See [Transaction Strategies](../../system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory) for the canonical participant-guard contract. This keeps the platform compatible with games that need unusual body plans or attachment models such as horns instead of hands, asymmetric limbs, species-specific slot topologies, or non-humanoid wearable layouts. diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index 676d374abe..140fc1ccc2 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -398,7 +398,7 @@ This section is the canonical source of truth for connect-token enforcement and - A hard Account or security revocation blocks new issuance for the revoked account or authority. A successful consume is terminal for that exact token `jti`. A deny-marker write becomes a confirmed terminal denial only after its configured same-connection `WAITAOF` acknowledgement succeeds; Gateway then never admits that `jti` again during its remaining acceptance window. Consuming one token does not prevent a later independently authorized issuance with a new request identity and `jti`. Gateway evaluates the token against its deployment-approved synchronized UTC epoch-millisecond wall clock: target future-`iat` tolerance permits acceptance no earlier than `iat - firemud.gateway.connectTokenClockSkewMs`, and target expiry tolerance permits acceptance no later than `exp + firemud.gateway.connectTokenClockSkewMs`. Therefore, when `exp - iat` is at the 30-second hard maximum, the complete possible acceptance interval is at most 30 seconds plus two configured skew intervals (40 seconds at the default 5-second skew); measured from the signed `iat` to the latest consume, the bound is 30 seconds plus one skew interval. An unavailable, timed-out, malformed, below-threshold, or otherwise ambiguous deny write is unconfirmed: the marker may have been written and Gateway must deny if it observes it, but the caller retains the bounded token-window outcome until the write is durably acknowledged or the token expires and must not report terminal no-grace revocation earlier. - Account owns two logically isolated, prefix-separated connect-token issuance-result families for idempotent `/auth/connect-token` retries: the current unversioned legacy `session:connect-token:tenant::account::scope::request:` map and the target `session:connect-token:v1:tenant::account::scope::request:` projection. **Current runtime:** the legacy value contains the raw issued token or deterministic cached failure. **Target state:** the target value carries `schemaVersion: "connect-token-issuance-result-v1"` and a bounded Account-encrypted response envelope containing the exact result, opened for an exact retry only after current authority and issuance state are reconciled; it is not JWT reconstruction or admission authority. Target readers never fall back to the legacy family. Because the legacy writer lacks an issuance fence, target enablement requires full Account-cohort quiescence, in-flight drain, and the configured legacy TTL/retry horizon. The full persistence contract is owned by [Account connect-token issuance persistence](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). Gateway alone owns the target replay-consumption, browser-revocation denial, and readiness/fence state in the Coordination Redis contract; an issuance-result projection, replay marker, deny marker, and readiness record never substitute for each other. - Replay and browser-revocation marker ownership is Gateway-only; downstream services do not participate in connect-token replay or browser-deny checks. - - Replay checks must be backed by the player-facing Coordination Redis deployment (not Cache/Rate-Limit Redis or per-pod memory) so `jti` replay decisions are consistent across horizontally scaled gateway pods and cannot be selectively evicted. The deployment requires Redis 7.2+ with AOF enabled, `noeviction`, replay-key ACL isolation, and admission-blocking capacity thresholds. The atomic marker script is followed by `WAITAOF requiredLocalAofCount requiredReplicaAofCount timeout`; `DURABLE_REPLAY_CONSUME_ACK` succeeds only when the reported AOF-fsync counts meet the configured thresholds, with at least one local AOF acknowledgement. The browser-deny write uses the same pinned Coordination connection and configured timeout/threshold after the write; its propagation remains in the default `redis.REPL_ALL` mode. An unavailable, timed-out, malformed, below-threshold, or otherwise ambiguous deny write is unconfirmed and cannot be reported as terminal revocation. `WAIT`, read-back, or a successful client write is not a substitute, and this contract does not claim protection from disk or hardware destruction. + - Replay checks must be backed by the player-facing Coordination Redis deployment (not Cache/Rate-Limit Redis or per-pod memory) so `jti` replay decisions are consistent across horizontally scaled gateway pods and cannot be selectively evicted. The deployment requires Redis 7.2+ with AOF enabled, `noeviction`, replay-key ACL isolation, and admission-blocking capacity thresholds. The atomic marker script is followed by `WAITAOF requiredLocalAofCount requiredReplicaAofCount timeout`; `DURABLE_REPLAY_CONSUME_ACK` succeeds only when the reported AOF-fsync counts meet the configured thresholds, with at least one local AOF acknowledgement. The browser-deny write uses the same pinned Coordination connection and configured timeout/threshold after the write; if a valid marker already exists, reassert it with its unchanged original absolute expiry before `WAITAOF`, or withhold the durable acknowledgement until the original write's durability is proven. Never extend its expiry; malformed or conflicting marker state stays non-mutating and fails closed. Its propagation remains in the default `redis.REPL_ALL` mode. An unavailable, timed-out, malformed, below-threshold, or otherwise ambiguous deny write is unconfirmed and cannot be reported as terminal revocation. `WAIT`, read-back, or a successful client write is not a substitute, and this contract does not claim protection from disk or hardware destruction. - Replay and browser-revocation state use the canonical target representation defined by the Redis ownership and recovery documents, with bounded cardinality and deterministic expiry at `exp + firemud.gateway.connectTokenClockSkewMs`. The readiness/fence record and marker state must remain one script-compatible Coordination Redis atomicity domain under that contract. The legacy representation emitted by the current writer is migration-only drift and cannot be treated as target state. - The replay and deny-marker prefixes are security-critical, non-evicting coordination state. Gateway's one consume script checks readiness state, signed fence/cutoff, and deny-marker absence before creating the replay marker; consumption is successful only after that script and the configured Redis 7.2+ `WAITAOF` acknowledgement both succeed. A deny marker that linearizes before or during the consume race returns a denial without creating the replay marker; a consume already linearized is spent and cannot be retroactively undone by a later browser logout. A browser revocation is confirmed only after its deny write and same-connection durability acknowledgement succeed; an uncertain deny write remains unconfirmed. Capacity or acknowledgement failure rejects the handshake rather than accepting an uncertain marker. A crash or connection loss between marker creation and acknowledgement is treated as uncertain consumption, not as an opportunity to unconsume or retry the token. - Coordination Redis cold start, reset, unexpected eviction signal, failover, capacity-safety breach, or any other event that cannot prove replay-marker continuity starts a shared replay-protection quarantine for at least the 30-second token lifetime maximum plus two `firemud.gateway.connectTokenClockSkewMs` intervals. One interval covers a latest tolerated future `iat`; the second covers acceptance through `exp + skew`. Account stops issuing connect tokens and Gateway rejects admission until that barrier expires, configuration and capacity checks pass, and a disposable marker script followed by the configured `WAITAOF` thresholds proves `DURABLE_REPLAY_CONSUME_ACK`; tokens from the earlier fence and issuance races cannot survive reopening. The current replay deployment has one shared continuity domain, so an unscoped continuity failure intentionally blocks new connect-token issuance and admission platform-wide; a future partitioned deployment may narrow quarantine only when it can prove the exact affected marker and fence domain. diff --git a/design/architecture/system-architecture-redis-cache-reference.md b/design/architecture/system-architecture-redis-cache-reference.md index 2033eb7243..6200a42e33 100644 --- a/design/architecture/system-architecture-redis-cache-reference.md +++ b/design/architecture/system-architecture-redis-cache-reference.md @@ -85,7 +85,7 @@ Cache/Rate-Limit Redis hosts prefixes that are not part of the coordination log | `ratelimit:::` | Cache / Rate-Limit | TTL-only (Class B) | Reset-tolerant | Spring Cloud Gateway and other edge/credential rate-limit buckets. Each individual subject has one opaque stable hash; no modulo collision pool or request-derived shard is used. Reset-induced heuristic shifts are acceptable, while hard authority remains outside evictable Redis. | | `ratelimit:` | Cache / Rate-Limit (current legacy; generic-client role unproved) | Legacy heuristic (not target Class B authority) | Reset-tolerant heuristic loss | Game Session's live `SessionRateLimiterImpl` command limiter. The current generic client may land on the wrong Redis role; the one-second counter/TTL is disposable and loss may relax or tighten heuristic limits. Cache-only writer registration and ACL proof do not make the legacy arity compatible with target helpers. Before any unversioned target `ratelimit:*` helper is enabled, stop the legacy writer, allow the maximum one-second TTL to elapse, and prove empty-key readback; an adopter that cannot prove that drain must use a distinct versioned prefix. | -The current `automation:queue:{tenantInstanceTag}:*` implementation is not yet TTL-only: its enqueue and rebuild paths append to Redis lists without `EXPIRE`, `LTRIM`, or another bound. Target adoption requires configuration-backed `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY` (exact values remain environment/service settings), applied atomically with every enqueue and rebuild. Truncation or expiry is acceptable only as pointer loss: Automation must re-drive from eligible durable PostgreSQL work-item rows, and reset/rebuild release requires every eligible durable identity to be rematerialized or durably settled. That release also requires the external, generation-bound Cache deployment maintenance gate to remain held through deletion, post-reset verification, and the authorized rebuild/readback; because the current gate and safe rebuild path are unavailable, queue reset/rebuild must fail closed. Until that policy and focused retention, memory-pressure, and rebuild proof exist, this is implementation/proof drift rather than a proven TTL-only cache. Separately, the live `tenantInstanceTag` builder concatenates raw nonblank IDs and has no proven delimiter/brace rejection or collision-safe encoding; it remains implementation drift until the shared encoded tuple or canonical UUID-boundary contract is enforced. +The current `automation:queue:{tenantInstanceTag}:*` implementation is not yet TTL-only: its enqueue and rebuild paths append to Redis lists without `EXPIRE`, `LTRIM`, or another bound. Target adoption requires configuration-backed `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY` (exact values remain environment/service settings), applied atomically with every enqueue and rebuild. Truncation or expiry is acceptable only as pointer loss: Automation must re-drive from eligible durable PostgreSQL work-item rows, and reset/rebuild release requires every eligible durable identity to be rematerialized or durably settled. That release also requires the external, generation-bound Cache deployment maintenance gate to remain held through deletion, post-reset verification, and the authorized rebuild/readback; because the current gate and safe rebuild path are unavailable, queue reset/rebuild must fail closed. Until that policy and focused retention, memory-pressure, and rebuild proof exist, this is implementation/proof drift rather than a proven TTL-only cache. Separately, the live `AutomationRedisKeys.tenantInstanceTag` concatenates raw IDs, and `requirePart` rejects only null or blank values; delimiter collisions and braces that alter Redis Cluster hash tags are not prevented. `AutomationQueueServiceImpl` passes persisted identity fields to the builder during enqueue and rebuild, and `AutomationQueuePublicationSupport` forwards rows without validating those fields. This remains implementation drift until the shared encoded tuple or canonical UUID-boundary contract is enforced at those paths. ### Canonical Social & Groups `chat:whisper` Class-B Contract diff --git a/design/architecture/system-architecture-redis-lua-patterns.md b/design/architecture/system-architecture-redis-lua-patterns.md index 902bd50d01..44f851a56e 100644 --- a/design/architecture/system-architecture-redis-lua-patterns.md +++ b/design/architecture/system-architecture-redis-lua-patterns.md @@ -47,7 +47,7 @@ Automation queue-pointer enqueue and rebuild are a separate Cache/Rate-Limit des The Gateway replay-consume descriptor is `gateway-connect-token-replay-consume/v1`: `redis_role=coordination`, `KEYS[1]=gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `KEYS[2]=gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, and `KEYS[3]=gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`. The descriptor must require the literal `{gateway-connect-token-replay-v1}` tag on every key, reject the untagged current-drift replay marker, and declare the stable outcomes `1` (marker created), `0` (already replayed), and `-1` (browser denied), with no mutation for `0` or `-1`. Focused contract tests must prove the three keys resolve to one Redis Cluster slot, reject any missing or different tag, preserve readiness/fence and deny-marker race ordering, and keep the same `KEYS` order under RESP2 and RESP3. Migration tests separately inventory/read back the current untagged replay prefix under quarantine and prove that it cannot be accepted by the target descriptor. -Browser revocation has a separate descriptor, `gateway-connect-token-browser-revoke/v1`, because its deny-marker mutation and durability acknowledgement are not the three-key replay-consume script contract. It uses `redis_role=coordination`, `KEYS[1]=gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and the token's absolute expiry (including the configured clock-skew allowance) as the bounded marker TTL. The idempotent write returns `1` when it creates the marker and `0` when the marker already exists; both outcomes identify the committed deny state, while malformed or conflicting state is non-mutating and fails closed. Gateway must immediately issue `WAITAOF requiredLocalAofCount requiredReplicaAofCount firemud.gateway.replayConsumeAckTimeoutMs` on the same pinned connection, with the same exact two-integer threshold validation as replay consumption; only that acknowledgement yields `DURABLE_BROWSER_REVOKE_ACK`. This descriptor must require the literal `{gateway-connect-token-replay-v1}` tag and must not be folded into, or represented as, the replay-consume descriptor's three-key invocation. The current implementation provides neither this deny-marker write nor its `WAITAOF` proof: it is replay-only, untagged, and Cache-bound migration drift. +Browser revocation has a separate descriptor, `gateway-connect-token-browser-revoke/v1`, because its deny-marker mutation and durability acknowledgement are not the three-key replay-consume script contract. It uses `redis_role=coordination`, `KEYS[1]=gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and the token's absolute expiry (including the configured clock-skew allowance) as the bounded marker TTL. A newly created marker may return `1`. An existing marker may return `0` only as an observation; it is not by itself proof on the current connection. Before `WAITAOF`, the existing-marker path must reassert the valid marker with its unchanged original absolute expiry on the same pinned connection, or withhold `DURABLE_BROWSER_REVOKE_ACK` until durability of the original write is proven. It must never extend the expiry. Malformed or conflicting marker state is non-mutating and fails closed. Gateway must immediately issue `WAITAOF requiredLocalAofCount requiredReplicaAofCount firemud.gateway.replayConsumeAckTimeoutMs` on the same pinned connection, with the same exact two-integer threshold validation as replay consumption; only that acknowledgement yields `DURABLE_BROWSER_REVOKE_ACK`. This descriptor must require the literal `{gateway-connect-token-replay-v1}` tag and must not be folded into, or represented as, the replay-consume descriptor's three-key invocation. The current implementation provides neither this deny-marker write nor its `WAITAOF` proof: it is replay-only, untagged, and Cache-bound migration drift. Entity-lock hard rule: each Redis tick Lua invocation may acquire at most one `tick:{tenantRegionTag}:lock:`. Piecemeal acquisition across invocations, a multi-lock whitelist, and a configurable multi-lock count are prohibited. A script fails closed when its declared or supplied key set would require more than one entity lock. Multi-entity invariants belong to an owning transaction or durable effect/workflow path, not Redis lock lifetime. See [ADR 0074](./decisions/adr-0074-one-entity-lock-per-redis-script.md). diff --git a/design/architecture/system-architecture-redis-usage-and-profiles.md b/design/architecture/system-architecture-redis-usage-and-profiles.md index db2342328c..2446b388df 100644 --- a/design/architecture/system-architecture-redis-usage-and-profiles.md +++ b/design/architecture/system-architecture-redis-usage-and-profiles.md @@ -139,7 +139,7 @@ Automation workloads split into two broad classes, with different expectations a - When work references a revocable component, the durable trigger/admission row and handoff payload retain the applicable component-revocation security-policy fence as independent parent evidence. It is included in the canonical handoff request digest and immutable readback/conflict comparison, revalidated through handoff, retry, replay, recovery, and final-effect boundaries, and excluded from Trigger Identity, Command-Handoff Identity, and their uniqueness keys; a changed or unavailable fence fails closed under the established disposition rather than minting a replacement identity. - Automation & Scripting creates or reuses a durable PostgreSQL trigger-instance / outbox row keyed by the applicable Trigger Identity branch. A schedule-derived pre-claim row uses `(tenantId, gameInstanceId, playableStateNamespaceId, stableOwnerKind, stableOwnerId, regionId, regionEpoch, entityId only when targetScopeType is entity-scoped, scriptId, eventType, eventSchemaVersion, scriptPatchVersion, scriptPinEpoch, isDryRun, scheduleDefinitionId, targetScopeType, targetScopeId, duePoint, triggerMode)`, plus `resumeWindowId` only when `triggerMode=CATCH_UP` and plugin identity `(pluginId, pluginVersionId, bindingId)` when applicable; `resumeWindowId` is absent otherwise. The paired `scriptPinControlPlaneRequestId` remains immutable owner evidence on the row and is exact-compared during admission, handoff, retry, replay, and recovery, but is excluded from uniqueness and derived `scriptEventId`. For plugin-owned schedules, the captured `pluginActivationEpoch` is an additional tagged dimension of due-candidate and firing-claim identity and therefore of the derived `scriptEventId`; the captured `lifecycleRevision` travels alongside as immutable non-identity lifecycle-fence evidence. Neither field is a per-command child-key dimension, and both are carried and revalidated through admission, handoff, retry, replay, and recovery per [Scripting Contracts §8](./system-architecture-scripting-contracts.md#8-plugin-version-fencing-and-control-plane-scope). The winning claim derives one immutable `scriptEventId`, and retries reuse it. An immediate event-driven row omits the scheduler-only fields and uses its generated stable `scriptEventId` to distinguish one event occurrence from another; its storage uniqueness branch must remain distinct from scheduled rows and includes the server-derived `sourceService` in its event-scope claim when the event is custom or service-specific. The immutable source Trigger Identity, including source `regionId` and `regionEpoch`, is retained on the row; current enqueue routing fields are separate. The complete per-command child handoff identity comprises the source runtime scope, optional distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`; it is stored separately from the parent Trigger Identity. The row also retains `cadence`, `unit`, `priorityTag`, `targetScopeType`, `targetScopeId`, binding priority/exclusivity, `scheduleSemanticsHash`, the pin operation's `controlPlaneRequestId`, owner/version metadata, due-point state, and `runtimeRegionId`/`runtimeRegionEpoch` when those fields apply, plus the captured plugin lifecycle pair when applicable. - Automation & Scripting then calls a Game Session gRPC/API contract such as `EnqueueAutomationCommandIfAbsent`, carrying the complete immutable Trigger Identity and child handoff identity: - - Parent Trigger/event-scope evidence: `tenantId`, `gameInstanceId`, `playableStateScope`, source `regionId`, source `regionEpoch`, `entityId` only for an entity-scoped trigger, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch`, paired `scriptPinControlPlaneRequestId`, `scriptEventId`, and `isDryRun`, plus applicable plugin identity `(pluginId, pluginVersionId, bindingId)`, captured `(pluginActivationEpoch, lifecycleRevision)` lifecycle-fence evidence, and the server-derived `sourceService` for custom or service-specific events. + - Parent Trigger Identity and separately carried evidence: `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, source `regionId`, source `regionEpoch`, `entityId` only for an entity-scoped trigger, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch`, `scriptEventId`, and `isDryRun`, plus applicable plugin identity `(pluginId, pluginVersionId, bindingId)` and the server-derived `sourceService` for custom or service-specific events. `playableStateScope`, paired `scriptPinControlPlaneRequestId`, and captured `lifecycleRevision` are separately carried and validated evidence; the owner request ID and `lifecycleRevision` are non-identity evidence. For plugin-owned schedules, `pluginActivationEpoch` retains its owner-defined candidate/firing-claim identity role. - Scheduled rows also carry `scheduleDefinitionId`, `targetScopeType`, `targetScopeId`, `triggerMode`, exactly one tagged `duePoint`: `dueTickId:` or `dueAt:`, and `resumeWindowId` only when `triggerMode=CATCH_UP`; immediate event-driven rows use the separate event branch, omit scheduler-only fields and `duePoint`, and carry a stable `scriptEventId`; their physical `dueTickId` and `dueAt` fields are both `NULL`. - Child handoff identity: complete source runtime scope, optional distinct target runtime scope, `automationDispatchId`, and `commandOrdinal`. `commandOrdinal` identifies the emitted command within the dispatch and is not replaced by `commandKind` or by `scriptEventId`. - Identity clarification: the source and target runtime scopes in the child handoff identity use `playableStateNamespaceId` and `targetPlayableStateNamespaceId` where applicable. `playableStateScope` and `targetPlayableStateScope` remain separately persisted, exact-validated policy/routing/authorization/migration-fence evidence and are excluded from child uniqueness. diff --git a/design/architecture/system-architecture-scripting-control-plane-operations.md b/design/architecture/system-architecture-scripting-control-plane-operations.md index cd28751d47..846c108843 100644 --- a/design/architecture/system-architecture-scripting-control-plane-operations.md +++ b/design/architecture/system-architecture-scripting-control-plane-operations.md @@ -259,7 +259,7 @@ Semantics: - `reason` is required and must be non-blank; Game Session validates it before reading the owned instance or purging queue or durable command state. - Idempotent. -- Under the shared queue mutation/tick lease, terminal-marks matching durable Game Session command rows before post-commit Redis queue/pending cleanup. `executionOutcome = LOST_BEFORE_STAGING` applies only to commands acknowledged `ACCEPTED_VOLATILE` whose ingress status is still `RECEIVED` or `ENQUEUED` and that have no surviving batch; `ACCEPTED_DURABLE` pre-batch work cannot use this outcome and remains under its durable retry/recovery contract. An explicitly retryable command with a durable prior tick-effect binding uses `executionOutcome = ABANDONED`. Both use `gameplayResult = NOT_APPLIED`, `failureCode = ROLLBACK_PURGED`, and the validated nonblank ingress `reason` as `failureMessage`. +- Under the shared queue mutation/tick lease, terminal-marks matching durable Game Session command rows before post-commit Redis queue/pending cleanup. `executionOutcome = LOST_BEFORE_STAGING` applies only to commands acknowledged `ACCEPTED_VOLATILE` whose ingress status is still `RECEIVED` or `ENQUEUED`, with no surviving durable batch, effect ledger, or source/effect claim, and only when an atomic owner-defined no-batch/version-fenced check wins; `ACCEPTED_DURABLE` pre-batch work cannot use this outcome and remains under its durable retry/recovery contract. An explicitly retryable command with a durable prior tick-effect binding may use `executionOutcome = ABANDONED` only when authoritative evidence proves that effect was unapplied and any already-declared applicable feature rule permits abandonment. A matching binding and `RETRY_QUEUED` status alone do not prove `NOT_APPLIED`; inconclusive work remains nonterminal and reconciliation-required, and this purge does not terminalize it. Any justified terminal mapping uses `gameplayResult = NOT_APPLIED`, `failureCode = ROLLBACK_PURGED`, and the validated nonblank ingress `reason` as `failureMessage`. - Batch-bound work that is not in the explicit retry queue is not purged through this hook; it requires effect-ledger remediation or rollback recovery because it has crossed the tick-batch boundary. - Emits an operator-visible metric for purge activity and for version-fence drops; exact metric names, labels, and increment units follow [Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix), while audit and handoff diagnostics follow the observability contract. diff --git a/design/architecture/system-architecture-scripting-dsl-for-designers.md b/design/architecture/system-architecture-scripting-dsl-for-designers.md index 715d031fdd..e5b83c1830 100644 --- a/design/architecture/system-architecture-scripting-dsl-for-designers.md +++ b/design/architecture/system-architecture-scripting-dsl-for-designers.md @@ -175,7 +175,7 @@ The platform performs **extensive validation** at design time and at publish tim - For **editor-time issues**, fix the graph based on validation errors in the Game Design Service UI and re-run validation before publishing. - For **runtime issues**, start from the script’s recent entries in `script_event_audit` and the associated metrics in `design/architecture/system-architecture-scripting-quotas-and-operations.md`, then adjust quotas or disable/throttle the script using the operational flows described there. - For **safe test runs**, the ADR 0114 command-plan preview endpoint is the target-state path for the Game Design / Logging & Admin UIs. Its current implementation boundary is summarized in [Implementation Status](#implementation-status). Once implemented, it will be a separate non-committing path that exercises the same sandbox and validation logic without live work or tick-queue handoff. Test tools are **privileged** and subject to their own rate limits and budgets so they cannot overload the scripting cluster; avoid running unbounded batches of previews against production tenants. - - When working with support or operators, use `scriptEventId` as a correlation ticket at the correct lifecycle layer after the applicable ingress has validated a supplied ID or allocated one, never by itself. A pre-resolution event-scope ticket or ingress-audit record carries the applicable fields available at that layer: `tenantId`, `eventType`, `eventSchemaVersion`, `isDryRun`, the exact `scriptPatchVersion`/`scriptPinEpoch` pair only after authoritative pin evidence is available, `scriptEventId` after the event-scope claim validates a supplied ID or allocates one, and, for gameplay/runtime events, `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, and `regionEpoch`; it also carries producer-derived `sourceService` where applicable. A fail-closed pre-admission audit retains any caller-supplied `scriptPatchVersion`/`scriptPinEpoch` only in explicitly marked unverified request-evidence fields on the existing ingress-audit surface, never as canonical ingress identity or exact pin evidence; it also retains a caller-supplied `scriptEventId` once the event-scope claim has validated it, including on a pre-handler denial. An unfired internally owned timer due candidate, including a `reload_failed` candidate, creates no `scriptEventId` and instead carries its event-scope `scheduleCandidateId`. The ticket does not invent ordinary handler-resolution fields. Owner-known exceptions are tenant-readiness `onLoad`, which includes its `scriptId`, and scheduler/timer candidates, which include schedule-owned `scriptId`, plugin provenance `(pluginId, pluginVersionId, bindingId)` when the durable schedule already owns that binding, and `pluginActivationEpoch` for plugin-owned candidate identity; `resumeWindowId` appears for `CATCH_UP` candidates, while captured `lifecycleRevision` travels as non-identity fence evidence. These are candidate/event identity fields, not resolved handler fields. After handler resolution, the ticket carries the complete applicable [Trigger Identity](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields), including `entityId` when entity-scoped and the resolved plugin/binding fields. Scheduler triggers additionally carry `triggerMode`, `scheduleDefinitionId`, `targetScopeType`/`targetScopeId`, plus exactly one applicable due point (`dueTickId` or `dueAt`). Tenant-readiness `onLoad` tickets explicitly omit `scriptPinEpoch`, `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `entityId` because they are pre-instance readiness work. Include command-level `outboxWorkItemId`, `automationDispatchId`, and `commandOrdinal` when a handoff child is in scope; those command-level fields are target-state until the Game Session handoff carries them end to end. + - When working with support or operators, use `scriptEventId` as a correlation ticket at the correct lifecycle layer after the applicable ingress has validated a supplied ID or allocated one, never by itself. A pre-resolution event-scope ticket or ingress-audit record carries the applicable fields available at that layer: `tenantId`, `eventType`, `eventSchemaVersion`, `isDryRun`, the exact `scriptPatchVersion`/`scriptPinEpoch` pair and paired `scriptPinControlPlaneRequestId` as non-identity owner evidence only after authoritative pin evidence is available, `scriptEventId` after the event-scope claim validates a supplied ID or allocates one, and, for gameplay/runtime events, `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, and `regionEpoch`; it also carries producer-derived `sourceService` where applicable. The owner request ID follows the paired evidence rule in [Scripting Contracts §3](./system-architecture-scripting-contracts.md#3-version-fencing-rollback-safety) and is not a third pin identity component. A fail-closed pre-admission audit retains any caller-supplied `scriptPatchVersion`/`scriptPinEpoch` only in explicitly marked unverified request-evidence fields on the existing ingress-audit surface, never as canonical ingress identity or exact pin evidence; it also retains a caller-supplied `scriptEventId` once the event-scope claim has validated it, including on a pre-handler denial. An unfired internally owned timer due candidate, including a `reload_failed` candidate, creates no `scriptEventId` and instead carries its event-scope `scheduleCandidateId`. The ticket does not invent ordinary handler-resolution fields. Owner-known exceptions are tenant-readiness `onLoad`, which includes its `scriptId`, and scheduler/timer candidates, which include schedule-owned `scriptId`, plugin provenance `(pluginId, pluginVersionId, bindingId)` when the durable schedule already owns that binding, and `pluginActivationEpoch` for plugin-owned candidate identity; `resumeWindowId` appears for `CATCH_UP` candidates, while captured `lifecycleRevision` travels as non-identity fence evidence. These are candidate/event identity fields, not resolved handler fields. After handler resolution, the ticket carries the complete applicable [Trigger Identity](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields), including `entityId` when entity-scoped and the resolved plugin/binding fields. Scheduler triggers additionally carry `triggerMode`, `scheduleDefinitionId`, `targetScopeType`/`targetScopeId`, plus exactly one applicable due point (`dueTickId` or `dueAt`). Tenant-readiness `onLoad` tickets explicitly omit `scriptPinEpoch`, `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, `regionEpoch`, and `entityId` because they are pre-instance readiness work. Include command-level `outboxWorkItemId`, `automationDispatchId`, and `commandOrdinal` when a handoff child is in scope; those command-level fields are target-state until the Game Session handoff carries them end to end. The Game Design and Logging & Admin audit/log views (for example `script_event_audit` queries and trace/log search) should support filtering by these fields so a single trigger can be followed end-to-end without ambiguity. Use the `AS-1.1` and `AS-1.5` entries in the [automation and scheduler runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status) to distinguish the live identity/read surfaces from target-state command-handoff coverage. For the detailed loop safety algorithm and runtime budget enforcement, see: diff --git a/design/architecture/system-architecture-scripting-operations-cookbook.md b/design/architecture/system-architecture-scripting-operations-cookbook.md index 6e1d676056..60950759fa 100644 --- a/design/architecture/system-architecture-scripting-operations-cookbook.md +++ b/design/architecture/system-architecture-scripting-operations-cookbook.md @@ -141,7 +141,7 @@ This section summarizes common failure and rollback scenarios and how operators In all of these cases, `script_event_audit` remains the primary source of truth for Automation-owned handler lifecycle. For the current live diagnostic boundary and target per-command identity contract, use [Command Identity and Live Handoff Boundary](./system-architecture-scripting-rollout-and-rollback.md#command-identity-and-live-handoff-boundary). Metrics defined by [normative Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix), together with audit and handoff diagnostics from the [Scripting & Automation Observability Contract](./system-architecture-scripting-observability-contract.md), indicate whether the problem is localized to a script/plugin, a tenant budget, or cluster capacity. -Target-state note: exact `scriptPinEpoch` propagation and final same-version old-epoch rejection are required at runtime-derived boundaries. The live `EnqueueAutomationCommandIfAbsentRequest` carries `scriptPatchVersion` but not `scriptPinEpoch`, so the current boundary cannot reject same-version work from an older epoch; this is an implementation gap, not a relaxation of the target fence. +Target-state note: exact `(scriptPatchVersion, scriptPinEpoch)` propagation and final same-version old-epoch rejection are required at runtime-derived boundaries. The request schema carries `scriptPinEpoch` and its paired owner request ID, but the authenticated Game Session receiver currently fails closed with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable` before command or queue mutation. Lower-level staging, replay, and final-execution code retains exact tuple checks where reached; this does not establish live receiver availability. Distinct-instance remote source/target tuple binding and remote final-effect fencing remain implementation gaps, not relaxations of the target fence. ## Rollback & Recovery Cookbook @@ -155,7 +155,7 @@ Game Session's committed exact pin and append-only rollout history are the sole For local diagnosis during a rollback: -The current runtime does not prove target-state drain recovery from lease age: unresolved `EVALUATING` work remains active and `PENDING_EVALUATION` remains pending; target cancellation treats `PENDING_EVALUATION` as cancelable pre-DSL work. These are pre-DSL states, not evaluated descriptor `PENDING` or `INDEXED` work. Keep the Automation admission barrier in place until exact pin convergence and schedule reconciliation succeed; do not wait for asynchronous cancel/purge cleanup. Cleanup remains bounded and non-blocking, while **target-state exact `(scriptPatchVersion, scriptPinEpoch)` fencing** remains authoritative. **Current live gap:** `EnqueueAutomationCommandIfAbsentRequest` carries `scriptPatchVersion` but not `scriptPinEpoch`, so the current handoff cannot reject same-version old-epoch work; do not infer target rejection as shipped. Ordinary gameplay ticks and player commands continue, except within a separately declared unfenced-effect workflow. Do not infer reclaim, terminalization, or safe resumption locally. +The current runtime does not prove target-state drain recovery from lease age: unresolved `EVALUATING` work remains active and `PENDING_EVALUATION` remains pending; target cancellation treats `PENDING_EVALUATION` as cancelable pre-DSL work. These are pre-DSL states, not evaluated descriptor `PENDING` or `INDEXED` work. Keep the Automation admission barrier in place until exact pin convergence and schedule reconciliation succeed; do not wait for asynchronous cancel/purge cleanup. Cleanup remains bounded and non-blocking, while **target-state exact `(scriptPatchVersion, scriptPinEpoch)` fencing** remains authoritative. **Current live boundary:** the request carries `scriptPinEpoch` and its paired owner request ID, but the authenticated Game Session receiver fails closed with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable` before command or queue mutation. Lower-level tuple checks remain narrower implementation behavior and do not establish receiver availability. Distinct-instance remote source/target tuple binding and remote final-effect fencing are separate implementation gaps. Ordinary gameplay ticks and player commands continue, except within a separately declared unfenced-effect workflow. Do not infer reclaim, terminalization, or safe resumption locally. For target-state admission containment during rollback, use the complete authoritative affected-scope enumeration from the durable PostgreSQL/runtime inventory described by the [Redis incident runbook](./system-architecture-redis-incident-runbook.md) to identify every regional scope and any actual unscoped/empty-region work. An omitted `regionId` is one exact unscoped row, never a wildcard; pause and read back each exact scope separately. Use the workflow-scoped `controlPlaneRequestId` with the explicit `PAUSED_FOR_ROLLBACK` step/target mode, reusing the same `(workflow ID, exact scope, step)` tuple only for an exact retry; the same workflow ID may span deliberate distinct scopes and the later `NORMAL` step. Missing enumeration or any exact-scope durable `APPLIED`/`ALREADY_APPLIED` acknowledgement/readback leaves the barrier in place, and no single omitted-region row authorizes an instance-wide success claim. The request-result and readback fields are owned by the [Scripting & Automation: Control Plane API](./system-architecture-scripting-control-plane-api.md#setautomationadmissionmode). The live `SetAutomationAdmissionMode`/`GetAutomationDrainStatus` surfaces do not yet provide that durable request-result acknowledgement or matching readback identity, so this per-scope sequence is not current recovery authorization; for a current incident, follow the [tick incident runbook's current-live containment branch](./system-architecture-tick-incident-runbook.md#stalled-tick-region) and its deployment-wide Automation fallback. @@ -200,7 +200,7 @@ Operator actions: - Automation admission should remain paused for the affected scope through repin and schedule reconciliation; **target-state cleanup** is asynchronous, bounded, and non-blocking and must not delay resumption. This is not a routine gameplay-tick pause. - **Target-state cleanup:** queued automation work items and staging entries that carry the displaced exact `(scriptPatchVersion, scriptPinEpoch)` tuple are drained/purged as bounded resource and diagnostic cleanup; cleanup completion is not the correctness barrier and must not be described as preventing execution after repin. - **Target-state cleanup:** if plugin versions are also being rolled back, disabled, or revoked, call `CancelPendingWorkItemsForPluginVersion(tenantId=11111111-1111-4111-8111-111111111111, gameInstanceId=44444444-4444-4444-8444-444444444444, pluginId=town-crier, pluginVersionId=town-crier-v22, pluginActivationEpoch=7, scriptPatchVersion=P22, scriptPinEpoch=41, workItemIds=[work-9,work-10], controlPlaneRequestId=RB-42-PLUGIN-01, actor=operator:alice, reason="rollback RB-42")` with a nonempty, unique batch of at most 100 parent IDs (and optional `regionId`) before queue purge. Callers group IDs by the exact tuple and repeat batches with new request IDs; an exact retry reuses the stored batch result. The operation covers all applicable bindings in that tuple; each bounded result retains its `workItemId` and `bindingId` evidence. `lifecycleRevision` is intentionally absent from this request example: it is not a selector or request-digest field, and is retained per row and in final-fence evidence for later revalidation beside `pluginActivationEpoch`. Cleanup remains asynchronous and non-blocking and is not the correctness barrier. - - **Target-state only:** before handoff, Automation validates and carries the exact `(pluginId, pluginVersionId, bindingId)`, captured `(pluginActivationEpoch, lifecycleRevision)` pair, and current lifecycle/publication/policy evidence for plugin work. That independent fence survives evaluation, persistence, handoff, replay, final execution, and dead-letter recovery. Same-epoch `DRAINING` permits only the immediately preceding `ENABLED` revision whose winning admission/fence compare-and-set durably committed before the transition; it does not admit new work. Game Session revalidates the exact script tuple and captured plugin lifecycle pair and rejects stale applicable plugin tuple or fence evidence at execution time, including same-version work from an older script epoch or plugin activation epoch. **Current live gap:** `EnqueueAutomationCommandIfAbsentRequest` carries `scriptPatchVersion` but lacks `scriptPinEpoch` and the complete plugin fence, so the current handoff cannot make those rejections; do not present them as shipped. + - **Target-state only:** before handoff, Automation validates and carries the exact `(pluginId, pluginVersionId, bindingId)`, captured `(pluginActivationEpoch, lifecycleRevision)` pair, and current lifecycle/publication/policy evidence for plugin work. That independent fence survives evaluation, persistence, handoff, replay, final execution, and dead-letter recovery. Same-epoch `DRAINING` permits only the immediately preceding `ENABLED` revision whose winning admission/fence compare-and-set durably committed before the transition; it does not admit new work. Game Session revalidates the exact script tuple and captured plugin lifecycle pair and rejects stale applicable plugin tuple or fence evidence at execution time, including same-version work from an older script epoch or plugin activation epoch. **Current live gap:** the request schema carries `scriptPinEpoch` and its paired owner request ID but not the complete plugin fence, and the authenticated receiver fails closed before queue or command mutation because its admission fence is unavailable. Do not present target execution rejection as shipped receiver behavior. - Use the [Command Identity and Live Handoff Boundary](./system-architecture-scripting-rollout-and-rollback.md#command-identity-and-live-handoff-boundary) contract. For current live incidents, correlate `script_event_audit`, the narrower Automation handoff rows, and the Game Session command/result/fence fields currently exposed; do not infer a complete Trigger Identity or downstream per-command disposition. 4. Repair and republish. - Fix the underlying script configuration in the Game Design Service and publish a new script-only patch version. diff --git a/design/architecture/system-architecture-scripting-quotas-and-operations.md b/design/architecture/system-architecture-scripting-quotas-and-operations.md index 48720005d3..15b7b9088f 100644 --- a/design/architecture/system-architecture-scripting-quotas-and-operations.md +++ b/design/architecture/system-architecture-scripting-quotas-and-operations.md @@ -267,7 +267,7 @@ The **target-state** canonical `script_event_audit` schema includes: For tenant-readiness `onLoad` triggers, `gameInstanceId`, `playableStateNamespaceId`, `playableStateScope`, `regionId`, `regionEpoch`, `entityId`, and `scriptPinEpoch` are omitted; they must not be populated with sentinel values. Their existing identity remains ``. Gameplay/runtime triggers require `scriptPinEpoch` with `scriptPatchVersion` and include the other fields when applicable according to the normative Trigger Identity table. -Current instance-scoped ingress validates the exact owner tuple before handler work is admitted, Automation persists that tuple on work-item and handoff-audit evidence, and the local Game Session handoff, durable staging/replay, and final execution boundaries revalidate it. The remaining downstream gap is distinct-instance remote source/target binding and remote final-effect fencing; see the [Automation & Scripting Service implementation status](./microservices/automation-scripting-service/runtime-and-data.md#implementation-status). +Current instance-scoped Automation ingress validates the exact owner tuple before handler work is admitted and persists it on work-item and handoff-audit evidence. Although `EnqueueAutomationCommandIfAbsentRequest` carries `scriptPinEpoch` and the paired owner request ID, the authenticated Game Session receiver currently fails closed with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable` before command or queue mutation; the live handoff is unavailable, not a missing-epoch-field path. Lower-level Game Session staging, replay, and final-execution checks retain exact tuple validation where reached. Distinct-instance remote source/target tuple binding and remote final-effect fencing remain implementation gaps; see the [Automation & Scripting Service implementation status](./microservices/automation-scripting-service/runtime-and-data.md#implementation-status) and [Game Session API implementation status](./microservices/game-session-service/api-contracts.md#implementation-status). - **Stage-aware outcome** - `finalStage` – the last stage reached for the trigger (for example `ADMISSION`, `DSL_EVAL`, `WORK_ITEM_PERSIST`, `TICK_HANDOFF`). diff --git a/design/architecture/system-architecture-tick-concepts-and-invariants.md b/design/architecture/system-architecture-tick-concepts-and-invariants.md index 92c423fc8d..276c3a9704 100644 --- a/design/architecture/system-architecture-tick-concepts-and-invariants.md +++ b/design/architecture/system-architecture-tick-concepts-and-invariants.md @@ -73,7 +73,7 @@ Lane fairness and the “one root actor action per eligible entity per tick” r Conceptually, domain services treat Redis locks and leases as **opaque tick-engine concerns**: handlers receive the mutation `EffectId` (root or persisted child), enclosing root lineage where applicable, typed operation, target aggregate, immutable request digest, and their own idempotency state. Ledger/guard/storage adapters may additionally expose the namespace-complete tick projection `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, region_epoch, tickId, effectKey, targetAggregateType, targetAggregateId)` for scope and ordering; `playableStateScope` is exact-validated evidence and the timeline coordinates are ordering metadata, not guard uniqueness. Handlers never read `tick:{tenantRegionTag}:lock:` or `tick-executor-lease:{tenantRegionTag}` to make application-level decisions, nor do they depend on Cache/Rate-Limit Redis keys (for example `inventory:*`, `view:*`, `ratelimit:*`) for correctness or ordering. Cache usage, when present, is encapsulated inside domain services and affects only latency, not the tick engine’s notion of “what happened” or “in which order”. - **Target-state automation identity:** Script-generated child dispatch persists the complete Command-Handoff Identity separately from the effect ledger/storage projection. The child identity is the complete source/target runtime scope plus `(automationDispatchId, commandOrdinal)`, as defined by the [normative Command-Handoff Identity table](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state). The complete applicable parent Trigger Identity, including `bindingId` when applicable, and `outboxWorkItemId` are retained for correlation only and are excluded from child uniqueness, deduplication, and replay selection. `scriptEventId` alone cannot distinguish fan-out commands. `effectKey` may encode the child pair only as deterministic descriptor/correlation metadata and scheduler tie-break metadata. It never replaces the root `EffectId`, typed operation, exact target aggregate, immutable request digest, sealed participant/manifest context, or digest-conflict enforcement. -- **Current-live fallback:** The Game Session handoff does not yet carry `commandOrdinal` or the full Trigger Identity. `TickStagingService` currently derives `effectKey` from `commandId`, falling back to a hash of command text plus the staging slot when no command id is available. This fallback is selection metadata only: durable tick batching rejects any queued entry without a `commandId` before staging or effect persistence. It is not the target-state automation identity and must not be documented as though `(automationDispatchId, commandOrdinal)` were enforced live. +- **Current live boundary:** The Game Session handoff does not yet carry `commandOrdinal` or the full Trigger Identity. `TickStagingService` derives `effectKey` from `commandId`; it retains a command-text-plus-slot helper branch, but `createBatchForTick` calls `requireDurableCommandIdentifiers` before selection and `commandSelections` repeats that guard before `effectKey` is called. That helper branch is unreachable for durable gameplay-command staging, not a live fallback. `effectKey` is not the target-state automation identity, and current behavior must not be documented as though `(automationDispatchId, commandOrdinal)` were enforced live. ### Coordination Exposure and Tick Replay Window diff --git a/design/architecture/system-architecture-tick-execution-flows.md b/design/architecture/system-architecture-tick-execution-flows.md index 8c6997569a..d451946b05 100644 --- a/design/architecture/system-architecture-tick-execution-flows.md +++ b/design/architecture/system-architecture-tick-execution-flows.md @@ -13,7 +13,7 @@ This document describes the target execution model. The current live runtime is - the durable owner/status surface is currently `{tenantId, gameInstanceId}`-scoped rather than true region-scoped; - `GetGameplayCommandStatus` is the canonical command-status API, but its live fields and state vocabulary are narrower than the accepted lifecycle described below; - the live batch/effect substrate exists with the current gameplay-command selected-work manifest on `tick_batch`, but timer/retry/remote-follow-up source-claim manifests, the target-state empty-cadence watermark path, cross-region result-return plumbing, and some richer command-status fields are still target-state follow-through. The current-live `ScheduleRequest`, `RemoteCommandCoordinator`, `RemoteFollowup`, and `RemoteFollowupResult` models/migrations omit `targetPlayableStateNamespaceId`, so the complete target-scope and request-digest equality contract below is not live or proven. The current-live runtime has no dedicated target-state empty-cadence status transition or `StreamTickHeartbeats` path. -- the live gameplay-command staging path still uses its current `commandId`/deterministic text-and-slot fallback when a complete authored handoff identity is unavailable. The target path is fail-closed: Game Session assigns the stable root `EffectId` before acknowledgement and rejects before acknowledgement when assignment fails. Target tick execution also rejects any missing or blank root `EffectId` before staging, ledger, or domain writes; a no-ID bypass is permitted only for an explicitly non-tick/control-plane path. If assignment fails after an `ACCEPTED_VOLATILE` acknowledgement, `LOST_BEFORE_STAGING` is limited to an eligible unbound `RECEIVED`/`ENQUEUED` command with no surviving batch; batch-bound or inconclusive work remains non-terminal/reconciliation-required and cannot become evidence-free `ABANDONED`. The target wording below is not a claim that the live fallback has already been removed from code. +- `createBatchForTick` calls `requireDurableCommandIdentifiers` before selection, and `commandSelections` repeats that guard before `effectKey` is called. The retained command-text-plus-slot `effectKey` branch is therefore an unreachable helper/legacy path, not a live gameplay-staging fallback. The target path is fail-closed: Game Session assigns the stable root `EffectId` before acknowledgement and rejects before acknowledgement when assignment fails. Target tick execution also rejects any missing or blank root `EffectId` before staging, ledger, or domain writes; a no-ID bypass is permitted only for an explicitly non-tick/control-plane path. If assignment fails after an `ACCEPTED_VOLATILE` acknowledgement, `LOST_BEFORE_STAGING` is limited to an eligible unbound `RECEIVED`/`ENQUEUED` command with no surviving batch; batch-bound or inconclusive work remains non-terminal/reconciliation-required and cannot become evidence-free `ABANDONED`. The current helper branch does not imply that the target root-identity contract is live. Naming convention: API, workflow, and EffectId prose uses `regionEpoch`. Snake-case forms such as `region_epoch`, `target_region_epoch`, and `due_tick_id` are reserved for explicitly identified SQL/storage fields, Redis payloads/keys, or schema examples. diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index db50a06402..7ae48c318a 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -52,7 +52,7 @@ The [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command- | --- | --- | --- | --- | | Acknowledgement (`ackLevel`) | `not implemented`: the live enqueue response exposes acceptance and `commandId`, but no canonical `ACCEPTED_VOLATILE`/`ACCEPTED_DURABLE` acknowledgement dimension is persisted or returned | `not proven`: no focused proof covers acknowledgement-level persistence or same-ID acknowledgement replay under [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) | `open`: add the durable field, status projection, ingress mapping, and focused retry/failover proof without adding a parallel status API | | Ingress (`ingressStatus`) | `partial`: the live command row uses progress values such as `ACCEPTED`, `STAGED`, `DRAINED`, and `RETRY_QUEUED` through `executionOutcome`; the canonical `RECEIVED`/`ENQUEUED`/`BOUND_TO_BATCH`/`TERMINAL` dimension is not yet separate | `partial`: current command-ingress, staging, and recovery tests prove the live progress paths, but not the canonical mapping required by [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) | `open`: persist and return `ingressStatus`, map legacy progress values, and prove reset/retry convergence | -| Execution outcome (`executionOutcome`) | `partial`: durable storage and status projection are live, including recovery outcomes; rollback purge uses `LOST_BEFORE_STAGING` before durable batch binding and `ABANDONED` only for an explicitly retryable command with a prior durable tick-effect binding, with `NOT_APPLIED` and a structured reason; complete canonical mapping across all terminal paths is not implemented | `partial`: [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java) and recovery tests cover current terminal updates and rollback purge scopes; complete [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) mapping across every terminal path is not yet proved | `open`: converge terminal vocabulary and prove every terminal path, including rollback purge, returns one durable outcome and reason | +| Execution outcome (`executionOutcome`) | `partial`: durable storage and status projection are live, including recovery outcomes; the current rollback-purge branch writes `ABANDONED`/`NOT_APPLIED` for an explicitly retryable command when it finds a durable prior tick-effect binding, but does not require authoritative evidence that the effect was unapplied; canonical evidence-qualified mapping across all terminal paths is not implemented | `partial`: [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java) and recovery tests cover current terminal updates and rollback purge scopes, but do not prove authoritative prior-effect outcome evidence or the complete [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) mapping | `open`: enforce evidence-qualified terminal outcomes and prove every terminal path, including rollback purge, returns one justified durable outcome and reason | | Gameplay result (`gameplayResult`) | `partial`: durable storage and status projection are live for current command and remote-result paths, but the canonical independent result vocabulary is not fully enforced across all terminal paths | `partial`: migrated effect and remote-runtime tests cover current success/failure/result propagation; a complete [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) proof for `SUCCESS`, `PARTIAL`, `FAILED`, `TIMEOUT`, and `NOT_APPLIED` is not recorded | `open`: retain this as a separate player/result-facing projection, add terminal mapping coverage, and prove it cannot be inferred solely from `executionOutcome` | ## Canonical Design Sources @@ -90,9 +90,9 @@ The current command lifecycle is explicit: `ACCEPTED` means durable identity exi | Command-id `(tenantId, gameInstanceId, commandId)` | `implemented` at the current durable ledger boundary; the canonical ADR 0016 status dimensions remain the `partial`/`not implemented` items classified above | `proven` for the current ledger read by [GameSessionControlPlaneGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java); the canonical dimensions remain only partially proved as classified above | | Automation-handoff `(tenantId, gameInstanceId, regionId, regionEpoch, automationDispatchId)` | `not implemented`: the proto carries the tuple and automation admission persists its identity, but the live status resolver still requires `command_id` and does not resolve this tuple | `not proven`: no focused `GetGameplayCommandStatus` proof establishes tuple lookup, tenant/scope validation, or status convergence through that identity | -Rollback queue purge controls cover script-patch and plugin-version scopes. Their ingress `reason` is required and non-blank. Enqueue and purge share renewable queue-mutation and tick leases; purge writes durable terminal state before post-commit Redis queue/pending cleanup, and tick staging discards stale payloads whose durable command is missing or no longer executable. The canonical [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) mapping uses `executionOutcome=LOST_BEFORE_STAGING` before durable batch binding and `executionOutcome=ABANDONED` only for an explicitly retryable command with a prior durable tick-effect binding. Both use `gameplayResult=NOT_APPLIED` and the required structured terminal-reason pair `failureCode=ROLLBACK_PURGED` plus `failureMessage=`, with `completedAt`. `GetGameplayCommandStatus` returns those durable fields. Focused unit proof covers both purge scopes, lock contention, commit-ordered cleanup, durable binding classification, and blank-reason rejection. Batch-bound work outside the explicit retry queue and already-applied work remain outside this purge path. +Rollback queue purge controls cover script-patch and plugin-version scopes. Their ingress `reason` is required and non-blank. Enqueue and purge share renewable queue-mutation and tick leases; purge writes durable terminal state before post-commit Redis queue/pending cleanup, and tick staging discards stale payloads whose durable command is missing or no longer executable. The target [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) mapping permits `executionOutcome=LOST_BEFORE_STAGING` only for `ACCEPTED_VOLATILE` work still in `RECEIVED` or `ENQUEUED`, with no surviving durable batch, effect ledger, or source/effect claim and a winning atomic owner-defined no-batch/version-fenced check; `ACCEPTED_DURABLE` pre-batch work remains under its durable retry/recovery contract. A retryable command with a prior durable tick-effect binding may use `executionOutcome=ABANDONED` only when authoritative evidence proves that effect was unapplied and any already-declared applicable feature rule permits abandonment. A matching binding and `RETRY_QUEUED` state alone are insufficient; inconclusive work remains nonterminal and reconciliation-required. Any justified terminal outcome uses `gameplayResult=NOT_APPLIED` and the structured terminal-reason pair `failureCode=ROLLBACK_PURGED` plus `failureMessage=`, with `completedAt`. `GetGameplayCommandStatus` returns those durable fields. Existing focused unit proof covers both purge scopes, lock contention, commit-ordered cleanup, current durable-binding classification, and blank-reason rejection, but does not prove the authoritative outcome evidence or no-batch fence required by the target contract. At target, batch-bound work outside the explicit retry queue and already-applied work must remain outside this purge path. -Current purge implementation/proof is narrower than the target mapping above: `TickQueueControlService.purgeCandidate` checks only `GameplayCommandRepository.hasDurableTickEffect(commandId)` and then classifies the row, rather than performing one atomic owner-defined CAS that proves no surviving batch, effect, or source claim. A concurrent staging, drain, or effect-claim race is therefore not excluded, and the focused purge tests do not establish the target no-batch/no-effect/no-source proof. The target contract remains unchanged; this is an implementation/proof gap and no code fix is claimed here. +Current purge implementation/proof is narrower than the target mapping above: `TickQueueControlService.purgeCandidate` checks only `GameplayCommandRepository.hasDurableTickEffect(commandId)` and then classifies the row. When a binding exists, `RETRY_QUEUED` is enough for the current code to write `ABANDONED`/`NOT_APPLIED`; it does not obtain authoritative evidence that the prior effect was unapplied. When no binding is found, the path also lacks one atomic owner-defined CAS proving no surviving batch, effect, or source claim. Concurrent staging, drain, or effect-claim races are therefore not excluded, and focused purge tests do not establish either target proof. The target contract remains unchanged; this is an implementation/proof gap and no runtime fix is claimed here. ### Scheduler and Queue Pressure diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index b47728f5d5..c58f6608c6 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -1845,6 +1845,23 @@ require_contains( "durable successful Set acknowledgement (`APPLIED` or `ALREADY_APPLIED`)", ], ) +require_contains( + "design/architecture/system-architecture-scripting-control-plane-operations.md", + [ + "no surviving durable batch, effect ledger, or source/effect claim", + "atomic owner-defined no-batch/version-fenced check wins", + "A matching binding and `RETRY_QUEUED` status alone do not prove `NOT_APPLIED`", + "inconclusive work remains nonterminal and reconciliation-required", + ], +) +require_contains( + "design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md", + [ + "does not require authoritative evidence that the effect was unapplied", + "`RETRY_QUEUED` is enough for the current code to write `ABANDONED`/`NOT_APPLIED`", + "no runtime fix is claimed here", + ], +) require_contains( "design/architecture/system-architecture-scripting-rollout-and-rollback.md", [ From dc25693a22bc470ab30add1230d0f56968797d11 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 13:47:05 +1300 Subject: [PATCH 45/68] docs(runtime): align charge, replay and recovery contract owners --- .../system-architecture-redis-lua-patterns.md | 2 +- .../architecture/system-architecture-redis-ops-access.md | 9 +++------ .../system-architecture-scripting-runtime-execution.md | 2 +- .../system-architecture-tick-failures-and-operations.md | 4 ++-- .../game-session-runtime-and-tick-coordination.md | 2 +- 5 files changed, 8 insertions(+), 11 deletions(-) diff --git a/design/architecture/system-architecture-redis-lua-patterns.md b/design/architecture/system-architecture-redis-lua-patterns.md index 44f851a56e..0d9dac1c17 100644 --- a/design/architecture/system-architecture-redis-lua-patterns.md +++ b/design/architecture/system-architecture-redis-lua-patterns.md @@ -45,7 +45,7 @@ The Lua Script Registry encodes these category→prefix→shard rules so that ca Automation queue-pointer enqueue and rebuild are a separate Cache/Rate-Limit descriptor boundary, not additions to the Coordination categories above. An atomic operation over `automation:queue:{tenantInstanceTag}:*` must declare `redis_role=cache`, use only queue keys for one exact `{tenantInstanceTag}` scope, and be authorized by `cache_app` for normal projection or by the target-only `automation_queue_rebuild_maint` ACL principal during an externally fenced reset/rebuild. The descriptor must carry the operation/fence, deployment generation, and exact prefix/scope admission fields described in the [Cache/Rate-Limit reset runbook](./system-architecture-redis-operations.md#external-cache-deployment-maintenance-gate); it must reject Coordination keys and `coord_app`, and its outcome must remain a best-effort pointer projection rather than durable-work authority. If the atomic enqueue/rebuild implementation uses single-key Redis commands instead of Lua, the same `redis_role`, key, slot, and ACL boundary still applies. These descriptors must be represented separately from the Coordination script categories in the ADR 0176 registry. -The Gateway replay-consume descriptor is `gateway-connect-token-replay-consume/v1`: `redis_role=coordination`, `KEYS[1]=gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `KEYS[2]=gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, and `KEYS[3]=gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`. The descriptor must require the literal `{gateway-connect-token-replay-v1}` tag on every key, reject the untagged current-drift replay marker, and declare the stable outcomes `1` (marker created), `0` (already replayed), and `-1` (browser denied), with no mutation for `0` or `-1`. Focused contract tests must prove the three keys resolve to one Redis Cluster slot, reject any missing or different tag, preserve readiness/fence and deny-marker race ordering, and keep the same `KEYS` order under RESP2 and RESP3. Migration tests separately inventory/read back the current untagged replay prefix under quarantine and prove that it cannot be accepted by the target descriptor. +The Gateway replay-consume descriptor is `gateway-connect-token-replay-consume/v1`: `redis_role=coordination`, `KEYS[1]=gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `KEYS[2]=gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, and `KEYS[3]=gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`. The descriptor must require the literal `{gateway-connect-token-replay-v1}` tag on every key, reject the untagged current-drift replay marker, and declare the stable outcomes `1` (marker created), `0` (already replayed), and `-1` (browser denied), with no mutation for `0` or `-1`. Focused contract tests must prove the three keys resolve to one Redis Cluster slot, reject any missing or different tag, preserve readiness/fence and deny-marker race ordering, and keep the same `KEYS` order under RESP2 and RESP3. Migration tests separately inventory/read back the current untagged replay prefix under quarantine and prove that it cannot be accepted by the target descriptor. Select and report implementation and runtime proof using [Validation and Runtime Proof](../developer-workflows/validation-and-runtime-proof.md). Browser revocation has a separate descriptor, `gateway-connect-token-browser-revoke/v1`, because its deny-marker mutation and durability acknowledgement are not the three-key replay-consume script contract. It uses `redis_role=coordination`, `KEYS[1]=gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and the token's absolute expiry (including the configured clock-skew allowance) as the bounded marker TTL. A newly created marker may return `1`. An existing marker may return `0` only as an observation; it is not by itself proof on the current connection. Before `WAITAOF`, the existing-marker path must reassert the valid marker with its unchanged original absolute expiry on the same pinned connection, or withhold `DURABLE_BROWSER_REVOKE_ACK` until durability of the original write is proven. It must never extend the expiry. Malformed or conflicting marker state is non-mutating and fails closed. Gateway must immediately issue `WAITAOF requiredLocalAofCount requiredReplicaAofCount firemud.gateway.replayConsumeAckTimeoutMs` on the same pinned connection, with the same exact two-integer threshold validation as replay consumption; only that acknowledgement yields `DURABLE_BROWSER_REVOKE_ACK`. This descriptor must require the literal `{gateway-connect-token-replay-v1}` tag and must not be folded into, or represented as, the replay-consume descriptor's three-key invocation. The current implementation provides neither this deny-marker write nor its `WAITAOF` proof: it is replay-only, untagged, and Cache-bound migration drift. diff --git a/design/architecture/system-architecture-redis-ops-access.md b/design/architecture/system-architecture-redis-ops-access.md index 582f2dd912..20cbb83a21 100644 --- a/design/architecture/system-architecture-redis-ops-access.md +++ b/design/architecture/system-architecture-redis-ops-access.md @@ -14,7 +14,7 @@ The target control-plane and maintenance contract in this document is ahead of t Use this doc as the canonical target-state contract for later reset/replay tooling, but do not assume every operation below is already available in the running codebase. Current operators, runbooks, Helm hooks, Jobs, and dashboards must not invoke the `coordination-maintenance` commands described below until that surface is implemented and end-to-end proven. -Current Gateway wiring is a frozen wrong-role exception: `GameplayHandshakeFilter` receives the generic reactive Redis template from the `spring.data.redis` binding, whose current profile uses `FIREMUD_REDIS_CACHE_HOST`, while writing only the untagged replay marker `gateway:connect-token:jti:*`. It has no current browser-deny, readiness, or replay-fence writer; those are target-only state. The replay prefix remains Coordination-owned in the target and must not be admitted as Cache state. A Cache reset inventory/readback that finds that prefix, or the generic Gateway writer, must abort without deletion. Target Gateway replay uses the named Coordination ACL and exact co-slotted keys `gateway:connect-token:{gatewayReplayDomain}:jti:*`, `gateway:connect-token:{gatewayReplayDomain}:deny:jti:*`, and `gateway:connect-token:{gatewayReplayDomain}:readiness`; migration requires quarantine, exact old replay-prefix inventory/readback, named Coordination client/ACL cutover, target-key readback, and same-connection `WAITAOF` proof before the current writer is drained and Cache reset admission can be considered safe. +Current Gateway wiring is a frozen wrong-role exception: `GameplayHandshakeFilter` receives the generic reactive Redis template from the `spring.data.redis` binding, whose current profile uses `FIREMUD_REDIS_CACHE_HOST`, while writing only the untagged replay marker `gateway:connect-token:jti:*`. It has no current browser-deny, readiness, or replay-fence writer; those are target-only state. The replay prefix remains Coordination-owned in the target and must not be admitted as Cache state. A Cache reset inventory/readback that finds that prefix, or the generic Gateway writer, must abort without deletion. Target Gateway replay uses the named Coordination ACL and exact co-slotted keys `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`; migration requires quarantine, exact old replay-prefix inventory/readback, named Coordination client/ACL cutover, target-key readback, and same-connection `WAITAOF` proof before the current writer is drained and Cache reset admission can be considered safe. ## Default Operator Surface @@ -91,12 +91,9 @@ Game Session's target dual-role wiring is explicit: `gamesession_coord_app` uses ## Configuration and Redis Role Selection -All tools and services refer to Redis deployments via **role-specific configuration**, not hard-coded URLs: +**Target role-specific configuration:** Coordination clients and ops tools read connection settings from `FIREMUD_REDIS_COORD_HOST` / `FIREMUD_REDIS_COORD_PORT` (or an equivalent `FIREMUD_REDIS_COORD_URL`), which identify the **Coordination Redis** deployment. Cache/rate-limit clients and tools read from `FIREMUD_REDIS_CACHE_HOST` / `FIREMUD_REDIS_CACHE_PORT` (or `FIREMUD_REDIS_CACHE_URL`), which identify the **Cache/Rate-Limit Redis** deployment. These describe the planned role-bound configuration, not current routing through typed role-specific clients. -- Coordination clients and ops tools read connection settings from `FIREMUD_REDIS_COORD_HOST` / `FIREMUD_REDIS_COORD_PORT` (or an equivalent `FIREMUD_REDIS_COORD_URL`), which identify the **Coordination Redis** deployment. -- Cache/rate-limit clients and tools read from `FIREMUD_REDIS_CACHE_HOST` / `FIREMUD_REDIS_CACHE_PORT` (or `FIREMUD_REDIS_CACHE_URL`), which identify the **Cache/Rate-Limit Redis** deployment. - -The current implemented Redis connection seam is the generic `firemud.redis.*` `RedisProperties` binding and `common-data-runtime` auto-configuration, which provides the injected Spring Redis connection factory/templates used by services. Deployment configuration supplies the role-specific endpoint routing through `FIREMUD_REDIS_COORD_*` and `FIREMUD_REDIS_CACHE_*`; this is not a current role-bound maintenance client or typed contract surface. The ADR 0176 shared foundation, owner-local descriptor contributions, and repository aggregation remain unimplemented. The following role-specific config types and factory methods are planned target-state examples only: they are not currently exposed by the repository and must not be presented as an available API. Target state may add a small shared configuration module in the existing split common modules or a dedicated tooling/contract module (for example, a future `common-redis-contracts` module, not an implemented module) exposing **role-specific typed configs and helpers** such as: +The current common Redis connection seam is `common-data-runtime`'s `DatabaseAutoConfiguration`: it reads the generic `firemud.redis.*` `RedisProperties` binding and creates its connection factory and templates from those properties only. It does not consume `FIREMUD_REDIS_COORD_*` or `FIREMUD_REDIS_CACHE_*` to select a Redis role or construct a role-bound client. The shared hosted profile routes the current generic endpoint to `redis-cache`; Gateway's `spring.data.redis` configuration is the separately documented Cache-bound exception. This is current generic endpoint wiring, not role-specific routing. The ADR 0176 shared foundation, owner-local descriptor contributions, and repository aggregation remain unimplemented. The following role-specific config types and factory methods are planned target-state examples only: they are not currently exposed by the repository and must not be presented as an available API. Target state may add a small shared configuration module in the existing split common modules or a dedicated tooling/contract module (for example, a future `common-redis-contracts` module, not an implemented module) exposing **role-specific typed configs and helpers** such as: - `RedisCoordConfig` + `createCoordinationRedisClient(...)` - `RedisCacheConfig` + `createCacheRedisClient(...)` diff --git a/design/architecture/system-architecture-scripting-runtime-execution.md b/design/architecture/system-architecture-scripting-runtime-execution.md index e6c998a015..29958a1b53 100644 --- a/design/architecture/system-architecture-scripting-runtime-execution.md +++ b/design/architecture/system-architecture-scripting-runtime-execution.md @@ -70,7 +70,7 @@ This section records current implementation boundaries, not target-state authori The current executor commits each per-item `PENDING_EVALUATION` to `EVALUATING` claim before running the DSL in a separate local transaction. After evaluation, each child’s `HANDOFF_IN_FLIGHT` intent commits before the Game Session RPC, which runs without an Automation transaction active; a definitive response is recorded in a separate guarded transaction. Failed pre-RPC intent persistence prevents dispatch, while ambiguous post-dispatch failure remains unresolved and is not reset for DSL replay. The durable evaluated-descriptor and reconciliation-owner layers needed for safe stage-aware recovery remain target-only. -The current runtime now includes a first durable pre-DSL trigger-record executor instead of stopping at ingress-only outbox materialization. During ingress, after handler resolution, Automation acquires per-script quota for live `STANDARD_RUNTIME` handlers before persisting `PENDING_EVALUATION` trigger records. The executor claims `PENDING_EVALUATION` rows without re-charging that per-script quota; it separately applies tenant-budget, publish-readiness, or isolated dry-run capacity controls as applicable before loading the persisted script definition, evaluating a current-boundary command-emission format, and handing emitted commands to Game Session through `EnqueueAutomationCommandIfAbsent`. The target full-Trigger-Identity admission and execution-start charge markers on the same durable pre-DSL trigger-record/work-item row remain unimplemented. The replay and evaluated-descriptor layers described by the target lifecycle are target-only. The current implementation still uses one `script_work_items` row spanning the pre-DSL trigger record and later handoff processing; it does not yet implement the target separation between durable trigger records and evaluated script work items or descriptor-only replay. +The current runtime now includes a first durable pre-DSL trigger-record executor instead of stopping at ingress-only outbox materialization. During ingress, after handler resolution, Automation acquires per-script quota for live `STANDARD_RUNTIME` handlers before persisting `PENDING_EVALUATION` trigger records. The executor claims `PENDING_EVALUATION` rows without re-charging that per-script quota; it separately applies tenant-budget, publish-readiness, or isolated dry-run capacity controls as applicable before loading the persisted script definition, evaluating a current-boundary command-emission format, and handing emitted commands to Game Session through `EnqueueAutomationCommandIfAbsent`. The target full-Trigger-Identity handler charge record is separate from the pre-DSL trigger-record/work-item row, is the sole authority for exactly-once admission and execution-start markers, and is linked from that row; this record and linkage remain unimplemented. The replay and evaluated-descriptor layers described by the target lifecycle are target-only. The current implementation still uses one `script_work_items` row spanning the pre-DSL trigger record and later handoff processing; it does not yet implement the target separation between durable trigger records and evaluated script work items or descriptor-only replay. ### Current evaluator boundary diff --git a/design/architecture/system-architecture-tick-failures-and-operations.md b/design/architecture/system-architecture-tick-failures-and-operations.md index 9fa6807910..a59228ee9b 100644 --- a/design/architecture/system-architecture-tick-failures-and-operations.md +++ b/design/architecture/system-architecture-tick-failures-and-operations.md @@ -14,9 +14,9 @@ This document describes the full target-state recovery and operator model. Curre - the live owner/status API is `GetRuntimeOwnershipStatus`, not yet a full region-scoped status surface; - the live fence token is opaque and compare-and-match based; - the live `tick_batch` / `tick_effect` ledger is real and now carries the current gameplay-command selected-work manifest on `tick_batch`, including current-boundary `enqueueSeq`, source metadata, and digest-checked replay reuse for surviving staged batches; live selected-work manifests do not yet preserve the required declared `phase`, `lane`, and `cost_class` metadata. The live `enqueueSeq` is allocated by one database-wide sequence; the region-scoped, cross-source allocator defined below is target-state. Timer/retry/remote-follow-up source-claim manifests, region-scoped replay controller breadth, and cross-region result-return semantics also remain target-state follow-through. -- the live gameplay-command staging path does not yet provide the complete target automation handoff identity: it derives `effectKey` from `commandId` and uses a deterministic text/slot fallback when no command ID is available. The target fail-closed contract below assigns the stable root `EffectId` before acknowledgement when possible and rejects before acknowledgement when assignment fails. If an already acknowledged `ACCEPTED_VOLATILE` command cannot receive that identity, `LOST_BEFORE_STAGING` remains limited to eligible `RECEIVED`/`ENQUEUED` work with no surviving batch; batch-bound or inconclusive work remains non-terminal/reconciliation-required and is never evidence-free `ABANDONED`. This document does not claim that target behavior is already live. +- The live gameplay-command staging path requires a present, nonblank durable `commandId` before Redis enqueue or durable batch staging, and malformed pre-existing entries fail closed before staging. `effectKey` is derived as `command:`; the retained text/slot helper fallback is unreachable through `createBatchForTick` and `commandSelections`, which require durable command identifiers before selection. This still does not provide the complete target Automation handoff identity. The accepted target path assigns a stable root `EffectId` before acknowledgement when possible, rejects before acknowledgement if assignment fails, and requires a persisted nonblank root before staging, ledger, or domain writes; an already acknowledged `ACCEPTED_VOLATILE` command that cannot receive that identity may become `LOST_BEFORE_STAGING` only when eligible in `RECEIVED`/`ENQUEUED` with no surviving batch. Batch-bound or inconclusive work remains non-terminal/reconciliation-required and is never evidence-free `ABANDONED`. The live staging checks do not prove that target root allocation or complete Automation identity. - The live rollback purge path is weaker than that target boundary: `TickQueueControlService.purgeCandidate` checks only `GameplayCommandRepository.hasDurableTickEffect(commandId)` before selecting `ABANDONED` versus `LOST_BEFORE_STAGING`. That non-atomic existence check does not prove the absence of a surviving batch, effect, or source claim, and it can race concurrent staging, drain, or effect ownership. The target atomic owner-defined CAS/no-batch proof remains unimplemented and unproved; this is a current implementation/proof gap, not a relaxation of the target `ACCEPTED_VOLATILE`/`RECEIVED`/`ENQUEUED` eligibility contract. -- Deterministic command-plan ordering, `planOrdinal`, and command-root allocation are proposal-only in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md), not current tick target state or proof obligations. The current `tickBatchId`/`effectKey` path does not prove any proposal-specific allocation behavior. +- The specific deterministic allocation mechanics and `planOrdinal` proposed in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) remain proposal-only, not current tick target requirements. They do not displace the accepted stable-root-before-acknowledgement and persisted nonblank-root-before-staging requirements above. The current `tickBatchId`/`effectKey` path does not prove any proposal-specific allocation behavior. - The accepted lane and fencing consequences are target-state requirements in this recovery model: selected-work manifests and replay records must preserve each item's declared `phase`, `lane`, and `cost_class`, while takeover reconciliation remains subject to the Redis lease plus durable executor-fence handshake owned by [Tick System and Runtime Design](./system-architecture-ticks.md). This document does not duplicate that owner protocol. Naming convention: API, workflow, and EffectId prose uses `regionEpoch`. Snake-case forms such as `region_epoch`, `last_region_epoch`, and `target_region_epoch` are reserved for explicitly identified SQL/storage fields, Redis payloads/keys, or schema examples. diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 7ae48c318a..e7ad594f81 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -90,7 +90,7 @@ The current command lifecycle is explicit: `ACCEPTED` means durable identity exi | Command-id `(tenantId, gameInstanceId, commandId)` | `implemented` at the current durable ledger boundary; the canonical ADR 0016 status dimensions remain the `partial`/`not implemented` items classified above | `proven` for the current ledger read by [GameSessionControlPlaneGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java); the canonical dimensions remain only partially proved as classified above | | Automation-handoff `(tenantId, gameInstanceId, regionId, regionEpoch, automationDispatchId)` | `not implemented`: the proto carries the tuple and automation admission persists its identity, but the live status resolver still requires `command_id` and does not resolve this tuple | `not proven`: no focused `GetGameplayCommandStatus` proof establishes tuple lookup, tenant/scope validation, or status convergence through that identity | -Rollback queue purge controls cover script-patch and plugin-version scopes. Their ingress `reason` is required and non-blank. Enqueue and purge share renewable queue-mutation and tick leases; purge writes durable terminal state before post-commit Redis queue/pending cleanup, and tick staging discards stale payloads whose durable command is missing or no longer executable. The target [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) mapping permits `executionOutcome=LOST_BEFORE_STAGING` only for `ACCEPTED_VOLATILE` work still in `RECEIVED` or `ENQUEUED`, with no surviving durable batch, effect ledger, or source/effect claim and a winning atomic owner-defined no-batch/version-fenced check; `ACCEPTED_DURABLE` pre-batch work remains under its durable retry/recovery contract. A retryable command with a prior durable tick-effect binding may use `executionOutcome=ABANDONED` only when authoritative evidence proves that effect was unapplied and any already-declared applicable feature rule permits abandonment. A matching binding and `RETRY_QUEUED` state alone are insufficient; inconclusive work remains nonterminal and reconciliation-required. Any justified terminal outcome uses `gameplayResult=NOT_APPLIED` and the structured terminal-reason pair `failureCode=ROLLBACK_PURGED` plus `failureMessage=`, with `completedAt`. `GetGameplayCommandStatus` returns those durable fields. Existing focused unit proof covers both purge scopes, lock contention, commit-ordered cleanup, current durable-binding classification, and blank-reason rejection, but does not prove the authoritative outcome evidence or no-batch fence required by the target contract. At target, batch-bound work outside the explicit retry queue and already-applied work must remain outside this purge path. +Rollback queue purge controls cover script-patch and plugin-version scopes. Their ingress `reason` is required and non-blank. Enqueue and purge share renewable queue-mutation and tick leases; purge writes durable terminal state before post-commit Redis queue/pending cleanup, and tick staging discards stale payloads whose durable command is missing or no longer executable. `GetGameplayCommandStatus` remains the existing status API for durable command state. Canonical purge eligibility and fencing are owned by [the queued-command purge contract](../../architecture/system-architecture-scripting-control-plane-operations.md#game-session-purge-queued-tick-commands-rollback-support); terminal status dimensions are owned by [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md). Existing focused unit proof covers both purge scopes, lock contention, commit-ordered cleanup, current durable-binding classification, and blank-reason rejection, but does not prove the authoritative outcome evidence or no-batch fence required by the target contract. Current purge implementation/proof is narrower than the target mapping above: `TickQueueControlService.purgeCandidate` checks only `GameplayCommandRepository.hasDurableTickEffect(commandId)` and then classifies the row. When a binding exists, `RETRY_QUEUED` is enough for the current code to write `ABANDONED`/`NOT_APPLIED`; it does not obtain authoritative evidence that the prior effect was unapplied. When no binding is found, the path also lacks one atomic owner-defined CAS proving no surviving batch, effect, or source claim. Concurrent staging, drain, or effect-claim races are therefore not excluded, and focused purge tests do not establish either target proof. The target contract remains unchanged; this is an implementation/proof gap and no runtime fix is claimed here. From d17e15a8a3304a54c43660e8cc3b0abd3798cf52 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 14:14:47 +1300 Subject: [PATCH 46/68] docs(runtime): align handoff identities and fenced action intent boundaries --- .../adr-0048-durable-idempotent-operator-write-execution.md | 2 +- .../system-architecture-redis-reset-and-recovery.md | 6 ++---- .../system-architecture-redis-usage-and-profiles.md | 2 +- .../system-architecture-scripting-examples-and-patterns.md | 2 +- ...stem-architecture-scripting-normative-contract-tables.md | 2 +- design/architecture/system-architecture-transactions.md | 4 ++-- 6 files changed, 8 insertions(+), 10 deletions(-) diff --git a/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md b/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md index 759316991f..7baa8ca3d6 100644 --- a/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md +++ b/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md @@ -129,7 +129,7 @@ Owner-side admission, feature-flag, and tick control RPCs are `internal_workload `/moderation/actions` and `ApplyModerationAction` are a Logging & Admin-owned policy-input/audit path, not a forwarded domain mutation. Account owns issuance of the Account authorization reference, and Logging & Admin validates and redeems it at the receiving boundary before the path can persist policy input and audit evidence. This path does not require or perform domain-owner redemption or enforcement. The separate live `EvaluateModerationPolicy` read remains input at the current Game Session and Social & Groups enforcement boundaries; Account enforces its account-wide categories from Account-owned state, while versioned propagation and domain enforcement remain target-state work. -Until its action-family schema, shared `mutationDigest/v1` vectors, Account issuance, and receiving-boundary validation/redemption are complete, this path remains unavailable/gated and these are target contract rules, not enablement. Once enabled, its durable intent uses the exact path request tuple: `policyIntentRequestId`, `mutationDigest`, action-family schema pair, typed scope/target/expected-version/mutation/audit-reason fields, and every schema-declared presence/absence value; any carried `controlPlaneRequestId` is correlation-only. Before Account issuance or receiving-boundary redemption, the exact `preAuthorizationReservationTuple/v1` and its claim fence are the idempotency identity; after Account returns, the unchanged authorization fingerprint, applicable authority evidence, and reservation fields are retained through receiving-boundary redemption and policy/audit persistence. An exact duplicate returns the stored lifecycle result without a second issuance, redemption, or policy write; any tuple, digest, schema, fingerprint, evidence, or claim mismatch returns `IDEMPOTENCY_CONFLICT` without mutation. The durable intent must exist before the first Account call; if it cannot be written, the path is not attempted. A successful receiving-boundary redemption is not by itself a committed policy outcome: policy-input and audit persistence must reach the durable terminal result. If persistence fails or the response is lost after redemption, the consumed reference is never redeemed again and no replacement reference is issued; the intent remains outcome-pending and a fenced recovery owner performs only an exact read-only lookup/reconciliation of the intent and policy/audit record until the stored result is known. No domain-owner execution phase, owner mutation, owner-result store, or owner-side `NOT_EXECUTED` proof is created for this path. +Until its action-family schema, shared `mutationDigest/v1` vectors, Account issuance, and receiving-boundary validation/redemption are complete, this path remains unavailable/gated and these are target contract rules, not enablement. Once enabled, the ADR 0048 orchestration reservation is keyed by stable `controlPlaneRequestId`, and duplicate/recovery lookup exact-compares its immutable `preAuthorizationReservationTuple/v1`. That tuple carries the moderation policy-intent identity `policyIntentRequestId`, `mutationDigest`, action-family schema pair, typed scope/target/expected-version/mutation/audit-reason fields, and every schema-declared presence/absence value. `policyIntentRequestId` remains the moderation-domain idempotency identity; any carried `controlPlaneRequestId` is correlation-only at that domain boundary. The reservation claim fence is transition authority for the current owner, not a fresh intent or duplicate identity: a stale owner/fence is rejected without mutation and is not collapsed into `IDEMPOTENCY_CONFLICT` for an otherwise unchanged request tuple. After Account returns, the exact stored `postAuthorizationExecutionTuple`, including the original authorization fingerprint, applicable authority evidence, and reservation fields, is retained through receiving-boundary redemption and policy/audit persistence; a refreshed claim fence may authorize a permitted transition but does not replace that stored tuple or create a new intent. An exact duplicate returns the stored lifecycle result without a second issuance, redemption, or policy write; an actual tuple, digest, schema, fingerprint, or evidence mismatch returns `IDEMPOTENCY_CONFLICT` without mutation. The durable intent must exist before the first Account call; if it cannot be written, the path is not attempted. A successful receiving-boundary redemption is not by itself a committed policy outcome: policy-input and audit persistence must reach the durable terminal result. If persistence fails or the response is lost after redemption, the consumed reference is never redeemed again and no replacement reference is issued; the intent remains outcome-pending and a fenced recovery owner performs only an exact read-only lookup/reconciliation of the intent and policy/audit record until the stored result is known. No domain-owner execution phase, owner mutation, owner-result store, or owner-side `NOT_EXECUTED` proof is created for this path. ### Redis-Backed Owner Mutations diff --git a/design/architecture/system-architecture-redis-reset-and-recovery.md b/design/architecture/system-architecture-redis-reset-and-recovery.md index 5796f37a7a..cd637c1d1c 100644 --- a/design/architecture/system-architecture-redis-reset-and-recovery.md +++ b/design/architecture/system-architecture-redis-reset-and-recovery.md @@ -42,10 +42,8 @@ Coordination Redis is treated as a **long‑lived, measured-exposure coordinatio - **Tenant‑scoped reset** – affects a single `tenantId`: - Clears the affected tenant-scoped gameplay coordination prefixes for all regions under one tenant. - - Preserves only `session:game:{tenantGameplayTag}::` records when operators explicitly choose `--preserve-sessions`; affected tenant-owned `session:game:index:*` projections are derived and may be dropped, but must reconcile before release. Untagged global account and issuer indexes are not narrow reset targets; replacement requires their complete owner-defined durable inventory, coverage proof, and exact readback before release. Pre-auth transport context is not covered by session preservation and is invalidated or rebuilt. - - Does not clear Account-owned `session:auth:token:` records, live legacy account/tenant auth projections, authority-generation projections, or target exact-input `session:connect-token:v1:*` issuance-result projections. Region- and tenant-scoped resets preserve these families because they are not region-scoped coordination state. The unversioned legacy `session:connect-token:*` map is only preserved and read back while present through its configured TTL/retry horizon, then owner-cleaned; if it is missing, changed, or untrusted, the affected handshake remains fenced and operators escalate. A missing or untrusted target `session:connect-token:v1:*` projection requires Account exact durable repair and readback before the affected operation can release. A tenant reset may terminate affected gameplay bindings, but it must not turn a tenant-region coordination reset into account-wide token revocation. - - Preserves only `session:game:{tenantGameplayTag}::` records when operators explicitly choose `--preserve-sessions`; the complete affected tenant-tagged character, account-tenant, tenant, and realm-grant `session:game:index:*` families may be dropped at this tenant scope, but must reconcile before release. A region-scoped reset instead reconciles only exact affected keys or members from durable inventory. Untagged global account and issuer indexes are not narrow reset targets; replacement requires their complete owner-defined durable inventory, coverage proof, and exact readback before release. Pre-auth transport context is not covered by session preservation and is invalidated or rebuilt. - - Does not clear Account-owned `session:auth:token:` records, live legacy account/tenant auth projections, target exact-input `session:connect-token:v1:*` issuance-result projections, or authority-generation projections. Region- and tenant-scoped resets preserve those records because they are not region-scoped coordination state. The unversioned legacy exact-input `session:connect-token:tenant::account::scope::request:` map is preserve/readback-only while present through its bounded TTL/retry horizon, then owner-cleaned; if it is missing, changed, or untrusted, the affected handshake remains fenced and requires escalation, never reconstruction, reminting, or repair as target authority. Target `session:connect-token:v1:*` projections are preserved by narrow resets and, if missing or untrusted, Account repairs and reads them back only from the exact durable issuance operation/encrypted envelope before the affected operation can release. A tenant reset may terminate affected gameplay bindings, but it must not turn a tenant-region coordination reset into account-wide token revocation or permit a live connect request to receive a different result on retry. + - Preserves only `session:game:{tenantGameplayTag}::` records when operators explicitly choose `--preserve-sessions`. At tenant scope, the complete affected tenant-tagged character, account-tenant, tenant, and realm-grant `session:game:index:*` families are derived and may be dropped, but must reconcile before release; a region-scoped reset instead updates or removes only exact affected keys or members from durable inventory. Untagged global account and issuer indexes are not narrow reset targets; any replacement requires their complete owner-defined durable inventory, coverage proof, and exact readback before release. Pre-auth transport context is not covered by session preservation and is invalidated or rebuilt. + - Region- and tenant-scoped resets preserve Account-owned `session:auth:token:` records, live legacy account/tenant auth projections, authority-generation projections, and target exact-input `session:connect-token:v1:*` issuance-result projections because these are not coordination-reset state. The unversioned legacy exact-input `session:connect-token:tenant::account::scope::request:` map is preserve/readback-only while present through its bounded TTL/retry horizon, then owner-cleaned; if it is missing, changed, or untrusted, the affected handshake remains fenced and requires escalation, never reconstruction, reminting, or repair as target authority. A missing or untrusted target `session:connect-token:v1:*` projection requires Account repair and exact readback only from the durable issuance operation/encrypted response envelope before the affected operation can release. A tenant reset may terminate affected gameplay bindings, but it must not turn a tenant-region coordination reset into account-wide token revocation or permit a live connect request to receive a different result on retry. - Often combined with an in‑game maintenance window or a revert/repin of tenant‑specific published content. - Used when: - A full in‑game reset is acceptable for a single tenant. diff --git a/design/architecture/system-architecture-redis-usage-and-profiles.md b/design/architecture/system-architecture-redis-usage-and-profiles.md index 2446b388df..75c592cc97 100644 --- a/design/architecture/system-architecture-redis-usage-and-profiles.md +++ b/design/architecture/system-architecture-redis-usage-and-profiles.md @@ -160,7 +160,7 @@ Automation workloads split into two broad classes, with different expectations a - Worked example: - A schedule for NPC `entityId=E1` becomes due at `(tenantId=7b3b074e-d597-4e9b-b96f-4f5946d26120, gameInstanceId=9a2bb6d1-74c7-4f81-a9e8-418e65f6ad78, playableStateNamespaceId=namespace-1, playableStateScope=shared, regionId=R1, regionEpoch=7, scriptPatchVersion=P3, scriptPinEpoch=4, scriptPinControlPlaneRequestId=pin-request-4, duePoint=dueTickId:420)`. - Automation & Scripting creates the canonical trigger claim for that due point and evaluates under the claim; before a winning evaluated-descriptor/outbox commit it has no dispatch or command-child identity. If evaluation emits one command, that first atomic commit allocates and persists `automationDispatchId=AD1` and `commandOrdinal=0`; a valid zero-command evaluation creates neither. The source trigger-claim row is unique on `(tenantId=7b3b074e-d597-4e9b-b96f-4f5946d26120, gameInstanceId=9a2bb6d1-74c7-4f81-a9e8-418e65f6ad78, playableStateNamespaceId=namespace-1, stableOwnerKind=SCRIPT, stableOwnerId=NPC_MOVE, regionId=R1, regionEpoch=7, entityId=E1, scriptId=NPC_MOVE, eventType=onInterval, eventSchemaVersion=v1, scriptPatchVersion=P3, scriptPinEpoch=4, isDryRun=false, scheduleDefinitionId=S1, targetScopeType=ENTITY, targetScopeId=E1, duePoint=dueTickId:420, triggerMode=CATCH_UP, resumeWindowId=RW1)`, plus any applicable plugin fields. `playableStateScope=shared` remains separately persisted and exact-validated policy/routing/authorization/migration-fence evidence, not a uniqueness dimension. Its `scriptPinControlPlaneRequestId=pin-request-4` remains persisted and exact-compared owner evidence on the candidate and claim, but is excluded from this uniqueness key and derived `scriptEventId`. This source trigger-claim projection is distinct from the Game Session durable admission projection, whose key is the complete child Command-Handoff Identity. The Game Session row retains the complete parent Trigger Identity and schedule projection, including the branch-specific target selector, due point, `resumeWindowId=RW1`, `cadence`, `unit`, `priorityTag`, `targetScopeType`, `targetScopeId`, binding priority/exclusivity, `scheduleSemanticsHash`, the pin operation's `controlPlaneRequestId`, owner/version metadata, due-point state, and `runtimeRegionId`/`runtimeRegionEpoch`, plus immutable `lane` and bounded `cost_class` metadata, as correlation and conflict/readback evidence. - - After that commit, it calls `EnqueueAutomationCommandIfAbsent` with the complete Trigger Identity, including `scriptPatchVersion=P3`, `scriptPinEpoch=4`, and `scriptPinControlPlaneRequestId=pin-request-4`, persisted `automationDispatchId=AD1`, `commandOrdinal=0`, scheduled candidate evidence `targetScopeType=ENTITY`, `targetScopeId=E1`, `triggerMode=CATCH_UP`, `resumeWindowId=RW1`, and `duePoint=dueTickId:420`, immutable `lane` and bounded `cost_class`, the target region timeline fields, and the deterministic command payload. A retry after the winning commit reuses `AD1` and its ordinal. + - After that commit, it calls `EnqueueAutomationCommandIfAbsent` with the complete Trigger Identity, including `scriptPatchVersion=P3` and `scriptPinEpoch=4`, alongside the persisted, exact-compared owner evidence `scriptPinControlPlaneRequestId=pin-request-4`; it also sends persisted `automationDispatchId=AD1`, `commandOrdinal=0`, scheduled candidate evidence `targetScopeType=ENTITY`, `targetScopeId=E1`, `triggerMode=CATCH_UP`, `resumeWindowId=RW1`, and `duePoint=dueTickId:420`, immutable `lane` and bounded `cost_class`, the target region timeline fields, and the deterministic command payload. A retry after the winning commit reuses `AD1` and its ordinal. - Game Session inserts or reads the durable admission row identified by the complete child Command-Handoff Identity: source runtime identity `(tenantId=7b3b074e-d597-4e9b-b96f-4f5946d26120, gameInstanceId=9a2bb6d1-74c7-4f81-a9e8-418e65f6ad78, playableStateNamespaceId=namespace-1, regionId=R1, regionEpoch=7)`, no distinct target scope, and `(automationDispatchId=AD1, commandOrdinal=0)`. The matching `playableStateScope=shared` is separately exact-validated evidence, excluded from uniqueness. It verifies the stored parent Trigger Identity and scheduled candidate evidence `targetScopeType=ENTITY`, `targetScopeId=E1`, `triggerMode=CATCH_UP`, `resumeWindowId=RW1`, and `duePoint=dueTickId:420` as immutable comparison evidence, validates the active lease, epoch, and due point for `R1`, maps the request to `tick:{tenantRegionTag}:queue:E1`, and returns `"ENQUEUED"` on the first successful materialization. - If the same trigger retries due to gRPC timeout with the same immutable Trigger and scheduled candidate evidence, including `targetScopeType=ENTITY`, `targetScopeId=E1`, `triggerMode=CATCH_UP`, `resumeWindowId=RW1`, and `duePoint=dueTickId:420`, Game Session sees the same durable admission row and returns a replay/no-op outcome instead of enqueuing a second command; a retry with a different due point or resume window is rejected as conflicting evidence under the same child identity. - If the region has already moved to `regionEpoch=8`, Game Session returns a stale-timeline outcome and Automation & Scripting re-derives what should happen next from the durable trigger-instance row instead of inferring state from Redis. diff --git a/design/architecture/system-architecture-scripting-examples-and-patterns.md b/design/architecture/system-architecture-scripting-examples-and-patterns.md index c527a1cc9d..fc238eb520 100644 --- a/design/architecture/system-architecture-scripting-examples-and-patterns.md +++ b/design/architecture/system-architecture-scripting-examples-and-patterns.md @@ -69,7 +69,7 @@ This example walks through how a typical `onEnterRegion` script executes end-to- - Scheduling follow-up timers (for example, delayed emotes or encounter escalation). 5. **Automation queue staging** - - The committed pre-DSL trigger is projected into `automation:queue:{tenantInstanceTag}:` only as a rebuildable pointer. Actions produced by the handler are evaluated within its one durable parent work item. Target evaluation atomically reaches `EVALUATED_COMMITTED` with one immutable command descriptor/child-dispatch row per emitted command, after which committed descriptor children are indexed into the queue; current implementation persists pre-DSL parent work and indexes only the derived parent pointer. + - The committed pre-DSL trigger is currently projected into `automation:queue:{tenantInstanceTag}:` as a derived parent-work pointer, but this current pointer is not rebuildable today, so queue reset/rebuild/resume remain unavailable and fail closed; see the [DSL Reference and Lifecycle implementation status](./system-architecture-scripting-dsl-reference-and-lifecycle.md#implementation-status). Actions produced by the handler are evaluated within its one durable parent work item. Target evaluation atomically reaches `EVALUATED_COMMITTED` with one immutable command descriptor/child-dispatch row per emitted command, after which committed descriptor children are indexed into the queue; current implementation persists pre-DSL parent work and indexes only the derived parent pointer. - Firing admission links the durable firing claim, one applicable resolved-handler audit row for every resolved handler, parent work items and queue-pointer projections only for handlers admitted by all handler-scoped gates (including quota), and due-point advancement in one atomic durable transition or a resumable idempotent recovery operation. Zero-handler firings create no handler audit, parent work item, or queue-pointer projection; handlers denied by a handler-scoped gate retain an audit row but create no parent work item or queue-pointer projection. Firing-claim and queue-link recovery completes missing links from the existing claim rather than re-evaluating the handler. - **Target-state only:** Each durable parent work item carries the originating `scriptEventId`, `scriptId`, `gameInstanceId`, `playableStateNamespaceId`, exact `scriptPatchVersion`/`scriptPinEpoch`, and region context. It retains `playableStateScope` separately as exact-validated policy/routing/authorization/migration-fence evidence, excluded from Trigger Identity, Command-Handoff Identity, uniqueness, and deduplication keys. The current instance-tagged queue pointer and `outboxWorkItemId`-only path do not establish namespace-complete identity or isolation. In the target handoff contract, each immutable emitted-command child is keyed by the complete source runtime scope plus any distinct target runtime scope, the persisted `automationDispatchId`, and deterministic `commandOrdinal` from canonical output order; both child identities are reused for every handoff, retry, and downstream disposition. The full parent Trigger Identity (including `bindingId` where applicable), `outboxWorkItemId`, and `scriptEventId` remain correlation only, while bounded `workItemIds[]` are parent-row selectors rather than child identities. The target `ListScriptHandoffEvents` child records are keyed by the complete Command-Handoff Identity, with `(automationDispatchId, commandOrdinal)` retained only as its dispatch-group suffix, and retain the full parent Trigger Identity while the handler audit remains one row. See [Implementation Status](#implementation-status) for the current live handoff boundary. diff --git a/design/architecture/system-architecture-scripting-normative-contract-tables.md b/design/architecture/system-architecture-scripting-normative-contract-tables.md index ab161e66d6..0786323b27 100644 --- a/design/architecture/system-architecture-scripting-normative-contract-tables.md +++ b/design/architecture/system-architecture-scripting-normative-contract-tables.md @@ -177,7 +177,7 @@ Notes: - If an implementation wants to treat some gameplay lifecycle events as “not tick-aligned”, it must define that exception explicitly in this table (not only in prose docs) and document why it is safe across scoped coordination resets. The default contract is that gameplay lifecycle triggers are fenced by `regionEpoch`. - Dry-run/test ingress must use a namespace separate from live ingress (`isDryRun=true`) regardless of whether `scriptEventId` is caller-generated or server-generated. -- Full Trigger Identity governs handler and Command-Handoff identity only. After the complete applicable Command-Handoff Identity is admitted/deduplicated and exact-maps to one durable target `commandId`, downstream authoritative service calls must use the mutation's persisted root-or-child `EffectId`, typed operation, exact target aggregate, and immutable request digest under `design/architecture/system-architecture-transactions.md`; a generated child uses its own persisted child identity while retaining the enclosing root only as lineage/reconciliation context. `scriptEventId`, `automationDispatchId`, and tick context remain correlation or admission metadata and cannot substitute for that mutation guard. +- Full Trigger Identity governs resolved-handler work only; it does not govern emitted-command child admission or deduplication. The complete applicable Command-Handoff Identity governs that child admission and deduplication. After it is admitted/deduplicated and exact-maps to one durable target `commandId`, downstream authoritative service calls must use the mutation's persisted root-or-child `EffectId`, typed operation, exact target aggregate, and immutable request digest under `design/architecture/system-architecture-transactions.md`; a generated child uses its own persisted child identity while retaining the enclosing root only as lineage/reconciliation context. `scriptEventId`, `automationDispatchId`, and tick context remain correlation or admission metadata and cannot substitute for that mutation guard. ## Table 1A: Event Ingress `scriptEventId` Ownership Matrix diff --git a/design/architecture/system-architecture-transactions.md b/design/architecture/system-architecture-transactions.md index 81edeff2e1..8e7eb97796 100644 --- a/design/architecture/system-architecture-transactions.md +++ b/design/architecture/system-architecture-transactions.md @@ -189,8 +189,8 @@ Required control-plane interfaces: - `RetryEffectReconciliation(tenantId, gameInstanceId, effectId, actionRequestId, actionDigest, expectedBacklogRevision, expectedStatus, authority: EffectReconciliationAuthority)` for explicit replay from `DEAD_LETTER` or stuck `PENDING`. - `AcknowledgeEffectDeadLetter(tenantId, gameInstanceId, effectId, reason, actionRequestId, actionDigest, expectedBacklogRevision, expectedStatus, authority: EffectReconciliationAuthority)` for audited operator decisions. It records the immutable acknowledgement evidence while leaving the row in `DEAD_LETTER` and the underlying effect outcome unchanged. - Logging & Admin dashboards should consume these APIs; operators should not mutate backlog tables directly. -- `actionRequestId` is stable for one requested control-plane action. Before any effect execution or external/authority call, the owner must persist a unique, digest-bound action-intent row keyed by the stable action-family request identity `(tenantId, gameInstanceId, effectId, actionRequestId)` with status `IN_PROGRESS`; `actionType` is an immutable tuple member, not a deduplication partition, and the existing identity must be loaded and compared before selecting the retry or acknowledgement branch. No action may execute without that intent. Reuse of the same request identity with a different action type or any other complete-tuple/digest difference fails closed as an identity conflict; it must not create a second intent row. `actionDigest` remains the API field name where useful and is the `mutationDigest/v1` value for the `effect-reconciliation-action/v1` action-family schema pair; it is not a competing `actionDigest/v1` digest owner. This family uses ADR 0047's exact seven top-level fields only: `scope` is the exact affected tenant/game/runtime scope; `target` is the effect identity plus exact target aggregate; `expectedVersion` is the expected backlog status and revision; `mutation` is the closed retry-or-ack action and its typed action inputs; and `auditReason` is the typed reason with explicit presence/value. `actionRequestId`, the opaque Account authorization reference, `EffectReconciliationAuthority` branch/reference/evidence, handoff/member evidence, actor/workload evidence, and reservation/fence fields remain excluded from the digest exactly as ADR 0047 requires and are separately exact-compared in the complete post-authorization/execution tuple. Absent and explicit `null` are distinct canonical values. The action-family mapping requires shared cross-language golden vectors, including absent/null cases, and explicit schema-version migration rules before any version change. -- Every `IN_PROGRESS` intent also records the current recovery owner/claim identity, a monotonic attempt fence, lease/deadline evidence, and the durable action identity used downstream. A successor may take over only through an owner-local CAS after lease expiry; stale owners and stale attempt fences are rejected before any backlog mutation or external call. The downstream owner or external operation must receive the stable action identity plus the current attempt fence, or an equivalent durable idempotency binding. For an owner-local backlog mutation, the action-intent row, backlog status/revision CAS, and final action result/outcome commit atomically in one owner-local transaction, so a successful local CAS cannot exist without the result persistence. Each intent has at most one terminal action result; a response is only a readback of that durable result. For an external or cross-service consequence, the action remains `IN_PROGRESS` until readback reconciliation against the exact effect guard, handoff and sealed member-manifest evidence, current backlog status/revision, and current attempt fence determines whether the consequence is applied, already applied, or still inconclusive. An ambiguous action must not be blindly reissued or assigned a new identity; the same `actionRequestId`/digest resumes reconciliation, while a changed digest fails closed as an identity conflict. Concurrent retry and acknowledgement actions serialize through the backlog CAS, rather than last-writer-wins behavior. +- `actionRequestId` is stable for one requested control-plane action. The unique, digest-bound action-intent row is keyed by the exact stable action-family request identity `(tenantId, gameInstanceId, effectId, actionRequestId)`; `actionType` is an immutable tuple member, not a deduplication partition, and the existing identity must be loaded and compared before selecting the retry or acknowledgement branch. For an owner-local backlog mutation, the intent row, backlog status/revision CAS, and final action result/outcome commit atomically in one owner-local transaction. For an external/authority or cross-service consequence, the owner must durably persist the intent with status `IN_PROGRESS` before the call. No action may execute without its intent. Reuse of the same request identity with a different action type or any other complete-tuple/digest difference fails closed as an identity conflict; it must not create a second intent row. `actionDigest` remains the API field name where useful and is the `mutationDigest/v1` value for the `effect-reconciliation-action/v1` action-family schema pair; it is not a competing `actionDigest/v1` digest owner. This family uses ADR 0047's exact seven top-level fields only: `scope` is the exact affected tenant/game/runtime scope; `target` is the effect identity plus exact target aggregate; `expectedVersion` is the expected backlog status and revision; `mutation` is the closed retry-or-ack action and its typed action inputs; and `auditReason` is the typed reason with explicit presence/value. `actionRequestId`, the opaque Account authorization reference, `EffectReconciliationAuthority` branch/reference/evidence, handoff/member evidence, actor/workload evidence, and reservation/fence fields remain excluded from the digest exactly as ADR 0047 requires and are separately exact-compared in the complete post-authorization/execution tuple. Absent and explicit `null` are distinct canonical values. The action-family mapping requires shared cross-language golden vectors, including absent/null cases, and explicit schema-version migration rules before any version change. +- Every `IN_PROGRESS` intent also records the current recovery owner/claim identity, a monotonic attempt fence, lease/deadline evidence, and the durable action identity used downstream. A successor may take over only through an owner-local CAS after lease expiry; stale owners and stale attempt fences are rejected before any backlog mutation or external call. The downstream owner or external operation must receive the stable action identity plus the current attempt fence, or an equivalent durable idempotency binding. Each intent has at most one terminal action result; a response is only a readback of that durable result. For an external/authority or cross-service consequence, the durable action remains `IN_PROGRESS` until readback reconciliation against the exact effect guard, handoff and sealed member-manifest evidence, current backlog status/revision, and current attempt fence determines whether the consequence is applied, already applied, or still inconclusive. An ambiguous action must not be blindly reissued or assigned a new identity; the same `actionRequestId`/digest resumes reconciliation, while a changed digest fails closed as an identity conflict. Concurrent retry and acknowledgement actions serialize through the backlog CAS, rather than last-writer-wins behavior. - The durable action ledger/result stores the digest, actor/time, expected state, CAS result, recovery claim/attempt fence, and returned outcome. Owner-local proof covers crash before the intent or before the atomic transaction commits, plus response loss after the committed result (which replays that result). Separately, external or cross-service proof covers a successful downstream CAS/consequence before local result persistence or a lost external response; recovery must reconcile the still-`IN_PROGRESS` intent from exact evidence. Lease expiry, takeover, stale-owner rejection, and all ambiguous cases must preserve the same action identity and either replay the committed result, reconcile the consequence, or remain safely inconclusive without a second action identity. `EffectReconciliationAuthority` is a typed union/reference carried by both mutating requests: From a5c91565ba01780ead8a9a4e4997a2e0874098b9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 14:50:43 +1300 Subject: [PATCH 47/68] docs: align scheduler identity and fail-closed admission proof --- design/architecture/system-architecture-redis-operations.md | 2 +- design/architecture/system-architecture-redis-ops-access.md | 2 +- .../system-architecture-scripting-runtime-execution.md | 4 ++-- .../system-architecture-scripting-scheduler-and-timers.md | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/design/architecture/system-architecture-redis-operations.md b/design/architecture/system-architecture-redis-operations.md index c8ade22025..657c8e7aeb 100644 --- a/design/architecture/system-architecture-redis-operations.md +++ b/design/architecture/system-architecture-redis-operations.md @@ -180,7 +180,7 @@ Goal: provide a simple, explicit runbook for resetting Cache/Rate-Limit Redis wi ### External Cache Deployment Maintenance Gate -The reset gate reuses the ADR-0085 external durable operation/fence pattern without making Cache/Rate-Limit Redis an authority. It is one durable operation outside the target deployment with an immutable `operationId`, exact environment/deployment identity and generation, a frozen complete registered writer and prefix inventory, and a durable external fencing token/generation. Before deletion, every ordinary writer must either pause and drain with an acknowledgement bound to that exact operation/fence or be denied Cache/Rate-Limit Redis connection/network admission. Writer admission and acknowledgements must revalidate the operation/fence and deployment generation after every restart or replacement; stale writers, stale operations, inventory changes, and missing, partial, or ambiguous evidence are rejected. Competing operations are serialized, and takeover, expiry, abort, and release each require durable evidence bound to the same operation/fence. A local Redis key is not the gate: the external gate must survive Redis and writer restarts and remain held through deletion, verification, and rebuild. Only the target-only named ACL principal `automation_queue_rebuild_maint`, bound to the same operation/fence, deployment generation, and exact registered `automation:queue:*` prefix/scope, may write while the gate is held; ordinary writers remain denied, and its completion/readback is required before release. This is not a generic cache or operator writer: any future non-Automation Cache/Rate-Limit rebuild, if needed, requires its own separately named owner principal and prefix contract. The current tooling does not yet provide this complete gate, writer acknowledgement/admission proof, or authorized rebuild path, so current operators must use the fallback above. +The reset gate reuses the ADR-0085 external durable operation/fence pattern without making Cache/Rate-Limit Redis an authority. It is one durable operation outside the target deployment with an immutable `operationId`, exact environment/deployment identity and generation, a frozen complete registered writer and prefix inventory, and a durable external fencing token/generation. Before deletion, every ordinary writer must either pause and drain with an acknowledgement bound to that exact operation/fence or be denied Cache/Rate-Limit Redis connection/network admission. Writer admission and acknowledgements must revalidate the operation/fence and deployment generation after every restart or replacement; stale writers, stale operations, inventory changes, and missing, partial, or ambiguous evidence are rejected. Competing operations are serialized, and takeover, expiry, abort, and release each require durable evidence bound to the same operation/fence. A local Redis key is not the gate: the external gate must survive Redis and writer restarts and remain held through deletion, verification, and rebuild. Only the target-only named ACL principal `automation_queue_rebuild_maint`, bound to the same operation/fence, deployment generation, and exact registered `automation:queue:*` prefix/scope, may write while the gate is held; ordinary writers remain denied, and its completion/readback is required before release. This narrow Automation rebuild writer is not privileged reset-deletion authority: Cache reset deletion separately requires actor/workload authorization for the exact complete registered prefix inventory, bound to the same operation/fence and deployment generation, plus deletion apply/readback proof under [Redis Ops Access](./system-architecture-redis-ops-access.md#canonical-control-plane-and-cli-contract). No shipped principal currently authorizes that complete inventory, so reset deletion remains unavailable and fail-closed. This is not a generic cache or operator writer: any future non-Automation Cache/Rate-Limit rebuild, if needed, requires its own separately named owner principal and prefix contract. The current tooling does not yet provide this complete gate, writer acknowledgement/admission proof, or authorized rebuild path, so current operators must use the fallback above. Cache/Rate-Limit Redis is fully reset-tolerant for the prefixes listed in [`system-architecture-redis-cache.md`](./system-architecture-redis-cache.md) and the reset policy matrix in [`system-architecture-redis-reset-and-recovery.md`](./system-architecture-redis-reset-and-recovery.md). A reset: diff --git a/design/architecture/system-architecture-redis-ops-access.md b/design/architecture/system-architecture-redis-ops-access.md index 20cbb83a21..9886e399bd 100644 --- a/design/architecture/system-architecture-redis-ops-access.md +++ b/design/architecture/system-architecture-redis-ops-access.md @@ -130,7 +130,7 @@ The target operator model interacts with coordination state through **supported To keep reset/replay behavior implementation-safe, the target maintenance/tooling surface is not left to per-runbook invention. Its initial public contract is deliberately small, whether eventually delivered as a CLI, an admin API, or both; it is not currently available for operator invocation: -This recovery contract is role-bound to Coordination Redis and to the exact scope advertised and proved by that runtime. It never targets Cache/Rate-Limit Redis. Cache or rate-limit clearing uses separate owner-supported tooling bound to the Cache/Rate-Limit deployment and an exact registered prefix inventory; it cannot accept coordination region, tenant, or cluster scope or invoke gameplay epoch, session, Account-projection, or replay recovery. Any future mutating cache reset must independently prove its actor/workload authorization, deployment and prefix scope, immutable evidence, cache-maintenance exclusion lock, and apply/readback postconditions before it is advertised. +This recovery contract is role-bound to Coordination Redis and to the exact scope advertised and proved by that runtime. It never targets Cache/Rate-Limit Redis. Cache or rate-limit clearing uses separate owner-supported tooling bound to the Cache/Rate-Limit deployment and an exact registered prefix inventory; it cannot accept coordination region, tenant, or cluster scope or invoke gameplay epoch, session, Account-projection, or replay recovery. An external durable operation/fence may authorize and serialize maintenance, but it does not grant Cache key-deletion authority: a mutating reset must separately authorize its actor/workload for the exact registered prefix inventory and bind that authorization to the same durable operation/fence and deployment generation, then prove deletion apply/readback. No shipped principal currently authorizes the complete Cache inventory, so this operation remains unavailable and fail-closed until that authorization and apply/readback proof exist. Any future mutating cache reset must also prove immutable evidence and the cache-maintenance exclusion lock before it is advertised. - `status(scope, operationId)` reports the canonical state, affected inventory, and recovery progress. - `recover(scope, sessionPolicy, mode)` starts the one public recovery/reset operation. Its protected issuance response returns the durable `operationId` and plaintext `maintenanceLockToken` only to the authenticated actor or workload principal authorized for and durably bound to that operation. That principal must retain the one-time plaintext token in protected custody, such as a permissioned token file, protected workload secret, or secret manager, because the controller stores only its digest and cannot reconstruct it after restart. Its canonical CLI mapping is `coordination-maintenance recover --mode --scope ...`: `mode` is `replay-first`, `reset`, or `session-schema-cleanup`; exactly one of `--preserve-sessions` or `--invalidate-sessions` is required where the mode supports session policy, and the choice is never inferred from scope. `scope` maps to `--scope` plus its scope arguments. Maintenance compatibility is derived from the selected mode and any durable migration, topology-change, restore, or exceptional-backup contract already bound to the operation; it is not a caller-selectable public flag. `--mode replay-first` maps to internal classification `replay_first` and persists `compatibilityClass=replay-first`; `--mode reset` maps to internal classification `reset_first` and persists `compatibilityClass=reset-first`; `--mode session-schema-cleanup` maps to internal and serialized `cleanup` (`compatibilityClass=cleanup`). Its internal pause-and-lock phase fences new work and acquires the maintenance lock; after the post-reset smoke check it remains fenced in `ready_to_reopen` until public continuation. diff --git a/design/architecture/system-architecture-scripting-runtime-execution.md b/design/architecture/system-architecture-scripting-runtime-execution.md index 29958a1b53..9f5839ffa3 100644 --- a/design/architecture/system-architecture-scripting-runtime-execution.md +++ b/design/architecture/system-architecture-scripting-runtime-execution.md @@ -82,9 +82,9 @@ The current claim boundary is the atomic PostgreSQL transition from `PENDING_EVA The current `onLoad` implementation slice is tenant-readiness work limited to configuration/runtime metadata validation and warming recomputable in-process caches. It does not perform per-entity setup or create handler-owned durable shared state. Platform-owned execution, readiness, and `script_event_audit` metadata remains required bookkeeping and is not a handler-created effect. The current implementation also lacks stale-`ONLOAD_RUNNING` generation recovery; that gap must not be handled by re-entering the same DSL execution. -At the live Game Session handoff boundary, the current `EnqueueAutomationCommandIfAbsentRequest` wire fields are exactly `tenant_id`, `game_instance_id`, `region_id`, `region_epoch`, `due_tick_id` (logically optional for immediate event-driven work), `automation_dispatch_id`, `automation_work_item_id`, `script_id`, `script_patch_version`, `target_entity_id`, `command`, `requires_solo_tick`, `plugin_id`, `plugin_version_id`, `playable_state_scope`, `world_slug`, `realm_slug`, `pointer_version`, `origin_source_kind`, `origin_source_state`, `origin_source_ordinal`, `origin_source_due_tick_id`, `origin_source_due_at_ms`, `binding_id`, `script_pin_epoch`, and `script_pin_control_plane_request_id`. Its response fields are exactly `accepted`, `admission_outcome`, `command_id`, and `error`. The current `playable_state_scope` is the source/current admitted routing scope, not a distinct target scope; `automation_work_item_id` is the wire alias for parent `outboxWorkItemId`. The request does not carry `command_ordinal`, `script_event_id`, `event_type`, `event_schema_version`, `is_dry_run`, `target_game_instance_id`, `target_playable_state_scope`, `target_region_id`, or `target_region_epoch`; those fields, the complete Trigger Identity, and the complete Command-Handoff Identity are target-only for this direct enqueue boundary. A command with a distinct target runtime scope must not be sent through this local enqueue mutation; if no existing remote follow-up path handles it, the local request rejects before its persistence/handoff attempt. The existing remote follow-up path remains separate and continues to carry its target scope. The supported source/current scope remains admitted. The current executor may attempt multiple emitted commands with local ordinals, but this narrower wire does not prove target per-command identity, deduplication, fencing, or independent progress. +At the live Game Session handoff boundary, the current `EnqueueAutomationCommandIfAbsentRequest` wire fields are exactly `tenant_id`, `game_instance_id`, `region_id`, `region_epoch`, `due_tick_id` (logically optional for immediate event-driven work), `automation_dispatch_id`, `automation_work_item_id`, `script_id`, `script_patch_version`, `target_entity_id`, `command`, `requires_solo_tick`, `plugin_id`, `plugin_version_id`, `playable_state_scope`, `world_slug`, `realm_slug`, `pointer_version`, `origin_source_kind`, `origin_source_state`, `origin_source_ordinal`, `origin_source_due_tick_id`, `origin_source_due_at_ms`, `binding_id`, `script_pin_epoch`, and `script_pin_control_plane_request_id`. Its response fields are exactly `accepted`, `admission_outcome`, `command_id`, and `error`. The current `playable_state_scope` is presented request evidence for the source/current routing scope, not proof of admitted scope; `automation_work_item_id` is the wire alias for parent `outboxWorkItemId`. The request does not carry `command_ordinal`, `script_event_id`, `event_type`, `event_schema_version`, `is_dry_run`, `target_game_instance_id`, `target_playable_state_scope`, `target_region_id`, or `target_region_epoch`; those fields, the complete Trigger Identity, and the complete Command-Handoff Identity are target-only for this direct enqueue boundary. A command with a distinct target runtime scope must not be sent through this local enqueue mutation; if no existing remote follow-up path handles it, the local request rejects before its persistence/handoff attempt. The authenticated enqueue RPC currently fails closed with `FAILED_PRECONDITION` (`automation_admission_receiver_fence_unavailable`) before command or queue mutation, so none of the request's scope fields establish successful admission through this receiver. The existing remote follow-up path remains separate and continues to carry its target scope. The current executor may attempt multiple emitted commands with local ordinals, but this narrower wire does not prove target per-command identity, deduplication, fencing, or independent progress. -The front exact ingress/timer tuple is live, with an important evidence distinction: an ingress claim records the caller's attempted `scriptPatchVersion`/`scriptPinEpoch`/`scriptPinControlPlaneRequestId` tuple, while an admitted instance-scoped trigger has that tuple validated against the authoritative Game Session read before handler work is created. A rejected pre-admission request, including an unavailable or mismatched authority result, may retain its attempted tuple as request evidence but must not be presented as an authoritative observation; the request ID is required whenever `scriptPinEpoch` is positive and is absent for both the unpinned `scriptPinEpoch=0` branch and the pre-instance tenant-readiness `onLoad` identity. For local instance-scoped Automation commands, Game Session compares that complete tuple with the current `GameInstance` before accepting or replaying a duplicate, locks and rechecks it while sealing fresh or replayed tick work, and rechecks the persisted tuple at final execution. The remote command handoff wire carries source `scriptPatchVersion`/`scriptPinEpoch`/`scriptPinControlPlaneRequestId` evidence, but its receiver does not yet persist or enforce the complete source/target tuple at admission and final effect; that remote boundary must not be presented as complete target enforcement. +The front exact ingress/timer tuple is live, with an important evidence distinction: an ingress claim records the caller's attempted `scriptPatchVersion`/`scriptPinEpoch`/`scriptPinControlPlaneRequestId` tuple, while an admitted instance-scoped trigger has that tuple validated against the authoritative Game Session read before handler work is created. A rejected pre-admission request, including an unavailable or mismatched authority result, may retain its attempted tuple as request evidence but must not be presented as an authoritative observation; the request ID is required whenever `scriptPinEpoch` is positive and is absent for both the unpinned `scriptPinEpoch=0` branch and the pre-instance tenant-readiness `onLoad` identity. Existing lower-level local instance-scoped command checks compare that complete tuple with the current `GameInstance` before acceptance or duplicate replay, recheck it while sealing fresh or replayed tick work, and recheck the persisted tuple at final execution where those paths are reached; they do not establish successful admission through the currently fail-closed authenticated enqueue RPC. The remote command handoff wire carries source `scriptPatchVersion`/`scriptPinEpoch`/`scriptPinControlPlaneRequestId` evidence, but its receiver does not yet persist or enforce the complete source/target tuple at admission and final effect; that remote boundary must not be presented as complete target enforcement. Target local instance admission and replay use Automation's bounded-fresh exact `(scriptPatchVersion, scriptPinEpoch, scriptPinControlPlaneRequestId)` projection; when it is absent or stale, Automation performs a bounded refresh from an owner-evidence-carrying authoritative Game Session read and fails closed if that refresh cannot prove the tuple. Direct Game Session reads remain the owner/final-fence source and are used to freeze a remote target tuple; neither path permits a patch-only local pointer or version-only fallback. See [ADR 0108](./decisions/adr-0108-no-degraded-script-admission-without-authoritative-pin.md) and the [cross-service version-fencing contract](./system-architecture-scripting-contracts.md#3-version-fencing-rollback-safety). diff --git a/design/architecture/system-architecture-scripting-scheduler-and-timers.md b/design/architecture/system-architecture-scripting-scheduler-and-timers.md index acb5845b23..6a73a1e327 100644 --- a/design/architecture/system-architecture-scripting-scheduler-and-timers.md +++ b/design/architecture/system-architecture-scripting-scheduler-and-timers.md @@ -1,6 +1,6 @@ # FireMUD System Architecture: Scripting Scheduler and Timer Lifecycle -This document defines the runtime scheduler, timer, and reload lifecycle for scripting and automation. It complements [Scripting DSL Reference & Event Lifecycle](./system-architecture-scripting-dsl-reference-and-lifecycle.md), which remains the canonical owner for DSL semantics, trigger identity, event fan-out, and determinism rules. +This document defines the runtime scheduler, timer, and reload lifecycle for scripting and automation. It complements [Scripting DSL Reference & Event Lifecycle](./system-architecture-scripting-dsl-reference-and-lifecycle.md), which remains the canonical owner for DSL semantics, trigger identity, event fan-out, and determinism rules. Documentation validation and proof selection follow the shared [Validation and Runtime Proof](../developer-workflows/validation-and-runtime-proof.md) workflow. Schedule transition semantics are owned here under [ADR 0110](./decisions/adr-0110-explicit-opt-in-schedule-continuity-across-script-transitions.md). The exact Game Session pin/epoch fence and no-routine-gameplay-pause rollback boundary remain owned by [Scripting & Automation: Rollout and Rollback](./system-architecture-scripting-rollout-and-rollback.md) and [ADR 0106](./decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md). Clocks and recovery remain linked to existing [ADR 0091](./decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md), not duplicated here. @@ -67,7 +67,7 @@ Every authored timer declares both its clock unit and recovery class. Tick/game - Tenant-local catch-up selection is not shared scheduler admission. A selected candidate still passes through ADR 0166 tenant-first scheduling and the applicable tenant and cluster ceilings. Capacity denial there terminally skips that due candidate within the same `resumeWindowId`: a tenant-ceiling denial records candidate-audit `finalStage=ADMISSION`, `finalOutcome=tenant_budget_exceeded`, and `finalReason=tenant_budget_exceeded`; a cluster-ceiling denial records candidate-audit `finalStage=ADMISSION`, `finalOutcome=quota_denied`, and `finalReason=cluster_limit_reached`. Either denial consumes its deterministic catch-up selection slot, creates no firing claim, handler Trigger Identity, or `scriptEventId`, and is not deferred, retried, backfilled, or reminted as catch-up. The terminal candidate audit, advance of the recurring schedule's canonical due state to its next ordinary future occurrence, and resume-window denial outcome are one atomic owner transaction; when one storage transaction is unavailable, a resumable idempotent reconciliation keyed by `(scheduleCandidateId, resumeWindowId)` must complete all three before the denial is settled or the window can complete. A partial or crashed denial therefore remains fenced and cannot be rediscovered from the unchanged overdue due point. That durable denial counts toward resume-window completion and does not suppress the schedule's next ordinary future occurrence. For live candidates (`isDryRun=false`), emit `automation_script_skips_total` with `scope="tenant"` and `reason="tenant_budget_exceeded"` for a tenant-ceiling denial, or `automation_script_skips_total` with `scope="cluster"` and `reason="cluster_limit_reached"` for a cluster-ceiling denial, using every other required bounded label from [normative Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix). For dry-run/test candidates (`isDryRun=true`), neither live-only family is emitted: no dedicated test-only candidate-ceiling metric is currently defined, so the settled candidate audit and mode-specific resume-window outcome are the complete observability surface. The handler-scoped test families are not used because the denial occurs before handler materialization. These candidate-level outcomes do not invoke `ScriptTenantBudgetService` or increment `automation_script_tenant_budget_denied_total`; do not increment the catch-up-truncation family for either shared-admission denial. Retryable authority, reload, or reconciliation fences remain governed by the separate nonterminal candidate lifecycle below and are not capacity denials. - After a due candidate passes admission, and before enqueueing that firing, the scheduler must claim or insert a durable trigger-instance row keyed by an instance-aware uniqueness projection. For `triggerMode=CATCH_UP`, the firing claim uniqueness and comparison include `resumeWindowId`, and the candidate-audit record carries the same ID, so failover or duplicate consumers cannot create duplicate logical triggers or consume a later window's cap. - - The projection must define the event-scope due-candidate identity, including `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, mandatory `stableOwnerKind` and `stableOwnerId`, `regionId`, `regionEpoch`, `eventType`, `eventSchemaVersion`, the exact `scriptPatchVersion` and `scriptPinEpoch`, `isDryRun`, `scheduleDefinitionId`, the persisted due point (`dueTickId` or `dueAt`), and `triggerMode`; include `entityId` only when the schedule target scope is entity-scoped, and `resumeWindowId` for catch-up claims. Each durable row, candidate, claim, and candidate audit also retains and revalidates the server-derived `playableStateScope` as immutable separately persisted policy/routing/authorization/migration-fence evidence; it does not participate in `scheduleCandidateId`, firing-claim, `scriptEventId`, Trigger Identity, or Command-Handoff Identity derivation. A core-script schedule must carry its durable `scriptId`; a plugin-owned schedule must carry `pluginId`, `pluginVersionId`, its schedule-owned `bindingId`, and the captured `(pluginActivationEpoch, lifecycleRevision)` pair. `pluginActivationEpoch` is the tagged candidate/firing-claim field; `lifecycleRevision` is required non-identity fence evidence. Core-script candidates omit both plugin lifecycle fields. Missing applicable namespace, durable owner, provenance, or either plugin lifecycle field, or namespace/scope evidence that mismatches the authoritative namespace, scope, and active-instance/region binding, rejects the candidate before deriving `scheduleCandidateId`, the firing claim, or `scriptEventId`; a legacy or corrupt row missing any applicable required field is not a candidate: record one deterministic non-candidate schedule-reconciliation outcome keyed by the existing durable `scheduleInstanceId` (the immutable physical row-generation reference, not the logical schedule/event identity) plus the originating `controlPlaneRequestId` from its pin operation or Automation runtime transition, with bounded missing-field reason codes; quarantine or tombstone it, create no `scheduleCandidateId`, `scriptEventId`, ingress audit, firing claim, or handler audit, and never replay it. A handler-only binding field not present on the schedule remains absent until handler resolution. The firing claim derives one event-scope `scriptEventId` from this complete due-candidate identity and propagates that ID unchanged into every resolved handler's full Trigger Identity. Globally unique schedule IDs do not replace runtime scope, exact pin tuple, explicit `isDryRun`, or timeline fencing. + - The projection must define the event-scope due-candidate identity, including `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, mandatory `stableOwnerKind` and `stableOwnerId`, `regionId`, `regionEpoch`, `eventType`, `eventSchemaVersion`, the exact `scriptPatchVersion` and `scriptPinEpoch`, `isDryRun`, `scheduleDefinitionId`, the target selector (`targetScopeType` and `targetScopeId` for `ENTITY`, `REGION`, or `GLOBAL` targets), the persisted due point (`dueTickId` or `dueAt`), and `triggerMode`; include `entityId` only when `targetScopeType=ENTITY`, and `resumeWindowId` for catch-up claims. Each durable row, candidate, claim, and candidate audit also retains and revalidates the server-derived `playableStateScope` as immutable separately persisted policy/routing/authorization/migration-fence evidence; it does not participate in `scheduleCandidateId`, firing-claim, `scriptEventId`, Trigger Identity, or Command-Handoff Identity derivation. A core-script schedule must carry its durable `scriptId`; a plugin-owned schedule must carry `pluginId`, `pluginVersionId`, its schedule-owned `bindingId`, and the captured `(pluginActivationEpoch, lifecycleRevision)` pair. `pluginActivationEpoch` is the tagged candidate/firing-claim field; `lifecycleRevision` is required non-identity fence evidence. Core-script candidates omit both plugin lifecycle fields. Missing applicable namespace, durable owner, provenance, or either plugin lifecycle field, or namespace/scope evidence that mismatches the authoritative namespace, scope, and active-instance/region binding, rejects the candidate before deriving `scheduleCandidateId`, the firing claim, or `scriptEventId`; a legacy or corrupt row missing any applicable required field is not a candidate: record one deterministic non-candidate schedule-reconciliation outcome keyed by the existing durable `scheduleInstanceId` (the immutable physical row-generation reference, not the logical schedule/event identity) plus the originating `controlPlaneRequestId` from its pin operation or Automation runtime transition, with bounded missing-field reason codes; quarantine or tombstone it, create no `scheduleCandidateId`, `scriptEventId`, ingress audit, firing claim, or handler audit, and never replay it. A handler-only binding field not present on the schedule remains absent until handler resolution. The firing claim derives one event-scope `scriptEventId` from this complete due-candidate identity and propagates that ID unchanged into every resolved handler's full Trigger Identity. Globally unique schedule IDs do not replace runtime scope, exact pin tuple, explicit `isDryRun`, or timeline fencing. - Candidates denied by a permanent or declared-skip cadence, reload, version, or event-policy outcome before handler binding are terminally consumed; they are recorded as event-scope `scheduleCandidateId` audits with no firing claim or `scriptEventId` and are not replayed later. A transient retryable reload, reconciliation, or authority fence instead retains a durable due-candidate state/claim keyed by `scheduleCandidateId` and the canonical due point under its original exact tuple and captured `(pluginActivationEpoch, lifecycleRevision)` pair, when applicable, as fenced/nonterminal evidence; this transient state is not a terminal candidate audit and carries no `finalStage`, `finalOutcome`, firing claim, handler Trigger Identity, or `scriptEventId` while fenced. Same-epoch retries reuse the candidate identity only while its complete captured fence evidence remains current. A lifecycle-revision mismatch fences the candidate under its original captured pair; reconciliation never refreshes or rebinds that candidate evidence. Unavailable, contradictory, or ambiguous owner evidence keeps it nonterminal. Once authoritative evidence proves that the captured revision is displaced and the ADR 0119 pre-`DRAINING` admission exception cannot apply, reconciliation terminalizes the candidate once under its original identity; it advances or retires a recurring/advisory row's canonical due state in the same durable reconciliation before any later candidate is admitted, while a correctness-bearing one-shot retains its original durable intent until an explicit terminal outcome and is never reminted. `DRAINING` cannot create a new firing; only already-admitted same-version/same-epoch work with the pre-barrier winning admission/fence CAS remains eligible under ADR 0119. A displaced old namespace, scope evidence, region epoch, exact pin tuple, or plugin activation epoch remains fenced under its original candidate identity and is never reused on the new timeline; target reconciliation derives a fresh candidate identity for the changed identity tuple before admission. The candidate ID is derived from the complete event-scope due-candidate identity: tenant/instance/playable-state namespace, stable schedule-owned script/plugin/binding identity when present, region and region epoch, exact script patch and pin epoch, event type and schema version, explicit `isDryRun`, schedule definition, trigger mode, target selector when applicable, and, for plugin-owned schedules, the tagged captured `pluginActivationEpoch`, and, when `triggerMode=CATCH_UP`, `resumeWindowId`, and the tagged due point. The server-derived `playableStateScope` is retained and exact-validated as separate policy/routing/authorization/migration-fence evidence and is not an identity input; an authority-proven scope transition starts a new lifecycle/namespace. A candidate that passes those gates creates at most one event-scope firing claim and deterministic event-scope `scriptEventId` for that due candidate, with the tagged plugin activation epoch included in that derivation, resolves handlers, and fans out zero or more handler work items, each with its own full Trigger Identity containing that same propagated ID; a pre-materialization handler quota denial is recorded per resolved handler with no handler work item, while an ordinary post-executor-claim `ScriptTenantBudgetService` denial records the existing handler identity and terminally cancels its already materialized work item before DSL evaluation. For plugin-owned candidates, the transient candidate state, reconciliation evidence, and retry/reload state retain the captured `(pluginActivationEpoch, lifecycleRevision)` pair. Reconciliation and retry revalidate both values against the current owner pair; `pluginActivationEpoch` is part of `scheduleCandidateId`, firing-claim, and derived `scriptEventId` identity, while `lifecycleRevision` is fence evidence only and is not added to those identities. From d4ffada6bd6baa865b310041461d5f162d3f6910 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 15:07:00 +1300 Subject: [PATCH 48/68] docs: clarify continuity transitions and gated break-glass writes --- design/architecture/system-architecture-redis-ops-access.md | 6 +++--- ...stem-architecture-scripting-normative-contract-tables.md | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/design/architecture/system-architecture-redis-ops-access.md b/design/architecture/system-architecture-redis-ops-access.md index 9886e399bd..73c95c2b0c 100644 --- a/design/architecture/system-architecture-redis-ops-access.md +++ b/design/architecture/system-architecture-redis-ops-access.md @@ -470,7 +470,7 @@ The table above is the canonical post-reset verification checklist. Other runboo After recovery release, the first real fenced staging/release step separately verifies that the staging CAS advances exactly `-1 → 0` and `APPLIED → STAGED`; later ticks use the immediate-next terminal transition. -**Target state only, once the canonical gated coordination-maintenance operation is implemented and proven:** Direct `redis-cli` writes to coordination prefixes are reserved for **break-glass scenarios** and must follow the incident guidelines in `system-architecture-redis.md` (auditing, post-incident reset, and verification). **Current deployments authorize no raw Coordination-prefix writes; any observed write is unsupported incident evidence and requires preserving the evidence, keeping the affected scope fenced, and escalating.** As an additional guardrail: +**Target state only, once the canonical gated coordination-maintenance operation is implemented and proven:** Direct `redis-cli` writes to coordination prefixes are not an operator write path. Target incident break-glass mutations must use the owner-authorized gated wrapper and follow the incident guidelines in `system-architecture-redis.md` (auditing, scoped reset, and verification); operators must not issue raw Redis writes. **Current deployments authorize no raw Coordination-prefix writes and do not yet provide this wrapper; any observed write is unsupported incident evidence and requires preserving the evidence, keeping the affected scope fenced, and escalating.** As an additional guardrail: - When target reset tooling exists, any break-glass write that mutates `tick:*`, `timer:*`, `retry:*`, `remote:*`, `session:*`, `tick-executor-lease:*`, `tick-events:*`, `tick-events-offset:*`, or `tick-events-lease:*` must be followed by a reset/cleanup scope that actually covers the mutated prefix before normal tick processing resumes. Without that tooling, preserve the incident evidence, keep the affected scope fenced, and escalate through [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) rather than attempting an unsupported follow-up reset: - For registered tagged region-scoped families (target `tick:{tenantRegionTag}:*`, excluding the legacy untagged `tick:lock::` family, plus `timer:*`, `retry:*`, and `tick-executor-lease:*`), run a region- or tenant-scoped coordination reset as appropriate. @@ -484,7 +484,7 @@ Manual mutations of Account-owned `session:auth:account:*`, `session:auth:tenant - **Current fallback:** after such writes, preserve incident evidence, keep the affected scope fenced, and escalate through [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). The Coordination Reset Model is target-state only and applies after its canonical gated coordination-maintenance operation is implemented and proven. -- When target reset tooling exists, break-glass flows should go through a small wrapper (CLI or Logging & Admin action) that: +- When target reset tooling exists, break-glass flows must go through the owner-authorized gated wrapper (CLI or Logging & Admin action) that: - Executes the minimal required Redis mutation. - Immediately triggers the appropriate scoped coordination reset. - Emits a structured audit event (for example `coordination_break_glass`) recording: @@ -516,7 +516,7 @@ This ensures that operators use the same abstractions as application code and re - Target state: the coordination maintenance CLI is shipped as part of the normal build/release pipeline under the canonical command name `coordination-maintenance`; environment packaging may wrap that command in a Gradle task, container entrypoint, or `dev-tools/` script. Once implemented and proven, target-state runbooks and Helm hooks may reference the bounded public operation names above. Current runbooks and Helm hooks must not invoke this unavailable command. - Target-state version rule: once the CLI is implemented and proven, operators must use only a version that matches the deployed services and Lua registry: - If the target CLI build version does **not** match the image tag or Git commit used for the running deployment, the target-state operator must not attempt coordination recovery actions; the operator must use the same artifact version or perform a coordinated upgrade. - - In the target state, break-glass or manual `redis-cli` operations are not an acceptable substitute for a mismatched maintenance CLI; they still require a scoped coordination reset afterwards and should be treated as incident-only paths. This does not make the unavailable CLI a current operator path. + - In the target state, manual `redis-cli` operations are not an acceptable substitute for a mismatched or unavailable maintenance CLI. Incident-only break-glass mutation must use the owner-authorized gated wrapper, which performs the scoped coordination reset and required verification; this does not make the unavailable wrapper or CLI a current operator path. Target-state runbooks may call the maintenance CLI entrypoint explicitly, after the implementation and proof gates above are complete, and should avoid embedding raw Redis commands. Current runbooks must not call the unavailable entrypoint. diff --git a/design/architecture/system-architecture-scripting-normative-contract-tables.md b/design/architecture/system-architecture-scripting-normative-contract-tables.md index 0786323b27..7163c7efd2 100644 --- a/design/architecture/system-architecture-scripting-normative-contract-tables.md +++ b/design/architecture/system-architecture-scripting-normative-contract-tables.md @@ -340,7 +340,7 @@ The exact resume formula, modulo-zero boundary behavior, and runtime scope/epoch ### Version-Owned Durable Schedule Migration (Normative) - `scheduleDefinitionId` participates in the stable logical continuity key but is not the durable row or trigger-claim identity. For a playable-state-scoped schedule, the continuity key is `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}`; `playableStateScope` is separately persisted exact-validated policy/routing/authorization/migration-fence evidence and is not a continuity-key component. `pluginId` is the stable plugin owner while `pluginVersionId`, `scriptPatchVersion`, and `scriptPinEpoch` remain provenance and exact execution-fence metadata. -- By default, a version transition tombstones the displaced interval and creates a target interval with fresh due state when a validated target definition exists. When authoritative reconciliation proves the target definition is absent, reconciliation follows the [scheduler owner rule](./system-architecture-scripting-scheduler-and-timers.md#explicit-continuity-across-script-transitions): it fences admission and atomically tombstones the displaced interval, terminalizes any proven-displaced candidates under their original identities as applicable, creates no replacement row, due state, firing claim, or `scriptEventId`, and never rebinds existing candidates or claims. If target-definition or other required authority is unavailable, contradictory, or ambiguous, reconciliation must not tombstone or create replacement state; it retains the displaced row, candidates, and claims fenced and nonterminal until authority reconciles. Only a later validated target reconciliation may create fresh state and identities. Carrying due state requires explicit compatible continuity declarations on both sides, `source.isDryRun == target.isDryRun`, typed interval/cadence/target/playable-scope checks, and the exact pin/epoch transition identity. A same-version repin is still a new epoch transition: the transition must atomically or resumably reconcile the stable row and retire or rewrite all displaced mutable schedule state, due candidates, and current list/read projections before admission resumes. Old-epoch firing claims retain their original exact `(scriptPatchVersion, scriptPinEpoch)` and `resumeWindowId`, and only pending claims may be fenced or terminal-marked; claims already in handoff reconcile the downstream outcome under their original exact fence. Neither pending-claim fencing/terminalization nor in-handoff reconciliation creates a new firing claim, handler identity, or `scriptEventId`. Immutable candidate-audit identity, outcome, exact tuple, and `resumeWindowId` are never rewritten. A transient due-candidate state/claim keyed by `scheduleCandidateId` may remain fenced while reconciliation is pending. It may settle into the one firing path only while its original exact `(scriptPatchVersion, scriptPinEpoch)` tuple and every applicable authoritative binding, runtime-scope, owner, and plugin lifecycle fence (including the captured `(pluginActivationEpoch, lifecycleRevision)` pair when applicable) remain current, or into one immutable terminal candidate audit. If authoritative evidence proves any applicable fence displaced, terminalize the candidate under its original identity with the applicable bounded terminal outcome/reason and create no firing claim or `scriptEventId`; if authority is unavailable, contradictory, or ambiguous, retain the fenced candidate as nonterminal until reconciled. It is never rebound to a new scope or epoch. `scheduleSemanticsHash` is diagnostic evidence only; equality cannot grant continuity. Replacement creation and retirement are one atomic durable result or a resumable, idempotent operation keyed by `controlPlaneRequestId`. +- By default, a version transition tombstones the displaced interval and creates a target interval with fresh due state when a validated target definition exists. When authoritative reconciliation proves the target definition is absent, reconciliation follows the [scheduler owner rule](./system-architecture-scripting-scheduler-and-timers.md#explicit-continuity-across-script-transitions): it fences admission and atomically tombstones the displaced interval, terminalizes any proven-displaced candidates under their original identities as applicable, creates no replacement row, due state, firing claim, or `scriptEventId`, and never rebinds existing candidates or claims. If target-definition or other required authority is unavailable, contradictory, or ambiguous, reconciliation must not tombstone or create replacement state; it retains the displaced row, candidates, and claims fenced and nonterminal until authority reconciles. Only a later validated target reconciliation may create fresh state and identities. Carrying due state requires explicit compatible continuity declarations on both sides, `source.isDryRun == target.isDryRun`, typed interval/cadence/target/playable-scope checks, and an exact pin/epoch transition: validate the prior/source `(scriptPatchVersion, scriptPinEpoch)` tuple and target tuple independently; they may differ across the transition, and both remain provenance and execution-fence metadata rather than members of the stable continuity key. A same-version repin is still a new epoch transition: the transition must atomically or resumably reconcile the stable row and retire or rewrite all displaced mutable schedule state, due candidates, and current list/read projections before admission resumes. Old-epoch firing claims retain their original exact `(scriptPatchVersion, scriptPinEpoch)` and `resumeWindowId`, and only pending claims may be fenced or terminal-marked; claims already in handoff reconcile the downstream outcome under their original exact fence. Neither pending-claim fencing/terminalization nor in-handoff reconciliation creates a new firing claim, handler identity, or `scriptEventId`. Immutable candidate-audit identity, outcome, exact tuple, and `resumeWindowId` are never rewritten. A transient due-candidate state/claim keyed by `scheduleCandidateId` may remain fenced while reconciliation is pending. It may settle into the one firing path only while its original exact `(scriptPatchVersion, scriptPinEpoch)` tuple and every applicable authoritative binding, runtime-scope, owner, and plugin lifecycle fence (including the captured `(pluginActivationEpoch, lifecycleRevision)` pair when applicable) remain current, or into one immutable terminal candidate audit. If authoritative evidence proves any applicable fence displaced, terminalize the candidate under its original identity with the applicable bounded terminal outcome/reason and create no firing claim or `scriptEventId`; if authority is unavailable, contradictory, or ambiguous, retain the fenced candidate as nonterminal until reconciled. It is never rebound to a new scope or epoch. `scheduleSemanticsHash` is diagnostic evidence only; equality cannot grant continuity. Replacement creation and retirement are one atomic durable result or a resumable, idempotent operation keyed by `controlPlaneRequestId`. - The preceding playable-scope checks validate separately persisted server-derived policy/routing/authorization/fence evidence; they do not add `playableStateScope` to continuity, candidate, or Trigger Identity. A presented scope mismatch remains fenced until authoritative reconciliation; only unchanged authoritative scope permits the existing namespace-keyed identity, while an authority-proven scope-policy transition starts a new playable-state lifecycle and namespace. - A new version/namespace-owned entry, or a target entry created after a namespace transition, must derive a new scheduler trigger claim and `scriptEventId`; a matching `scheduleDefinitionId`, due point, handler, or old `playableStateNamespaceId` must never be used to reuse a Trigger Identity across the migration. A presented `playableStateScope` mismatch remains an admission/migration fence requiring authoritative reconciliation and exact evidence validation; an authority-proven transition must allocate the new namespace before fresh identity, and no path may silently reuse the old identity while fenced. From 8a8bb241380be01be19ac23e4ab65af7747e6b21 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 15:24:38 +1300 Subject: [PATCH 49/68] docs: separate current wire and staging proof from target behavior --- .../microservices/automation-scripting-service/README.md | 2 +- .../automation-scripting-service/api-contracts.md | 4 ++-- .../system-architecture-redis-usage-and-profiles.md | 2 +- ...ystem-architecture-scripting-examples-and-patterns.md | 9 +++++---- .../system-architecture-tick-incident-runbook.md | 2 +- 5 files changed, 10 insertions(+), 9 deletions(-) diff --git a/design/architecture/microservices/automation-scripting-service/README.md b/design/architecture/microservices/automation-scripting-service/README.md index bced4193e2..7a76c040ad 100644 --- a/design/architecture/microservices/automation-scripting-service/README.md +++ b/design/architecture/microservices/automation-scripting-service/README.md @@ -42,7 +42,7 @@ The current Automation pin projection and wire contract now retain the observed - Faction reputation influences NPC aggression states. NPCs may become `FLEEING` or `SURRENDERED` when low on health or morale, allowing players to resolve encounters non-lethally. - Web UI for creating and testing scripts using a component-based DSL. - Advanced AI modules support formations, squads, and complex behaviors. -- Procedural population is not a live NPC/loot handoff: the current population hook calls bounded, seeded `PveEncounterService.generateEvent(...)` for each generated room and discards the returned event. It does not spawn or persist NPCs/loot or emit tick-driven commands. Full World-owned generation and tick handoff remain target work; see [Automation and Scheduler Runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#active-gaps). Scripts do not persist world topology or directly mutate World Management instance rows. +- Procedural population is not a live NPC/loot handoff: the current population hook calls seeded `PveEncounterService.generateEvent(...)` for each generated room, selecting an event from small in-memory region lists and discarding the returned event. It does not spawn or persist NPCs/loot or emit tick-driven commands. Full World-owned generation and tick handoff remain target work; see [Automation and Scheduler Runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#active-gaps). Scripts do not persist world topology or directly mutate World Management instance rows. - `ScriptQuotaService` enforces fairness quotas and per-script resource limits. ## Document Map diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md index ae7f85ab47..b85785acca 100644 --- a/design/architecture/microservices/automation-scripting-service/api-contracts.md +++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md @@ -85,8 +85,8 @@ On the current public Automation & Scripting API, `workItemId` and `workItemIds` Domain services such as Game Session and Game Logic deliver automation events through event-ingress RPCs (for example `TriggerScriptEvent`). The required identity fields, endpoint ownership, and audit behavior are defined in the [normative scripting contract tables](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields); the following list describes the service-local wire envelope: -- `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, and `entityId` for the target runtime context when applicable. -- resolved `playableStateScope` for gameplay-originated events as separately persisted, exact-validated policy/routing/authorization/migration-fence evidence. It stays explicit for handler/work fencing and operator read models but is excluded from Trigger Identity, timer-follow-up identity, uniqueness, and deduplication keys; see the [normative identity tables](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). +- The current `TriggerScriptEventRequest` carries `tenantId`, `gameInstanceId`, `regionId`, and `entityId` when applicable. `playableStateNamespaceId` is part of the target runtime identity but is absent from the current proto; see the canonical [normative scripting contract tables](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) for target identity requirements. +- `playableStateScope` is carried for gameplay-originated events as separately persisted, exact-validated policy/routing/authorization/migration-fence evidence. Current scope evidence does not prove the complete target namespace/scope tuple. It stays explicit for handler/work fencing and operator read models but is excluded from Trigger Identity, timer-follow-up identity, uniqueness, and deduplication keys; see the [normative identity tables](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). - `regionEpoch` for gameplay/runtime triggers and scheduler triggers so Trigger Identity is fenced across scoped coordination resets. - `scriptEventId` in the normalized applicable Trigger Identity. Its wire requirement follows the [ingress ownership matrix](../../system-architecture-scripting-normative-contract-tables.md#table-1a-event-ingress-scripteventid-ownership-matrix), and it is not a complete idempotency key by itself. - `isDryRun` so live and dry-run/test traffic are always in separate idempotency namespaces. diff --git a/design/architecture/system-architecture-redis-usage-and-profiles.md b/design/architecture/system-architecture-redis-usage-and-profiles.md index 75c592cc97..d458ce8185 100644 --- a/design/architecture/system-architecture-redis-usage-and-profiles.md +++ b/design/architecture/system-architecture-redis-usage-and-profiles.md @@ -13,7 +13,7 @@ Separate Coordination and Cache/Rate-Limit Redis processes exist in current mani Account-owned auth, authority-generation, and connect-token projections remain reset-sensitive rather than fully reset-tolerant. The current live `session:auth:account:*` and `session:auth:tenant:*` projections, and target-only `session:auth:token:*` and `session:auth:generation:*` projections, are preserved by region/tenant resets; cluster or cold-start loss requires Account-owned repair and exact readback. The unversioned legacy connect-token map remains preserve/readback-only through its TTL/retry horizon, while target versioned exact-result projections require their owner repair contract. Their region/tenant-preserve versus cluster/cold-start repair consequences are canonical in the [Redis Reset & Recovery reset matrix](./system-architecture-redis-reset-and-recovery.md#global-index-family-recovery-consequence); this usage document records ownership and profile wiring only and does not redefine that matrix. Current reset/reopen remains blocked until Account-owned repair, exact projection readback, and the matrix's applicable evidence gates are implemented and proved. The current hosted application wiring still exposes one generic `firemud.redis` client, with the shared hosted profile setting `FIREMUD_REDIS_HOST=redis-cache`; the role-specific Redis variables are present in the profile but are not consumed by the shared client configuration. Consequently, Game Session and Account coordination/auth paths cannot claim Coordination endpoint isolation in the hosted profile and may currently land on Cache/Rate-Limit Redis. This is implementation drift against ADR 0171, not a new role contract: hosted `pr-preview` and every other non-ephemeral/player-facing environment require named role clients and fail-closed endpoint-collision handling. The only exception is an explicitly labelled one-shot ephemeral CI/test stack, which may remain live after a collision only while surfacing the shared endpoint and forfeiting role-isolation, replay, and SLO evidence. -The shared `ConflictTracker` is another concrete consumer of this generic wiring: current Entity and Game Session callers emit `conflict:entity::` and `conflict:session::` through `RedisConflictTracker`, which performs separate `INCR` and `EXPIRE` calls and only warns when expiry fails. These counters are reset-tolerant diagnostics, never authority, but their current endpoint placement and mutation sequence remain implementation drift. The target role, owner, finite cardinality, TTL, ACL, and atomic-helper convergence are defined in [Redis Architecture](./system-architecture-redis.md#coordination-vs-cache-prefixes) and its [reset-policy entry](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary); no current runtime proof is implied. +The shared `ConflictTracker` is another concrete consumer of this generic wiring: current Entity and Game Session callers emit `conflict:entity::` and `conflict:session::` through `RedisConflictTracker`, which performs separate `INCR` and `EXPIRE` calls, warns when `EXPIRE` does not return true, and does not catch command exceptions. If increment succeeds but expiry fails, the counter may remain without a TTL. These counters are reset-tolerant diagnostics, never authority, but their current endpoint placement and mutation sequence remain implementation drift. The target role, owner, finite cardinality, TTL, ACL, and atomic-helper convergence are defined in [Redis Architecture](./system-architecture-redis.md#coordination-vs-cache-prefixes) and its [reset-policy entry](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary); no current runtime proof is implied. The hosted Helm Cache/Rate-Limit Redis process has a separate configuration drift: the enabled hosted overlay provisions a persistent cache volume, while the in-chart `redis-cache` Deployment starts Redis with AOF enabled and does not set `maxmemory` or an eviction policy. This does not provide the bounded, eviction-driven Cache/Rate-Limit profile and can retain disposable cache/rate-limit state across restart; the hosted cache process must load the cache profile or declare equivalent bounded settings before this environment can claim the target cache posture. diff --git a/design/architecture/system-architecture-scripting-examples-and-patterns.md b/design/architecture/system-architecture-scripting-examples-and-patterns.md index fc238eb520..5873f2060c 100644 --- a/design/architecture/system-architecture-scripting-examples-and-patterns.md +++ b/design/architecture/system-architecture-scripting-examples-and-patterns.md @@ -22,7 +22,7 @@ Companion docs: ## Implementation Status -These examples are target-state first. The target evaluated-work-item lifecycle uses one durable parent work item per admitted resolved handler: it starts `PENDING_EVALUATION`, transitions to `EXECUTING`, and atomically reaches `EVALUATED_COMMITTED` with immutable evaluated command descriptors/child-dispatch rows. A handler denied before work-item materialization keeps its handler audit outcome but creates no parent work item. Executor acceptance, the execution-start charge marker, and the fenced capacity lease commit before DSL evaluation; committed descriptors are later replayed without DSL re-entry. The current legacy evaluator collects a bounded list of emitted commands and attempts a separate Game Session handoff for each. For a same-scope target, `ENQUEUED` means Game Session accepted the command into its local tick queue, while idempotent `DUPLICATE_NOOP` confirms a prior local acceptance; for a distinct target scope, `REMOTE_SCHEDULED` means only that the remote follow-up was scheduled and does not claim local tick-queue admission. That legacy handoff does not carry `commandOrdinal` or the complete Trigger/Command-Handoff Identity end-to-end, so target per-command identity, deduplication, and independent progress remain unproved. The current `automation:queue` is a pre-DSL parent-work pointer projection; target committed-descriptor replay, a rebuildable evaluated-work queue projection, end-to-end `commandOrdinal`, and independent per-command recovery/progress are unavailable. Unresolved current-live `EVALUATING` work remains fail-closed and active, and the live runtime lacks `EVALUATED_COMMITTED` descriptor replay without DSL re-entry. See [Cross-Service Contracts](./system-architecture-scripting-contracts.md#implementation-status), the [normative Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state), [ADR 0063](./decisions/adr-0063-durable-per-dispatch-script-handoff.md), and the [automation and scheduler runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). +These examples are target-state first. The target evaluated-work-item lifecycle uses one durable parent work item per admitted resolved handler: it starts `PENDING_EVALUATION`, transitions to `EXECUTING`, and atomically reaches `EVALUATED_COMMITTED` with immutable evaluated command descriptors/child-dispatch rows. A handler denied before work-item materialization keeps its handler audit outcome but creates no parent work item. Executor acceptance, the execution-start charge marker, and the fenced capacity lease commit before DSL evaluation; committed descriptors are later replayed without DSL re-entry. The current legacy evaluator collects a bounded list of emitted commands and attempts a separate Game Session handoff for each. Both current authenticated Game Session receiving RPCs (`EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup`) fail closed with `FAILED_PRECONDITION` (`automation_admission_receiver_fence_unavailable`) before mutation, so this path currently proves neither local tick-queue acceptance nor remote follow-up scheduling. `ENQUEUED` and `DUPLICATE_NOOP` describe local acceptance dispositions, while `REMOTE_SCHEDULED` describes only remote follow-up scheduling; none is a successful outcome established by those current receivers. That legacy handoff does not carry `commandOrdinal` or the complete Trigger/Command-Handoff Identity end-to-end, so target per-command identity, deduplication, and independent progress remain unproved. The current `automation:queue` is a pre-DSL parent-work pointer projection; target committed-descriptor replay, a rebuildable evaluated-work queue projection, end-to-end `commandOrdinal`, and independent per-command recovery/progress are unavailable. Unresolved current-live `EVALUATING` work remains fail-closed and active, and the live runtime lacks `EVALUATED_COMMITTED` descriptor replay without DSL re-entry. See [Cross-Service Contracts](./system-architecture-scripting-contracts.md#implementation-status), the [normative Command-Handoff Identity](./system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state), [ADR 0063](./decisions/adr-0063-durable-per-dispatch-script-handoff.md), and the [automation and scheduler runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). --- @@ -70,11 +70,11 @@ This example walks through how a typical `onEnterRegion` script executes end-to- 5. **Automation queue staging** - The committed pre-DSL trigger is currently projected into `automation:queue:{tenantInstanceTag}:` as a derived parent-work pointer, but this current pointer is not rebuildable today, so queue reset/rebuild/resume remain unavailable and fail closed; see the [DSL Reference and Lifecycle implementation status](./system-architecture-scripting-dsl-reference-and-lifecycle.md#implementation-status). Actions produced by the handler are evaluated within its one durable parent work item. Target evaluation atomically reaches `EVALUATED_COMMITTED` with one immutable command descriptor/child-dispatch row per emitted command, after which committed descriptor children are indexed into the queue; current implementation persists pre-DSL parent work and indexes only the derived parent pointer. - - Firing admission links the durable firing claim, one applicable resolved-handler audit row for every resolved handler, parent work items and queue-pointer projections only for handlers admitted by all handler-scoped gates (including quota), and due-point advancement in one atomic durable transition or a resumable idempotent recovery operation. Zero-handler firings create no handler audit, parent work item, or queue-pointer projection; handlers denied by a handler-scoped gate retain an audit row but create no parent work item or queue-pointer projection. Firing-claim and queue-link recovery completes missing links from the existing claim rather than re-evaluating the handler. + - Ordinary event ingress such as `onEnterRegion` proceeds through event-scope admission and handler resolution/handler-scoped gates; it does not require the scheduler firing claim or due-point advancement described under the target `onInterval` timer lifecycle below. - **Target-state only:** Each durable parent work item carries the originating `scriptEventId`, `scriptId`, `gameInstanceId`, `playableStateNamespaceId`, exact `scriptPatchVersion`/`scriptPinEpoch`, and region context. It retains `playableStateScope` separately as exact-validated policy/routing/authorization/migration-fence evidence, excluded from Trigger Identity, Command-Handoff Identity, uniqueness, and deduplication keys. The current instance-tagged queue pointer and `outboxWorkItemId`-only path do not establish namespace-complete identity or isolation. In the target handoff contract, each immutable emitted-command child is keyed by the complete source runtime scope plus any distinct target runtime scope, the persisted `automationDispatchId`, and deterministic `commandOrdinal` from canonical output order; both child identities are reused for every handoff, retry, and downstream disposition. The full parent Trigger Identity (including `bindingId` where applicable), `outboxWorkItemId`, and `scriptEventId` remain correlation only, while bounded `workItemIds[]` are parent-row selectors rather than child identities. The target `ListScriptHandoffEvents` child records are keyed by the complete Command-Handoff Identity, with `(automationDispatchId, commandOrdinal)` retained only as its dispatch-group suffix, and retain the full parent Trigger Identity while the handler audit remains one row. See [Implementation Status](#implementation-status) for the current live handoff boundary. 6. **Automation ticks and tick command enqueue** - - **Current legacy path:** For each emitted command, Automation calls Game Session over internal gRPC. For a same-scope target, Game Session admits the command idempotently and invokes tick enqueue; `ENQUEUED` means local queue admission and `DUPLICATE_NOOP` confirms prior local acceptance. For a distinct target scope, the successful `REMOTE_SCHEDULED` result records only remote follow-up scheduling and does not claim local tick-queue admission. + - **Current legacy path:** For each emitted command, Automation attempts a separate Game Session internal gRPC handoff. The authenticated current receiving RPCs fail closed with `FAILED_PRECONDITION` (`automation_admission_receiver_fence_unavailable`) before mutation, so this path does not establish local tick-queue admission or remote follow-up scheduling. The `ENQUEUED`, `DUPLICATE_NOOP`, and `REMOTE_SCHEDULED` dispositions describe acceptance outcomes, not successful outcomes proved by these current receivers. - **Target path:** Automation will later use the durable evaluated-command descriptor and rebuildable queue projection to hand resulting commands to Game Session, which owns enqueueing them into `tick:{tenantRegionTag}:queue:` using the tick engine’s Lua registry and invariants. The target descriptor/recovery and complete command identity/progress guarantees remain unavailable. 7. **Execution, audit, and observability** @@ -116,7 +116,7 @@ If the `scriptPatchVersion` pinned by the Game Session Service for a given game This example shows how a script that runs on a fixed cadence (for example, an NPC patrol) moves through the pipeline using `onInterval`. The target scheduler admits at most one durable event-scope firing claim and one derived `scriptEventId` for each due candidate; retries reuse that claim and never create a second firing. For the target-only, unimplemented timer and failover internals (including the reserved region-scoped coordination keys `automation:timer:{tenantRegionTag}` and `script-scheduler:{tenantRegionTag}:lastTickId`, whose future stored entries must remain instance-aware), see [End-to-End `onInterval` Timer Lifecycle](./system-architecture-scripting-scheduler-and-timers.md#end-to-end-oninterval-timer-lifecycle). -The complete target fixed-cadence pipeline below—durable timer firing, evaluated command descriptors, rebuildable queue projection, and complete per-command handoff identity—is target-state only and remains unimplemented. Current live behavior is narrower but does include the legacy path: Automation reaches the pre-DSL work-item and queue-pointer projection, evaluates a bounded command list, and hands each emitted command separately to Game Session. For same-scope targets, `ENQUEUED` admits the command into the local tick queue and `DUPLICATE_NOOP` confirms prior local acceptance; for distinct target scopes, `REMOTE_SCHEDULED` records only remote follow-up scheduling and does not claim local tick-queue admission. The current pointer projection is not the target rebuildable evaluated-work projection, and target descriptor replay/recovery, end-to-end `commandOrdinal`, and independent per-command progress guarantees remain unavailable or unproved. +The complete target fixed-cadence pipeline below—durable timer firing, evaluated command descriptors, rebuildable queue projection, and complete per-command handoff identity—is target-state only and remains unimplemented. Current live behavior is narrower: Automation reaches the pre-DSL work-item and queue-pointer projection, evaluates a bounded command list, and attempts a separate Game Session handoff per emitted command. The authenticated current receiving RPCs fail closed with `FAILED_PRECONDITION` (`automation_admission_receiver_fence_unavailable`) before mutation, so these attempts prove neither local tick-queue admission nor remote follow-up scheduling. The current pointer projection is not the target rebuildable evaluated-work projection, and target descriptor replay/recovery, end-to-end `commandOrdinal`, and independent per-command progress guarantees remain unavailable or unproved. 1. **Script configuration and publish** - A designer configures an NPC patrol script in the Game Design Service, binding an `onInterval` handler with a chosen cadence (for example, every N ticks) and a sequence of waypoints. @@ -129,6 +129,7 @@ The complete target fixed-cadence pipeline below—durable timer firing, evaluat 3. **Firing `onInterval` and enforcing budgets** - When an interval becomes due, the scheduler first applies event-scope candidate gates (cadence, reload/version visibility, and applicable event-policy checks); a permanent or declared skip is recorded by a deterministic `scheduleCandidateId` derived from the complete event-scope due-candidate identity defined by the [scheduler and timer owner](./system-architecture-scripting-scheduler-and-timers.md#interval-entry-identity-and-due-point-persistence), including required `stableOwnerKind`/`stableOwnerId` and, only for `triggerMode=CATCH_UP`, `resumeWindowId` (whose only generation component is `resumeGeneration`), plus captured `(pluginActivationEpoch, lifecycleRevision)` evidence for plugin-owned schedules. For plugin-owned schedules, `pluginActivationEpoch` is the tagged candidate/firing/derived `scriptEventId` identity field and input to that deterministic derivation; `lifecycleRevision` travels as fence evidence only. Core schedules use the exact `(scriptPatchVersion, scriptPinEpoch)` tuple and do not imply a separate core generation. A transient reload/reconciliation/authority-fence outcome instead retains the same due-candidate state under the complete applicable exact fence predicate: the original exact tuple, runtime scope/region epoch, schedule-owned provenance and binding, owner evidence, and captured lifecycle pair when plugin-owned, with no terminal candidate audit or `finalStage`/`finalOutcome`; only when every predicate element still matches may it resume after reconciliation. A lifecycle-revision mismatch fences the candidate under its captured evidence; reconciliation never refreshes or rebinds it. If authoritative evidence proves any other predicate no longer matches, the candidate does not resume or rebind and follows the scheduler owner's applicable terminal candidate outcome/reason; unavailable or ambiguous authority remains fenced and nonterminal. Retries reuse the candidate, firing claim, and derived `scriptEventId` only while the complete applicable candidate identity and captured fence evidence remain unchanged; all other runtime scope/region epoch, exact pin tuple, schedule-owned binding/provenance, due point, catch-up window, and plugin activation-epoch mismatches remain fenced. Core schedules require the same exact pin tuple and no separate core generation. An activation-epoch or core exact-tuple transition fences the old identity and derives a fresh one only before the new candidate is admitted. A lifecycle-revision-only change never mints a replacement candidate: a `DRAINING` transition cannot start a new firing, while already-admitted work may retain the existing identity only with ADR 0119's winning admission/fence CAS committed before the durable drain barrier. Neither path creates a firing claim, `scriptEventId`, or handler identity until its candidate gates pass. The lifecycle pair is not part of stable schedule/continuity identity, handler Trigger Identity, or Command-Handoff Identity. After handlers are bound, all handler-scoped gates run; a quota denial is handler-scoped `ADMISSION/quota_denied` with no work item, queue projection, lease, or execution marker, while only handlers admitted by all handler-scoped gates (including quota) create durable queued work. The later execution scheduler considers queued handler work in canonical order for the artifact-estimate prefix reservation; its remainder remains durably queued/deferred. When a handler is selected, a separately fenced capacity lease is acquired and its fence, executor acceptance, execution-start marker, and `EXECUTING` transition commit in one Automation-owned durable transaction before evaluation. The firing transition records one audit row for every resolved handler, including denied handlers, and creates work/queue projections only for handlers admitted by all handler-scoped gates; firing-claim and queue-link retries do not re-run the DSL, while eligible pre-`EVALUATED_COMMITTED` evaluation recovery may re-run the frozen DSL under the original identity and evidence. - If multiple handlers are bound to the timer event, the timer firing is admitted once at event scope and then fans out into handler-scoped Trigger Identities whose outcomes are tracked independently. + - **Target timer-firing transition only:** Firing admission links the durable firing claim, one applicable resolved-handler audit row for every resolved handler, parent work items and queue-pointer projections only for handlers admitted by all handler-scoped gates (including quota), and due-point advancement in one atomic durable transition or a resumable idempotent recovery operation. Zero-handler firings create no handler audit, parent work item, or queue-pointer projection; handlers denied by a handler-scoped gate retain an audit row but create no parent work item or queue-pointer projection. Firing-claim and queue-link recovery completes missing links from the existing claim rather than re-evaluating the handler. See the [scheduler and timer owner](./system-architecture-scripting-scheduler-and-timers.md#end-to-end-oninterval-timer-lifecycle). - If an event-scope candidate gate is a permanent or declared skip, the due candidate is terminally consumed and recorded in metrics and an event-scope audit keyed by the same complete event-scope `scheduleCandidateId` identity. A transient reload/reconciliation/authority-fence gate instead retains the same due-candidate state and canonical due point under the complete applicable exact fence predicate described above, including the captured `(pluginActivationEpoch, lifecycleRevision)` pair and runtime-scope, binding, and owner evidence; without a terminal candidate audit or `finalStage`/`finalOutcome`, only that unchanged predicate may resume after reconciliation. A lifecycle-revision mismatch fences the candidate under its captured evidence; reconciliation never refreshes or rebinds it. Any other non-match remains governed by the scheduler owner's existing fenced/terminal resolution and is not rebound. Neither path creates a firing claim, handler Trigger Identity, or `scriptEventId`; `scriptEventId` is minted only after firing claim/admission succeeds. Handler quota denial after a firing claim is instead recorded under that handler's full Trigger Identity and does not consume the candidate as an event-scope skip. - If the event-scope candidate is allowed, the scheduler enqueues the `onInterval` trigger for sandbox execution and advances the canonical due point (`dueTickId` for tick cadence or `dueAt` for wall-clock cadence) according to the cadence or resume rule within that atomic durable firing transition or its resumable idempotent recovery operation, and then derives `nextTick` or `nextRunAt` from that due point. This keeps the cadence stable even if some intervals are occasionally delayed by load. If the timer survives a reload or rollback because the logical schedule is preserved, the next due point is recalculated from the canonical resume rule rather than by replaying the paused window. diff --git a/design/architecture/system-architecture-tick-incident-runbook.md b/design/architecture/system-architecture-tick-incident-runbook.md index 47ba7dc56c..1f19720541 100644 --- a/design/architecture/system-architecture-tick-incident-runbook.md +++ b/design/architecture/system-architecture-tick-incident-runbook.md @@ -349,7 +349,7 @@ Normal replay and re-enqueue in this section apply only to effects from the curr Correlation is a lookup aid, not proof of application. Always establish the exact deployment mode before selecting an identity, and verify the candidate against the complete durable ledger projection, current ownership boundary, and participant/domain evidence. -- **Current-live correlation:** Prefer the durable `commandId` when it is present in the command ledger and selected-work manifest. When no command ID is available, the current implementation may use the documented `command-text::slot:` fallback to locate a candidate in the selected-work manifest. That text-and-slot value is only non-authorizing correlation: verify it against the exact scope and epoch, the batch `manifest_digest`, the ledger row, its linked root `EffectId` and participant guards, and authoritative domain state before invoking the service-owned verifier. The fallback is mutable implementation metadata, never a canonical identity, replacement for a missing root `EffectId`, or authority to transition a row to `APPLIED`. +- **Current-live correlation:** Prefer the durable `commandId` when it is present in the command ledger and selected-work manifest. When it is absent from a legacy selected-work manifest, operators may use the documented `command-text::slot:` fallback only to locate a candidate. Newly created durable batches and selections reject entries without durable command IDs in `createBatchForTick` and `commandSelections`; this fallback is not a batch-creation or selection path. The text-and-slot value is only non-authorizing correlation: verify it against the exact scope and epoch, the batch `manifest_digest`, the ledger row, its linked root `EffectId` and participant guards, and authoritative domain state before invoking the service-owned verifier. The fallback is mutable implementation metadata, never a canonical identity, replacement for a missing root `EffectId`, or authority to transition a row to `APPLIED`. - **Target-state correlation:** Use only the persisted mutation `EffectId` and its complete concrete ledger/participant projection, retaining any enclosing root `EffectId` as lineage/reconciliation context (including the typed participant-guard identity and target aggregate). `commandId`, `effectKey`, command text, and trace attributes may narrow a search but cannot establish identity, authorize reconciliation, or permit an `APPLIED` transition. ## Using Proved Workflow Traces During Tick Incidents From db22bf384983bbeb6f13652ec421f26eaffb479d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 15:40:57 +1300 Subject: [PATCH 50/68] docs: qualify pre-staging loss and centralize proof guidance --- .../system-architecture-scripting-normative-contract-tables.md | 2 +- design/architecture/system-architecture-tick-execution-flows.md | 2 +- design/architecture/system-architecture-transactions.md | 2 +- .../implementation-tracking/automation-and-scheduler-runtime.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/design/architecture/system-architecture-scripting-normative-contract-tables.md b/design/architecture/system-architecture-scripting-normative-contract-tables.md index 7163c7efd2..a88dc3b01f 100644 --- a/design/architecture/system-architecture-scripting-normative-contract-tables.md +++ b/design/architecture/system-architecture-scripting-normative-contract-tables.md @@ -99,7 +99,7 @@ The canonical scheduler preimage fields are serialized in this fixed order: ` Date: Thu, 1 Oct 2026 16:07:35 +1300 Subject: [PATCH 51/68] docs: clarify work-bearing identity and lifecycle result evidence --- .../world-creation-workflow.md | 2 +- .../system-architecture-tick-execution-flows.md | 4 ++-- ...stem-architecture-tick-failures-and-operations.md | 2 +- design/project-management/ai-observations.md | 12 ++++++++++++ .../automation-and-scheduler-runtime.md | 2 +- 5 files changed, 17 insertions(+), 5 deletions(-) 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 c9f696327b..25a312d181 100644 --- a/design/architecture/microservices/world-management-service/world-creation-workflow.md +++ b/design/architecture/microservices/world-management-service/world-creation-workflow.md @@ -174,7 +174,7 @@ Temporal owns orchestration and workflow progress using the canonical `world-lif ### Lifecycle signal identity and serialization -The target workflow must represent each activate, fail, or terminate request as a durable queued signal/update envelope carrying a stable operation identity, normalized request digest, expected lifecycle epoch/status, and owner CAS evidence. Exact retries read back one logical result; changed identity, digest, status, or epoch fails closed, and conflicting lifecycle operations follow explicit precedence/conflict rules rather than last-writer-wins behavior. A signal may not be combined with or overwrite another logical operation whose outcome is still unresolved. +The target workflow must represent each activate, fail, or terminate request as a durable queued signal/update envelope carrying a stable operation identity, normalized request digest, and expected lifecycle epoch/status. Owner-generated CAS evidence is recorded in the result only after the local lifecycle CAS commits as the winner; it is not request-envelope authority. Exact retries read back one logical result; changed identity, digest, status, or epoch fails closed, and conflicting lifecycle operations follow explicit precedence/conflict rules rather than last-writer-wins behavior. A signal may not be combined with or overwrite another logical operation whose outcome is still unresolved. **Current implementation gap:** `TemporalWorldLifecycleWorkflowImpl` stores only one pending epoch/reason per signal type and has no operation identity or digest. Repeated same-type signals overwrite one another, while an activate and terminate received together are both processed sequentially; termination then reuses the pre-activation epoch after activation has advanced it and can retry until the workflow fails. The current `TemporalWorldLifecycleOrchestrator`/workflow path therefore does not provide one durable lifecycle result for concurrent or lost signal requests. This is in addition to the existing `AlreadyStarted` identity-comparison gap above and remains unproved until the queued envelope, owner lifecycle CAS, conflict handling, and readback result are implemented. diff --git a/design/architecture/system-architecture-tick-execution-flows.md b/design/architecture/system-architecture-tick-execution-flows.md index e06d7836b4..906768cbc6 100644 --- a/design/architecture/system-architecture-tick-execution-flows.md +++ b/design/architecture/system-architecture-tick-execution-flows.md @@ -13,7 +13,7 @@ This document describes the target execution model. The current live runtime is - the durable owner/status surface is currently `{tenantId, gameInstanceId}`-scoped rather than true region-scoped; - `GetGameplayCommandStatus` is the canonical command-status API, but its live fields and state vocabulary are narrower than the accepted lifecycle described below; - the live batch/effect substrate exists with the current gameplay-command selected-work manifest on `tick_batch`, but timer/retry/remote-follow-up source-claim manifests, the target-state empty-cadence watermark path, cross-region result-return plumbing, and some richer command-status fields are still target-state follow-through. The current-live `ScheduleRequest`, `RemoteCommandCoordinator`, `RemoteFollowup`, and `RemoteFollowupResult` models/migrations omit `targetPlayableStateNamespaceId`, so the complete target-scope and request-digest equality contract below is not live or proven. The current-live runtime has no dedicated target-state empty-cadence status transition or `StreamTickHeartbeats` path. -- `createBatchForTick` calls `requireDurableCommandIdentifiers` before selection, and `commandSelections` repeats that guard before `effectKey` is called. The retained command-text-plus-slot `effectKey` branch is therefore an unreachable helper/legacy path, not a live gameplay-staging fallback. The target path is fail-closed: Game Session assigns the stable root `EffectId` before acknowledgement and rejects before acknowledgement when assignment fails. Target tick execution also rejects any missing or blank root `EffectId` before staging, ledger, or domain writes; a no-ID bypass is permitted only for an explicitly non-tick/control-plane path. Separately, [ADR 0016](./decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) and the [transactions command/effect boundary](./system-architecture-transactions.md) permit command-scope `LOST_BEFORE_STAGING`/`NOT_APPLIED` only when an unbound `ACCEPTED_VOLATILE` command (ingress status `RECEIVED` or `ENQUEUED`, with no surviving `tickBatchId`) is proven lost before durable staging. This loss is not an EffectId-assignment failure: assignment failure is rejected before acknowledgement, and any root `EffectId` assigned before acknowledgement remains the same stable identity. Batch-bound or inconclusive work remains non-terminal/reconciliation-required and cannot become evidence-free `ABANDONED`. The current helper branch does not imply that the target root-identity contract is live. +- `createBatchForTick` calls `requireDurableCommandIdentifiers` before selection, and `commandSelections` repeats that guard before `effectKey` is called. The retained command-text-plus-slot `effectKey` branch is therefore an unreachable helper/legacy path, not a live gameplay-staging fallback. For work-bearing commands from non-empty plans, the target path is fail-closed: Game Session assigns the stable root `EffectId` before acknowledgement and rejects before acknowledgement when assignment fails. The work-bearing tick path also rejects any missing or blank root `EffectId` before staging, ledger, or domain writes; a no-ID bypass is permitted only for an explicitly non-tick/control-plane path. Status-only no-effect `SUCCESS` follows the Enqueue rule below and is outside root allocation and tick recovery. Separately, [ADR 0016](./decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) and the [transactions command/effect boundary](./system-architecture-transactions.md) permit command-scope `LOST_BEFORE_STAGING`/`NOT_APPLIED` only when an unbound `ACCEPTED_VOLATILE` command (ingress status `RECEIVED` or `ENQUEUED`, with no surviving `tickBatchId`) is proven lost before durable staging. This loss is not an EffectId-assignment failure: assignment failure is rejected before acknowledgement, and any root `EffectId` assigned before acknowledgement remains the same stable identity. Batch-bound or inconclusive work remains non-terminal/reconciliation-required and cannot become evidence-free `ABANDONED`. The current helper branch does not imply that the target root-identity contract is live. Naming convention: API, workflow, and EffectId prose uses `regionEpoch`. Snake-case forms such as `region_epoch`, `target_region_epoch`, and `due_tick_id` are reserved for explicitly identified SQL/storage fields, Redis payloads/keys, or schema examples. @@ -44,7 +44,7 @@ Within a region’s tick, root actor commands and their effects proceed through 1. **Enqueue** - Game Session accepts commands from Telnet and WebSocket clients, AI, or automation. - Work-bearing commands are enqueued into per-entity (or occasionally per-region) queues such as `tick:{tenantRegionTag}:queue:`. - - If admission resolves to no gameplay effects, the same durable command-status transaction records the canonical terminal outcome (`ingressStatus=TERMINAL`, `executionOutcome=APPLIED`, and `gameplayResult=SUCCESS` under [ADR 0053](./decisions/adr-0053-command-atomicity-by-invariant-class.md) and [ADR 0016](./decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md)). This status-only write creates no effect ledger row or `tick_batch`, advances no tick-domain state, and does not enqueue the command; an accepted no-effect command therefore cannot remain `ENQUEUED`, and retries return its stored terminal outcome. Command-plan ordinal and ID-generation/allocation mechanics remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). + - If admission resolves to no gameplay effects, the same durable command-status transaction records the canonical terminal outcome (`ingressStatus=TERMINAL`, `executionOutcome=APPLIED`, and `gameplayResult=SUCCESS` under [ADR 0053](./decisions/adr-0053-command-atomicity-by-invariant-class.md) and [ADR 0016](./decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md)). This status-only write allocates no root `EffectId`, creates no effect ledger row or `tick_batch`, advances no tick-domain state, and does not enqueue the command; an accepted no-effect command therefore cannot remain `ENQUEUED`, and retries return its stored terminal outcome. Command-plan ordinal and ID-generation/allocation mechanics remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). 2. **Target Resolution (read-only)** - During the tick, the executor resolves targets from the pinned snapshot for that ``: - Single-target actions select a specific entity or room. diff --git a/design/architecture/system-architecture-tick-failures-and-operations.md b/design/architecture/system-architecture-tick-failures-and-operations.md index a59228ee9b..b44941fd7c 100644 --- a/design/architecture/system-architecture-tick-failures-and-operations.md +++ b/design/architecture/system-architecture-tick-failures-and-operations.md @@ -14,7 +14,7 @@ This document describes the full target-state recovery and operator model. Curre - the live owner/status API is `GetRuntimeOwnershipStatus`, not yet a full region-scoped status surface; - the live fence token is opaque and compare-and-match based; - the live `tick_batch` / `tick_effect` ledger is real and now carries the current gameplay-command selected-work manifest on `tick_batch`, including current-boundary `enqueueSeq`, source metadata, and digest-checked replay reuse for surviving staged batches; live selected-work manifests do not yet preserve the required declared `phase`, `lane`, and `cost_class` metadata. The live `enqueueSeq` is allocated by one database-wide sequence; the region-scoped, cross-source allocator defined below is target-state. Timer/retry/remote-follow-up source-claim manifests, region-scoped replay controller breadth, and cross-region result-return semantics also remain target-state follow-through. -- The live gameplay-command staging path requires a present, nonblank durable `commandId` before Redis enqueue or durable batch staging, and malformed pre-existing entries fail closed before staging. `effectKey` is derived as `command:`; the retained text/slot helper fallback is unreachable through `createBatchForTick` and `commandSelections`, which require durable command identifiers before selection. This still does not provide the complete target Automation handoff identity. The accepted target path assigns a stable root `EffectId` before acknowledgement when possible, rejects before acknowledgement if assignment fails, and requires a persisted nonblank root before staging, ledger, or domain writes; an already acknowledged `ACCEPTED_VOLATILE` command that cannot receive that identity may become `LOST_BEFORE_STAGING` only when eligible in `RECEIVED`/`ENQUEUED` with no surviving batch. Batch-bound or inconclusive work remains non-terminal/reconciliation-required and is never evidence-free `ABANDONED`. The live staging checks do not prove that target root allocation or complete Automation identity. +- The live gameplay-command staging path requires a present, nonblank durable `commandId` before Redis enqueue or durable batch staging, and malformed pre-existing entries fail closed before staging. `effectKey` is derived as `command:`; the retained text/slot helper fallback is unreachable through `createBatchForTick` and `commandSelections`, which require durable command identifiers before selection. This still does not provide the complete target Automation handoff identity. For work-bearing commands from non-empty plans, the accepted target path requires stable root `EffectId` assignment before acknowledgement, rejects before acknowledgement if assignment fails, and requires the persisted nonblank root before staging, ledger, or domain writes. Status-only no-effect `SUCCESS` follows the canonical [Enqueue rule](./system-architecture-tick-execution-flows.md) and is outside this staging/recovery path. An already acknowledged `ACCEPTED_VOLATILE` command may become `LOST_BEFORE_STAGING` only when the owner proves it remains unbound in `RECEIVED`/`ENQUEUED` with no surviving batch. Batch-bound or inconclusive work remains non-terminal/reconciliation-required and is never evidence-free `ABANDONED`. The live staging checks do not prove that target root allocation or complete Automation identity. - The live rollback purge path is weaker than that target boundary: `TickQueueControlService.purgeCandidate` checks only `GameplayCommandRepository.hasDurableTickEffect(commandId)` before selecting `ABANDONED` versus `LOST_BEFORE_STAGING`. That non-atomic existence check does not prove the absence of a surviving batch, effect, or source claim, and it can race concurrent staging, drain, or effect ownership. The target atomic owner-defined CAS/no-batch proof remains unimplemented and unproved; this is a current implementation/proof gap, not a relaxation of the target `ACCEPTED_VOLATILE`/`RECEIVED`/`ENQUEUED` eligibility contract. - The specific deterministic allocation mechanics and `planOrdinal` proposed in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) remain proposal-only, not current tick target requirements. They do not displace the accepted stable-root-before-acknowledgement and persisted nonblank-root-before-staging requirements above. The current `tickBatchId`/`effectKey` path does not prove any proposal-specific allocation behavior. - The accepted lane and fencing consequences are target-state requirements in this recovery model: selected-work manifests and replay records must preserve each item's declared `phase`, `lane`, and `cost_class`, while takeover reconciliation remains subject to the Redis lease plus durable executor-fence handshake owned by [Tick System and Runtime Design](./system-architecture-ticks.md). This document does not duplicate that owner protocol. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index fe66a4bd22..8192dad296 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -169,3 +169,15 @@ Entry format: - Observation: the runtime audit flattened the active CLI observation into a generic unresolved-finding string before the controller's existing exact-identity overlap check could run. A controller regression with a mocked empty audit did not exercise that adapter interaction. - Expected pattern: preserve structured run/lock-owner/head/parent/patch evidence through the audit and test the real adapter-to-allocation path. Permit only positively verified same-candidate overlap; genuine pending findings and incomplete identities remain held. - Outcome: the bounded controller/runtime correction passes real-adapter overlap and refusal regressions; live request verification follows publication. The running CLI was not interrupted, and no duplicate Hosted request or private-state bypass was used. + +- `2026-10-01`: An ownership clarification is not a lane-wide stop + - Context: the human transferred the #2916 controller child to Overseer for review/fix cycles while Gameplay still owned #2839. Gameplay ended its turn after acknowledging the transfer, requiring an explicit resume. + - Observation: the child-only ownership boundary was incorrectly treated as a stopping point for the continuing parent assignment. + - Expected pattern: stop touching the transferred child, but continue the owned parent and independent review lanes. A coordination acknowledgement or status answer must not terminate the standing train without an explicit pause or actual blocker. + - Outcome: Gameplay resumed #2839, preserved the child untouched, adjudicated its complete saved CLI result, and dispatched the accepted parent-only corrections. + +- `2026-10-01`: Distinguish request admission contention from an active provider review + - Context: several closely launched #2839 Hosted/CLI commands produced a delayed Hosted refusal saying another Hosted request was active, without a new posted trigger; a guarded later request posted normally. + - Observation: the exact contention phase and cause remain unproven. That refusal alone does not establish that CodeRabbit is reviewing, and preparation delay consumes eligible Hosted windows independently of provider duration. + - Expected pattern: retain the canonical request handle and verify its actual posted or refused outcome. Investigate the narrow admission/lock boundary without bypassing duplicate-request or exact-identity safeguards; keep the other safe lane moving. + - Reconsideration trigger: investigate when the controller owner can reproduce the contention or another eligible Hosted window is lost; do not silently label an unposted request as an active review. 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 69e0a23497..90566dcb7c 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -177,7 +177,7 @@ Automation never writes Game Session tick keys directly. The live queue uses ins Current enqueue/rebuild is RPUSH-only (with no target pointer TTL or maximum length), and `tenantInstanceTag` still concatenates raw IDs, so retention, memory-pressure, and collision-safe opaque encoding remain unproved. Canonical queue and Redis mechanics are owned by [Scripting Runtime Execution](../../architecture/system-architecture-scripting-runtime-execution.md) and [Redis](../../architecture/system-architecture-redis.md); this tracker records the current implementation gaps. -Game Session retains a lower-level idempotent `EnqueueAutomationCommandIfAbsent` helper that persists automation dispatch/work-item correlation on the gameplay command ledger before tick staging. The authenticated receiver RPC remains fail-closed before live mutation because its Automation admission-epoch receiver fence is absent; lower-level helper proofs do not establish live receiver admission. See the [Game Session receiver candidate status](#game-session-receiver-candidate) and [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). The separate durable tick staging/replay and final tuple recheck remain implemented and do not establish that the receiver admitted a request. Numeric gameplay `targetEntityId` is captured as `characterId` so durable execution can resolve an active session without a caller-owned `sessionId`. Automation assigns a per-command `automationDispatchId`, preserves the full routing bundle, and retains helper paths for local admission or durable remote follow-up to a different target runtime scope. Before re-enqueuing an existing `ACCEPTED` but unstaged Automation command, the lower-level admission helper revalidates the request's captured region identity and epoch against current runtime ownership and rejects unavailable, paused, or advanced ownership without mutation; already-materialized or terminal exact retries retain stored-result readback behavior. Once receiver admission is available, local scripting commands use Game Session's actor-action path; a remote follow-up uses the owner-defined passive/inbound path, while any gameplay command it emits uses the actor-action path. The current `scheduleFollowup` terminal-timeout/late-result path can reopen an existing terminal coordinator/follow-up pair; this remains the implementation/proof gap recorded in Game Session runtime/data. The live Game Session enqueue proto/storage remains narrower than the target automation handoff contract: it does not yet carry full Trigger Identity, `commandOrdinal`, immutable `lane`, or `cost_class`, so complete child identity, lane/cost conflict and digest checks, deduplication, readback, retry, recovery preservation, and enforcement remain unimplemented or unproved. Canonical handoff mechanics are owned by [ADR 0063](../../architecture/decisions/adr-0063-durable-per-dispatch-script-handoff.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), and [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary); tick lane semantics remain owned by [Tick Concepts & Invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md). This tracker records the local actor-path consequence and current gap. +Game Session retains a lower-level idempotent `EnqueueAutomationCommandIfAbsent` helper that persists automation dispatch/work-item correlation on the gameplay command ledger before tick staging. The authenticated receiver RPC remains fail-closed before live mutation because its Automation admission-epoch receiver fence is absent; lower-level helper proofs do not establish live receiver admission. See the [Game Session receiver candidate status](#game-session-receiver-candidate) and [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). The separate durable tick staging/replay and final tuple recheck remain implemented and do not establish that the receiver admitted a request. Numeric gameplay `targetEntityId` is captured as `characterId` so durable execution can resolve an active session without a caller-owned `sessionId`. Automation assigns a per-command `automationDispatchId`, preserves the full routing bundle, and retains helper paths for local admission or durable remote follow-up to a different target runtime scope. Before re-enqueuing an existing `ACCEPTED` but unstaged Automation command, the lower-level admission helper revalidates the request's captured region identity and epoch against current runtime ownership and rejects unavailable, paused, or advanced ownership without mutation; already-materialized or terminal exact retries retain stored-result readback behavior. Once receiver admission is available, lane assignment follows the canonical [Tick Concepts & Invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); this tracker records no separate lane rule. The current `scheduleFollowup` terminal-timeout/late-result path can reopen an existing terminal coordinator/follow-up pair; this remains the implementation/proof gap recorded in Game Session runtime/data. The live Game Session enqueue proto/storage remains narrower than the target automation handoff contract: it does not yet carry full Trigger Identity, `commandOrdinal`, immutable `lane`, or `cost_class`, so complete child identity, lane/cost conflict and digest checks, deduplication, readback, retry, recovery preservation, and enforcement remain unimplemented or unproved. Canonical handoff mechanics are owned by [ADR 0063](../../architecture/decisions/adr-0063-durable-per-dispatch-script-handoff.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), and [Scripting Contracts](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary). This tracker records the local actor-path consequence and current gap. The target remote-follow-up contract is owned by [Scripting & Automation: Cross-Service Contracts](../../architecture/system-architecture-scripting-contracts.md#3-version-fencing-rollback-safety). Current `ScriptHandoffEvent` persistence and readback now carry the source `scriptPinEpoch`, but they do not yet bind the source tuple to the target tuple or prove downstream target admission against that binding. The legacy target-side `trigger_script_event` path is therefore deterministically disabled until the complete source/target tuple-plus-owner binding exists: missing, malformed, or mismatched tuple evidence is a terminal fail-closed outcome, while unavailable authority remains non-admitted and retryable. Same-instance cross-region work and semantic target `UNPINNED` handling remain subject to that owner contract. From 850b40c5395de86b3f24d9c14d24301d40aff2c6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 16:28:24 +1300 Subject: [PATCH 52/68] docs: align runtime authority and implementation status --- ...ting-event-ingress-idempotency-identity.md | 20 +++++++++---------- ...ble-idempotent-operator-write-execution.md | 2 +- ...-specific-timer-durability-and-recovery.md | 2 +- ...ffect-fanout-and-lightweight-idle-ticks.md | 2 +- .../runtime-and-data.md | 2 +- .../game-design-service/modding-framework.md | 2 +- ...e-scripting-dsl-reference-and-lifecycle.md | 2 +- ...chitecture-tick-concepts-and-invariants.md | 2 +- .../automation-and-scheduler-runtime.md | 2 +- ...e-session-runtime-and-tick-coordination.md | 4 ++-- .../world-runtime-and-movement.md | 2 +- 11 files changed, 21 insertions(+), 21 deletions(-) diff --git a/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md b/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md index 0003477c13..0ebba5fc38 100644 --- a/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md +++ b/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md @@ -4,6 +4,8 @@ Superseded by [ADR 0172](./adr-0172-parent-event-and-frozen-handler-execution-identity.md) +This ADR preserves historical ingress-idempotency context, not an independent current identity contract. [ADR 0172](./adr-0172-parent-event-and-frozen-handler-execution-identity.md) owns parent-event and frozen-handler execution identity; [Scripting Normative Contract Tables](../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) owns the current endpoint-specific Trigger Identity fields and scheduler candidate preimage. + ## Implementation Status The live `ScriptScheduleInstanceServiceImpl.TimerFiringCandidate.identity()` implementation remains narrower than the canonical scheduler preimage until the target and owner/plugin fields are carried. It currently uses resolved `playableStateScope` in the identity preimage and emits `eventSchemaVersion=v1`, `isDryRun=false`, and `triggerMode=TRIGGER_MODE_CATCH_UP`; authoritative `playableStateNamespaceId` identity and separate non-identity scope evidence are target-state. The current values remain explicit preimage inputs even while they are constant. It has no cross-producer golden-vector proof for the canonical preimage or its numeric formatting rules. See the [automation and scheduler runtime tracker](../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). @@ -14,24 +16,22 @@ Event-ingress RPCs into the Automation & Scripting Service must be idempotent un ## Decision -Automation & Scripting treats event ingress as at-most-once per **Trigger Identity**. The exact endpoint-specific field matrix is owned by [Scripting Normative Contract Tables](../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) so the ADR and runtime contract cannot evolve as competing tuples. +The original decision treated event ingress as at-most-once per **Trigger Identity**. Current endpoint-specific identity semantics are owned by [Scripting Normative Contract Tables](../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) and [ADR 0172](./adr-0172-parent-event-and-frozen-handler-execution-identity.md); the notes below preserve context without defining a competing tuple. -- Gameplay/runtime handler identity includes the applicable `tenantId`, `gameInstanceId`, authoritative `playableStateNamespaceId`, `regionId`, `regionEpoch`, `entityId`, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch`, `scriptEventId`, and `isDryRun` fields. The server-derived `playableStateScope` is retained and exact-validated as immutable policy/routing/authorization/fence evidence, not as a uniqueness discriminator. An authoritative scope transition starts a new playable-state lifecycle and namespace; stale presented scope with unchanged authority may reuse the existing identity. -- `isDryRun` is always an identity dimension so live and test execution cannot collide. -- Scheduler/timer triggers additionally carry a due point and trigger mode. The canonical scheduler candidate preimage, its conditional branches, serialization, hash, and proof requirements are owned by [Table 1's Scheduler Candidate Identity Preimage](../system-architecture-scripting-normative-contract-tables.md#scheduler-candidate-identity-preimage-normative); this superseded ADR preserves no competing specification. -- Tenant-readiness `onLoad` follows the explicit non-runtime exception in the normative table and does not invent sentinel runtime, region, or entity identity. -- Plugin-trigger identity additionally carries plugin and binding identity where the invocation unit is plugin- or binding-scoped. +- Presented `playableStateScope` is exact-validated evidence, not a uniqueness discriminator. Stale or mismatched scope remains fenced until authoritative reconciliation; a namespace-keyed identity may be reused only if authority proves scope unchanged. An authority-proven transition starts a new playable-state lifecycle and namespace. +- Live/test separation, tenant-readiness `onLoad` exceptions, and plugin/binding identity follow the applicable fields and branches in the normative table and ADR 0172; this superseded ADR does not define their current schema. +- Scheduler/timer candidate identity, including its conditional branches, serialization, hash, and proof requirements, is owned by [Table 1's Scheduler Candidate Identity Preimage](../system-architecture-scripting-normative-contract-tables.md#scheduler-candidate-identity-preimage-normative). -Ordinary event-ingress callers must reuse the same full applicable Trigger Identity, including the same `scriptEventId`, when retrying a logically identical trigger. Scheduler retries instead reuse the same complete due-candidate/firing-claim identity and its deterministically derived `scriptEventId`; that derived ID is propagated into resolved handler identities but remains excluded from `TimerFiringCandidate.identity()`'s scheduler preimage. +Retry identity and handler materialization follow the current Trigger Identity and scheduler-candidate owners linked above; the original decision's retry rule is historical context rather than a separate current specification. ## Consequences -- Protos and service contracts must carry enough fields to represent the endpoint-specific Trigger Identity, including the playable-state namespace, immutable scope fence evidence, dry-run mode, and due-point or plugin dimensions where applicable. -- Audit records (`script_event_audit`) must be keyed by Trigger Identity, not by `scriptEventId` alone. +- Current proto and service requirements for endpoint-specific Trigger Identity and frozen handler execution are owned by [Scripting Normative Contract Tables](../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) and [ADR 0172](./adr-0172-parent-event-and-frozen-handler-execution-identity.md); this ADR's original consequence is historical context. +- Audit records (`script_event_audit`) follow the current Trigger Identity contract, not `scriptEventId` alone. ## Implementation and Proof Obligations -Implementation and proof must satisfy the canonical identity matrix and scheduler-preimage requirements in [Scripting Normative Contract Tables](../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields), including its required vectors and exact-retry behavior. Select and report the required checks and evidence under [Validation and Runtime Proof](../../developer-workflows/validation-and-runtime-proof.md); record execution results in PR/CI evidence or implementation-tracking documents rather than in this decision record. +Current implementation and proof obligations are owned by [ADR 0172](./adr-0172-parent-event-and-frozen-handler-execution-identity.md) and the canonical identity matrix and scheduler-preimage requirements in [Scripting Normative Contract Tables](../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). Select and report checks under [Validation and Runtime Proof](../../developer-workflows/validation-and-runtime-proof.md); this superseded ADR is not an independent proof authority. ## References diff --git a/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md b/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md index 7baa8ca3d6..605eea768e 100644 --- a/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md +++ b/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md @@ -66,7 +66,7 @@ If that Logging and Admin reservation claim has expired on a terminal owner-exec The current domain owner authenticates the delivery provider, rechecks its own current owner/gameplay fence and the unchanged reservation claim fence, and redeems the exact reference with Account before allocating the initial owner attempt. Account redemption must still validate the exact caller workload, tuple, current authority, membership, applicable privilege, and issuance fence; successful redemption consumes the reference and binds the durable redemption result to that attempt. Handoff timeout, provider/owner fence loss, tuple or fingerprint mismatch, expired or revoked reference, Account `NOT_FOUND`, delivery failure, or redemption failure after the authorized-to-owner transition remains `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` until one of the two applicable terminal-proof forms above is established durably; only then may it transition to `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION`. The original authorization and consumed reference are never reused after a failed or ambiguous post-authorization handoff. An ambiguous handoff is read-only and non-replayable; it never authorizes business execution, and any later business attempt requires a new explicit operator request, fresh Account authorization, and a new reference. -For a forwarded owner-mutation family, after the reservation owner receives the Account authorization reference, it atomically enriches the exact `preAuthorizationReservationTuple/v1` into the canonical complete `postAuthorizationExecutionTuple`. The latter contains the complete pre-authorization tuple plus `issuanceKind`, the `authorizationReferenceFingerprint` returned unchanged by Account for the exact opaque reference, exact authenticated workload and actor binding, applicable workload/policy identity, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, and the exact immutable `authorityEvidenceBundle/v1` defined in ADR 0047. It explicitly retains the immutable typed `targetOwner` from the reservation and every schema-bound typed presence/absence value; no declared value may be dropped during tuple completion. Logging and Admin never derives or recomputes the fingerprint or any authority evidence. Its durable record may retain the operator intent and Account-returned fingerprint; any opaque reference held by Logging and Admin is protected, bounded in-flight delivery material only, not a recovery authority record or competing copy of Account's authority. The workload identity is the exact authenticated Logging and Admin mTLS identity; an automated request also binds `automation_policy_id` and `automation_policy_version`, while a human request has an explicit no-automation-policy value. Schema-bound absent or null values represented by the digest are stored as bound values rather than omitted during tuple completion. The reservation CAS and initial `ACCOUNT_AUTHORIZATION/RESERVED` record are prerequisites to issuance: if that pre-record commit fails, Account issuance must not be attempted, and the request uses the applicable pre-authorization outcome; `AUTHORIZATION_PENDING` is not recorded or returned because no phase record exists. If Account issuance has been dispatched or a reference may exist, but tuple completion cannot be written, the durable record remains `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` under its applicable claim/recovery rules, and the original request tuple, Account response/reference fingerprint, reservation owner and claim fence, and all returned authority/evidence fields are retained in their owning durable records; the opaque reference itself remains only in Account's protected authority record and bounded in-flight delivery material. It must not be forwarded, reissued, or treated as `NOT_EXECUTED_BEFORE_AUTHORIZATION` until durable proof establishes that no authorization reference exists, cannot still be issued, and no owner-forward call occurred or can still occur. If no reference could have existed and the no-dispatch proof is complete, the pre-authorization terminal outcome may be recorded instead. The action-family request identity is canonical across HTTP, Java/domain contracts, ADRs, and audit records; its action-family mapping and moderation correlation rule are defined above. Protobuf contracts may use the language-standard wire spelling `control_plane_request_id`, which maps directly to the non-moderation identifier; it is not a second idempotency key. +For a forwarded owner-mutation family, after the reservation owner receives the Account authorization reference, it atomically enriches the exact `preAuthorizationReservationTuple/v1` into the canonical complete `postAuthorizationExecutionTuple`. The latter contains the complete pre-authorization tuple plus `issuanceKind`, the `authorizationReferenceFingerprint` returned unchanged by Account for the exact opaque reference, exact authenticated workload and actor binding, applicable workload/policy identity, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, and the exact immutable `authorityEvidenceBundle/v1` defined in ADR 0047. It explicitly retains the immutable typed `targetOwner` from the reservation and every schema-bound typed presence/absence value; no declared value may be dropped during tuple completion. Logging and Admin never derives or recomputes the fingerprint or any authority evidence. Its durable post-authorization record must persist the Account-returned `authorizationReferenceFingerprint` unchanged as part of the canonical `postAuthorizationExecutionTuple`; this is required tuple evidence, not optional context. Any opaque reference held by Logging and Admin is protected, bounded in-flight delivery material only, not a recovery authority record or competing copy of Account's authority. The workload identity is the exact authenticated Logging and Admin mTLS identity; an automated request also binds `automation_policy_id` and `automation_policy_version`, while a human request has an explicit no-automation-policy value. Schema-bound absent or null values represented by the digest are stored as bound values rather than omitted during tuple completion. The reservation CAS and initial `ACCOUNT_AUTHORIZATION/RESERVED` record are prerequisites to issuance: if that pre-record commit fails, Account issuance must not be attempted, and the request uses the applicable pre-authorization outcome; `AUTHORIZATION_PENDING` is not recorded or returned because no phase record exists. If Account issuance has been dispatched or a reference may exist, but tuple completion cannot be written, the durable record remains `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` under its applicable claim/recovery rules, and the original request tuple, Account response/reference fingerprint, reservation owner and claim fence, and all returned authority/evidence fields are retained in their owning durable records; the opaque reference itself remains only in Account's protected authority record and bounded in-flight delivery material. It must not be forwarded, reissued, or treated as `NOT_EXECUTED_BEFORE_AUTHORIZATION` until durable proof establishes that no authorization reference exists, cannot still be issued, and no owner-forward call occurred or can still occur. If no reference could have existed and the no-dispatch proof is complete, the pre-authorization terminal outcome may be recorded instead. The action-family request identity is canonical across HTTP, Java/domain contracts, ADRs, and audit records; its action-family mapping and moderation correlation rule are defined above. Protobuf contracts may use the language-standard wire spelling `control_plane_request_id`, which maps directly to the non-moderation identifier; it is not a second idempotency key. For a forwarded owner-mutation family, Account first issues the applicable opaque bounded operator authorization reference defined by ADR 0047. A human request uses the typed Account `IssueHumanOperatorAuthorizationReference` path and requires the current `control-ui` identity; its reference is bound to the `human_operator` issuance kind, current token `jti`, account generation, role-assurance result, applicable `tenant_generation` or `target_tenant_generation`, any required `privileged_control` predicate, exact authenticated workload and actor binding, complete applicable authority tuple, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, exact tenant/scope, immutable typed `targetOwner`, action family, `actionFamilySchemaId`, `actionFamilySchemaVersion`, actor, the action-family request identity, `mutationDigest`, issue time, and expiry. An unattended request uses the typed Account `IssueAutomationOperatorAuthorizationReference` path with `exact_mtls_workload_plus_versioned_automation_policy`; the current automation branch is restricted to tenant-scoped action families that require no `privileged_control`, and its reference is bound to the `automation_operator` issuance kind, exact Logging and Admin workload mTLS identity, `automation_policy_id`, `automation_policy_version`, exact `tenant_generation`, complete applicable authority tuple, independent applicable `membershipVersion` when applicable, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, exact tenant/scope, immutable typed `targetOwner`, action family, `actionFamilySchemaId`, `actionFamilySchemaVersion`, the action-family request identity, `mutationDigest`, issue time, and expiry. It carries no user account, end-user token, `control-ui` identity, global-role authority, or human elevation. Logging and Admin forwards that reference and its unchanged generation, evidence-bundle, predicate evidence, reservation owner, claim fence, immutable typed `targetOwner`, and every schema-bound typed presence/absence value with the typed request, digest, schema pair, exact scope, and same request identifier to the authoritative domain owner. The owner: diff --git a/design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md b/design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md index 371b511e7a..d9f1a5d9c5 100644 --- a/design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md +++ b/design/architecture/decisions/adr-0072-class-specific-timer-durability-and-recovery.md @@ -54,7 +54,7 @@ Recovery classes are: Redis timer keys, due indexes, leader checkpoints, and wake-up hints are rebuildable and disposable for every class. Durable timer identity, due state, recovery policy, resume-window identity, and terminal or skipped outcomes live outside Redis whenever the class requires recovery or audit. -For target-state `COALESCE_ONE` recovery, Automation owns one durable timer-recovery resume-window record per playable-state namespace/runtime scope, epoch, and `isDryRun` mode. Its `resumeWindowId` is the exact tuple ``. A durable compare-and-set creates or returns the one `OPEN` window for that namespace/runtime scope, epoch, and mode; the server-derived `playableStateScope` is retained and exact-validated as immutable policy/routing/authorization/fence evidence, not as a uniqueness input. An authoritative scope transition starts a new playable-state lifecycle and namespace; stale presented scope with unchanged authority may reuse the existing identity. Leader, worker, takeover, and attempt IDs never participate in the identity. At creation, the durable record binds the exact `(scriptPatchVersion, scriptPinEpoch)` tuple as immutable execution-fence evidence without adding it to `resumeWindowId`, freezes the effective numeric tenant-local cap and the selection-policy revision, and persists a frozen pre-window `recoveryStart` watermark plus a monotonic `lastObservedThrough` watermark for each applicable clock domain. Each observation supplies an `observedThrough` watermark, which is durably recorded as the new `lastObservedThrough` only with settlement under that `resumeWindowId`. `recoveryStart` is the exclusive lower bound for the first scan, the prior `lastObservedThrough` is exclusive for every later scan, and the current `observedThrough` is inclusive, so the ranges are `(recoveryStart, observedThrough]` initially and `(lastObservedThrough, observedThrough]` thereafter. A candidate exactly at the inclusive through point is eligible once; a candidate at an exclusive lower bound is not rediscovered. Same-window retries, observations, and takeovers re-read and compare those persisted watermarks and reuse the record, its mode-specific `resumeWindowId`, and its frozen cap and selection-policy revision unchanged; each `CATCH_UP` firing claim and candidate audit includes that ID in uniqueness and comparison. A cap or selection-policy change applies only to a later window allocated after this one reaches `COMPLETE`. The current window becomes `COMPLETE` only after the selected candidates' firing or shared-admission-denial outcomes and all cap-excluded candidate outcomes governed by its frozen values are durable. Only a later recovery episode after completion allocates the next `resumeGeneration`, producing a distinct mode-specific `resumeWindowId`. +For target-state `COALESCE_ONE` recovery, Automation owns one durable timer-recovery resume-window record per playable-state namespace/runtime scope, epoch, and `isDryRun` mode. Its `resumeWindowId` is the exact tuple ``. A durable compare-and-set creates or returns the one `OPEN` window for that namespace/runtime scope, epoch, and mode; the server-derived `playableStateScope` is retained and exact-validated as immutable policy/routing/authorization/fence evidence, not as a uniqueness input. An authority-proven scope transition starts a new playable-state lifecycle and namespace. Stale or mismatched presented scope remains fenced until authoritative reconciliation; the namespace-keyed resume-window identity may be reused only when authority proves the scope unchanged. Leader, worker, takeover, and attempt IDs never participate in the identity. At creation, the durable record binds the exact `(scriptPatchVersion, scriptPinEpoch)` tuple as immutable execution-fence evidence without adding it to `resumeWindowId`, freezes the effective numeric tenant-local cap and the selection-policy revision, and persists a frozen pre-window `recoveryStart` watermark plus a monotonic `lastObservedThrough` watermark for each applicable clock domain. Each observation supplies an `observedThrough` watermark, which is durably recorded as the new `lastObservedThrough` only with settlement under that `resumeWindowId`. `recoveryStart` is the exclusive lower bound for the first scan, the prior `lastObservedThrough` is exclusive for every later scan, and the current `observedThrough` is inclusive, so the ranges are `(recoveryStart, observedThrough]` initially and `(lastObservedThrough, observedThrough]` thereafter. A candidate exactly at the inclusive through point is eligible once; a candidate at an exclusive lower bound is not rediscovered. Same-window retries, observations, and takeovers re-read and compare those persisted watermarks and reuse the record, its mode-specific `resumeWindowId`, and its frozen cap and selection-policy revision unchanged; each `CATCH_UP` firing claim and candidate audit includes that ID in uniqueness and comparison. A cap or selection-policy change applies only to a later window allocated after this one reaches `COMPLETE`. The current window becomes `COMPLETE` only after the selected candidates' firing or shared-admission-denial outcomes and all cap-excluded candidate outcomes governed by its frozen values are durable. Only a later recovery episode after completion allocates the next `resumeGeneration`, producing a distinct mode-specific `resumeWindowId`. A scope-level durable atomic epoch transition must move each prior epoch's `OPEN` resume window, independently for each `isDryRun` mode, out of `OPEN` before any corresponding new-epoch `OPEN` window can be created. Claims from the prior window remain fenced to, and are reconciled under, their original `regionEpoch`, `isDryRun`, and resume-window identity; they cannot be admitted through the new window. The transition follows the existing evidence-based completion and terminalization rules and does not invent a new terminal status or recovery policy. diff --git a/design/architecture/decisions/adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md b/design/architecture/decisions/adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md index 4325ed9396..c7d8e3fcf6 100644 --- a/design/architecture/decisions/adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md +++ b/design/architecture/decisions/adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md @@ -41,7 +41,7 @@ Every global or multi-region effect first creates one durable parent identity. A Fan-out creates an idempotent durable child or injection row for every affected region before publishing any wake signal for that region. The parent and children expose pending, injected, terminal, and feature-specific outcome information sufficient to show partial injection. Game Session owns fan-out reconciliation. A feature may not casually assign another durable coordinator: any transfer must follow [ADR 0057](./adr-0057-game-session-owned-reconciliation-with-isolated-workers.md)'s complete authority-transfer model and a new accepted ADR defining the new owner's ledger/backlog, frozen participant set, retry/reconciliation, outcome, audit, retention, and worker controls. The owner retries missing injections, reconciles duplicate attempts to the same child identity, and derives the visible parent outcome. -The exact child-identity allocation, manifest schema, and replay binding are not selected by this accepted fan-out decision. They are described only as a non-authoritative pending proposal in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); no implementation may treat that proposal as current target state. +The owner-defined child ordinal and durable owner-scope/root/parent/ordinal-to-child-`EffectId` admission mapping are accepted target contract under [ADR 0069](./adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) and [ADR 0075](./adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). Only the exact ordinal scalar format and any additional allocator mechanics or manifest schema remain unresolved proposal-only details in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); that proposal does not change the accepted mapping or establish implementation. Redis markers, notifications, or equivalent wake signals are disposable latency hints. Losing a hint cannot erase a child, and duplicating one cannot create another logical regional effect. Each child enters the target region's ordinary durable inbound-effect path and remains subject to that region's lease, executor fence, epoch checks, lane budgets, and idempotency rules. 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 3c74e48cda..5fc70179de 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -115,7 +115,7 @@ Ordinary owner-local dead-letter recovery/retry remains non-conflicting routine - **Cache/Rate-Limit Redis usage** - Stores script quota counters and similar best-effort aggregates in Cache/Rate-Limit Redis using prefixes such as `automation:quota::`, `automation:tenant-budget::tier:`, the dry-run/test quota families `automation:test:quota::script::tenant` and `automation:test:quota::script::principal:`, the dry-run capacity families `automation:test:capacity:{}:tenant`, `automation:test:capacity:{}:lease:`, `automation:test:capacity:{automation-test-capacity}:cluster`, and `automation:test:capacity:{automation-test-capacity}:cluster:lease::`, the readiness capacity families `automation:readiness:capacity:{}:tenant`, `automation:readiness:capacity:{}:lease:`, `automation:readiness:capacity:{automation-readiness-capacity}:cluster`, and `automation:readiness:capacity:{automation-readiness-capacity}:cluster:lease::`, and `automation:queue:{tenantInstanceTag}:*`. - Treats these keys as transient operational data; PostgreSQL remains authoritative for script definitions and long-lived automation state. - - Quota and queue-oriented prefixes are best-effort TTL-only caches unless explicitly documented as strongly validated caches with versioned payloads and stricter invalidation semantics. + - Quota prefixes are best-effort TTL-only caches unless explicitly documented as strongly validated caches with versioned payloads and stricter invalidation semantics. `automation:queue` is an explicit exception: current RPUSH-only pointer lists have neither TTL nor a bound, and the target pointer-liveness TTL and maximum list length apply only once implemented, as detailed in the ownership table below. Ownership and durability expectations for Automation & Scripting prefixes: diff --git a/design/architecture/microservices/game-design-service/modding-framework.md b/design/architecture/microservices/game-design-service/modding-framework.md index c07e746447..aa9e9c9d26 100644 --- a/design/architecture/microservices/game-design-service/modding-framework.md +++ b/design/architecture/microservices/game-design-service/modding-framework.md @@ -468,7 +468,7 @@ For operator verification during rollback, disablement, or signer revocation, us Live plugin executions (`isDryRun=false`) participate in the same observability pipeline as live core scripts and use shared identifiers and live metric families. The current legacy materialized dry-run/test handler path records a terminal `finalStage=DSL_EVAL`, `finalOutcome=dry_run_completed`, and `finalReason=dry_run_no_handoff` in `script_event_audit`; target ADR 0114 command-plan previews remain isolated to the preview result/audit surface or direct authorized result path. Preview/test executions use the corresponding test-only metric families and do not increment live families: -- Each resolved live plugin handler is recorded in `script_event_audit` with the required Trigger Identity fields (including `tenantId` and `gameInstanceId` only for instance-bound handlers; tenant-readiness `onLoad` omits instance fields), plus `pluginId` / `pluginVersionId` and stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`). Pre-handler admission outcomes are recorded in `script_event_ingress_audit` and create no handler row. +- Each resolved live plugin handler is recorded in `script_event_audit` with the applicable required Trigger Identity fields, including `regionEpoch` for gameplay/runtime events; `tenantId` and `gameInstanceId` are present only for instance-bound handlers, while tenant-readiness `onLoad` omits instance fields (see canonical [normative Table 1](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields)). The audit also records `pluginId` / `pluginVersionId` and stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`). Pre-handler admission outcomes are recorded in `script_event_ingress_audit` and create no handler row. - The shared Automation trigger, skip, drop, sandbox-failure, and runtime metric families expose plugin behavior alongside core automation using only the finite `script_kind`, `plugin_origin`, `event_class`, and other bounded dimensions defined by [normative Table 4](../../system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix). Exact plugin and version identities never become Prometheus labels. Logging & Admin may surface exact plugin and version identities only through explicitly approved audit records, protected logs, named span families whose documented incident query requires them, and authorized control-plane or diagnostic queries. Trace use follows [ADR 0167](../../decisions/adr-0167-allowlisted-sensitive-trace-attributes.md): producer-side span-family allowlists, least-privilege environment-scoped access with audited queries, finite profile-defined retention, and declared export/privacy/erasure handling apply; availability in all logs, traces, or queries is not implied. On those approved surfaces, operators can: 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 04fde8cf65..545ab5de52 100644 --- a/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md +++ b/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md @@ -101,7 +101,7 @@ The required Trigger Identity fields and target-scope exceptions are defined in | 3 | **Script work item** | For each admitted resolved handler, one durable parent work item owns the applicable Trigger Identity and pre-DSL lifecycle; when it reaches `EVALUATED_COMMITTED`, it gains immutable evaluated command descriptor/child-dispatch rows, one per emitted command, with version metadata. A handler denied before work-item materialization has no parent work item. The descriptor rows have independent handoff statuses while the parent marker remains the recovery boundary. | **Target state only:** each work item/descriptor and queue-index pointer retains and exact-validates authoritative `playableStateNamespaceId`, with `playableStateScope` separately exact-validated; an `outboxWorkItemId` alone is not isolation evidence. The displayed `automation:queue:{tenantInstanceTag}:` is the current pointer-key shape, not a target identity contract. **Current implementation:** that queue is only a derived pre-DSL parent-work pointer projection for `PENDING_EVALUATION`/`EVALUATING`, not an evaluated-command descriptor index or proof of namespace isolation. | | 4 | **Tick command** | A concrete command that the Game Session Service executes during game ticks under its normal locking and idempotency rules. | Enqueued into `tick:{tenantRegionTag}:queue:` for consumption by the tick loop. | -Triggers lead to durable parent work items for admitted handlers; their DSL runs execute within those parents and, after `EVALUATED_COMMITTED`, gain immutable descriptor children plus queue-pointer projection entries. Target queue staging retains and exact-validates the authoritative `playableStateNamespaceId` and separately validates `playableStateScope`; the current instance-tagged key, work item/pointer, and outbox-ID-only claim do not establish namespace isolation. Automation's execution loop turns committed descriptors into tick commands for the Game Session Service. +Admitted triggers lead to durable parent work items, and their DSL runs execute within those parents. **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. diff --git a/design/architecture/system-architecture-tick-concepts-and-invariants.md b/design/architecture/system-architecture-tick-concepts-and-invariants.md index 276c3a9704..903d2b2b89 100644 --- a/design/architecture/system-architecture-tick-concepts-and-invariants.md +++ b/design/architecture/system-architecture-tick-concepts-and-invariants.md @@ -8,7 +8,7 @@ This document summarizes the **core concepts and invariants** of the FireMUD tic This document describes the target-state invariants. The target ownership model is a region-scoped Redis liveness lease paired with a durable executor fence and authority-fenced takeover/replay recovery for each ``. The live deployment has not yet converged on that region-scoped boundary: durable ownership is currently instance-scoped at `{tenantId, gameInstanceId}`, exposed through `RuntimeOwnershipStatus` with selected region fields and an opaque compare-and-match fence. True region-scoped lease/fence installation, `RegionStatus` authority, and takeover reconciliation remain target-state implementation and proof work. The invariants below therefore remain the canonical target contract and must not be read as a claim that the target recovery protocol is already live. -The exact `scriptPinEpoch` propagation and final same-version old-epoch rejection described above are now enforced for the live instance-bound Automation handoff and final Game Session execution. Complete source/target remote tuple binding and broader target command identity remain target-state gaps; the target invariant remains required at those boundaries. +Where reached, lower-level instance-bound Automation and Game Session checks enforce exact `scriptPinEpoch` propagation and final same-version old-epoch rejection. The authenticated live `EnqueueAutomationCommandIfAbsent` receiver still fails closed with `FAILED_PRECONDITION` (`automation_admission_receiver_fence_unavailable`) before command or queue mutation, so those checks do not prove successful live receiver admission. Complete source/target remote tuple binding and broader target command identity remain target-state gaps, along with other identity gaps; the target invariant remains required at those boundaries. ## What This Covers 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 90566dcb7c..1f892e4376 100644 --- a/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md +++ b/design/project-management/implementation-tracking/automation-and-scheduler-runtime.md @@ -205,7 +205,7 @@ Game Session pin reads remain distinct: `GetPinnedScriptPatchVersion` reports pi ## Active Gaps -- `AS-1.4` scheduler ordering is current implementation drift: `ScriptScheduleInstanceServiceImpl` sorts candidates by clock lane first, then that lane's due point (`dueTickId` for tick candidates or epoch-millisecond `dueAt` for wall-clock candidates), then `priorityTag`, and finally schedule key, with round-robin grouping applied only after that sort. Lane/due-point order can therefore outrank bounded priority; due-point comparison is lane-local and does not compare the distinct clock domains. The target remains bounded priority-first ordering with stable schedule-instance identity round-robin fairness. No scheduler algorithm change is claimed by this tracker. +- `AS-1.4` scheduler ordering is current implementation drift: `ScriptScheduleInstanceServiceImpl` sorts candidates by clock lane first, then that lane's due point (`dueTickId` for tick candidates or epoch-millisecond `dueAt` for wall-clock candidates), then `priorityTag`, and finally schedule key, with round-robin grouping applied only after that sort. Lane/due-point order can therefore outrank priority; due-point comparison is lane-local and does not compare the distinct clock domains. The target ordering and fairness contract is owned by the [scheduler and timer lifecycle](../../architecture/system-architecture-scripting-scheduler-and-timers.md#catch-up-truncation-must-use-one-stable-fairness-algorithm). No scheduler algorithm change is claimed by this tracker. - The live clock-lane key is `wallClock ? 1 : 0` (tick candidates precede wall-clock candidates); the recorded drift is the lane and due-point precedence over priority, not a claim that wall-clock candidates always run first. - The evaluator is intentionally bounded to persisted script definitions, structured command emission, simple conditions, and target fan-out. Richer graph/runtime evaluation, compiled artifacts, and a broader sandbox execution seam are not implemented and require a separate runtime slice. - Script-driven generation and richer procedural population are not established gameplay slices; the current runtime does not provide the broader procedural-population flow described by the target architecture. diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index e7ad594f81..cdb2fd0687 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -106,9 +106,9 @@ Redis queue-to-pending staging currently creates one durable `tick_batch` with ` Batch states are `STAGED`, `DRAINED`, `APPLIED`, and `ABANDONED`. Effect states are `STAGED`, `DRAINED`, `APPLIED`, `REPLAY_NOOP`, `REJECTED`, and `ABANDONED`. Existing pending work is correlated to an older staged batch or to a bounded `PENDING_REPLAY` batch created during recovery. The current tick boundary requires durable command identity; it does not retain a no-`commandId` recovery path. -The current `REPLAY_NOOP` and `REJECTED` effect statuses are implementation drift from the accepted [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) and [transaction effect contract](../../architecture/system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory): `REPLAY_NOOP` is an `APPLIED` outcome/reason, never a status, and a rejected or fenced effect is not terminally settled merely because execution did not proceed. The live executor persists those statuses and can mark a batch `APPLIED` once no `DRAINED` rows remain, without requiring every effect to be `APPLIED` or evidence-qualified `ABANDONED`. Target convergence must preserve the canonical terminal set, retain replay/rejection reasons separately, leave inconclusive work reconciliation-required, and add focused participant-set and batch-aggregation proof; the ADR and transaction owner remain authoritative for the mapping. +The live executor currently persists `REPLAY_NOOP` and `REJECTED` effect statuses, and can mark a batch `APPLIED` once no `DRAINED` rows remain without requiring every effect to be `APPLIED` or evidence-qualified `ABANDONED`. This is implementation drift from the accepted [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) and [transaction effect contract](../../architecture/system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory); focused participant-set and batch-aggregation proof remains absent. Those owners define the target status and recovery mapping. -The stale-fence path is a concrete instance of that drift: for a non-remote gameplay-command batch, `TickBatchExecutionService.executeDurableEffects` routes a stale-ownership `DRAINED` batch to `abandonStaleDrainedBatch`, which marks every remaining `DRAINED` effect `ABANDONED` and requeues its commands without domain evidence. Remote-followup batches instead route to `markRemoteFollowupBatchAbandoned` and do not requeue gameplay commands. The stale-fence handling can therefore terminalize unfinished effects without evidence that they were unapplied; an effect that started before the fence changed can be replayed and applied twice. Target recovery requires the ADR 0069 evidence-qualified `APPLIED`/`ABANDONED` decision, with inconclusive effects retained as non-terminal reconciliation work; focused stale-fence proof remains absent. +The stale-fence path is a concrete instance of that drift: for a non-remote gameplay-command batch, `TickBatchExecutionService.executeDurableEffects` routes a stale-ownership `DRAINED` batch to `abandonStaleDrainedBatch`, which marks every remaining `DRAINED` effect `ABANDONED` and requeues its commands without domain evidence. Remote-followup batches instead route to `markRemoteFollowupBatchAbandoned` and do not requeue gameplay commands. The stale-fence handling can therefore terminalize unfinished effects without evidence that they were unapplied; an effect that started before the fence changed can be replayed and applied twice. Focused stale-fence proof remains absent; target settlement and replay authority are defined by [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) and the [transaction effect contract](../../architecture/system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory). Legacy `TickStaging` rows with `commandId='-'` remain unresolved: the current parser and Lua path fail closed, and no authoritative drain, migration, or command-correlation proof exists for them. The sealed gameplay-command selected-work manifest is the current replay contract. It records explicit `regionId`, `enqueueSeq`/comparable source ordering, source kind/type and state, due tick/point, target and routing facts, automation dispatch/work-item identity, script/plugin provenance, and source-state metadata. `enqueueSeq` is used as `sourceOrdinal` where available instead of a transient batch slot. Durable command and remote-follow-up rows also persist their latest origin-source and queue-source tuples so status and operator reads do not need to parse manifests or payload JSON. Complete timer/retry/remote-follow-up source-claim manifests remain target-state follow-through; timer/automation-origin work appears in the current sealed manifest only after materialization as a gameplay command with its provenance and ordering fields retained. 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 ac5ddc96cb..a8ccf449ab 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -16,7 +16,7 @@ This tracker is the permanent reader-facing implementation record for world runt - `GR-2.1` / `SF-2.3`: The synchronous termination seam returns a `TERMINATED` snapshot before checking a supplied `terminationRequestId`; mismatched terminal retries therefore are not fail-closed, and exact identity/conflict proof remains incomplete. See [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). - `GR-2.1` / `SF-2.1`: Versioned topology and spawn schemas carry tenant/version columns but use scalar parent foreign keys, so the database does not enforce child/parent scope equality. Composite ownership enforcement (or an equivalent owner-local guard) and database readback proof remain incomplete; this is separate from sentinel-default and hierarchy/version-graph backfill drift. See [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). - `GR-2.1` / `AR-1.5`: The WMS design handoff performs only a remote Game Design Draft-state check before its local mutation transaction. Durable owner-freeze acknowledgement and commit-bound `versionStateEpoch`/`publicationFence` evidence are absent, so a pre-check can race publication; the target handoff and race semantics belong to [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md#publication-freeze-and-owner-handoff), with local status and proof consequences in [World Management Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#implementation-status). -- The current Temporal lifecycle signal implementation keeps one mutable pending slot per operation and can overwrite repeated requests or process activate plus terminate against a stale epoch; this race and its focused proof remain incomplete. The target durable signal/update contract and conflict semantics are owned by [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). +- `GR-2.1` / `AR-3.1`: The current Temporal lifecycle signal implementation keeps one mutable pending slot per operation and can overwrite repeated requests or process activate plus terminate against a stale epoch; this race and its focused proof remain incomplete. The target durable signal/update contract and conflict semantics are owned by [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). These links add decision provenance only; they do not upgrade world runtime, lifecycle, or Draft mutation status. From a0e1611a21d0b3f8f4b36160b41a88a51350f96f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 16:56:16 +1300 Subject: [PATCH 53/68] docs: require complete tick settlement and qualified recovery --- ...inistic-effect-id-allocation-and-replay-binding.md | 2 +- .../system-architecture-redis-operations.md | 2 +- ...architecture-scripting-control-plane-operations.md | 2 +- .../system-architecture-tick-execution-flows.md | 4 ++-- design/architecture/system-architecture-ticks.md | 2 +- dev-tools/tests/architecture-doc-contracts.sh | 11 ++++++++++- 6 files changed, 16 insertions(+), 7 deletions(-) diff --git a/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md b/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md index 2cade3fd26..236b48d70b 100644 --- a/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md +++ b/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md @@ -29,7 +29,7 @@ The move from the conflicting draft number ADR 0182 to ADR 0183 is mechanical pr Generated chains and global fan-out need an identity that survives retries, crashes, replay, runtime replacement, and reconciliation without turning semantic fields into an ID. This proposal considers a durable semantic command plan, stable `planOrdinal`, and command-root binding, as well as generated-child and fan-out allocation. Candidate suppression must remain auditable without inventing an ID for work that never entered execution. -This proposal records design options for command-plan order and root allocation, exact UUIDv7 scalar identity, versioned canonical serialization, generated-child/fan-out manifests, and atomic allocation. All remain pending human approval. ADR 0069's independently accepted identity, replay, and terminal-outcome rules continue to apply without establishing any of these allocation choices. +This proposal records design options for command-plan ordering and `planOrdinal`, command-root identity/allocation owner and key, exact `EffectId` scalar format, versioned canonical serialization, additional allocator mechanics, command-plan/manifest binding, and atomic allocation; these remain pending human approval. Separately, [ADR 0069](./adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), [ADR 0075](./adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md), and [ADR 0077](./adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md) establish the accepted owner-defined child ordinal and durable owner-scope/root/parent/ordinal-to-child-`EffectId` mapping. Those child-identity requirements remain target contract independently of this proposal; ADR 0183 does not replace them or make its additional format, allocator, or manifest choices current. The independently accepted identity, replay, and terminal-outcome rules of ADR 0069 also continue to apply. ## Decision diff --git a/design/architecture/system-architecture-redis-operations.md b/design/architecture/system-architecture-redis-operations.md index 657c8e7aeb..b55c93356a 100644 --- a/design/architecture/system-architecture-redis-operations.md +++ b/design/architecture/system-architecture-redis-operations.md @@ -176,7 +176,7 @@ Manual AOF surgery is not supported. Either the AOF is trusted and replayed as-i Goal: provide a simple, explicit runbook for resetting Cache/Rate-Limit Redis without entangling it with Coordination Redis resets. -> **Target state only — unavailable today.** The external Cache deployment maintenance gate, `FLUSHDB`/`FLUSHALL` or clustered deletion, client release, and authorized Automation rebuild/readback sequence below are not current operator instructions. The repository does not yet provide the required external gate, writer admission/acknowledgement proof, or authorized rebuild path. Current operators must preserve cache, reset, and incident evidence, avoid destructive reset or client-release actions, keep affected writers/clients quarantined or stopped, and use the safe fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) and escalation path. +> **Target state only — unavailable today.** The external Cache deployment maintenance gate, `FLUSHDB`/`FLUSHALL` or clustered deletion, client release, and authorized Automation rebuild/readback sequence below are not current operator instructions. The repository does not yet provide the required external gate, writer admission/acknowledgement proof, or authorized rebuild path. Current operators must preserve cache, reset, and incident evidence and avoid destructive reset or client-release actions. Affected writers may be quarantined or stopped only through an existing supported readiness control; if none applies, leave the deployment untouched, preserve evidence, and escalate through the safe fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) and escalation path. ### External Cache Deployment Maintenance Gate diff --git a/design/architecture/system-architecture-scripting-control-plane-operations.md b/design/architecture/system-architecture-scripting-control-plane-operations.md index 846c108843..bf21079a0b 100644 --- a/design/architecture/system-architecture-scripting-control-plane-operations.md +++ b/design/architecture/system-architecture-scripting-control-plane-operations.md @@ -284,7 +284,7 @@ Inputs: `reason` is required and must be non-blank; Game Session validates it before reading the owned instance or purging queue/durable command state. -Semantics and outputs: same as `PurgeQueuedTickCommandsForScriptPatch`, including `LOST_BEFORE_STAGING` only for commands acknowledged `ACCEPTED_VOLATILE` that remain `RECEIVED` or `ENQUEUED` with no surviving batch, while `ACCEPTED_DURABLE` pre-batch work remains under its durable retry/recovery contract; durably batch-bound retry uses `ABANDONED`. Both outcomes use `gameplayResult = NOT_APPLIED`, `failureCode = ROLLBACK_PURGED`, and the validated nonblank ingress `reason` as `failureMessage`, scoped to plugin-produced commands by the `pluginId` and `pluginVersionId` provenance carried from Automation into Game Session during handoff. +Plugin rows are selected by their stored `pluginId` and `pluginVersionId` provenance. `LOST_BEFORE_STAGING` eligibility, the validated nonblank ingress `reason`, and evidence-qualified batch-bound handling follow [PurgeQueuedTickCommandsForScriptPatch](#purgequeuedtickcommandsforscriptpatch); inconclusive work remains nonterminal under that owner contract. ### Automation & Scripting: Drain/Purge Hooks (Rollback Support) diff --git a/design/architecture/system-architecture-tick-execution-flows.md b/design/architecture/system-architecture-tick-execution-flows.md index 906768cbc6..d949c86eec 100644 --- a/design/architecture/system-architecture-tick-execution-flows.md +++ b/design/architecture/system-architecture-tick-execution-flows.md @@ -372,7 +372,7 @@ Conceptually, tick commit proceeds through these phases: - Domain services process staged effects under participant guards keyed by the persisted mutation `EffectId` (root ID for a root mutation, child ID for a generated child), with `rootEffectId` retained separately as lineage, and update authoritative PostgreSQL state in their own databases. - Game Session records the outcome of each effect in its tick effect ledger (`SCHEDULED` → `APPLIED` or `ABANDONED`) only when the durable domain evidence and existing recovery policy permit that transition; inconclusive old-epoch work remains non-terminal reconciliation work under its original mutation `EffectId`, with enclosing `rootEffectId` retained as lineage and reconciliation context. Domain services do not write to the Game Session ledger directly. 4. **Commit visibility** - - For a non-empty batch, the current-epoch commit predicate: terminal (`APPLIED` or `ABANDONED`) evidence under the existing evidence policy is required for every required participant in that tick's complete expected current-epoch participant set. Once that predicate holds, one fenced durable commit boundary transitions `tick_batch.status` to `COMMITTED` and advances the commit authority `RegionStatus.lastCommittedTickId` for the complete current scope under the same `executorFence`; only then may the target-state tick heartbeat be emitted. Inconclusive old-epoch rows remain non-terminal reconciliation work outside this current-epoch commit predicate; they may still block unsafe next-tick progression, reset-scope convergence, or reopening. A truly empty boundary uses the separate fenced one-tick status transition and post-commit heartbeat branch above, with no batch ledger. The current-live deployment instead advances the committed tick fields on `RuntimeOwnershipStatus` under the current-live opaque fence; `ObserveRuntimeTickProgress` reports that progress, and neither `RegionStatus` nor `StreamTickHeartbeats` is implied to be live. + - For a non-empty batch, the current-epoch commit predicate: terminal (`APPLIED` or `ABANDONED`) evidence under the existing evidence policy is required for every eligible ledger row in that tick's complete expected current-epoch participant set. Once that predicate holds, one fenced durable commit boundary transitions `tick_batch.status` to `COMMITTED` and advances the commit authority `RegionStatus.lastCommittedTickId` for the complete current scope under the same `executorFence`; only then may the target-state tick heartbeat be emitted. Inconclusive old-epoch rows remain non-terminal reconciliation work outside this current-epoch commit predicate; they may still block unsafe next-tick progression, reset-scope convergence, or reopening. A truly empty boundary uses the separate fenced one-tick status transition and post-commit heartbeat branch above, with no batch ledger. The current-live deployment instead advances the committed tick fields on `RuntimeOwnershipStatus` under the current-live opaque fence; `ObserveRuntimeTickProgress` reports that progress, and neither `RegionStatus` nor `StreamTickHeartbeats` is implied to be live. - Cross-region coordinator rows such as `PENDING_REMOTE` are not part of this terminal set; they are durable workflow state outside the committing tick batch. 5. **Coordination cleanup** - A final commit/cleanup script clears the `pending` entry for the tick and releases any entity locks for that region only after exact equality between the pending envelope set and the durable batch/ledger expected set has been established. `expected_effect_count` and any digest are diagnostic hints and cannot authorize cleanup on their own. @@ -381,7 +381,7 @@ Conceptually, tick commit proceeds through these phases: From the perspective of the `(regionEpoch, tickId)` timeline: - A tick is `durable_committed` once: - - For a non-empty tick, the current-epoch commit predicate: terminal (`APPLIED` or `ABANDONED`) evidence is required, where the evidence policy permits terminalization, for every required participant in that tick's complete expected current-epoch participant set. Inconclusive old-epoch rows remain non-terminal reconciliation work outside this current-epoch commit predicate; they may still block unsafe next-tick progression, reset-scope convergence, or reopening. A truly empty tick instead proves the authoritative no-due-work/source-claim condition and commits the fenced one-tick status transition, and + - For a non-empty tick, the current-epoch commit predicate: terminal (`APPLIED` or `ABANDONED`) evidence is required, where the evidence policy permits terminalization, for every eligible ledger row in that tick's complete expected current-epoch participant set. Inconclusive old-epoch rows remain non-terminal reconciliation work outside this current-epoch commit predicate; they may still block unsafe next-tick progression, reset-scope convergence, or reopening. A truly empty tick instead proves the authoritative no-due-work/source-claim condition and commits the fenced one-tick status transition, and - The target-state commit authority `RegionStatus.lastCommittedTickId`, or the current-live committed tick fields on `RuntimeOwnershipStatus`, has advanced to that `(regionEpoch, tickId)` under the applicable fence. `ObserveRuntimeTickProgress` may confirm current-live progress but does not replace the durable authority. - A tick is `coordination_cleared` once: - There is no remaining `pending` entry for that tick in Redis and lock cleanup for that tick has completed. diff --git a/design/architecture/system-architecture-ticks.md b/design/architecture/system-architecture-ticks.md index 28c35cd349..6d3d932571 100644 --- a/design/architecture/system-architecture-ticks.md +++ b/design/architecture/system-architecture-ticks.md @@ -97,7 +97,7 @@ Consumers that persist offsets must key stable consumer identity by `(tenantId, FireMUD uses two explicit tick boundaries for ``: - **`durable_committed`** (authoritative commit boundary): - - The current-epoch commit predicate: terminal (`APPLIED` or `ABANDONED`) evidence is required, where the evidence policy permits terminalization, for every required participant in that tick's complete expected current-epoch participant set. Inconclusive old-epoch rows remain non-terminal reconciliation work outside this current-epoch commit predicate; they may still block unsafe next-tick progression, reset-scope convergence, or reopening. There are no remaining `SCHEDULED` ledger rows for that tick's batch. + - The current-epoch commit predicate: terminal (`APPLIED` or `ABANDONED`) evidence is required, where the evidence policy permits terminalization, for every eligible ledger row in that tick's complete expected current-epoch participant set. Required-versus-optional classification affects command-result aggregation, not tick commit. Inconclusive old-epoch rows remain non-terminal reconciliation work outside this current-epoch commit predicate; they may still block unsafe next-tick progression, reset-scope convergence, or reopening. There are no remaining `SCHEDULED` ledger rows for that tick's batch. - **Target-state only:** For a non-empty batch, `tick_batch.status` is `COMMITTED` in this same fenced durable visibility boundary; a `CREATED`, `REDIS_STAGED`, or otherwise non-committed batch cannot advertise committed progress. The current-live code retains `APPLIED` as its batch terminal status and uses the committed tick fields on `RuntimeOwnershipStatus` as its commit-authority watermark under the same opaque fence; `ObserveRuntimeTickProgress` is the progress feed and does not replace that durable authority. - Target-state `RegionStatus.lastCommittedTickId` has been advanced to the complete `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)` scope as part of that same durable visibility boundary. - **`coordination_cleared`** (in-flight clearance boundary): diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index c58f6608c6..ad5a6cc15e 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -2155,7 +2155,7 @@ for tick_commit_path in ( tick_commit_path, [ "current-epoch commit predicate: terminal (`APPLIED` or `ABANDONED`) evidence", - "every required participant in that tick's complete expected current-epoch participant set", + "every eligible ledger row in that tick's complete expected current-epoch participant set", "Inconclusive old-epoch rows remain non-terminal reconciliation work outside this current-epoch commit predicate", "may still block unsafe next-tick progression, reset-scope convergence, or reopening", ], @@ -2163,11 +2163,20 @@ for tick_commit_path in ( require_absent( tick_commit_path, [ + "every required participant in that tick's complete expected current-epoch participant set", "An inconclusive old-epoch row remains non-terminal and blocks this advancement", "inconclusive old-epoch work remains non-terminal and prevents this boundary", ], ) +require_contains( + "design/architecture/system-architecture-ticks.md", + [ + "every eligible ledger row in that tick's complete expected current-epoch participant set", + "Required-versus-optional classification affects command-result aggregation, not tick commit", + ], +) + automation_base = (root / "k8s/base/automation-scripting-service.yaml").read_text(encoding="utf-8") game_design_base = (root / "k8s/base/game-design-service.yaml").read_text(encoding="utf-8") automation_helm = (root / "k8s/helm/firemud/templates/apps.yaml").read_text(encoding="utf-8") From 279d2677252b017a5d941ae352bf0a76b818c2f2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:30:55 +1300 Subject: [PATCH 54/68] docs: close replay fencing and target-state contract gaps --- ...terministic-fair-entity-tick-scheduling.md | 2 +- .../runtime-and-data.md | 2 +- .../game-design-service/modding-framework.md | 4 +- .../system-architecture-gateway.md | 2 +- ...system-architecture-identifier-glossary.md | 2 +- .../system-architecture-redis-ops-access.md | 2 +- ...rchitecture-scripting-control-plane-api.md | 2 +- ...tecture-scripting-examples-and-patterns.md | 6 +-- ...stem-architecture-tick-incident-runbook.md | 2 +- .../architecture/system-architecture-ticks.md | 2 +- .../gameplay-rules-entities-and-effects.md | 2 +- dev-tools/tests/architecture-doc-contracts.sh | 43 +++++++++++++++++++ .../src/main/resources/openapi.yaml | 6 +-- 13 files changed, 60 insertions(+), 17 deletions(-) diff --git a/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md b/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md index 867513751f..3e43fd9dcd 100644 --- a/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md +++ b/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md @@ -49,7 +49,7 @@ Within one entity's eligible queue, work uses persisted deterministic ordering: `entity_enqueue_seq` is monotonic within the entity's current region epoch and assigned by the owning Game Session admission/scheduling path. Same-tick derived children use the persisted parent order plus deterministic child ordinals rather than completion timing. New sources map into this tuple and do not introduce private tie-breakers. -The historical final tuple label `commandId_or_effectKey` is one normalized, persisted, source-specific stable identity slot: `command` uses `commandId`; `timer` uses the timer member ID; `retry` uses the persisted retry member/effect identity required by its owning contract; `remote_followup` uses the durable follow-up row ID; and `generated_effect` uses its recorded child `EffectId` as the slot value. Parent/root identity and child ordinal remain recorded audit and ordering context; they do not replace the child effect identity. The selected manifest retains the source-to-slot mapping and that context for each item; this does not introduce a second tuple or schema field. The child-ID allocation choice remains pending in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) and is not current target state. +The historical final tuple label `commandId_or_effectKey` is one normalized, persisted, source-specific stable identity slot: `command` uses `commandId`; `timer` uses the timer member ID; `retry` uses the persisted retry member/effect identity required by its owning contract; `remote_followup` uses the durable follow-up row ID; and `generated_effect` uses its recorded child `EffectId` as the slot value. Parent/root identity and child ordinal remain recorded audit and ordering context; they do not replace the child effect identity. The selected manifest retains the source-to-slot mapping and that context for each item; this does not introduce a second tuple or schema field. For generated children, the owner-defined ordinal and durable owner-scope/root/parent/ordinal-to-child-`EffectId` mapping are mandatory and replay-stable under accepted [ADR 0075](./adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). Only scalar choices and additional allocator mechanics remain pending in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); that proposal does not defer the accepted child identity or mapping requirement. Across eligible entities, each lane uses persisted deterministic rotating/deficit scheduling. The scheduler accounts for declared work cost, advances only with the durable selected batch, and ensures a permanently eligible entity eventually receives capacity within a healthy epoch. Non-best-effort priority classes declare bounded aging or `maxDeferralTicks`; work explicitly classified as best effort follows its declared delay/drop policy. 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 5fc70179de..0048d2555f 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -105,7 +105,7 @@ This behavior ensures that a script patch either becomes the new active version **Target-state recovery evidence:** Automation owns a monotonic `failureGeneration` per `(tenantId, outboxWorkItemId)` and initializes/advances it exactly once in the same atomic transition that enters `DEAD_LETTERED`; exact transition retries/no-ops do not advance it. Dead-letter rows retain the immutable failure stage and current `failureGeneration`, original Trigger Identity, exact patch/epoch, immutable `lane` and bounded `cost_class`, owner-committed `controlPlaneRequestId`, plugin provenance and captured `pluginActivationEpoch`/`lifecycleRevision` where applicable, frozen manifest, immutable evaluated output, and a complete descriptor/child-dispatch ledger keyed by the full Command-Handoff Identity. Per-item request results, recovery claims/attempts, successful-recovery evidence, and `already_recovered` readback bind `(tenantId, outboxWorkItemId, failureGeneration)`; one active claim exists per current generation and stale owners/generations fail CAS. A new request resolves the current failure generation atomically, so older-generation evidence remains immutable and cannot satisfy or block a newer current generation. Per-child recovery state records each child status, its persisted `handoffRequirement`, attempt/claim information, and durable downstream acknowledgement or outcome. The evaluated output and complete ledger are replay input; an evaluated-output or command digest is integrity evidence only and cannot substitute for the retained output or descriptor identity. `outboxWorkItemId`, the parent Trigger Identity, and `scriptEventId` remain correlation-only identifiers and are not child identity. The frozen manifest retains `priorityTag`, `quotaClass`, `lane`, `cost_class`, `componentCostRegistryDigest`, and `artifactRuntimeCapDigest` where applicable; evaluation-stage and post-evaluation recovery reuse that evidence verbatim without recomputing mutable registry, cap, scheduler-policy, or required/optional classification values. Evaluation-stage recovery may retry the original graph; post-evaluation recovery only resumes unfinished children. Missing or contradictory evidence, including missing or changed lane/cost, plugin lifecycle-fence, or handoff-requirement values at handoff, replay, or recovery, remains dead-lettered and fails closed. Schedule reconciliation defaults to cancel-and-recreate, with continuity only when the authored stable identity and compatibility declaration explicitly match. -Ordinary owner-local dead-letter recovery/retry remains non-conflicting routine replay when it only replays the owner’s existing durable PostgreSQL work-item truth. Target `automation:queue:*` queue-pointer rebuild is non-conflicting routine reprojection only through the owner-reconciled `PENDING_EVALUATION` status/owner/CAS gate; current reset/rebuild/resume remains unavailable and must fail closed because the implementation cannot distinguish safe from stale claims. Automation records the owner classification and the evidence for that exemption, including the exact durable identity, source snapshot/cursor, request or output digest, and affected scope; this does not grant maintenance authority. Any maintenance or reset mutation, including one reached from dead-letter recovery or pointer rebuild, must instead carry the unchanged ADR-0085 external maintenance handoff with its exact `operationId`, external maintenance fence/lock binding, classifier, immutable evidence digest, and complete affected scope, or fail closed. +Ordinary owner-local dead-letter recovery/retry is non-conflicting routine replay only when complete stage-specific recovery evidence proves the eligible transition and, for post-evaluation work, the persisted child ledger records each child disposition; ambiguous states such as `EVALUATING` or `HANDOFF_IN_FLIGHT` do not qualify merely because PostgreSQL contains a work item. Apply the canonical stage-aware eligibility and recovery rules in [Scripting & Automation: Control Plane API](../../system-architecture-scripting-control-plane-api.md#replaydeadletteredworkitems). Target `automation:queue:*` queue-pointer rebuild is non-conflicting routine reprojection only through the owner-reconciled `PENDING_EVALUATION` status/owner/CAS gate; current reset/rebuild/resume remains unavailable and must fail closed because the implementation cannot distinguish safe from stale claims. Automation records the owner classification and the evidence for that exemption, including the exact durable identity, source snapshot/cursor, request or output digest, and affected scope; this does not grant maintenance authority. Any maintenance or reset mutation, including one reached from dead-letter recovery or pointer rebuild, must instead carry the unchanged ADR-0085 external maintenance handoff with its exact `operationId`, external maintenance fence/lock binding, classifier, immutable evidence digest, and complete affected scope, or fail closed. ## Redis Roles and Prefixes diff --git a/design/architecture/microservices/game-design-service/modding-framework.md b/design/architecture/microservices/game-design-service/modding-framework.md index aa9e9c9d26..5a3b99ff73 100644 --- a/design/architecture/microservices/game-design-service/modding-framework.md +++ b/design/architecture/microservices/game-design-service/modding-framework.md @@ -354,7 +354,7 @@ Design-time publication and runtime activation are separate: - **Disable after drain** – reserves a same-epoch `targetLifecycleRevision = current lifecycleRevision + 1` for `DRAINING` without making it current, installs that exact target through Game Session, and waits for durable acknowledgement before committing the Automation owner state/history/revision. Once `DRAINING` is committed, only already-admitted work whose winning admission/fence CAS durably committed the immediately preceding `ENABLED` revision before the durable Automation-owned `DRAINING` admission barrier was created may complete within the bounded drain policy; capture or observation alone is insufficient. At bounded completion or forced timeout, it independently reserves `targetPluginActivationEpoch = current pluginActivationEpoch + 1` and `targetLifecycleRevision = current lifecycleRevision + 1` from the committed owner row for `DISABLED`, installs and durably acknowledges that exact target through Game Session, then commits the Automation owner state/history/epoch/revision. New triggers are rejected once draining begins and cleanup remains asynchronous. See [ADR 0119](../../decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md) for the single canonical drain exception rather than repeating its full fence contract here. - Updating a plugin involves setting a new `pendingVersionId`, loading and validating the new plugin graphs and bindings, reconciling plugin-owned timers and other derived scheduler state, and then atomically switching `activeVersionId` if validation succeeds. If validation or activation-state reconciliation fails, the new version is marked `FAILED`, `activeVersionId` remains unchanged, and triggers for the failed version are rejected at admission with an appropriate `finalOutcome` (for example, `version_unavailable` or `plugin_version_failed`). -Plugin triggers share the same Trigger Identity and `scriptEventId` lifecycle as regular scripts. Pre-handler admission outcomes are recorded in `script_event_ingress_audit` and create no handler row. Each resolved live handler invocation has one `script_event_audit` row with the required Trigger Identity fields, including `tenantId` and `gameInstanceId` only for instance-bound handlers; tenant-readiness `onLoad` uses its pre-instance identity and omits instance fields. Gameplay/runtime handlers also carry `playableStateNamespaceId` and `regionEpoch`, plus separately persisted exact-validated `playableStateScope` policy/routing/authorization/migration-fence evidence, `pluginId` / `pluginVersionId`, and stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`) so operators can correlate plugin behavior with publish and enable/disable operations and still distinguish “DSL evaluated” from “accepted into tick queues”. The current legacy materialized dry-run/test handler path also records one handler audit row for its terminal result. Target ADR 0114 command-plan previews instead use the isolated preview result/audit surface or direct authorized result path and never create a handler row. Per-command acceptance, retry, and downstream outcomes belong in handoff child records keyed by the complete Command-Handoff Identity (source/target runtime scope plus `automationDispatchId` and `commandOrdinal`), not by dispatch ID alone and not in extra handler audit rows. The parent Trigger Identity and `outboxWorkItemId` remain correlation-only. +Plugin triggers share the same Trigger Identity and `scriptEventId` lifecycle as regular scripts. Pre-handler admission outcomes are recorded in `script_event_ingress_audit` and create no handler row. Each resolved live handler invocation has one `script_event_audit` row with the required Trigger Identity fields: `tenantId` is required for every handler, while `gameInstanceId` is required for instance-bound handlers and omitted for tenant-readiness `onLoad` (see normative [Table 1](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields)). Gameplay/runtime handlers also carry `playableStateNamespaceId` and `regionEpoch`, plus separately persisted exact-validated `playableStateScope` policy/routing/authorization/migration-fence evidence, `pluginId` / `pluginVersionId`, and stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`) so operators can correlate plugin behavior with publish and enable/disable operations and still distinguish “DSL evaluated” from “accepted into tick queues”. The current legacy materialized dry-run/test handler path also records one handler audit row for its terminal result. Target ADR 0114 command-plan previews instead use the isolated preview result/audit surface or direct authorized result path and never create a handler row. Per-command acceptance, retry, and downstream outcomes belong in handoff child records keyed by the complete Command-Handoff Identity (source/target runtime scope plus `automationDispatchId` and `commandOrdinal`), not by dispatch ID alone and not in extra handler audit rows. The parent Trigger Identity and `outboxWorkItemId` remain correlation-only. At handler admission, before evaluation or handoff, a plugin handler must prove and capture `breakerState=CLOSED` for the exact active `pluginVersionId` and runtime scope. That captured admission decision remains valid through evaluation and handoff; a later breaker trip blocks only newly resolved handlers and does not retroactively cancel accepted work. A disabled breaker is recorded as the bounded handler admission outcome above; it cannot be inferred from or folded into the lifecycle `pluginState`. @@ -468,7 +468,7 @@ For operator verification during rollback, disablement, or signer revocation, us Live plugin executions (`isDryRun=false`) participate in the same observability pipeline as live core scripts and use shared identifiers and live metric families. The current legacy materialized dry-run/test handler path records a terminal `finalStage=DSL_EVAL`, `finalOutcome=dry_run_completed`, and `finalReason=dry_run_no_handoff` in `script_event_audit`; target ADR 0114 command-plan previews remain isolated to the preview result/audit surface or direct authorized result path. Preview/test executions use the corresponding test-only metric families and do not increment live families: -- Each resolved live plugin handler is recorded in `script_event_audit` with the applicable required Trigger Identity fields, including `regionEpoch` for gameplay/runtime events; `tenantId` and `gameInstanceId` are present only for instance-bound handlers, while tenant-readiness `onLoad` omits instance fields (see canonical [normative Table 1](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields)). The audit also records `pluginId` / `pluginVersionId` and stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`). Pre-handler admission outcomes are recorded in `script_event_ingress_audit` and create no handler row. +- Each resolved live plugin handler is recorded in `script_event_audit` with the applicable required Trigger Identity fields, including `tenantId` for every handler and `regionEpoch` for gameplay/runtime events; `gameInstanceId` is required for instance-bound handlers and omitted for tenant-readiness `onLoad` (see normative [Table 1](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields)). The audit also records `pluginId` / `pluginVersionId` and stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`). Pre-handler admission outcomes are recorded in `script_event_ingress_audit` and create no handler row. - The shared Automation trigger, skip, drop, sandbox-failure, and runtime metric families expose plugin behavior alongside core automation using only the finite `script_kind`, `plugin_origin`, `event_class`, and other bounded dimensions defined by [normative Table 4](../../system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix). Exact plugin and version identities never become Prometheus labels. Logging & Admin may surface exact plugin and version identities only through explicitly approved audit records, protected logs, named span families whose documented incident query requires them, and authorized control-plane or diagnostic queries. Trace use follows [ADR 0167](../../decisions/adr-0167-allowlisted-sensitive-trace-attributes.md): producer-side span-family allowlists, least-privilege environment-scoped access with audited queries, finite profile-defined retention, and declared export/privacy/erasure handling apply; availability in all logs, traces, or queries is not implied. On those approved surfaces, operators can: diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index 140fc1ccc2..f7a684d23c 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -401,7 +401,7 @@ This section is the canonical source of truth for connect-token enforcement and - Replay checks must be backed by the player-facing Coordination Redis deployment (not Cache/Rate-Limit Redis or per-pod memory) so `jti` replay decisions are consistent across horizontally scaled gateway pods and cannot be selectively evicted. The deployment requires Redis 7.2+ with AOF enabled, `noeviction`, replay-key ACL isolation, and admission-blocking capacity thresholds. The atomic marker script is followed by `WAITAOF requiredLocalAofCount requiredReplicaAofCount timeout`; `DURABLE_REPLAY_CONSUME_ACK` succeeds only when the reported AOF-fsync counts meet the configured thresholds, with at least one local AOF acknowledgement. The browser-deny write uses the same pinned Coordination connection and configured timeout/threshold after the write; if a valid marker already exists, reassert it with its unchanged original absolute expiry before `WAITAOF`, or withhold the durable acknowledgement until the original write's durability is proven. Never extend its expiry; malformed or conflicting marker state stays non-mutating and fails closed. Its propagation remains in the default `redis.REPL_ALL` mode. An unavailable, timed-out, malformed, below-threshold, or otherwise ambiguous deny write is unconfirmed and cannot be reported as terminal revocation. `WAIT`, read-back, or a successful client write is not a substitute, and this contract does not claim protection from disk or hardware destruction. - Replay and browser-revocation state use the canonical target representation defined by the Redis ownership and recovery documents, with bounded cardinality and deterministic expiry at `exp + firemud.gateway.connectTokenClockSkewMs`. The readiness/fence record and marker state must remain one script-compatible Coordination Redis atomicity domain under that contract. The legacy representation emitted by the current writer is migration-only drift and cannot be treated as target state. - The replay and deny-marker prefixes are security-critical, non-evicting coordination state. Gateway's one consume script checks readiness state, signed fence/cutoff, and deny-marker absence before creating the replay marker; consumption is successful only after that script and the configured Redis 7.2+ `WAITAOF` acknowledgement both succeed. A deny marker that linearizes before or during the consume race returns a denial without creating the replay marker; a consume already linearized is spent and cannot be retroactively undone by a later browser logout. A browser revocation is confirmed only after its deny write and same-connection durability acknowledgement succeed; an uncertain deny write remains unconfirmed. Capacity or acknowledgement failure rejects the handshake rather than accepting an uncertain marker. A crash or connection loss between marker creation and acknowledgement is treated as uncertain consumption, not as an opportunity to unconsume or retry the token. - - Coordination Redis cold start, reset, unexpected eviction signal, failover, capacity-safety breach, or any other event that cannot prove replay-marker continuity starts a shared replay-protection quarantine for at least the 30-second token lifetime maximum plus two `firemud.gateway.connectTokenClockSkewMs` intervals. One interval covers a latest tolerated future `iat`; the second covers acceptance through `exp + skew`. Account stops issuing connect tokens and Gateway rejects admission until that barrier expires, configuration and capacity checks pass, and a disposable marker script followed by the configured `WAITAOF` thresholds proves `DURABLE_REPLAY_CONSUME_ACK`; tokens from the earlier fence and issuance races cannot survive reopening. The current replay deployment has one shared continuity domain, so an unscoped continuity failure intentionally blocks new connect-token issuance and admission platform-wide; a future partitioned deployment may narrow quarantine only when it can prove the exact affected marker and fence domain. + - Coordination Redis cold start, reset, unexpected eviction signal, failover, capacity-safety breach, or any other event that cannot prove replay-marker continuity starts a shared replay-protection quarantine for at least the 30-second token lifetime maximum plus two `firemud.gateway.connectTokenClockSkewMs` intervals. One interval covers a latest tolerated future `iat`; the second covers acceptance through `exp + skew`. Account stops issuing connect tokens and Gateway rejects admission until that barrier expires, configuration and capacity checks pass, and a disposable marker script followed by the configured `WAITAOF` thresholds proves `DURABLE_REPLAY_CONSUME_ACK`; tokens from the earlier fence and issuance races cannot survive reopening. Before normal release, old Gateway replay writers must be drained or authoritatively blocked and the complete tagged replay state and readiness/fence state must be authoritative, in addition to the lifetime, skew, configuration/capacity, and disposable-marker `WAITAOF` gates above. If any old-version writer or admission remains allowed, release additionally requires a separately proven cross-version guard; none is currently implemented or proven, so that mixed-version release path remains forbidden. The current replay deployment has one shared continuity domain, so an unscoped continuity failure intentionally blocks new connect-token issuance and admission platform-wide; a future partitioned deployment may narrow quarantine only when it can prove the exact affected marker and fence domain. - Replay-quarantine lifecycle is a monitored security state. Gateway must emit low-cardinality `gateway.connect_token.replay_quarantine_entries_total{reason=...}`, `gateway.connect_token.replay_quarantine_exits_total{outcome=...}`, `gateway.connect_token.replay_quarantine_active`, and `gateway.connect_token.replay_quarantine_duration_seconds`, plus structured records containing the shared `replayAdmissionFence`, `state`, `quarantineStartedAt`, `quarantineUntil`, and `openedAt` values. Alertmanager must alert when a player-facing quarantine is entered, remains active past `quarantineUntil` or has no observed exit, or exits without fresh `DURABLE_REPLAY_CONSUME_ACK` proof. Dashboards must show entry/exit counts and duration. Labels must exclude `jti`, tenant identifiers, and other high-cardinality values. - Replay-cache outage behavior: - Player-facing environments (`/ws/game/**` in `enforce` mode): fail closed with HTTP `403` and `CONNECT_REPLAY_PROTECTION_UNAVAILABLE` when replay protection is unavailable. diff --git a/design/architecture/system-architecture-identifier-glossary.md b/design/architecture/system-architecture-identifier-glossary.md index 42ea1dc8d3..da8d6d57f6 100644 --- a/design/architecture/system-architecture-identifier-glossary.md +++ b/design/architecture/system-architecture-identifier-glossary.md @@ -84,7 +84,7 @@ World Management may use a numeric room row key as `roomInstanceId` only when it Tick-driven, cross-service mutations are at-least-once and must be idempotent. -- `EffectId` – the persisted mutation identity for one logical effect. Retries, replay, and reconciliation preserve the same mutation identity and immutable request digest under the accepted effect contract. A generated child has its own persisted child `EffectId` while retaining enclosing-root and parent lineage where applicable. Command-root allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +- `EffectId` – the persisted mutation identity for one logical effect. Retries, replay, and reconciliation must preserve the same mutation identity and validate the immutable request digest under the accepted effect contract. A generated child has its own persisted child `EffectId` while retaining enclosing-root and parent lineage where applicable. Current Entity replay looks up by `(tenantId, effectId)` but does not validate a request digest, so it does not prove this target contract. Command-root allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). - `deterministic effect plan` – a proposed ordered set of command-root effects described in pending [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); it is not an accepted canonical term or requirement. - `planOrdinal` – a proposed command-root allocation field described in pending [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); it is not an accepted identity or ordering contract. - **Participant guard identity** – a deterministic uniqueness identity under the owning runtime-family contract. For owner-classified S1/S2 families, the durable guard partition is `(tenantId, playableStateNamespaceId)` plus the owning identity/effect (`EffectId`, typed operation, and target aggregate); `gameInstanceId` is not a uniqueness dimension and is carried and exact-validated separately as active-runtime authorization/fence evidence. Only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)` as its durable partition; an unknown or unclassified family is rejected before any participant-guard allocation or admission and is never treated as S3 by default. A root effect uses its root `EffectId`; a generated child mutation uses its persisted child `EffectId`, while the enclosing root remains lineage and reconciliation context rather than collapsing sibling guards. The child ordinal participates in deterministic child-ID derivation under the owning contract but is not a second guard-key field. For S1/S2, `playableStateNamespaceId` is the uniqueness partition; `playableStateScope` and `gameInstanceId` are separately persisted, exact-validated routing/authorization/fence evidence and are not additional uniqueness dimensions. Same family-partitioned guard identity with the same request and evidence returns the prior result; a changed tenant, namespace, owning effect, operation, target, scope, digest, or separately validated active-instance fence fails closed. Work explicitly outside playable-state scope must use an accepted owner-specific idempotency/partition contract; it cannot omit namespace/scope and proceed under this gameplay participant-guard contract. The durable outcome and other evidence/reconciliation fields are mutable guard-row state protected by CAS, not part of uniqueness identity. A conserved multi-participant operation normally shares one effect identity but still follows [ADR 0053](./decisions/adr-0053-command-atomicity-by-invariant-class.md)'s atomicity/co-location/reservation semantics. diff --git a/design/architecture/system-architecture-redis-ops-access.md b/design/architecture/system-architecture-redis-ops-access.md index 73c95c2b0c..fd31b6335d 100644 --- a/design/architecture/system-architecture-redis-ops-access.md +++ b/design/architecture/system-architecture-redis-ops-access.md @@ -14,7 +14,7 @@ The target control-plane and maintenance contract in this document is ahead of t Use this doc as the canonical target-state contract for later reset/replay tooling, but do not assume every operation below is already available in the running codebase. Current operators, runbooks, Helm hooks, Jobs, and dashboards must not invoke the `coordination-maintenance` commands described below until that surface is implemented and end-to-end proven. -Current Gateway wiring is a frozen wrong-role exception: `GameplayHandshakeFilter` receives the generic reactive Redis template from the `spring.data.redis` binding, whose current profile uses `FIREMUD_REDIS_CACHE_HOST`, while writing only the untagged replay marker `gateway:connect-token:jti:*`. It has no current browser-deny, readiness, or replay-fence writer; those are target-only state. The replay prefix remains Coordination-owned in the target and must not be admitted as Cache state. A Cache reset inventory/readback that finds that prefix, or the generic Gateway writer, must abort without deletion. Target Gateway replay uses the named Coordination ACL and exact co-slotted keys `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`; migration requires quarantine, exact old replay-prefix inventory/readback, named Coordination client/ACL cutover, target-key readback, and same-connection `WAITAOF` proof before the current writer is drained and Cache reset admission can be considered safe. +Current Gateway wiring is a frozen wrong-role exception: `GameplayHandshakeFilter` receives the generic reactive Redis template from the `spring.data.redis` binding, whose current profile uses `FIREMUD_REDIS_CACHE_HOST`, while writing only the untagged replay marker `gateway:connect-token:jti:*`. It has no current browser-deny, readiness, or replay-fence writer; those are target-only state. The replay prefix remains Coordination-owned in the target and must not be admitted as Cache state. A Cache reset inventory/readback that finds that prefix, or the generic Gateway writer, must abort without deletion. Target Gateway replay uses the named Coordination ACL and exact co-slotted keys `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`; migration requires quarantine, exact old replay-prefix inventory/readback, named Coordination client/ACL cutover, target-key readback, and same-connection `WAITAOF` proof before the current writer is drained and Cache reset admission can be considered safe. Quarantine release and Cache-reset admission remain fail-closed until the [Gateway replay-quarantine release gate](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake) is proven; the current untagged replay state and generic writer do not satisfy it. If old-version writers/admission cannot be excluded, release additionally requires a separately proven cross-version guard, which is not currently implemented or proven. ## Default Operator Surface diff --git a/design/architecture/system-architecture-scripting-control-plane-api.md b/design/architecture/system-architecture-scripting-control-plane-api.md index c23ca66cd5..de5a5d5f36 100644 --- a/design/architecture/system-architecture-scripting-control-plane-api.md +++ b/design/architecture/system-architecture-scripting-control-plane-api.md @@ -743,7 +743,7 @@ Contract rules: - For plugin-backed work, the recovery claim and attempt capture the exact `(pluginActivationEpoch, lifecycleRevision)` fence in addition to the script pin tuple. Work that references a revocable component also retains the applicable component-revocation security-policy fence as an independent recovery input; neither plugin lifecycle evidence nor ordinary component-policy evidence substitutes for it. Claim acquisition and each pre-evaluation/dispatch revalidation compare both lifecycle values with current owner evidence; a `lifecycleRevision` mismatch outside ADR 0119's same-epoch `DRAINING` predecessor eligibility is rejected with `plugin_binding_mismatch`, while `plugin_disabled` remains reserved for a lifecycle transition that invalidates admitted work. - Same-epoch `DRAINING` is the only predecessor exception: already-admitted work captured under the immediately preceding `ENABLED` lifecycle revision may finish only when its winning admission/fence compare-and-set committed before the durable `DRAINING` admission barrier was created (and therefore before the lifecycle transition) and every other exact fence passes. Arbitrary lower or non-predecessor revisions are rejected; see [ADR 0119](./decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md). -- Replay is fail-closed per work item. Eligibility requires exact current `(scriptPatchVersion, scriptPinEpoch)`, applicable plugin identity/version/binding and captured `(pluginActivationEpoch, lifecycleRevision)`, region/`regionEpoch`, and routing-bundle match to the immutable admitted evidence. For plugin work, the current scoped plugin activation/lifecycle, component-policy decision, capability-grant evidence, and signer/publication evidence must also be fresh and valid. +- Replay is fail-closed per work item. Eligibility requires exact current `(scriptPatchVersion, scriptPinEpoch)`, plus the separately captured nonblank `scriptPinControlPlaneRequestId` owner/fence evidence exact-compared with Game Session before evaluation and before each dispatch. The request ID is not part of the execution identity tuple. This owner evidence is distinct from the replay mutation's `controlPlaneRequestId`, which identifies the recovery request. Eligibility also requires applicable plugin identity/version/binding and captured `(pluginActivationEpoch, lifecycleRevision)`, region/`regionEpoch`, and routing-bundle match to the immutable admitted evidence. For plugin work, the current scoped plugin activation/lifecycle, component-policy decision, capability-grant evidence, and signer/publication evidence must also be fresh and valid. - After exact-request idempotency and current `failureGeneration` resolution, immutable successful-recovery evidence bound to that same current generation returns `outcome=already_recovered` before aggregate-status or active-claim checks; `recovery_in_progress` applies only when no same-generation successful-recovery evidence exists and an active claim remains. After that precedence check, retained evidence proving that the selected parent's recovery inputs were purged—including `descriptorEvidencePurgedAt` for an `EVALUATED_COMMITTED` parent or the retained purge outcome for a pre-DSL row—returns `outcome=rejected` with `rejectionReason=stage_evidence_unavailable` and creates no claim/attempt. Using that internal identity, recovery compares-and-sets the current parent recovery aggregate `status=DEAD_LETTERED` together with a persisted recovery claim/attempt record containing `(tenantId, outboxWorkItemId, failureGeneration)`, the expected exact `(scriptPatchVersion, scriptPinEpoch)`, runtime scope, applicable plugin binding tuple and captured `(pluginActivationEpoch, lifecycleRevision)`, and `controlPlaneRequestId`, before evaluation or dispatch. A post-evaluation parent may retain its `EVALUATED_COMMITTED` descriptor marker and complete output/child ledger while this separate recovery aggregate is `DEAD_LETTERED`; that is the eligible `resumed_dispatch` case. A selected row in any other aggregate status remains unchanged and returns `outcome=rejected` with `rejectionReason=work_item_not_dead_lettered`. If a different `controlPlaneRequestId` targets a row with an active `IN_PROGRESS` claim for that generation, its stored deterministic request result is `outcome=rejected` with `rejectionReason=recovery_in_progress` and it creates no new claim/attempt, evaluation, or dispatch. If a created claim/attempt reaches terminal `FAILED`, its stored request result is `outcome=recovery_failed` with a required, bounded failureReason and no `rejectionReason`; an exact retry returns that stored result and reason without a new attempt. An expired claim is reclaimed under the same attempt record and identity (with a new owner fence when needed), never by inserting a duplicate recovery attempt or audit record; lease expiry alone does not allow a different request to create an attempt. A later new request may create one new attempt only after the prior attempt is terminal `FAILED` and fresh eligibility/fence checks pass. A prior successful recovery generation remains immutable; it is not `already_recovered` evidence for a newer current failure generation. - Evaluation-stage recovery uses the frozen original trigger/input manifest and exact graph, preserving the original work-item and `scriptEventId` identity; before its winning evaluated-descriptor/outbox commit it allocates no dispatch or command-child identity. If it emits commands, that first atomic descriptor commit allocates and persists the `automationDispatchId` and deterministic ordinals; retries after a winning commit reuse them. A valid zero-command evaluation creates no dispatch identity. It may invoke the DSL evaluator again for eligible gameplay/runtime work outside normal admission. Tenant-readiness `onLoad` remains at-most-once and is excluded from evaluation replay. Post-evaluation recovery uses only the immutable evaluated output and complete child-dispatch ledger keyed by the full Command-Handoff Identity, preserving original child identities and per-child recovery state without invoking the DSL. `HANDED_OFF` (accepted), `CANCELED`, and `DEAD_LETTERED` children are terminal and no-op. An already `HANDOFF_IN_FLIGHT` child is fenced and reconciled against the durable downstream outcome, never blindly redispatched; if that outcome is ambiguous, the child remains active/unresolved, the same recovery attempt remains `IN_PROGRESS`, no temporary or terminal per-row application result is stored, and `resumed_dispatch` is not reported. The initiating request or an exact retry attaches to that same attempt until a terminal result is available or its transport deadline expires; a transport deadline does not store a different result. Immediately before evaluation, and immediately before each post-evaluation dispatch, it revalidates the immutable admitted source runtime identity `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch)`, optional distinct target runtime identity `(targetGameInstanceId, targetPlayableStateNamespaceId, targetRegionId, targetRegionEpoch)`, separately validated source/target `playableStateScope` routing/fence evidence, exact `(scriptPatchVersion, scriptPinEpoch)`, and the immutable admitted source routing bundle `(playableStateScope, worldSlug, realmSlug, pointerVersion)`; when the target is distinct, recovery also persists and exact-compares the target bundle `(targetPlayableStateScope, targetWorldSlug, targetRealmSlug, targetPointerVersion)` against that same target. Together with the recorded binding, captured `(pluginActivationEpoch, lifecycleRevision)`, and current scoped plugin activation/lifecycle, component-policy, capability-grant, and signer/publication evidence, these checks preserve the source bundle and same-target semantics. For any revocable component, the retained component-revocation security-policy fence is independently revalidated at evaluation, each post-evaluation dispatch, and immediately before gameplay effects; it is not substituted by lifecycle or ordinary component-policy evidence. `DRAINING` blocks new trigger admission but does not invalidate already-admitted recovery; only a lifecycle transition that invalidates admitted work, such as `DISABLED`, revocation, or policy-driven disablement, uses `plugin_disabled`. Only after that dispatch-time revalidation succeeds may a `PENDING` or `INDEXED` child transition by durable compare-and-set to `HANDOFF_IN_FLIGHT` under the existing recovery claim/attempt fence and dispatch. Missing, stale, or temporarily unavailable evidence fails closed with the applicable established bounded reason (`authority_unavailable`, `component_policy_unavailable`, or `signer_policy_unavailable`); proven publication, component/capability, signer, tuple, epoch, or scope mismatches use `plugin_version_not_published`, `plugin_component_policy_blocked`, `signer_revoked`, `plugin_binding_mismatch`, `plugin_activation_epoch_mismatch`, `script_pin_epoch_mismatch`, or `runtime_scope_mismatch` as applicable. A `lifecycleRevision` mismatch outside the bounded `DRAINING` predecessor exception uses `plugin_binding_mismatch`; `plugin_disabled` remains reserved for an invalidating lifecycle transition. It never resolves a latest/local graph, and never regenerates an output after a child was accepted. - Before claim acquisition, a committed lifecycle invalidation wins as `plugin_disabled`; when no such invalidation is committed, a directly proven signer or component-policy failure uses `signer_revoked` or `plugin_component_policy_blocked`, respectively. Rows with missing/contradictory stage evidence or any fence mismatch discovered before claim acquisition remain `DEAD_LETTERED` and return a deterministic per-row `outcome=rejected` with the applicable bounded `rejectionReason`, with no claim/attempt. If the same evidence failure occurs after a claim/attempt exists, the first failing stage's bounded `failureReason` is persisted and that attempt terminalizes as `FAILED`; later lifecycle changes do not rewrite it. The attempt returns/stores `outcome=recovery_failed` with no `rejectionReason`; an exact retry returns the stored deterministic result. A rejected row is not partially changed or counted as successful. diff --git a/design/architecture/system-architecture-scripting-examples-and-patterns.md b/design/architecture/system-architecture-scripting-examples-and-patterns.md index 5873f2060c..25190f2dc4 100644 --- a/design/architecture/system-architecture-scripting-examples-and-patterns.md +++ b/design/architecture/system-architecture-scripting-examples-and-patterns.md @@ -48,7 +48,7 @@ This example walks through how a typical `onEnterRegion` script executes end-to- 2. **`onEnterRegion` event is emitted** - After the move is committed and the player is now in the new region, the Game Session Service emits an `onEnterRegion` **script event** to the Automation & Scripting Service over gRPC. - Conceptually this is a unary `TriggerScriptEvent` call on the Automation & Scripting Service that carries: - - `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, and `regionId`; `playableStateScope` is carried separately as exact-validated policy/routing/authorization/migration-fence evidence, not as an identity field. + - `tenantId`, `gameInstanceId`, and `regionId`; the target Trigger Identity additionally requires `playableStateNamespaceId`, which current `TriggerScriptEventRequest` does not carry. The current request carries `playableStateScope` separately as exact-validated policy/routing/authorization/migration-fence evidence, not as an identity field. - Target `entityId` (for example, an NPC guarding the room). - `eventType=onEnterRegion`. - The exact currently pinned `(scriptPatchVersion, scriptPinEpoch)` tuple for that game. @@ -80,7 +80,7 @@ This example walks through how a typical `onEnterRegion` script executes end-to- 7. **Execution, audit, and observability** - On subsequent ticks, the Game Session Service selects at most one root actor action per eligible entity in the `actor_action` lane; the separately bounded `passive_effect` lane includes passive, inbound, and actor-generated effect sources without consuming that actor-action slot. Both lanes follow their canonical fairness and conflict-resolution rules. - **Automation observability (Table 4 authority; current-vs-target status):** Canonical families such as `automation_script_triggers_total`, `automation_script_skips_total`, `automation_script_triggers_dropped_total`, and `automation_tick_events_enqueued_total` have names, finite labels, and increment units owned solely by [normative Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix); the quota counters `script_quota_allowed_total` and `script_quota_denied_total` are separately instrumented current evidence. The implemented evaluator's live `automation_script_work_item_outcomes_total` follows the Table 4 `service`, `stage`, `outcome`, `priority`, and bounded `source_class` label contract. Table 4 defines target materialized dry-run/test attempts with `automation_script_test_runs_total` (including capacity-denied results) and applicable test runtime, sandbox-failure, and `automation_script_test_capacity_denied_total` families; the canonical runs, runtime, and sandbox families remain unimplemented, while the current evaluator does emit a reused `automation_script_test_capacity_denied_total` metric with nonconforming labels. Current dry-run evidence also includes implementation-specific admission/capacity families `automation_script_test_runs_allowed_total`, `automation_script_test_runs_denied_total`, and `automation_script_test_capacity_{reserved,released}_total`; these current metrics do not prove Table 4 conformance, and dry-run terminal outcomes remain suppressed from the live family. **Target state:** an admitted live event resolving zero handlers contributes only metric-only `outcome=admitted_no_handlers`; **current implementation:** ingress still returns `admissionReason=admitted_no_handlers` and persists the ingress-audit row, with no handler-audit row. Tenant-readiness `onLoad` is separate and uses its readiness-owner `READY`/`FAILED` status and audit path, including `zero_handler_manifest_unverifiable` when applicable. The current ingress response/audit drift is documented in the [scripting observability contract](./system-architecture-scripting-observability-contract.md#ingress-audit-vs-handler-audit). - - An audit record is written to `script_event_audit` for each resolved handler Trigger Identity, with identifiers such as `scriptEventId`, `scriptId`, `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`, and `tickId`, plus separately persisted exact-validated `playableStateScope` evidence and stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`) so operators can distinguish “DSL evaluated” from “accepted into tick queues”, enabling replay and troubleshooting as described in the same quotas and operations document. + - **Target-state audit contract:** An audit record is written to `script_event_audit` for each resolved handler Trigger Identity, with identifiers such as `scriptEventId`, `scriptId`, `tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`, and `tickId`, plus separately persisted exact-validated `playableStateScope` evidence and stage-aware outcome fields (`finalStage`, `finalOutcome`, `finalReason`) so operators can distinguish “DSL evaluated” from “accepted into tick queues”, enabling replay and troubleshooting as described in the same quotas and operations document. Current `TriggerScriptEventRequest` has no `playableStateNamespaceId`; its `playableStateScope` remains separate evidence and cannot substitute for the target namespace identity. ### Mixed Fan-Out Example @@ -140,7 +140,7 @@ The complete target fixed-cadence pipeline below—durable timer firing, evaluat - Target-state work-item behavior: Each durable parent work item carries the full applicable Trigger Identity, including `scriptEventId`, `scriptId`, `gameInstanceId`, `playableStateNamespaceId`, version metadata, and the immutable trigger-created `regionId` and `regionEpoch`; it retains `playableStateScope` separately as exact-validated policy/routing/authorization/migration-fence evidence. Plugin-backed work also retains its captured `(pluginActivationEpoch, lifecycleRevision)` pair unchanged through the durable queue, handoff, retry, replay, recovery, and final execution, revalidating it as fence evidence rather than handler or command identity. If current entity state is needed to route the work at enqueue time, persist separate fields such as `enqueueRegionId` and `enqueueRegionEpoch`; never overwrite the original trigger fields. Deduplication, fencing, and replay continue to use the original `regionId` and `regionEpoch`. In the target handoff contract, each immutable emitted-command child uses the complete source runtime scope plus any distinct target runtime scope, a persisted `automationDispatchId`, and deterministic `commandOrdinal` from canonical output order; retries reuse that complete child identity. Parent Trigger Identity, `outboxWorkItemId`, and `scriptEventId` remain correlation only. See [Implementation Status](#implementation-status) for the current live handoff boundary. 5. **Execution, audit, and observability** - - **Target state only/unimplemented:** Automation later claims each durable parent work item in `PENDING_EVALUATION`, transitions the parent to `EXECUTING` under the fenced capacity lease, and atomically commits emitted command descriptors/child-dispatch rows at `EVALUATED_COMMITTED`; it uses `automation:queue` only as a rebuildable pointer index over committed descriptor children and hands resulting commands to the Game Session Service over internal gRPC so Game Session can enqueue them into the appropriate `tick:{tenantRegionTag}:queue:`. **Current legacy:** Automation drains the pre-DSL `automation:queue` parent-pointer projection (with a durable-scan fallback), evaluates each bounded parent work item, and attempts one Game Session handoff per emitted command. For same-scope targets, `ENQUEUED` means Game Session accepted the command into the local tick queue and `DUPLICATE_NOOP` confirms prior local acceptance; for distinct target scopes, `REMOTE_SCHEDULED` means only that the remote follow-up was scheduled and does not claim local tick-queue admission. Target descriptor replay/recovery, a rebuildable evaluated-work projection, complete command identity/`commandOrdinal` propagation, and independent per-command progress are unavailable or unproved. + - **Target state only/unimplemented:** Automation later claims each durable parent work item in `PENDING_EVALUATION`, transitions the parent to `EXECUTING` under the fenced capacity lease, and atomically commits emitted command descriptors/child-dispatch rows at `EVALUATED_COMMITTED`; it uses `automation:queue` only as a rebuildable pointer index over committed descriptor children and hands resulting commands to the Game Session Service over internal gRPC so Game Session can enqueue them into the appropriate `tick:{tenantRegionTag}:queue:`. **Current legacy:** Automation drains the pre-DSL `automation:queue` parent-pointer projection (with a durable-scan fallback), evaluates each bounded parent work item, and attempts one Game Session handoff per emitted command. The current authenticated receiving RPCs fail closed with `FAILED_PRECONDITION` (`automation_admission_receiver_fence_unavailable`) before mutation, so these attempts prove neither local tick-queue acceptance nor remote follow-up scheduling; see [Implementation Status](#implementation-status). Target descriptor replay/recovery, a rebuildable evaluated-work projection, complete command identity/`commandOrdinal` propagation, and independent per-command progress are unavailable or unproved. - On subsequent ticks, the Game Session Service selects at most one root actor action per eligible entity in the `actor_action` lane; the separately bounded `passive_effect` lane includes passive, inbound, and actor-generated effect sources without consuming that actor-action slot. Patrol movements and emotes follow the canonical lane fairness and conflict-resolution rules. - **Target-state observability only:** `automation_script_triggers_total` increments once per resolved live handler using its applicable outcome and the finite scheduler/timer `event_class` value owned by [normative Table 4](./system-architecture-scripting-normative-contract-tables.md#table-4-metrics-label-matrix), not once per interval. An admitted live event that resolves zero handlers increments once at event scope with metric-only `outcome=admitted_no_handlers`; this target example does not imply dry-run metrics or execution. If a resolved handler produces work that is accepted into tick queues, `automation_tick_events_enqueued_total` increases. The evaluator's live `automation_script_work_item_outcomes_total` uses the Table 4 label contract and excludes dry-run/test executions. Canonical dry-run/test terminal, runtime, and sandbox-failure families remain target-only; current dry-run evidence is limited to its implemented quota and capacity admission counters. Zero-handler ingress returns `admitted=true`, `admissionOutcome=TRIGGER_ADMISSION_OUTCOME_ADMITTED`, and `resolvedHandlerCount=0`; `admitted_no_handlers` is metric-only and is not returned or persisted in `script_event_ingress_audit` or `script_event_audit`. See the [scripting observability contract](./system-architecture-scripting-observability-contract.md#ingress-audit-vs-handler-audit) for the target/current boundary. An audit record is written to `script_event_audit` per resolved handler so missed or delayed intervals can be debugged using stage-aware fields (`finalStage`, `finalOutcome`, `finalReason`) alongside identifiers like `scriptEventId`, `scriptId`, `scheduleDefinitionId`, the persisted due point, and `tickId`. - The target `ListScriptHandoffEvents` view composes downstream execution dispositions keyed by the complete source/optional-target Command-Handoff Identity, with persisted `automationDispatchId` and deterministic `commandOrdinal`; `(automationDispatchId, commandOrdinal)` is only its suffix. Parent Trigger Identity, `outboxWorkItemId`, `workItemIds[]`, and `scriptEventId` are correlation/selectors only and cannot replace that child identity. See [Implementation Status](#implementation-status) for the current live read boundary and the metrics and audit sections in `design/architecture/system-architecture-scripting-quotas-and-operations.md` for interpretation. diff --git a/design/architecture/system-architecture-tick-incident-runbook.md b/design/architecture/system-architecture-tick-incident-runbook.md index 1f19720541..19e570fa19 100644 --- a/design/architecture/system-architecture-tick-incident-runbook.md +++ b/design/architecture/system-architecture-tick-incident-runbook.md @@ -265,7 +265,7 @@ When this section uses target-only `tick_effects_*` replay-ledger metrics, requi - Validate Redis health (latency, memory pressure, and unreplicated-write exposure) using Redis coordination dashboards. 3. **Apply scoped remediation** - Resolve each affected scope from authoritative runtime/control-plane records and carry the complete tuple `` plus the current executor fence; the bounded metrics bucket is not sufficient evidence. - - **Current-live branch:** because any deployed containment boundary is at most instance-scoped, enumerate and record every affected region and namespace/scope under the ``, obtain the broader-scope approval gate, and apply only a deployed containment/fencing control that provides authoritative scope evidence; if none is available, keep the affected scope fenced or stopped, mark exact containment unverified, and escalate. Use `GetRuntimeOwnershipStatus` plus `ObserveRuntimeTickProgress` only as evidence-only status and forward-progress reads. Require authoritative readback of that full enumeration and fence before any cleanup action; do not describe this as an exact regional pause or reset. + - **Current-live branch:** because any deployed containment boundary is at most instance-scoped, enumerate and record every affected region and namespace/scope under the ``, obtain the broader-scope approval gate, and apply only a deployed containment/fencing control that provides authoritative scope evidence; if none is available, preserve any active broader containment, block further mutations, mark exact containment unverified, and escalate under the current-live [executor fencing/drain gate](#act-stalled-tick-region). Use `GetRuntimeOwnershipStatus` plus `ObserveRuntimeTickProgress` only as evidence-only status and forward-progress reads. Require authoritative readback of that full enumeration and fence before any cleanup action; do not describe this as an exact regional pause or reset. - **Target state only, once implemented and proven:** use the exact namespace/region-qualified pause and cleanup controls, with CAS/readback proving the carried tuple and executor fence at each mutating step. If a region remains stuck, execute the region-scoped coordination reset flow in `system-architecture-redis-reset-and-recovery.md`; missing or mismatched evidence fails closed. - Keep current-live instances/deployments paused and non-accepting while Automation projection recovery is unavailable. Resume only after executable owner-reconciled recovery, authoritative full-scope readback, and the canonical smoke gate. If ledger backlog also accumulates, trigger ledger replay-controller remediation for the same fully resolved scope. 4. **Verify convergence** diff --git a/design/architecture/system-architecture-ticks.md b/design/architecture/system-architecture-ticks.md index 6d3d932571..9ed2946796 100644 --- a/design/architecture/system-architecture-ticks.md +++ b/design/architecture/system-architecture-ticks.md @@ -68,7 +68,7 @@ The canonical scheduler has two independently bounded lanes: The phases are ordered as follows: (1) due start-of-tick passive effects, (2) one selected actor action for each still-eligible entity, and (3) effects generated by those selected actor actions. Only phase-1 effects completed before phase-2 eligibility evaluation may change same-tick eligibility; work selected but not completed, or deferred by lane, per-entity, cost, or region budget overflow, affects a later tick. Passive or inbound work that becomes due after start selection is also deferred to a later tick; phase 3 does not drain it. A completed start-of-tick effect may make an entity ineligible to act. An actor-generated effect does not retrospectively remove an action that already executed, and neither lane may recursively grant another root actor action in the same tick. -Every work source declares its phase, lane, and cost class before admission. Within one entity's eligible queue, the persisted manifest orders work by `(priority, due_tick_id, entity_enqueue_seq, source_kind, commandId_or_effectKey)`, with due points normalized before selection. `entity_enqueue_seq` is allocated within the complete entity scope `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch)`; it is not a region-global or instance-only sequence. Across eligible entities, persisted rotating/deficit scheduling accounts for declared cost and advances only with the durable selected batch; bounded aging or `maxDeferralTicks` applies where declared. Each lane has separate per-entity count and cost caps, region-wide work budgets, bounded carry-over/backoff, and pressure metrics. Overflow is deferred without changing its persisted ordering inputs or retry/action/effect identity; a new source cannot silently introduce a custom scheduler. See [ADR 0065](./decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md). +Every work source declares its phase, lane, and cost class before admission. Within one entity's eligible queue, the persisted manifest orders work by `(priority, due_tick_id, entity_enqueue_seq, source_kind, commandId_or_effectKey)`, with due points normalized before selection. `entity_enqueue_seq` is allocated within the complete entity scope `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch, entityId)`; it is not a region-global or instance-only sequence. Across eligible entities, persisted rotating/deficit scheduling accounts for declared cost and advances only with the durable selected batch; bounded aging or `maxDeferralTicks` applies where declared. Each lane has separate per-entity count and cost caps, region-wide work budgets, bounded carry-over/backoff, and pressure metrics. Overflow is deferred without changing its persisted ordering inputs or retry/action/effect identity; a new source cannot silently introduce a custom scheduler. See [ADR 0065](./decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md). --- 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 d754c4290c..9658bd53ef 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 @@ -126,7 +126,7 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, - Accepted TICK-04 remains an implementation and proof gap: current replay paths do not establish cross-service operation/target/request-digest-bound participant guards, causal read composition, stale-precondition handling, or mixed-floor handling. The canonical mutation identity, participant-guard, and root/child lineage rules are owned by [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), and the [identifier glossary](../../architecture/system-architecture-identifier-glossary.md); pending generated-child allocation is recorded only in the non-authoritative [ADR 0183 proposal](../../architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). This tracker records implementation and proof status only. - [ADR 0059](../../architecture/decisions/adr-0059-causal-floor-cross-service-presentation-reads.md) accepts a causal floor plus actual opaque World/Entity component versions; current LOOK composition still has scope-marker compatibility behavior, bounded stale-floor retry, and final read-fence error mapping gaps. This tracker does not claim the accepted presentation identity is implemented. - [ADR 0060](../../architecture/decisions/adr-0060-world-owned-ambient-facts-and-logic-owned-consequences.md) and [ADR 0061](../../architecture/decisions/adr-0061-single-owner-spatial-mutations-across-split-authority.md) keep ambient/location facts in World, item holders in Entity, and root outcomes/reconciliation in Game Session. Current gameplay has no complete cross-owner mutation/targeting proof; the accepted ownership direction does not promote current item or movement seams. -- The repository still advertises HTTP inventory/equipment mutation controllers that call Entity directly outside Game Session effect, tick, and barrier admission. These routes are not production-safe gameplay paths unless explicitly isolated under a separately approved owner/admin contract; their presence is implementation drift, not a second gameplay ingress. +- Reachable tenant-access-checked administrative `POST`/`DELETE` inventory/equipment mutation handlers persist `ItemInstance` and `ItemStack` through Entity outside Game Session effect, tick, and barrier admission and do not require character ownership. `ScopedCharacterResolver` verifies tenant, character, and playable-state scope; persistence outside Game Session admission remains a gap. The current paths do not establish an admin-role check or an approved owner/admin contract. - Broader gameplay families remain unimplemented or unproved against the target contracts owned by [ADR 0056](../../architecture/decisions/adr-0056-one-hot-path-fan-out-owner.md), [ADR 0069](../../architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md), [ADR 0075](../../architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md), and the canonical [Transactions generated-effect-chain contract](../../architecture/system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory). - The parent inventory slice remains partially implemented as a domain: manual happy-path verification over both WebSocket and Telnet is still unchecked, and later nested-container UX, crafting/material flows, banking/vendor/mail/trade, loot generation, scripted item behavior, durability, and richer client filtering are not implemented. diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index ad5a6cc15e..2e331af3f2 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -2174,6 +2174,49 @@ require_contains( [ "every eligible ledger row in that tick's complete expected current-epoch participant set", "Required-versus-optional classification affects command-result aggregation, not tick commit", + "`entity_enqueue_seq` is allocated within the complete entity scope `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch, entityId)`", + ], +) +require_contains( + "design/architecture/system-architecture-scripting-examples-and-patterns.md", + [ + "The current authenticated receiving RPCs fail closed with `FAILED_PRECONDITION` (`automation_admission_receiver_fence_unavailable`) before mutation", + "prove neither local tick-queue acceptance nor remote follow-up scheduling", + "the target Trigger Identity additionally requires `playableStateNamespaceId`, which current `TriggerScriptEventRequest` does not carry", + "The current request carries `playableStateScope` separately as exact-validated policy/routing/authorization/migration-fence evidence, not as an identity field", + "**Target-state audit contract:** An audit record is written to `script_event_audit` for each resolved handler Trigger Identity", + "Current `TriggerScriptEventRequest` has no `playableStateNamespaceId`; its `playableStateScope` remains separate evidence and cannot substitute for the target namespace identity", + ], +) +require_absent( + "design/architecture/system-architecture-scripting-examples-and-patterns.md", + [ + "For same-scope targets, `ENQUEUED` means Game Session accepted the command into the local tick queue", + "for distinct target scopes, `REMOTE_SCHEDULED` means only that the remote follow-up was scheduled", + ], +) +require_contains( + "design/architecture/system-architecture-tick-incident-runbook.md", + [ + "if none is available, preserve any active broader containment, block further mutations, mark exact containment unverified, and escalate", + "current-live [executor fencing/drain gate](#act-stalled-tick-region)", + ], +) +require_contains( + "design/architecture/system-architecture-gateway.md", + [ + "Before normal release, old Gateway replay writers must be drained or authoritatively blocked", + "the complete tagged replay state and readiness/fence state must be authoritative", + "If any old-version writer or admission remains allowed, release additionally requires a separately proven cross-version guard", + "none is currently implemented or proven, so that mixed-version release path remains forbidden", + ], +) +require_contains( + "design/architecture/system-architecture-redis-ops-access.md", + [ + "Quarantine release and Cache-reset admission remain fail-closed until the [Gateway replay-quarantine release gate](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake) is proven", + "the current untagged replay state and generic writer do not satisfy it", + "If old-version writers/admission cannot be excluded, release additionally requires a separately proven cross-version guard, which is not currently implemented or proven", ], ) diff --git a/services/automation-scripting-service/src/main/resources/openapi.yaml b/services/automation-scripting-service/src/main/resources/openapi.yaml index afebd50337..73017e9e76 100644 --- a/services/automation-scripting-service/src/main/resources/openapi.yaml +++ b/services/automation-scripting-service/src/main/resources/openapi.yaml @@ -2,9 +2,9 @@ openapi: 3.0.3 info: title: Automation Scripting Service API description: >- - API for NPC automation and script management. Current REST routes are - unauthenticated and trust caller-supplied tenant/subject selectors; this - is an implementation security gap, not tenant-isolation proof. + This OpenAPI document currently describes only the GET /ping health-check + endpoint; it defines no tenant- or subject-scoped operations or + authentication. version: 1.0.0 license: name: PolyForm Noncommercial License 1.0.0 From ccddab664c4ef484673a251b95af33039a9e3fba Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:59:29 +1300 Subject: [PATCH 55/68] docs: qualify full-version publication participant gate --- .../game-design-service/operations.md | 2 +- dev-tools/tests/architecture-doc-contracts.sh | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index ec5eba5173..fe81283160 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -16,7 +16,7 @@ The target publish contract binds the stable `publish_request_id` to one canonic The publication artifact/release-bundle state, allocated version state, participant/release evidence, and publish-attempt terminal state must commit atomically in one Game Design owner-local transaction. If the workflow boundary cannot provide that transaction, the adopter must use an explicit durable state machine with readback reconciliation; it must never expose `SUCCEEDED` until the artifact and version commit is durably readable and bound to the same immutable request and attempt evidence. A terminal attempt is therefore not an acknowledgement that a separate transaction was started: it is the commit/readback proof of the publication state. -**Current implementation status:** full-version publication reserves its Draft version and PENDING attempt in one owner-local transaction. After participant reads and object export, its final owner-local transaction records participant evidence, artifact state, release bundle, Published version, verified digests, and the SUCCEEDED attempt together. An ambiguous final commit is resolved by exact attempt/version/bundle/artifact readback rather than an independent terminal-success transaction. The remaining gap is the external phase: participant collection and mutable object-key export occur before that final transaction without a durable external-phase owner, private candidate namespace, or export deduplication. Same-request retries can therefore race before the final Game row lock; a late exporter can overwrite bytes after another attempt's release attestation, while definite-failure cleanup can race an active exporter. The final local transaction does not prove safe external-write ownership, cleanup, or ambiguous object-store recovery. +**Current implementation status:** full-version publication reserves its Draft version and PENDING attempt in one owner-local transaction. After participant reads and object export, its final owner-local transaction records participant evidence, artifact state, release bundle, Published version, verified digests, and the SUCCEEDED attempt together. An ambiguous final commit is resolved by exact attempt/version/bundle/artifact readback rather than an independent terminal-success transaction. This implemented success path is behind the required participant digest gate: ordinary full-version requests currently cannot reach it because Game Logic rejects the required full-version participant request without an owner-local manifest/provenance digest. The canonical participant gate and current availability are documented in [Version Control](./version-control.md#owner-to-owner-digest-authorization-and-tenant-identity); script-patch publication does not require the Game Logic participant. The remaining gap is the external phase: participant collection and mutable object-key export occur before that final transaction without a durable external-phase owner, private candidate namespace, or export deduplication. Same-request retries can therefore race before the final Game row lock; a late exporter can overwrite bytes after another attempt's release attestation, while definite-failure cleanup can race an active exporter. The final local transaction does not prove safe external-write ownership, cleanup, or ambiguous object-store recovery. The target attempt record must immutably bind the normalized preallocation request digest, workflow/request identity, allocated version, artifact/release identity, and owner evidence. Every attempt transition must CAS both the expected status and monotonic attempt revision; only the still-current attempt owner may publish a terminal result. Failure cleanup may delete or mark provisional state only when it conditionally owns the same still-current nonterminal attempt and the target has not been won or published. Same-identity/same-digest retries must read back and replay the existing state; a different digest, stale revision/status, or contradictory artifact/version readback fails closed. Focused proof must cover crashes before and after each commit/readback boundary, concurrent exact retries, different-digest reuse, and a losing failure cleanup racing a winning publisher. diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index 2e331af3f2..228913a299 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -2229,6 +2229,9 @@ automation_runtime = ( game_design_version_control = ( root / "design/architecture/microservices/game-design-service/version-control.md" ).read_text(encoding="utf-8") +game_design_operations = ( + root / "design/architecture/microservices/game-design-service/operations.md" +).read_text(encoding="utf-8") deployment_environments = ( root / "design/architecture/infrastructure/deployment-environments.md" ).read_text(encoding="utf-8") @@ -2360,6 +2363,18 @@ for path, text in ( if term not in text: raise SystemExit(f"{path}: missing Game Design V26 rollout-compatibility term {term!r}") +for term in ( + "This implemented success path is behind the required participant digest gate", + "ordinary full-version requests currently cannot reach it because Game Logic rejects the required full-version participant request", + "script-patch publication does not require the Game Logic participant", + "[Version Control](./version-control.md#owner-to-owner-digest-authorization-and-tenant-identity)", +): + if term not in game_design_operations: + raise SystemExit( + "design/architecture/microservices/game-design-service/operations.md: " + f"missing full-version publication availability qualification {term!r}" + ) + print("architecture doc contracts passed") PY From 033c45fbabd6bfdad919b895a2c425553f9230e1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:23:05 +1300 Subject: [PATCH 56/68] docs: require maintenance admission for incident ledger repair --- .../system-architecture-scripting-contracts.md | 2 +- .../system-architecture-tick-incident-runbook.md | 3 ++- dev-tools/tests/architecture-doc-contracts.sh | 12 ++++++++++++ 3 files changed, 15 insertions(+), 2 deletions(-) diff --git a/design/architecture/system-architecture-scripting-contracts.md b/design/architecture/system-architecture-scripting-contracts.md index 0b6f4a3f74..2a6b72156e 100644 --- a/design/architecture/system-architecture-scripting-contracts.md +++ b/design/architecture/system-architecture-scripting-contracts.md @@ -22,7 +22,7 @@ The current evaluator supports a bounded emitted-command collection per work ite - A **script work item** is the post-DSL output staged by Automation & Scripting (domain commands + metadata such as `scriptId`, `scriptPatchVersion`, and `scriptEventId`). It preserves the immutable source Trigger Identity, including the source `regionId` and `regionEpoch` when applicable; any enqueue or current-routing identity is carried separately and must not overwrite the source trigger fields. - A **tick command** is a unit of work that has been accepted into an entity’s tick queue by Game Session and will be executed under tick locks and replay semantics. - **Target-state command handoff:** Every script work item that emits gameplay commands receives one stable `automationDispatchId`, and each emitted command carries a deterministic `commandOrdinal` under that dispatch. The pair is only the final discriminator within the complete Command-Handoff Identity; one handler may fan out into multiple commands, and a pair without its complete source/target runtime scope is not a command identity. -- **Target-state command handoff:** The complete Command-Handoff Identity is the canonical identity for evaluated child-dispatch handoff deduplication, execution-fence reporting, replay selection, and correlation. It is not the downstream effect guard: authoritative effect idempotency uses the persisted mutation `EffectId` (the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child mutation), typed operation, exact target aggregate, and stored/compared immutable request digest, with any enclosing `rootEffectId` retained only as lineage and reconciliation context and conflicts failing closed. The `(automationDispatchId, commandOrdinal)` pair is only a display suffix and is insufficient by itself; `automationDispatchId` identifies a dispatch group, and `scriptEventId` alone must never identify a fan-out command. See [Implementation Status](#implementation-status) for the current evaluator boundary. +- **Target-state command handoff:** The complete Command-Handoff Identity is the canonical identity for evaluated child-dispatch handoff deduplication, execution-fence reporting, replay selection, and correlation. It is not the downstream effect guard: authoritative effect idempotency uses the persisted mutation `EffectId` (the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child mutation), typed operation, exact target aggregate, and stored/compared immutable request digest, with any enclosing `rootEffectId` retained only as lineage and reconciliation context and conflicts failing closed. The `(automationDispatchId, commandOrdinal)` pair is only an identity suffix and is insufficient by itself; `automationDispatchId` identifies a dispatch group, and `scriptEventId` alone must never identify a fan-out command. See [Implementation Status](#implementation-status) for the current evaluator boundary. Target-state handoff linkage uses the complete Command-Handoff Identity: complete source/target runtime scope, `automationDispatchId`, and `commandOrdinal`. The current implementation is narrower than this target: because Trigger Identity and `commandOrdinal` are not carried end to end, current live linkage and retry diagnostics use `outboxWorkItemId`, `gameSessionCommandId`, available `automationDispatchId`, and `script_event_audit`. This fallback is not complete command-level deduplication or replay evidence. The remaining gap is tracked under `AS-1.5` and its Game Session handoff dependency in the [automation and scheduler runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). diff --git a/design/architecture/system-architecture-tick-incident-runbook.md b/design/architecture/system-architecture-tick-incident-runbook.md index 19e570fa19..ec6ab50cc3 100644 --- a/design/architecture/system-architecture-tick-incident-runbook.md +++ b/design/architecture/system-architecture-tick-incident-runbook.md @@ -326,6 +326,7 @@ Normal replay and re-enqueue in this section apply only to effects from the curr - For “applied but not marked” rows: - Do not update ledger rows directly to `APPLIED` from ad hoc SQL, a generic admin endpoint, or a one-off script. - Select the verifier/reconcile branch from the deployment mode; do not require target-state fields from the current-live schema or weaken the target-state gate: + - **Maintenance admission applies to both branches:** Before either verifier CAS may mutate a ledger row, validate the exact ADR 0085 external maintenance handoff, durably persist it, and pass it unchanged with the reconciliation evidence. Owner, epoch, executor, manifest, or participant proof does not replace this external admission. If the handoff is missing or unproved, make no mutation and use the existing fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) and escalate. See [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#coordination-reset-model) and [ADR 0085](./decisions/adr-0085-evidence-gated-coordination-replay-and-fenced-reset.md). - **Current-live:** Run the service-owned verifier for the exact current-live ledger projection and its persisted mutation `EffectId` (retaining any enclosing root as lineage), including `effectKey` and target aggregate identity, within the narrower `` scope. Because `playableStateNamespaceId` is not persisted at this current-live boundary, this branch cannot establish namespace-complete S1/S2 binding and must not infer the namespace from `gameInstanceId`. Read `GetRuntimeOwnershipStatus` (the current instance-scoped ownership boundary) and require the current `regionEpoch` and opaque `executorFence` to match the batch/ledger ownership snapshot. Verify that the current selected-work manifest and its `manifest_digest` match the durable source and ledger projections and the expected participant evidence. This branch may be processed without `sealed_execution_context_digest` or `sealed_execution_context_ref`, which are not present at the current-live boundary. The service-owned verifier must atomically CAS the current owner/epoch/fence, require complete manifest and participant-evidence set equality, transition the matching `SCHEDULED` row(s) to `APPLIED`, and record replay-verification evidence (including the evidence digest/reference and `replay_ok` audit) in one durable transaction. Missing, extra, or conflicting evidence, or any owner/epoch/fence mismatch, affects zero rows and fails closed with no ledger mutation. The owning domain must prove the effect is already reflected in authoritative state or in its durable participant guard; a replay no-op is not a third ledger status. - **Target-state:** Read the current region authority from `RegionStatus`/`GetRegionTickStatus` and require exact current `regionEpoch`/`executorFence` equality. For S1/S2, require the complete namespace-bound projection `` and exact-compare `playableStateNamespaceId` (as well as every other immutable scope, identity, timeline, and target field) across the ledger, manifest, sealed context, and participant set. Require exactly one immutable sealed execution-context binding: either `sealed_execution_context_digest` or `sealed_execution_context_ref` resolved to its immutable digest, with the referenced context and digest matching the batch and replay request. The complete participant-projection set, sealed context, current authority/fence, and every `SCHEDULED` ledger transition must pass the same evidence-qualified CAS; a missing, stale, mismatched, incomplete, extra, or conflicting value affects zero rows and fails closed with no ledger mutation. - In either branch, replay no-op is an attempt outcome, not a third ledger status, and the verifier must not reconcile a mutation under a different persisted `EffectId` across region epochs; any enclosing `rootEffectId` remains lineage and reconciliation context rather than the effect-level identity. @@ -337,7 +338,7 @@ Normal replay and re-enqueue in this section apply only to effects from the curr - For old-epoch rows, first enumerate every durable old-epoch effect and follow-up independently of Redis hints. Use the authority-fenced attestation under the original `EffectId` described in [Inconclusive Old-Epoch Reconciliation Policy](./system-architecture-tick-failures-and-operations.md#inconclusive-old-epoch-reconciliation-policy); the affected scope cannot reopen while any row remains unresolved. A new epoch lineage may be created only after both the original effect and its source claim are authority-fenced terminal `ABANDONED`; an explicitly approved maintenance or saga/outbox flow may then create a fresh current-epoch identity with durable lineage and revalidated scope. No normal replay may create or drive that new lineage, and the original effect identity must not be re-driven across the epoch boundary. - For replay-controller starvation: - Reduce per-region replay batch monopolization or other hot-region pressure first. - - **Target state only, once implemented and proven:** If the region remains starved, run scoped replay-controller remediation for the affected complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch)` after authoritative enumeration and exact validation; incomplete or caller-supplied namespace/scope evidence must fail closed before any replay or maintenance mutation. Escalate to broader reset actions only after that exact scope evidence is qualified. Current operators must use the fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) instead. + - **Target state only, once implemented and proven:** If the region remains starved, run scoped replay-controller remediation for the affected complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch)` after authoritative enumeration and exact validation; this incident remediation is maintenance, not ordinary crash replay. Before its first mutation, validate the exact ADR 0085 external maintenance handoff, durably persist it, and pass it unchanged; ledger, owner, epoch, executor, or participant evidence alone does not authorize the maintenance operation. Missing or unproved handoff means no mutation: use the fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) and escalate. See [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#coordination-reset-model) and [ADR 0085](./decisions/adr-0085-evidence-gated-coordination-replay-and-fenced-reset.md). Incomplete or caller-supplied namespace/scope evidence must also fail closed before any replay or maintenance mutation. Escalate to broader reset actions only after that exact scope evidence is qualified. Current operators must use the fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) instead. 4. **Prevent recurrence** - Review Game Session and domain handlers to ensure: - Ledger status transitions happen atomically with domain commits where required. diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index 228913a299..14aae89fe4 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -1710,10 +1710,15 @@ require_contains( require_contains( "design/architecture/system-architecture-scripting-contracts.md", [ + "The `(automationDispatchId, commandOrdinal)` pair is only an identity suffix and is insufficient by itself", "always-isolated test-only breaker or gate", "no environment, tenant, or request opt-in may cross that boundary", ], ) +require_absent( + "design/architecture/system-architecture-scripting-contracts.md", + ["(automationDispatchId, commandOrdinal)` pair is only a display suffix"], +) require_absent( "design/architecture/system-architecture-scripting-contracts.md", ["separate breaker or explicitly opt-in per environment/tenant"], @@ -1873,6 +1878,13 @@ require_contains( require_contains( "design/architecture/system-architecture-tick-incident-runbook.md", [ + "**Maintenance admission applies to both branches:**", + "Before either verifier CAS may mutate a ledger row, validate the exact ADR 0085 external maintenance handoff, durably persist it, and pass it unchanged with the reconciliation evidence.", + "Owner, epoch, executor, manifest, or participant proof does not replace this external admission.", + "If the handoff is missing or unproved, make no mutation and use the existing fail-closed [Current Operator Fallback]", + "this incident remediation is maintenance, not ordinary crash replay.", + "Before its first mutation, validate the exact ADR 0085 external maintenance handoff, durably persist it, and pass it unchanged", + "Missing or unproved handoff means no mutation: use the fail-closed [Current Operator Fallback]", "may be applied as an initial emergency fence", "For any reset or recovery mutation, Automation must be contained before relying on Game Session tick/region containment", "complete affected scope set from the authoritative durable PostgreSQL/runtime inventory", From 662e9471b937d7e3b09d64e19a474f2c03593231 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:37:22 +1300 Subject: [PATCH 57/68] docs: align replay guards and recovery admission contracts --- .../entity-management-service/operations.md | 4 +- .../game-design-service/version-control.md | 3 +- .../game-session-service/runtime-and-data.md | 4 +- ...m-architecture-redis-reset-and-recovery.md | 2 +- ...system-architecture-scripting-contracts.md | 2 +- ...m-architecture-scripting-event-registry.md | 2 +- .../architecture/system-architecture-ticks.md | 2 +- dev-tools/tests/architecture-doc-contracts.sh | 59 +++++++++++++++++++ 8 files changed, 68 insertions(+), 10 deletions(-) diff --git a/design/architecture/microservices/entity-management-service/operations.md b/design/architecture/microservices/entity-management-service/operations.md index 96b548e378..0be0214be6 100644 --- a/design/architecture/microservices/entity-management-service/operations.md +++ b/design/architecture/microservices/entity-management-service/operations.md @@ -4,7 +4,7 @@ This document collects Entity Management’s readiness model, tick-lock/tick-ide ## Implementation Status -The complete participant-guard contract described here—persisted mutation `EffectId` (the root `EffectId` for a root operation or the generated operation's persisted child `EffectId`, with the enclosing `rootEffectId` retained as lineage), typed operation and target, immutable `requestDigest`, and complete replay verification—is target-state. The current `EntityMutationEffectReplayService` and schema provide narrower effect/operation replay and do not yet enforce or prove the target mutation-boundary contract. Its duplicate-marker catch also runs inside the surrounding transaction, so a PostgreSQL unique-race loser can inherit an aborted/rollback-only transaction rather than reliably replaying or returning conflict; a conflict-safe insert or isolated marker transaction plus real PostgreSQL concurrent proof is required. [Transaction Strategies](../../system-architecture-transactions.md) is the canonical owner of participant-guard and replay-verification semantics. The pending [ADR 0183 proposal](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative. +The complete participant-guard contract described here—persisted mutation `EffectId` (the root `EffectId` for a root operation or the generated operation's persisted child `EffectId`, with the enclosing `rootEffectId` retained as lineage), typed operation and target, immutable `requestDigest`, and complete replay verification—is target-state. The current `EntityMutationEffectReplayService` and schema provide narrower effect/operation replay and do not yet enforce or prove the target mutation-boundary contract. Its duplicate-marker catch also runs inside the surrounding transaction, so a PostgreSQL unique-race loser can inherit an aborted/rollback-only transaction rather than reliably replaying or returning conflict; correction must use a conflict-safe insert or a same-transaction savepoint around marker handling while keeping the marker and mutation atomic, never an isolated marker transaction. Actual PostgreSQL concurrent proof remains unavailable. [Transaction Strategies](../../system-architecture-transactions.md) is the canonical owner of participant-guard and replay-verification semantics. The pending [ADR 0183 proposal](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) is non-authoritative. The current replacement-validation path is also narrower than the target contract: `ValidateEntityUpgradeMappings` does not yet bind the stable `playableStateNamespaceId`, owner-resolved `playableStateScope`, and active-instance authorization to the exact source/target versions, and the live result may echo a supplied `remapSetId` without locally validating or applying its mapping. This is an implementation/proof gap; the echo is not compatibility or cleanup evidence. @@ -57,7 +57,7 @@ Examples: - treats a guard conflict as a replay only after verifying the complete effect and target state, and otherwise reconciles or fails closed with the original mutation identity and its enclosing root `EffectId` lineage. Damage does not assume an at-most-one-damage-per-aggregate-per-tick invariant, so the per-aggregate `entity_tick_state` watermark is not sufficient for this path. - **Trade between two entities** – when a tick performs a trade between `fromEntityId` and `toEntityId`: - - **Target state:** the complete Command-Handoff Identity identifies an admitted automation command and is an input to allocating or looking up that command's stable root `EffectId`; it does not replace the effect identity or participant guards. `(automationDispatchId, commandOrdinal)` is only that command identity's dispatch-group suffix and must be interpreted with the complete source/target scope; a non-automation command instead uses its admitted `commandId`. `scriptEventId`, participant/item fields, and mutable payload text are never fallback identities. Every retry and owner commit preserves the resulting root identity, typed operation/target projections, and immutable request digest. The live Game Session handoff does not yet carry the full automation command identity end to end, so the current path uses the admitted `commandId` and available persisted work-item/dispatch fields; it must reject a missing command identity rather than synthesize one from the participants. This target gap is tracked under `AS-1.5` in the [automation and scheduler runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status); + - **Target state:** retain the admitted command/source identity for source evidence, and use the complete Command-Handoff Identity for automation handoff and deduplication; the handoff identity is not a mandatory input to root `EffectId` allocation or lookup. Root allocation and lookup details remain proposal-only under pending [ADR 0183](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md), not accepted target state. `(automationDispatchId, commandOrdinal)` is only that command identity's dispatch-group suffix and must be interpreted with the complete source/target scope; a non-automation command instead has its admitted `commandId`. `scriptEventId`, participant/item fields, and mutable payload text are never fallback identities. Every retry and owner commit preserves the resulting root identity, typed operation/target projections, and immutable request digest. The live Game Session handoff does not yet carry the full automation command identity end to end, so the current path uses the admitted `commandId` and available persisted work-item/dispatch fields; it must reject a missing command identity rather than synthesize one from the participants. This target gap is tracked under `AS-1.5` in the [automation and scheduler runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status); - **Illustrative proposal only (not an accepted canonical encoding):** before encoding, the handler would validate every identity-bearing and typed field against its declared type and domain; it would not encode malformed input, fallback identities, or alternate textual spellings. Quantity would be parsed as its declared numeric type and rendered as canonical base-10 decimal, so semantically equal values such as `1` and `01` produce identical bytes. The exact scalar/encoding contract remains pending human review in [ADR 0183](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); - **Illustrative proposal only (not an accepted canonical encoding):** the handler would serialize the admitted identity, the stable per-effect trade discriminator, and the validated canonical fields in a fixed versioned order using canonical UTF-8 length-prefixed fields, for example `trade:v1|:|:|:|:|:|:`. If later accepted, the exact resulting bytes would be the retry identity and would be reused unchanged, while sibling effects from one command and separate admitted trades would remain distinct; the pending ADR 0183 proposal is not an implementation or target-state requirement; - no canonical one-trade-per-`(fromEntityId,toEntityId,itemId)`-per-tick invariant exists, so the participant/item tuple alone cannot be the effect key; diff --git a/design/architecture/microservices/game-design-service/version-control.md b/design/architecture/microservices/game-design-service/version-control.md index f858dc1e44..921444e405 100644 --- a/design/architecture/microservices/game-design-service/version-control.md +++ b/design/architecture/microservices/game-design-service/version-control.md @@ -29,8 +29,7 @@ Current cross-seam security status is also blocked: Account's runtime membership The Game Design Service is the canonical history store for world and entity content even though domain services own the runtime templates: -- Each revision and commit references concrete domain objects (rooms, regions, - NPCs, items, templates) via stable identifiers maintained by the owning domain services. +- Current Game Design revision rows reference concrete domain objects (rooms, regions, NPCs, items, templates) through stable identifiers maintained by the owning domain services. Target durable commits will group those revisions and retain their domain-object references in the branch/commit history model; that branch/commit model and its APIs are not implemented, while current version-scoped revision history remains available through the existing revision/version surfaces. - **Target state:** During authoring, design tools apply revisions incrementally to domain services’ **Draft** template rows via idempotent design APIs bound to the complete commit/revision identity and affected-epoch set. Draft template graphs in World Management, Entity Management, and related services are then the authoritative snapshots of world and entity data for each version. In this document, a **remote `Draft` state** means the authoritative Game Design `GetVersionState` response for the target `(tenantId, versionId)` reports `versionState=DRAFT`; it does not mean that a remote service-layer read proves a WMS transaction is serialized with publication. - **Current first slice:** `SaveRevision` optionally calls World Management to apply a mutation and only afterward unconditionally inserts the Game Design revision; Game Design has no matching deduplication lookup or uniqueness constraint. This ordering is therefore not idempotent shared-Draft proof; the current partial-application and retry gap is recorded in Implementation Status. - **Target state:** When a version is published, the service coordinates the durable Temporal `publish` workflow that validates and finalizes the existing Draft data in each domain service and transitions the version to Published as described in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). Full-version publication is not satisfied by a short synchronous `common-saga`; that substrate is limited to caller-owned retry/compensation operations that do not make a release publish-complete. No separate design database is copied into domain services at publish time. **Current implementation:** the Temporal-disabled synchronous fallback remains active and does not establish that durability contract. The former Automation admin-guard denial is closed by the distinct Game Design workload peer and exact publication-read guards, but the Temporal-enabled path is still not proved end to end because Automation's full-version content selection remains tenant-wide and live mounted-certificate, activity, and multi-version proof remain absent. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index ba592d5c34..29f55ace47 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -22,7 +22,7 @@ The sections below define the target-state runtime contract. Current implementat - The target spatial/ambient reconciliation contract is not a current Game Session surface: the typed `EffectReconciliationAuthority`, durable `effect_reconciliation_backlog`/authority schema, immutable effect guards, durable action ledger/results, and list/retry/acknowledgement APIs remain unimplemented. Current persistence is limited to `tick_batch`/`tick_effect` and narrower domain/remote-follow-up reconciliation; see [Game Session API status](./api-contracts.md#implementation-status) and the normative [transaction reconciliation owner](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects). - The target remote-follow-up contract makes terminal timeout/late outcomes immutable under the original identity: exact retries return the stored terminal outcome, and a late-applied result requires a separately documented feature-specific compensation flow. The current `scheduleFollowup` replay path returns an existing retryable-timeout pair or valid terminal pair without mutation, with focused unit proof for terminal-pair replay. This does not establish exact serialized timeout/result arbitration under concurrency, complete terminal-failure mirroring, missing-coordinator recovery, or late-result compensation. The live `late_result_requires_reconciliation` path also writes `LATE_RESULT_RECONCILED`/`PARTIAL` and mirrors `APPLIED`/`PARTIAL` to the origin without a separately identified compensation/saga flow; post-abandon re-drive and compensation ownership remain unproved. - Current tick staging has Redis-first windows that are not the target durable-first boundary: ingress pushes the queue payload before marking the durable command `STAGED`, and tick processing moves queue entries to Redis `pending` before creating the durable `tick_batch`/`tick_effect` rows. A crash or Redis loss in either window can strand a `STAGED` command with no batch/effect, while startup recovery only handles `ACCEPTED` rows with no staging timestamp and purge can classify a no-effect row as `LOST_BEFORE_STAGING`. Current crash recovery is limited to durable records that exist; there is no recovery path for a `STAGED` command without a corresponding `tick_batch`/`tick_effect`, and missing staging or effect evidence does not prove that materialization or application did not occur. Only explicitly classified volatile ingress may receive that evidence-qualified outcome; durable accepted work needs a durable source claim/materialization recovery path and its feature-specific replay/re-drive contract. The target boundary creates the durable batch/effect/source claim before `pending` staging and treats Redis-only residue as reconstructible coordination state; the current ordering and no-batch recovery are implementation drift. -- The target stale-fence contract preserves a drained effect under its original mutation `EffectId` and enclosing root lineage while evidence-fenced reconciliation determines whether it is `APPLIED` or safely unapplied. `ABANDONED` requires authoritative participant/domain evidence; ordinary retry/replay retains the original command/effect identity, and only a conclusive post-abandon re-drive allocates a new command ID and root. The current implementation instead marks stale drained batches/effects `ABANDONED` on the fence/technical signal alone and requeues the same command, after which a later batch derives a new effect identity. This is unsafe implementation drift: a crash after participant mutation but before ledger terminalization can permit duplicate logical application or false abandonment. +- The target stale-fence contract preserves a drained effect under its original mutation `EffectId` and enclosing root lineage while evidence-fenced reconciliation determines whether it is `APPLIED` or safely unapplied. A new identity may be re-driven only after authoritative participant/domain evidence conclusively terminalizes the original effect as `ABANDONED` and the owning source command/claim is terminalized; ordinary retry/replay retains the original command/effect identity. Root allocation details remain proposal-only under [ADR 0183](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). The current implementation instead marks stale drained batches/effects `ABANDONED` on the fence/technical signal alone and requeues the same command, after which a later batch derives a new effect identity. This is unsafe implementation drift: a crash after participant mutation but before ledger terminalization can permit duplicate logical application or false abandonment. - `BLOCK` is also on the current durable effect replay/no-op seam; other state-changing command families still need to migrate onto it. - Current Game Session code still defaults `FIREMUD_AUTH_SESSION_EXPIRATION_MS` to one hour and does not enforce the target five-minute continuity cap. - Current Game Session code has not converged on the canonical bounded `session:game:*` index families or proved their repair protocol: it still uses transitional `sessionctx:*` and tenant/identity lookup records and does not implement/prove the generation-safe global `accountIndexMember` set, the partitioned global issuer index, or their cross-slot repair/acknowledgement flows. This is implementation/proof drift, not a transfer of ownership or a different member shape. @@ -234,7 +234,7 @@ Game Session now has a real current-boundary durable gameplay execution seam ins - accepted gameplay commands persist a durable command ledger row with both a human-safe sanitized text projection and the canonical raw command payload used for later execution; - the tick runtime stages Redis queue work into durable `tick_batch` / `tick_effect` rows before drain commit, including the current-boundary selected-work manifest, expected effect count, and manifest digest on the batch row; - after drain commit, Game Session resumes from any durable `DRAINED` effects for that queue boundary and executes the supported command families from the ledger itself rather than assuming Redis drain already implies terminal gameplay work; -- drained effects re-check the durable runtime owner row before application. In the target contract, a stale fence preserves the effect under its original mutation `EffectId` and enclosing root lineage for evidence-fenced reconciliation; only authoritative evidence that the effect was unapplied may permit `ABANDONED`, and an ordinary retry/replay must retain the original command/effect identity. A post-abandon re-drive is the only path that may allocate a new command ID/root with explicit lineage. The current implementation instead marks stale drained effects/batches `ABANDONED` from the fence/technical signal alone, requeues the same command, and lets a later batch derive a new effect identity; this is unsafe implementation drift that can duplicate a mutation or falsely terminalize an uncertain effect. +- drained effects re-check the durable runtime owner row before application. In the target contract, a stale fence preserves the effect under its original mutation `EffectId` and enclosing root lineage for evidence-fenced reconciliation; only authoritative evidence that the effect was unapplied may permit `ABANDONED`. A new identity may be re-driven only after that conclusive terminalization and terminalization of the owning source command/claim; ordinary retry/replay must retain the original command/effect identity. Root allocation details remain proposal-only under [ADR 0183](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). The current implementation instead marks stale drained effects/batches `ABANDONED` from the fence/technical signal alone, requeues the same command, and lets a later batch derive a new effect identity; this is unsafe implementation drift that can duplicate a mutation or falsely terminalize an uncertain effect. The live ledger does not yet prove the target retention boundary. Game Session owns cleanup for its command receipts, batches, effects, manifests, and its `tick_effect` ledger/projection. Each domain service owns its participant guards and local cleanup; Game Session retains cross-service blocker references and safe-watermark consequences until those owners provide the evidence that permits ledger cleanup. The family-specific application of [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md) is: diff --git a/design/architecture/system-architecture-redis-reset-and-recovery.md b/design/architecture/system-architecture-redis-reset-and-recovery.md index cd637c1d1c..f5598553b9 100644 --- a/design/architecture/system-architecture-redis-reset-and-recovery.md +++ b/design/architecture/system-architecture-redis-reset-and-recovery.md @@ -260,7 +260,7 @@ A region- or tenant-scoped reset parent cannot claim global account- or issuer-i | `chat:say::*`, `chat:whisper:::*`, legacy `chat:whisper::`, `chat:tell::*`, `chat:guild::*`, `chat:city::*`, `chat:account::*` | Cache/Rate-Limit | **Reset-tolerant** | Target and live legacy chat projections are cleared; reads use or fall back to authoritative Social/PostgreSQL history where the communication type promises durable player history, while non-durable projections may rebuild or remain absent. Reset/TTL loss may create gaps or non-contiguous windows only in transient Redis projections and cannot create a durable-history entitlement gap. `chat:city` is a current legacy TTL projection, not durable history and not `SHOUT`. | `WHISPER` reset scope is the complete gameplay recipient namespace `(tenantId, playableStateNamespaceId, characterId)`, and reset cleanup includes the live legacy `chat:whisper::` prefix alongside the target prefix until migration completes. Resets drop recent in-memory history but do not lose persisted moderation logs where required; the legacy prefix must not be used for history/refill across same-account characters or namespaces. No `SHOUT` Redis/reset family exists until a selected profile publishes its type/storage/topology contract. | | `script-scheduler:{tenantRegionTag}:lastTickId` (target-only, once implemented) | Coordination | **Reset-tolerant (target-only, once implemented)** | Once implemented, Automation scheduler treats the next heartbeat as its baseline and may re-scan due interval boundaries, but durable trigger-instance uniqueness prevents duplicate logical trigger creation. Until then, no current reset operation is defined for this unimplemented target projection. | Target-state Automation scheduler checkpoint for “every N ticks” triggers; once implemented, losing it causes the scheduler to re-establish its baseline from the heartbeat stream while PostgreSQL-backed trigger-instance rows remain the de-duplication boundary. | | `automation:timer:{tenantRegionTag}` (target-only, once implemented) | Coordination | **Reset-tolerant (target-only, once implemented)** | Once implemented, Automation timer indexes for affected regions are discarded and rebuilt from durable schedules, trigger-instance rows, and heartbeat progress. Until then, no current reset operation is defined for this unimplemented target projection. | Target-state region-scoped coordination index for script timers/intervals. Once implemented, entries must remain instance-aware in payload and rebuild logic (`gameInstanceId`, and plugin identifiers when applicable) even though the Redis key is region-scoped for slotting/locality. | -| `automation:queue:{tenantInstanceTag}:*` | Cache/Rate-Limit | **Current reset/recovery unavailable; fail-closed (target reset-tolerant)** | Queue entries are disposable pointers: losing all Redis list contents does not lose PostgreSQL `script_work_items`, but missing pointers do not authorize resume. The current `rebuildPendingWorkItemIndex` selects only `PENDING_EVALUATION` rows, but has no stale-owner or compare-and-set reconciliation gate and cannot establish a safe disposition for existing `EVALUATING` rows, so queue reset, rebuild, and resume are unavailable. Do not flush, rebuild, or resume this projection as a supported current operation; keep the affected `{tenantId, gameInstanceId}` scope paused/fenced and escalate to the Automation owner. Once owner status reconciliation/reclamation, CAS fencing, and exact readback are implemented and proven, tooling may drop and rebuild only this pointer projection from the authoritative rows before releasing the scope. | The queue is a derived pointer projection, never execution authority; PostgreSQL work-item state remains authoritative. See the [Automation & Scripting API contract](./microservices/automation-scripting-service/api-contracts.md#implementation-status) and [runtime/data owner contract](./microservices/automation-scripting-service/runtime-and-data.md#redis-roles-and-prefixes). | +| `automation:queue:{tenantInstanceTag}:*` | Cache/Rate-Limit | **Current reset/recovery unavailable; fail-closed (target reset-tolerant)** | Queue entries are disposable pointers: losing all Redis list contents does not lose PostgreSQL `script_work_items`, but missing pointers do not authorize resume. The current `rebuildPendingWorkItemIndex` selects only `PENDING_EVALUATION` rows, but has no stale-owner or compare-and-set reconciliation gate and cannot establish a safe disposition for existing `EVALUATING` rows, so queue reset, rebuild, and resume are unavailable. Do not flush, rebuild, or resume this projection as a supported current operation; keep the affected `{tenantId, gameInstanceId}` scope paused/fenced and escalate to the Automation owner. Before any future rebuild can release that scope, owner reconciliation must establish a definitive stage-aware disposition for ambiguous post-DSL handoffs from a durable evaluated descriptor, retaining durable handoff intent without replaying the DSL, then complete owner CAS fencing and exact readback. Only after these conditions are implemented and proven may tooling drop and rebuild this pointer projection from authoritative rows. | The queue is a derived pointer projection, never execution authority; PostgreSQL work-item state remains authoritative. See the [Automation & Scripting API contract](./microservices/automation-scripting-service/api-contracts.md#implementation-status) and [runtime/data owner contract](./microservices/automation-scripting-service/runtime-and-data.md#redis-roles-and-prefixes) for the durable evaluated-descriptor and recovery boundary. | | `automation:quota::*`, `automation:tenant-budget::tier:`, `automation:test:quota::script::tenant`, `automation:test:quota::script::principal:`, `automation:test:capacity:{}:tenant`, `automation:test:capacity:{}:lease:`, `automation:test:capacity:{automation-test-capacity}:cluster`, `automation:test:capacity:{automation-test-capacity}:cluster:lease::`, `automation:readiness:capacity:{}:tenant`, `automation:readiness:capacity:{}:lease:`, `automation:readiness:capacity:{automation-readiness-capacity}:cluster`, `automation:readiness:capacity:{automation-readiness-capacity}:cluster:lease::` | Cache/Rate-Limit | **Reset-tolerant** | Quota windows and capacity reservations restart from an empty state; durable automation work/readiness state remains authoritative. The service does not rebuild the one-minute quota windows or ten-minute readiness leases; new requests acquire fresh disposable reservations. | Best-effort counters and owner-token leases; resets clear them but do not affect authoritative state. Repeated resets or lease expiry may temporarily relax test fairness or readiness concurrency, but must not change which durable work eventually runs. Only the Automation service's Cache/Rate-Limit ACL may access these families; they are not Coordination Redis scheduler/tick keys. Tenant counter/lease pairs use the tenant hash tag, while cluster counter/lease pairs use their fixed family hash tag. | | `tick-events-lease:{tenantRegionTag}` (target-only, once implemented) | Coordination | **Reset-tolerant (target-only, once implemented)** | The target lease is currently unavailable; once implemented, observer leases are dropped, consumers reacquire them, and may duplicate best-effort processing until offsets are re-established. | Used only to avoid duplicate tick-event consumption work. Losing it is safe because tick events are observers/hints; correctness derives from the committed heartbeat/RegionStatus timeline and durable domain state. | | `tick-events:{tenantRegionTag}` and all `tick-events-offset:{tenantRegionTag}:{consumerId}` keys (target-only, once implemented) | Coordination | **Reset-tolerant (target-only, once implemented)** | The target stream and offsets are currently unavailable; once implemented, tick event streams and every consumer's offset are dropped, and observers re-establish their baselines from the gRPC heartbeat and domain state. Any surviving per-consumer offset value is reusable only when its stored `region_epoch` matches the current control-plane epoch; otherwise it is discarded before resume. | Tick event streams are best-effort observer/wakeup hints (for example, reconnection hints and faster scheduler discovery). Each offset value stores `{tenantId, gameInstanceId, regionId, consumerId, region_epoch, latestTickId, streamOffset}`. Streams are retention-capped (default `tick_events_maxlen = 2048` per region). Correctness derives from the committed heartbeat/RegionStatus timeline plus durable PostgreSQL schedules/effects; missing or duplicated events must not change which schedules eventually fire. | diff --git a/design/architecture/system-architecture-scripting-contracts.md b/design/architecture/system-architecture-scripting-contracts.md index 2a6b72156e..dfee640d45 100644 --- a/design/architecture/system-architecture-scripting-contracts.md +++ b/design/architecture/system-architecture-scripting-contracts.md @@ -22,7 +22,7 @@ The current evaluator supports a bounded emitted-command collection per work ite - A **script work item** is the post-DSL output staged by Automation & Scripting (domain commands + metadata such as `scriptId`, `scriptPatchVersion`, and `scriptEventId`). It preserves the immutable source Trigger Identity, including the source `regionId` and `regionEpoch` when applicable; any enqueue or current-routing identity is carried separately and must not overwrite the source trigger fields. - A **tick command** is a unit of work that has been accepted into an entity’s tick queue by Game Session and will be executed under tick locks and replay semantics. - **Target-state command handoff:** Every script work item that emits gameplay commands receives one stable `automationDispatchId`, and each emitted command carries a deterministic `commandOrdinal` under that dispatch. The pair is only the final discriminator within the complete Command-Handoff Identity; one handler may fan out into multiple commands, and a pair without its complete source/target runtime scope is not a command identity. -- **Target-state command handoff:** The complete Command-Handoff Identity is the canonical identity for evaluated child-dispatch handoff deduplication, execution-fence reporting, replay selection, and correlation. It is not the downstream effect guard: authoritative effect idempotency uses the persisted mutation `EffectId` (the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child mutation), typed operation, exact target aggregate, and stored/compared immutable request digest, with any enclosing `rootEffectId` retained only as lineage and reconciliation context and conflicts failing closed. The `(automationDispatchId, commandOrdinal)` pair is only an identity suffix and is insufficient by itself; `automationDispatchId` identifies a dispatch group, and `scriptEventId` alone must never identify a fan-out command. See [Implementation Status](#implementation-status) for the current evaluator boundary. +- **Target-state command handoff:** The complete Command-Handoff Identity is the canonical identity for evaluated child-dispatch handoff deduplication, execution-fence reporting, replay selection, and correlation. It is not the downstream effect guard: authoritative effect idempotency uses the persisted mutation `EffectId` (the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child mutation), typed operation, exact target aggregate, and stored/compared immutable request digest, with any enclosing `rootEffectId` retained only as lineage and reconciliation context and conflicts failing closed. Participant-guard identity follows the owner-classified rules in [Transaction Strategies](./system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory): S1/S2 use the `(tenantId, playableStateNamespaceId)` partition, and only explicitly classified S3 uses `(tenantId, gameInstanceId)`; `playableStateScope` and `requestDigest` are exact-validated evidence, not uniqueness dimensions, and unclassified families fail before admission. The `(automationDispatchId, commandOrdinal)` pair is only an identity suffix and is insufficient by itself; `automationDispatchId` identifies a dispatch group, and `scriptEventId` alone must never identify a fan-out command. See [Implementation Status](#implementation-status) for the current evaluator boundary. Target-state handoff linkage uses the complete Command-Handoff Identity: complete source/target runtime scope, `automationDispatchId`, and `commandOrdinal`. The current implementation is narrower than this target: because Trigger Identity and `commandOrdinal` are not carried end to end, current live linkage and retry diagnostics use `outboxWorkItemId`, `gameSessionCommandId`, available `automationDispatchId`, and `script_event_audit`. This fallback is not complete command-level deduplication or replay evidence. The remaining gap is tracked under `AS-1.5` and its Game Session handoff dependency in the [automation and scheduler runtime tracker](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). diff --git a/design/architecture/system-architecture-scripting-event-registry.md b/design/architecture/system-architecture-scripting-event-registry.md index ea1b9918ad..e0523f7f95 100644 --- a/design/architecture/system-architecture-scripting-event-registry.md +++ b/design/architecture/system-architecture-scripting-event-registry.md @@ -68,7 +68,7 @@ Required semantics for those fields: - The exact identity fields applicable to this event at each stage: the event-scope ingress subset before handler resolution and the full handler Trigger Identity after each handler resolves, as defined by the [normative identity tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). - Ordinary producer event-scope ingress must not require, fabricate, or use synthetic values for handler-only fields. In particular, `scriptId`, `pluginId`, `pluginVersionId`, and `bindingId` are unavailable before handler resolution; they become required only when the resolved handler's scope requires them. - Tenant-readiness `onLoad` is the deliberate exception for `scriptId`: its event-scope identity targets one script and includes that `scriptId` so Automation can derive the deterministic `scriptEventId` before handler resolution. This does not authorize fabricated runtime-ingress script IDs; `pluginId`, `pluginVersionId`, and `bindingId` remain post-resolution fields. - - Scheduler/timer due candidates are another deliberate pre-handler exception: because Automation already materialized a durable schedule with its owner identity, the scheduler firing identity and deterministic event-scope `scriptEventId` include the schedule-owned `scriptId` and any schedule-owned `pluginId`, `pluginVersionId`, and `bindingId`; plugin-owned candidates also include the captured `pluginActivationEpoch`, and `CATCH_UP` candidates include `resumeWindowId`. The captured `lifecycleRevision` travels alongside as required non-identity fence evidence and is not included in candidate, firing-claim, or `scriptEventId` identity. For gameplay/runtime and scheduler candidates, the paired nonblank `scriptPinControlPlaneRequestId` is retained and exact-compared as owner/fence evidence, but is excluded from candidate, firing-claim, work-item, and derived event identity. The scheduler must not fabricate a field absent from that schedule. This scheduler-owned exception does not authorize ordinary producer ingress to supply handler-only identity. + - Scheduler/timer due candidates are another deliberate pre-handler exception: because Automation already materialized a durable schedule with its owner identity, the scheduler firing identity and deterministic event-scope `scriptEventId` include the schedule-owned `scriptId` and any schedule-owned `pluginId`, `pluginVersionId`, and `bindingId`; plugin-owned candidates also include the captured `pluginActivationEpoch`, and `CATCH_UP` candidates include `resumeWindowId`. Gameplay/runtime and scheduler candidate identity also includes the exact Game Session `(scriptPatchVersion, scriptPinEpoch)` tuple required by the target-state exact-fence rule below and the [normative identity tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). The paired nonblank `scriptPinControlPlaneRequestId` and captured `lifecycleRevision` travel alongside as required, exact-compared non-identity owner/fence evidence; they are excluded from candidate, firing-claim, work-item, and derived event identity. The scheduler must not fabricate a field absent from that schedule. This scheduler-owned exception does not authorize ordinary producer ingress to supply handler-only identity. - For every gameplay-originated event, this set must unconditionally include `playableStateNamespaceId` in the applicable gameplay/runtime identity, regardless of whether the realm is shared or isolated. The producer must resolve that namespace authoritatively before admission; a missing, unresolved, stale, or contradictory namespace fails closed. An explicitly declared non-gameplay contract may omit it only when the registry entry is classified outside gameplay/runtime and uses the non-gameplay Trigger Identity branch. `playableStateScope` remains separately persisted, exact-validated policy/routing/authorization/migration-fence evidence; it is excluded from Trigger Identity, event-scope, handoff, schedule, and other uniqueness/deduplication keys. See the [normative identity tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). - **Target-state exact-fence requirement:** For gameplay/runtime and scheduler events, the identity set includes the exact Game Session `scriptPatchVersion` and `scriptPinEpoch`; the paired nonblank `scriptPinControlPlaneRequestId` is separately required owner/fence evidence, exact-compared with Game Session, and excluded from registry idempotency identity and keys. A version-only or partial identity tuple is incomplete and cannot be admitted after a repin. - `snapshotAuthority` diff --git a/design/architecture/system-architecture-ticks.md b/design/architecture/system-architecture-ticks.md index 9ed2946796..9fd274605e 100644 --- a/design/architecture/system-architecture-ticks.md +++ b/design/architecture/system-architecture-ticks.md @@ -431,7 +431,7 @@ Crash recovery re-invokes a domain handler for a staged effect only when durable ## Timers and Time Scaling -Every scheduler/timer source carries exactly one tagged, persisted source due point: `dueTickId` for tick-based scheduling or immutable `dueAt` for wall-clock scheduling; it carries neither both nor neither as its source due point. Tick-based queued commands, retries, remote follow-ups, and tick timers use their persisted `dueTickId` directly. A wall-clock timer remains eligible from its immutable `dueAt` (`now >= dueAt`). Once eligible, one durable firing-claim/admission transaction reads the authoritative target timeline and assigns/persists exactly one target `regionEpoch` and `due_tick_id` ordering coordinate (normally the next committable tick), together with the source claim. Retries and replays reuse those persisted values and never recompute them from cadence or wall time. An epoch change follows old-epoch reconciliation and new admission; it never rebinds the old firing. The within-entity tuple uses the persisted admission `due_tick_id` for wall-clock timers and the persisted `dueTickId` for tick timers. Wall-clock timestamps and tick IDs are different domains and must not be compared numerically or aliased. +Every scheduler/timer source carries exactly one tagged, persisted source due point: `dueTickId` for tick-based scheduling or immutable `dueAt` for wall-clock scheduling; it carries neither both nor neither as its source due point. Tick-based queued commands, retries, remote follow-ups, and tick timers use their persisted `dueTickId` directly. A wall-clock timer remains eligible from its immutable `dueAt` (`now >= dueAt`). Only wall-clock timer admission assigns a separate tick-ordering coordinate: once eligible, one durable firing-claim/admission transaction reads the authoritative target timeline and assigns/persists exactly one target `regionEpoch` and `due_tick_id` (normally the next committable tick), together with the source claim. Tick timers reuse their persisted `dueTickId` as both source due point and ordering coordinate. Retries and replays reuse the persisted target epoch and ordering coordinate and never recompute them from cadence or wall time. An epoch change follows old-epoch reconciliation and new admission; it never rebinds the old firing. The within-entity tuple uses the persisted admission `due_tick_id` for wall-clock timers and the persisted `dueTickId` for tick timers. Wall-clock timestamps and tick IDs are different domains and must not be compared numerically or aliased. Timer projections are stored and scheduled via Redis timer keys and remain aligned with the tick heartbeat and tick cadence. Time-scaling rules may speed up or slow down perceived time while preserving ordering, but a later cadence or time-scale change never rewrites an existing due point. Wall-clock eligibility uses caller-supplied `now_ms` in Lua (never Redis `TIME`); tick eligibility uses the committed region timeline. diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index 14aae89fe4..a928a27c6b 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -1711,6 +1711,7 @@ require_contains( "design/architecture/system-architecture-scripting-contracts.md", [ "The `(automationDispatchId, commandOrdinal)` pair is only an identity suffix and is insufficient by itself", + "Participant-guard identity follows the owner-classified rules in [Transaction Strategies](./system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory): S1/S2 use the `(tenantId, playableStateNamespaceId)` partition, and only explicitly classified S3 uses `(tenantId, gameInstanceId)`; `playableStateScope` and `requestDigest` are exact-validated evidence, not uniqueness dimensions, and unclassified families fail before admission.", "always-isolated test-only breaker or gate", "no environment, tenant, or request opt-in may cross that boundary", ], @@ -1719,6 +1720,64 @@ require_absent( "design/architecture/system-architecture-scripting-contracts.md", ["(automationDispatchId, commandOrdinal)` pair is only a display suffix"], ) +require_contains( + "design/architecture/microservices/entity-management-service/operations.md", + [ + "a conflict-safe insert or a same-transaction savepoint around marker handling while keeping the marker and mutation atomic, never an isolated marker transaction", + "Actual PostgreSQL concurrent proof remains unavailable.", + "retain the admitted command/source identity for source evidence, and use the complete Command-Handoff Identity for automation handoff and deduplication", + "the handoff identity is not a mandatory input to root `EffectId` allocation or lookup", + "Root allocation and lookup details remain proposal-only under pending [ADR 0183]", + ], +) +require_absent( + "design/architecture/microservices/entity-management-service/operations.md", + ["is an input to allocating or looking up that command's stable root `EffectId`"], +) +require_contains( + "design/architecture/microservices/game-session-service/runtime-and-data.md", + [ + "A new identity may be re-driven only after authoritative participant/domain evidence conclusively terminalizes the original effect as `ABANDONED` and the owning source command/claim is terminalized; ordinary retry/replay retains the original command/effect identity.", + "A new identity may be re-driven only after that conclusive terminalization and terminalization of the owning source command/claim; ordinary retry/replay must retain the original command/effect identity.", + "Root allocation details remain proposal-only under [ADR 0183]", + ], +) +require_absent( + "design/architecture/microservices/game-session-service/runtime-and-data.md", + [ + "only a conclusive post-abandon re-drive allocates a new command ID and root", + "A post-abandon re-drive is the only path that may allocate a new command ID/root", + ], +) +require_contains( + "design/architecture/microservices/game-design-service/version-control.md", + [ + "Current Game Design revision rows reference concrete domain objects", + "Target durable commits will group those revisions and retain their domain-object references", + "that branch/commit model and its APIs are not implemented, while current version-scoped revision history remains available", + ], +) +require_contains( + "design/architecture/system-architecture-redis-reset-and-recovery.md", + [ + "Before any future rebuild can release that scope, owner reconciliation must establish a definitive stage-aware disposition for ambiguous post-DSL handoffs from a durable evaluated descriptor, retaining durable handoff intent without replaying the DSL, then complete owner CAS fencing and exact readback.", + ], +) +require_contains( + "design/architecture/system-architecture-scripting-event-registry.md", + [ + "Gameplay/runtime and scheduler candidate identity also includes the exact Game Session `(scriptPatchVersion, scriptPinEpoch)` tuple", + "The paired nonblank `scriptPinControlPlaneRequestId` and captured `lifecycleRevision` travel alongside as required, exact-compared non-identity owner/fence evidence; they are excluded from candidate, firing-claim, work-item, and derived event identity.", + ], +) +require_contains( + "design/architecture/system-architecture-ticks.md", + [ + "Only wall-clock timer admission assigns a separate tick-ordering coordinate", + "Tick timers reuse their persisted `dueTickId` as both source due point and ordering coordinate.", + "Wall-clock timestamps and tick IDs are different domains and must not be compared numerically or aliased.", + ], +) require_absent( "design/architecture/system-architecture-scripting-contracts.md", ["separate breaker or explicitly opt-in per environment/tenant"], From 9bff813ad91e1038c854b38362bf4179e440776d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:59:35 +1300 Subject: [PATCH 58/68] docs: qualify target charge records and complete audit schema identity --- ...ecture-scripting-observability-contract.md | 1 + ...rchitecture-scripting-runtime-execution.md | 2 +- dev-tools/tests/architecture-doc-contracts.sh | 20 +++++++++++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/design/architecture/system-architecture-scripting-observability-contract.md b/design/architecture/system-architecture-scripting-observability-contract.md index 158cdbd437..5534b6ce52 100644 --- a/design/architecture/system-architecture-scripting-observability-contract.md +++ b/design/architecture/system-architecture-scripting-observability-contract.md @@ -75,6 +75,7 @@ The following is the canonical target `script_event_audit` field list (with the - `scriptId` - `pluginId`, `pluginVersionId`, and `bindingId` (required for resolved plugin handlers) - `eventType` + - `eventSchemaVersion` (admitted event and payload contract version, including tenant-readiness `onLoad`; see [normative Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields)) - `scriptPatchVersion` - `scriptPinEpoch` (required for gameplay/runtime and scheduler triggers; absent for tenant-readiness `onLoad`) - `scriptPinControlPlaneRequestId` (retained immutable owner/audit evidence, required with a positive `scriptPinEpoch` for every instance-scoped gameplay/runtime and scheduler trigger; absent with the entire pin tuple for pre-instance requests such as tenant-readiness `onLoad`; epoch-zero records represent explicitly unpinned state only on contracts that support that state and are not valid instance-scoped trigger admission) diff --git a/design/architecture/system-architecture-scripting-runtime-execution.md b/design/architecture/system-architecture-scripting-runtime-execution.md index 9f5839ffa3..e52a6c9a74 100644 --- a/design/architecture/system-architecture-scripting-runtime-execution.md +++ b/design/architecture/system-architecture-scripting-runtime-execution.md @@ -291,7 +291,7 @@ Every compiled script artifact must carry enough normalized output-cost metadata Runtime metering is incremental and happens before constructing each generated command or data-dependent collection. The evaluator charges the artifact-pinned conservative prospective serialized-byte bound together with cumulative command count, per-entity count, payload/collection bounds, and every data-dependent cap declared by the pinned metadata before construction or allocation. After bounded descriptors are staged, their exact serialized size is checked against the pinned ceiling immediately before atomic persistence. A run that would exceed any cap stops with the stage-correct `DSL_EVAL` non-success outcome and bounded reason; an independent serializer or persistence transaction failure remains `WORK_ITEM_PERSIST`. It must not construct an unbounded intermediate result and discover a cap violation only at handoff. -Generated output is atomic per resolved handler: either every bounded descriptor for that handler is durably persisted with its parent evidence, or none of that handler's generated output is persisted or handed off. A failed output-meter check, serialized-size ceiling check, or persistence transaction discards all staged output for that handler; an output-limit failure therefore prevents evaluated descriptor/work-item/child-handoff persistence, while the owning pre-DSL trigger-record/work-item row still commits the terminal `DSL_EVAL` audit outcome and the separate durable handler charge record preserves any admission/execution-start charge markers already reached. It must not leave a partial command set that a retry could interpret as successful work. Event-scope ingress may reject a missing or conflicting artifact-cost digest with its ingress `OUTPUT_BUDGET_EXCEEDED` outcome, while a handler that exceeds a runtime cap records the canonical handler-scoped `DSL_EVAL` outcome and reason from [Table 2](./system-architecture-scripting-normative-contract-tables.md#table-2-script_event_audit-stages-and-outcomes). +Generated output is atomic per resolved handler: either every bounded descriptor for that handler is durably persisted with its parent evidence, or none of that handler's generated output is persisted or handed off. A failed output-meter check, serialized-size ceiling check, or persistence transaction discards all staged output for that handler; an output-limit failure therefore prevents evaluated descriptor/work-item/child-handoff persistence, while the owning pre-DSL trigger-record/work-item row still commits the terminal `DSL_EVAL` audit outcome. Target state also preserves any admission/execution-start charge markers already reached in the separate durable handler charge record, as defined by [Scripting Quotas & Operations](./system-architecture-scripting-quotas-and-operations.md#budget-accounting-rules); that record and its linkage are not claimed as current implementation. It must not leave a partial command set that a retry could interpret as successful work. Event-scope ingress may reject a missing or conflicting artifact-cost digest with its ingress `OUTPUT_BUDGET_EXCEEDED` outcome, while a handler that exceeds a runtime cap records the canonical handler-scoped `DSL_EVAL` outcome and reason from [Table 2](./system-architecture-scripting-normative-contract-tables.md#table-2-script_event_audit-stages-and-outcomes). ## Budget Charge Points diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index a928a27c6b..68ec64f965 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -1801,6 +1801,26 @@ require_contains( "it is not persisted breaker authority and does not own transition history or reset", ], ) +require_contains( + "design/architecture/system-architecture-scripting-runtime-execution.md", + [ + "Target state also preserves any admission/execution-start charge markers already reached in the separate durable handler charge record", + "as defined by [Scripting Quotas & Operations](./system-architecture-scripting-quotas-and-operations.md#budget-accounting-rules)", + "that record and its linkage are not claimed as current implementation", + ], +) +require_absent( + "design/architecture/system-architecture-scripting-runtime-execution.md", + ["the separate durable handler charge record preserves any admission/execution-start charge markers already reached"], +) +require_contains( + "design/architecture/system-architecture-scripting-observability-contract.md", + [ + "`eventType`", + "`eventSchemaVersion` (admitted event and payload contract version, including tenant-readiness `onLoad`; see [normative Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields))", + "`scriptPatchVersion`", + ], +) require_contains( "design/architecture/microservices/automation-scripting-service/sandbox-runtime-design.md", [ From 80573cdaa86335aa0ad83d595126146300e01db2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:20:21 +1300 Subject: [PATCH 59/68] docs: align proof records and fence resume identity reuse --- ...ecific-script-timer-clocks-and-recovery.md | 2 +- ...rchitecture-scripting-runtime-execution.md | 2 +- ...stem-architecture-tick-incident-runbook.md | 2 +- dev-tools/tests/architecture-doc-contracts.sh | 31 +++++++++++++++++++ 4 files changed, 34 insertions(+), 3 deletions(-) diff --git a/design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md b/design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md index 9977b2383d..4b0bee93e5 100644 --- a/design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md +++ b/design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md @@ -47,7 +47,7 @@ Durable recurring schedules declare exactly one missed-firing policy: - `SKIP_MISSED` emits no synthetic firing for missed boundaries. - `COALESCE_ONE` may emit at most one synthetic firing for one logical schedule in a durable resume window. -One durable, mode-scoped resume-window identity covers the complete recovery attempt across repeated scans or progress observations: live and dry-run/test recovery use separate windows and separate caps, with `isDryRun` included in the window identity and every candidate-selection, firing-claim, candidate-audit, and proof comparison. The authoritative `playableStateNamespaceId` is part of the due and resume-window identity; server-derived `playableStateScope` remains immutable policy/routing/authorization/migration-fence evidence, is exact-validated alongside that identity, and is not a uniqueness discriminator. An authoritative scope transition starts a new playable-state lifecycle and namespace; stale presented scope with unchanged authority may reuse the existing identity. Each window also binds the exact `(scriptPatchVersion, scriptPinEpoch)` as immutable execution-fence evidence without adding the pin tuple to `resumeWindowId`, and at creation freezes the effective numeric tenant-local cap plus the selection-policy revision that defines grouping, ordering, round-robin passes, and tie breaks. Repeated observations, retries, and takeovers reuse those frozen values unchanged and cannot remint another catch-up firing for the same schedule and window; a cap or policy change applies only to a later window after the current one reaches `COMPLETE`. The deterministic fair tenant-local cap applies within each mode-specific resume window, which is already scoped to one tenant, and selects coalesced candidates across complete stable schedule-instance identities; cap-excluded candidates are dropped with bounded audit and metrics under that window's frozen policy rather than deferred into an unbounded backlog. Selected candidates still enter the shared scheduler/cluster admission layer, where [ADR 0166](./adr-0166-attributable-script-breakers-and-tenant-first-fairness.md) tenant-first fairness precedes priority; catch-up cannot bypass per-tenant or cluster ceilings. A selected candidate denied by a tenant or cluster capacity ceiling is terminally skipped under the same due-candidate, `isDryRun`, and `resumeWindowId` identity with bounded audit, consumes its deterministic selection slot, creates no firing claim or `scriptEventId`, and is never deferred, retried, backfilled, or reminted as catch-up. Its next ordinary future cadence remains eligible. +One durable, mode-scoped resume-window identity covers the complete recovery attempt across repeated scans or progress observations: live and dry-run/test recovery use separate windows and separate caps, with `isDryRun` included in the window identity and every candidate-selection, firing-claim, candidate-audit, and proof comparison. The authoritative `playableStateNamespaceId` is part of the due and resume-window identity; server-derived `playableStateScope` remains immutable policy/routing/authorization/migration-fence evidence, is exact-validated alongside that identity, and is not a uniqueness discriminator, as defined by the [normative Trigger Identity contract](../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) and [Timer Resume Rule](../system-architecture-scripting-scheduler-and-timers.md#timer-resume-rule-normative). A stale or mismatched presented scope fails closed for reuse until authoritative evidence is reconciled and exact validation succeeds. Only reconciled matching scope with unchanged authority may reuse the existing namespace-keyed identity; an authority-proven scope transition starts a new playable-state lifecycle and namespace. Each window also binds the exact `(scriptPatchVersion, scriptPinEpoch)` as immutable execution-fence evidence without adding the pin tuple to `resumeWindowId`, and at creation freezes the effective numeric tenant-local cap plus the selection-policy revision that defines grouping, ordering, round-robin passes, and tie breaks. Repeated observations, retries, and takeovers reuse those frozen values unchanged and cannot remint another catch-up firing for the same schedule and window; a cap or policy change applies only to a later window after the current one reaches `COMPLETE`. The deterministic fair tenant-local cap applies within each mode-specific resume window, which is already scoped to one tenant, and selects coalesced candidates across complete stable schedule-instance identities; cap-excluded candidates are dropped with bounded audit and metrics under that window's frozen policy rather than deferred into an unbounded backlog. Selected candidates still enter the shared scheduler/cluster admission layer, where [ADR 0166](./adr-0166-attributable-script-breakers-and-tenant-first-fairness.md) tenant-first fairness precedes priority; catch-up cannot bypass per-tenant or cluster ceilings. A selected candidate denied by a tenant or cluster capacity ceiling is terminally skipped under the same due-candidate, `isDryRun`, and `resumeWindowId` identity with bounded audit, consumes its deterministic selection slot, creates no firing claim or `scriptEventId`, and is never deferred, retried, backfilled, or reminted as catch-up. Its next ordinary future cadence remains eligible. Every exact script-pin selection change is a resume-window transition, including a same-patch repin that advances `scriptPinEpoch`, even when the runtime region and region epoch are unchanged. Before any new exact-pin timer admission, durable reconciliation must move every prior mode-specific `OPEN` window for the affected scope out of `OPEN`, fence its claims to the prior exact pin and `resumeWindowId`, and preserve those claims and candidate audits for settlement under their original identities. They cannot consume the next window's cap or be rewritten for the target pin. After the target exact `(scriptPatchVersion, scriptPinEpoch)` and its schedules reconcile, a still-required catch-up episode allocates the next monotonic `resumeGeneration` independently for each mode and therefore a distinct mode-specific `resumeWindowId`; retries of this transition are idempotent under the initiating `controlPlaneRequestId`. diff --git a/design/architecture/system-architecture-scripting-runtime-execution.md b/design/architecture/system-architecture-scripting-runtime-execution.md index e52a6c9a74..d4e2733a71 100644 --- a/design/architecture/system-architecture-scripting-runtime-execution.md +++ b/design/architecture/system-architecture-scripting-runtime-execution.md @@ -229,7 +229,7 @@ Target-state recovery is idempotent by stable `controlPlaneRequestId` for each o ## `scriptEventId` Lifecycle and Deduplication -Trigger Identity, endpoint-specific `scriptEventId` ownership, audit uniqueness, and command-level retry identity are defined in the [normative contract tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) and [cross-service scripting contracts](./system-architecture-scripting-contracts.md#4-scripteventid-identity-and-at-most-once-dedupe). Runtime persistence carries the applicable identity on the durable pre-DSL trigger record and resulting evaluated script work item, preserving it across queue projection, claims, and handoff attempts. +Trigger Identity, endpoint-specific `scriptEventId` ownership, audit uniqueness, and command-level retry identity are defined in the [normative contract tables](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) and [cross-service scripting contracts](./system-architecture-scripting-contracts.md#4-scripteventid-identity-and-at-most-once-dedupe). In the current implementation, one `script_work_items` row carries the applicable identity from the pre-DSL trigger through evaluation and handoff processing; separate evaluated-work-item records and descriptor replay remain target-state only. ## Runtime Deployment & Versioning diff --git a/design/architecture/system-architecture-tick-incident-runbook.md b/design/architecture/system-architecture-tick-incident-runbook.md index ec6ab50cc3..61a3e7ad7d 100644 --- a/design/architecture/system-architecture-tick-incident-runbook.md +++ b/design/architecture/system-architecture-tick-incident-runbook.md @@ -8,7 +8,7 @@ For the detailed tick design, see: - `design/architecture/system-architecture-tick-concepts-and-invariants.md` - `design/architecture/system-architecture-tick-failures-and-operations.md` -Validation and runtime-proof selection for changes to this runbook follows the shared [Validation and Runtime Proof workflow](../developer-workflows/validation-and-runtime-proof.md); record execution results in PR/CI evidence or the owning implementation tracker. +Validation and runtime-proof selection for changes to this runbook follows the shared [Validation and Runtime Proof workflow](../developer-workflows/validation-and-runtime-proof.md); record execution results in PR/CI evidence, and update the owning implementation tracker when capability or proof status changes. Redis coordination behavior and reset flows are defined in: diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index 68ec64f965..d8766820ad 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -2466,6 +2466,37 @@ for term in ( f"missing full-version publication availability qualification {term!r}" ) +require_contains( + "design/architecture/system-architecture-tick-incident-runbook.md", + [ + "record execution results in PR/CI evidence, and update the owning implementation tracker when capability or proof status changes", + ], +) +require_absent( + "design/architecture/system-architecture-tick-incident-runbook.md", + ["record execution results in PR/CI evidence or the owning implementation tracker"], +) +require_contains( + "design/architecture/system-architecture-scripting-runtime-execution.md", + [ + "one `script_work_items` row carries the applicable identity from the pre-DSL trigger through evaluation and handoff processing", + "separate evaluated-work-item records and descriptor replay remain target-state only", + ], +) +require_contains( + "design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md", + [ + "A stale or mismatched presented scope fails closed for reuse until authoritative evidence is reconciled and exact validation succeeds", + "Only reconciled matching scope with unchanged authority may reuse the existing namespace-keyed identity", + "an authority-proven scope transition starts a new playable-state lifecycle and namespace", + "[Timer Resume Rule](../system-architecture-scripting-scheduler-and-timers.md#timer-resume-rule-normative)", + ], +) +require_absent( + "design/architecture/decisions/adr-0091-class-specific-script-timer-clocks-and-recovery.md", + ["stale presented scope with unchanged authority may reuse the existing identity"], +) + print("architecture doc contracts passed") PY From 2fd21cfd710ccde4fb358864c72b579e787a075e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 19:48:15 +1300 Subject: [PATCH 60/68] docs: align replay proof and complete participant terminal evidence --- ...effect-id-allocation-and-replay-binding.md | 2 + .../sandbox-runtime-design.md | 2 +- .../world-creation-workflow.md | 2 +- .../system-architecture-gateway.md | 1 + .../system-architecture-redis-ops-access.md | 2 +- .../architecture/system-architecture-redis.md | 10 +-- .../system-architecture-temporal-workflows.md | 6 +- ...stem-architecture-tick-incident-runbook.md | 2 +- .../system-architecture-transactions.md | 2 +- dev-tools/tests/architecture-doc-contracts.sh | 80 ++++++++++++++++++- 10 files changed, 93 insertions(+), 16 deletions(-) diff --git a/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md b/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md index 236b48d70b..d31768c6e4 100644 --- a/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md +++ b/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md @@ -39,6 +39,8 @@ The canonical scalar `EffectId` is an opaque, lowercase, hyphenated UUIDv7 textu If accepted, Game Session would own command-root allocation, while the owner of a generated child, non-command root, or remote/fan-out leg would own its corresponding allocation boundary. Each boundary would allocate once, durably persist the value, and atomically bind it to the complete immutable owner scope, operation, exact target where applicable, request digest, enclosing root, parent, and stable ordinal. Insert-if-absent uniqueness would cover the logical mapping and scalar claim. A collision or any conflicting binding would fail closed; it would not remint or substitute an ID. +Under this proposal, a command root's enclosing root is its own persisted `EffectId`, and its parent is explicitly absent (`null`). The first allocation durably binds that exact root mapping; retry and replay reuse the same scalar and binding. + Retries, replay, failover, and reconciliation read and reuse the persisted mapping and exact scalar. Participants receive the persisted mutation identity and use it in their guard, ledger, response, and terminal outcome. The enclosing root remains lineage and reconciliation context for a child; it does not replace the child's identity or collapse siblings. A post-abandon re-drive receives a new explicitly linked identity under its own admission contract. ### Proposed command-root serialization refinements diff --git a/design/architecture/microservices/automation-scripting-service/sandbox-runtime-design.md b/design/architecture/microservices/automation-scripting-service/sandbox-runtime-design.md index 1592da72ed..9e5a9c574c 100644 --- a/design/architecture/microservices/automation-scripting-service/sandbox-runtime-design.md +++ b/design/architecture/microservices/automation-scripting-service/sandbox-runtime-design.md @@ -103,7 +103,7 @@ For the [ADR 0114](../../decisions/adr-0114-command-plan-preview-dry-run-isolati 4. **Command staging** - For eligible instance-bound gameplay/runtime runs, successful emitted commands are bounded descriptors staged into the already admitted per-handler durable work item and persisted atomically, then follow the separate durable Game Session handoff path. The already admitted `automation:queue:*` projection remains the pre-evaluation discovery pointer and is not a handoff queue. - Tenant-readiness `onLoad` is outside this descriptor-staging and handoff path. After readiness validation/evaluation it terminates with only platform-owned readiness, audit, and fencing evidence: it emits no gameplay descriptors or dispatch identity, creates no gameplay work, and never calls `EnqueueAutomationCommandIfAbsent`. This is the local sandbox consequence of the canonical [`onLoad` runtime contract](../../system-architecture-scripting-runtime-execution.md#onload-semantics-and-failure-handling). - - For those eligible instance-bound gameplay/runtime runs, target-state handoff through `EnqueueAutomationCommandIfAbsent` uses the [normative Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state): source `playableStateNamespaceId`/region identity, optional distinct target namespace/region identity, the `automationDispatchId` allocated and persisted by the first atomic durable evaluated-descriptor/outbox commit only when commands are emitted, and a deterministic `commandOrdinal` starting at `0` in canonical emitted-command order. Source and target `playableStateScope` values are separately validated routing/fence evidence, not identity fields. Pre-commit evaluation retries preserve the Trigger/work-item/frozen-input identity and allocate no command-child identity; retries after a winning commit reuse its dispatch ID and ordinals. A valid zero-command evaluation creates no dispatch identity. Game Session deduplicates the complete child identity. The parent Trigger Identity and `outboxWorkItemId` are correlation-only and are excluded from command-child uniqueness and deduplication; they are not substitutes for the complete child identity. The live handoff remains narrower and is not complete child-identity proof; see the [current runtime handoff status](../../system-architecture-scripting-runtime-execution.md#current-implementation-status). + - For those eligible instance-bound gameplay/runtime runs, target-state handoff through `EnqueueAutomationCommandIfAbsent` uses the [normative Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state): source tenant/game-instance ownership (`tenantId`, `gameInstanceId`) and `playableStateNamespaceId`/region identity, optional distinct target game-instance ownership and namespace/region identity, the `automationDispatchId` allocated and persisted by the first atomic durable evaluated-descriptor/outbox commit only when commands are emitted, and a deterministic `commandOrdinal` starting at `0` in canonical emitted-command order. Source and target `playableStateScope` values are separately validated routing/fence evidence, not identity fields. Pre-commit evaluation retries preserve the Trigger/work-item/frozen-input identity and allocate no command-child identity; retries after a winning commit reuse its dispatch ID and ordinals. A valid zero-command evaluation creates no dispatch identity. Game Session deduplicates the complete child identity. The parent Trigger Identity and `outboxWorkItemId` are correlation-only and are excluded from command-child uniqueness and deduplication; they are not substitutes for the complete child identity. The live handoff remains narrower and is not complete child-identity proof; see the [current runtime handoff status](../../system-architecture-scripting-runtime-execution.md#current-implementation-status). - Before constructing each generated command or data-dependent collection for an eligible instance-bound gameplay/runtime run, the engine applies the artifact-pinned conservative prospective serialized-byte bound together with command-count, per-entity, and data-dependent caps. Before atomic persistence, it checks the exact bounded serialized size of the staged descriptors against the pinned ceiling. Any cap exceed is a non-success outcome; all staged output for that handler is discarded and no partial work item or handoff is committed. The evaluator accepts only the artifact-pinned `componentCostRegistryDigest` and `artifactRuntimeCapDigest` plus their embedded payloads as validated by the runtime owner; it does not estimate from a newer local registry. - Eligible instance-bound gameplay/runtime work reaches this stage only after the earlier execution-scheduler selection over queued work. Target-state handoff uses the event-count ceiling (`AUTOMATION_TICK_MAX_EVENTS`) and only documented `automation:*` Redis prefixes for projection and quotas. The Automation & Scripting Service never writes `tick:*` keys directly; it hands off commands to Game Session over internal gRPC so Game Session can enqueue tick commands under its own tick and locking model. Current live capacity enforcement is the aggregate per-tenant, priority-tier reservation described below. 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 25a312d181..40bfe0b055 100644 --- a/design/architecture/microservices/world-management-service/world-creation-workflow.md +++ b/design/architecture/microservices/world-management-service/world-creation-workflow.md @@ -11,7 +11,7 @@ Target state: World creation is a long-running process that prepares the initial the Game Session Service. - `playableStateNamespaceId` – identifies durable playable state independently of the replaceable runtime instance. World retains the resolved namespace across replacement and uses the instance id only for topology and other explicitly instance-scoped state. -The cross-platform workflow placement and adopter-proof requirements are owned by [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification) and [Temporal Control-Plane Workflows](../../system-architecture-temporal-workflows.md). This document records the World Management consequences: the target `world-lifecycle` workflow coordinates the local lifecycle commands and read surface, while World Management's durable lifecycle row and epoch remain authoritative. Its canonical Temporal workflow ID is stable per world instance, and retries use that workflow identity plus durable launch/workflow identity and the shared digest-bound step identity (stable step name, deterministic occurrence, execution role, and immutable request digest; see [ADR 0078](../../decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md)). Gameplay ticks and live in-world mutations remain outside this workflow. Current lifecycle proof covers the extracted command path and Temporal-backed status surface, while full durable step-guard and restart/failure proof remains an implementation gap noted below. The current `TemporalWorldLifecycleOrchestrator` also treats `WorkflowExecutionAlreadyStarted` as reuse and returns the existing snapshot without exact-comparing its complete immutable prepared-launch identity with the incoming request. Until that race path validates at least the exact `controlPlaneRequestId` and `launchDescriptorId` plus every other immutable `PreparedWorldInstanceRequest` field, a conflicting request can observe the existing workflow as a successful retry; this is an implementation and race-proof gap, not target authorization to reuse a mismatched workflow. +The cross-platform workflow placement and adopter-proof requirements are owned by [Transaction Strategies](../../system-architecture-transactions.md#mandatory-workflow-adopter-classification) and [Temporal Control-Plane Workflows](../../system-architecture-temporal-workflows.md). This document records the World Management consequences: the target `world-lifecycle` workflow coordinates the local lifecycle commands and read surface, while World Management's durable lifecycle row and epoch remain authoritative. Its canonical Temporal workflow ID is `world-lifecycle::game-instance:`, stable per `(tenantId, gameInstanceId)` across workflow run replacement, and retries use that workflow identity plus durable launch/workflow identity and the shared digest-bound step identity (stable step name, deterministic occurrence, execution role, and immutable request digest; see [ADR 0078](../../decisions/adr-0078-digest-bound-workflow-and-step-retry-identities.md)). Gameplay ticks and live in-world mutations remain outside this workflow. Current lifecycle proof covers the extracted command path and Temporal-backed status surface, while full durable step-guard and restart/failure proof remains an implementation gap noted below. The current `TemporalWorldLifecycleOrchestrator` also treats `WorkflowExecutionAlreadyStarted` as reuse and returns the existing snapshot without exact-comparing its complete immutable prepared-launch identity with the incoming request. Until that race path validates at least the exact `controlPlaneRequestId` and `launchDescriptorId` plus every other immutable `PreparedWorldInstanceRequest` field, a conflicting request can observe the existing workflow as a successful retry; this is an implementation and race-proof gap, not target authorization to reuse a mismatched workflow. ## Implementation Status diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index f7a684d23c..2602768c75 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -402,6 +402,7 @@ This section is the canonical source of truth for connect-token enforcement and - Replay and browser-revocation state use the canonical target representation defined by the Redis ownership and recovery documents, with bounded cardinality and deterministic expiry at `exp + firemud.gateway.connectTokenClockSkewMs`. The readiness/fence record and marker state must remain one script-compatible Coordination Redis atomicity domain under that contract. The legacy representation emitted by the current writer is migration-only drift and cannot be treated as target state. - The replay and deny-marker prefixes are security-critical, non-evicting coordination state. Gateway's one consume script checks readiness state, signed fence/cutoff, and deny-marker absence before creating the replay marker; consumption is successful only after that script and the configured Redis 7.2+ `WAITAOF` acknowledgement both succeed. A deny marker that linearizes before or during the consume race returns a denial without creating the replay marker; a consume already linearized is spent and cannot be retroactively undone by a later browser logout. A browser revocation is confirmed only after its deny write and same-connection durability acknowledgement succeed; an uncertain deny write remains unconfirmed. Capacity or acknowledgement failure rejects the handshake rather than accepting an uncertain marker. A crash or connection loss between marker creation and acknowledgement is treated as uncertain consumption, not as an opportunity to unconsume or retry the token. - Coordination Redis cold start, reset, unexpected eviction signal, failover, capacity-safety breach, or any other event that cannot prove replay-marker continuity starts a shared replay-protection quarantine for at least the 30-second token lifetime maximum plus two `firemud.gateway.connectTokenClockSkewMs` intervals. One interval covers a latest tolerated future `iat`; the second covers acceptance through `exp + skew`. Account stops issuing connect tokens and Gateway rejects admission until that barrier expires, configuration and capacity checks pass, and a disposable marker script followed by the configured `WAITAOF` thresholds proves `DURABLE_REPLAY_CONSUME_ACK`; tokens from the earlier fence and issuance races cannot survive reopening. Before normal release, old Gateway replay writers must be drained or authoritatively blocked and the complete tagged replay state and readiness/fence state must be authoritative, in addition to the lifetime, skew, configuration/capacity, and disposable-marker `WAITAOF` gates above. If any old-version writer or admission remains allowed, release additionally requires a separately proven cross-version guard; none is currently implemented or proven, so that mixed-version release path remains forbidden. The current replay deployment has one shared continuity domain, so an unscoped continuity failure intentionally blocks new connect-token issuance and admission platform-wide; a future partitioned deployment may narrow quarantine only when it can prove the exact affected marker and fence domain. + - Recovery obtains post-reset replay readiness through a logical typed Gateway-owned readiness-probe operation, called by trusted recovery through the existing authenticated owning-service maintenance API boundary. This is target behavior, not a new public RPC or an implemented operation. The probe is bound under the existing Redis owner contracts to the exact durable maintenance operation and fence, the shared replay domain, the expected `replayAdmissionFence`, and the authoritative quarantine/readiness, configuration, and capacity evidence. Gateway uses one pinned Coordination Redis connection for one fresh invocation of the canonical consume script with a disposable marker, then issues `WAITAOF` on that same connection. It yields `DURABLE_REPLAY_CONSUME_ACK` only when the consume returns `1`, creates the marker, the configured local and replica durability thresholds are met, and readback still proves the same operation/fence, replay domain, replay fence, quarantine state, configuration, and capacity conditions. A `0` or `-1`, connection loss, threshold timeout, malformed or uncertain result, or changed fence/quarantine/configuration/capacity fails closed; Gateway never retries an old marker to claim a new acknowledgement. Cleanup is a separate guarded write and readback, outside the acknowledgement. This operation proves neither Account projection readiness nor permission to enable normal player admission; the recovery owner still applies all other release gates. The operation and its producer/consumer proof are currently unimplemented, so the post-reset checklist is not yet executable for this gate. - Replay-quarantine lifecycle is a monitored security state. Gateway must emit low-cardinality `gateway.connect_token.replay_quarantine_entries_total{reason=...}`, `gateway.connect_token.replay_quarantine_exits_total{outcome=...}`, `gateway.connect_token.replay_quarantine_active`, and `gateway.connect_token.replay_quarantine_duration_seconds`, plus structured records containing the shared `replayAdmissionFence`, `state`, `quarantineStartedAt`, `quarantineUntil`, and `openedAt` values. Alertmanager must alert when a player-facing quarantine is entered, remains active past `quarantineUntil` or has no observed exit, or exits without fresh `DURABLE_REPLAY_CONSUME_ACK` proof. Dashboards must show entry/exit counts and duration. Labels must exclude `jti`, tenant identifiers, and other high-cardinality values. - Replay-cache outage behavior: - Player-facing environments (`/ws/game/**` in `enforce` mode): fail closed with HTTP `403` and `CONNECT_REPLAY_PROTECTION_UNAVAILABLE` when replay protection is unavailable. diff --git a/design/architecture/system-architecture-redis-ops-access.md b/design/architecture/system-architecture-redis-ops-access.md index fd31b6335d..318d61b0ed 100644 --- a/design/architecture/system-architecture-redis-ops-access.md +++ b/design/architecture/system-architecture-redis-ops-access.md @@ -461,7 +461,7 @@ The complete checklist and the applicable recovery release gates are mandatory f | Ledger convergence | No real tick-ledger row is created, advanced, or terminalized by smoke. The smoke check verifies that the real ledger is unchanged; `APPLIED`, `ABANDONED`, or other terminal outcomes from a synthetic durable row are not available until the separate isolation mechanism is decided. | | Cleanup | Any temporary probe lease or lock is released, no smoke-created `pending` state remains, and the sampled region is not considered in-flight. No durable batch or ledger cleanup is used as a substitute for isolation. | | Durable advancement | PostgreSQL `lastCommittedTickId`, the real tick ledger, and the real Redis tick metadata remain at their pre-smoke recovery values; real `tickId=0` is neither consumed nor authorized. | -| Replay-domain readiness | When the workflow affects the shared replay domain, `replayAdmissionFence` is advanced, the lifetime-plus-skew quarantine is observed, and one fresh invocation of the canonical replay-consume script runs on the same pinned Redis connection using the target tagged `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `jti`, and `deny:jti` keys. The invocation must return `1` and create a disposable replay marker, followed by one same-connection `WAITAOF` local/replica durability acknowledgement meeting configured thresholds. A `0` or `-1` result is non-mutating and cannot supply a second write acknowledgement; any cleanup is a separate guarded cleanup write/readback and is not part of `DURABLE_REPLAY_CONSUME_ACK`. Only after that acknowledgement may the probe yield `DURABLE_REPLAY_CONSUME_ACK` before the operation reaches `AWAITING_RESUME`. This post-reset replay revalidation and durable consume proof are separate from `post_reset_replacement_verification/v1` and Account projection evidence. Select and report implementation and runtime proof using [Validation and Runtime Proof](../developer-workflows/validation-and-runtime-proof.md); the current untagged replay marker is migration-only drift and not target proof. Timeout, malformed, below-threshold, or uncertain results fail closed. | +| Replay-domain readiness | When the workflow affects the shared replay domain, trusted recovery calls Gateway's typed readiness-probe operation through the existing authenticated owning-service maintenance API boundary. The operation must return `DURABLE_REPLAY_CONSUME_ACK` before recovery reaches `AWAITING_RESUME`; Gateway's ownership, fence binding, consume, and durability contract is defined in [Gateway replay readiness](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake). This is target-only and currently unimplemented, so the checklist is not yet executable for this gate. Its result is distinct from `post_reset_replacement_verification/v1` and Account projection evidence, and does not itself enable normal player admission. | | Scope sampling | For tenant- or cluster-scoped resets, the smoke check samples at least one representative region per affected executor/shard group rather than only one global region. | The high-level recovery workflow must compose these phases without inventing alternate write paths or omitting required steps such as command-record convergence. diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index 15d7716b3a..fca3f6dfef 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -160,7 +160,7 @@ Legacy inventory/readback is permitted only as a bounded, read-only evidence ope - `current_tick_state` – the Redis-side execution state for `current_tick_id`. Allowed values are: - `STAGED` – Redis `pending`/queue state exists for this tick and hot-path scripts may continue to add idempotent entries for the same tick. - `RESOLVING` – durable domain/application work for this tick is in progress or being reconciled; no newer tick may be staged yet. - - `APPLIED` – every required participant in this tick's complete expected participant-projection set for the exact current `(region_epoch, tickId)` has explicit durable terminal evidence: its participant outcome is `APPLIED` or `ABANDONED` in the PostgreSQL-backed ledger or an equivalent durable terminal record, and the existing evidence policy permits the tick to be terminal. The fenced recovery baseline uses `current_tick_id = -1` with `APPLIED` as its terminal no-prior-tick marker before the first tick is staged. An inconclusive participant belonging to this current-epoch tick keeps this tick non-terminal and reconciliation-required. An unresolved old-epoch participant is outside this current-epoch participant set; it remains non-terminal under its original mutation identity and can still block reset-scope convergence or reopening. The mere presence of a reconciliation-backlog item is not evidence of a terminal outcome. Handler-level replay/no-op results are recorded separately as `replay_ok` attempt outcomes and do not satisfy this requirement by themselves. + - `APPLIED` – every eligible ledger row in this tick's complete expected participant-projection set for the exact current `(region_epoch, tickId)` has explicit durable terminal evidence: its participant outcome is `APPLIED` or `ABANDONED` in the PostgreSQL-backed ledger or an equivalent durable terminal record, and the existing evidence policy permits the tick to be terminal. Required-versus-optional classification affects command-result aggregation, not tick commit. The fenced recovery baseline uses `current_tick_id = -1` with `APPLIED` as its terminal no-prior-tick marker before the first tick is staged. An inconclusive participant belonging to this current-epoch tick keeps this tick non-terminal and reconciliation-required. An unresolved old-epoch participant is outside this current-epoch participant set; it remains non-terminal under its original mutation identity and can still block reset-scope convergence or reopening. The mere presence of a reconciliation-backlog item is not evidence of a terminal outcome. Handler-level replay/no-op results are recorded separately as `replay_ok` attempt outcomes and do not satisfy this requirement by themselves. - `ABANDONED` – the tick was intentionally terminated for the current epoch only after the owner/fenced recovery decision and evidence policy permit that terminal state (for example due to reset/recovery); no more work for that `(region_epoch, tickId)` may be staged through hot-path scripts. Reset scope alone does not authorize bulk terminalization. - `current_tick_terminal_at_ms` – absent/NULL while `current_tick_state` is `STAGED` or `RESOLVING`; set exactly once when the current tick first terminalizes as `APPLIED` or `ABANDONED`, and cleared/absent again when a newer tick is staged. Exact retries of that same terminal transition preserve the stored value, while a conflicting caller value is a non-mutating idempotency conflict. It is used for observability and bounded cleanup only, never for correctness decisions inside Lua. - Illustrative Redis hash contents: @@ -187,7 +187,7 @@ Legacy inventory/readback is permitted only as a bounded, read-only evidence ope - The first script or caller that hands staged effects to durable domain/application processing flips the state to `RESOLVING`. - Replays for the same tick must treat `STAGED` and `RESOLVING` as the same logical in-flight tick and may only add idempotent effect entries for that same `current_tick_id`. - `RESOLVING -> APPLIED`: - - Only after the durable tick ledger or equivalent durable terminal records for `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, region_epoch, tickId)` contain explicit `APPLIED` or `ABANDONED` evidence for every required participant in that exact current-tick participant set and the existing evidence policy permits terminalization. An inconclusive participant in that current-epoch set keeps this tick non-terminal. An inconclusive old-epoch participant is not silently included in the current-tick set: it remains non-terminal under its original mutation identity and follows the old-epoch reconciliation and reopen gates. A reconciliation-backlog item may identify work still needing reconciliation, but its presence alone cannot establish `APPLIED`; replay/no-op is a handler attempt outcome, recorded as `replay_ok`, not a ledger status. + - Only after the durable tick ledger or equivalent durable terminal records for `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, region_epoch, tickId)` contain explicit `APPLIED` or `ABANDONED` evidence for every eligible ledger row in that exact current-tick participant set and the existing evidence policy permits terminalization. Required-versus-optional classification affects command-result aggregation, not tick commit. An inconclusive participant in that current-epoch set keeps this tick non-terminal. An inconclusive old-epoch participant is not silently included in the current-tick set: it remains non-terminal under its original mutation identity and follows the old-epoch reconciliation and reopen gates. A reconciliation-backlog item may identify work still needing reconciliation, but its presence alone cannot establish `APPLIED`; replay/no-op is a handler attempt outcome, recorded as `replay_ok`, not a ledger status. - `RESOLVING -> ABANDONED`: - Only after the control plane or recovery tooling has made an explicit, evidence-qualified terminal decision to abandon the tick for the current epoch; reset scope alone is insufficient. - `APPLIED` or `ABANDONED` for tick `T`: @@ -204,7 +204,7 @@ Legacy inventory/readback is permitted only as a bounded, read-only evidence ope - Obtain their authoritative baseline for `(region_epoch, tickId)` from PostgreSQL RegionStatus/tick effect ledger and heartbeats, not from `current_tick_id`. - On a normal cold start with empty Coordination Redis and no active recovery, the next winning tick executor initializes `tick:{tenantRegionTag}:meta` during hot-path staging from PostgreSQL `RegionStatus` only when `requestedTickId` is the durable first-eligible tick, the caller explicitly proves that the exact environment and deployment are a documented non-reset profile, and the caller presents durable proof that all prior batches, effects, and commands are evidence-qualified terminal or that no unresolved work exists; without any of those guards or that proof, the region remains fenced. Schedulers and operators do not treat missing `meta` as a manual pre‑seeding task. While reset recovery is active, missing metadata keeps the scope fenced and hot-path staging must not create or recreate it until the canonical recovery release in [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md). - During reset recovery, the reset owner first establishes the durable new epoch, then initializes and verifies `tick:{tenantRegionTag}:meta` from that same authoritative baseline while the scope remains fenced. Only after that readback and the owner-defined recovery gates complete may the scope be released. The reset lifecycle and release prerequisites remain canonical in [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#canonical-reset-sequence-boundary); this hub records only the local metadata and stale-key consequences. - - Treat Redis `pending` contents as an implementation detail of the hot path, not as proof of durable convergence. The durable proof that a tick is safe to move past is explicit terminal `APPLIED` or `ABANDONED` evidence for every required participant in that tick's complete expected current-epoch participant set in the PostgreSQL ledger or equivalent durable terminal records; reconciliation-backlog presence and `replay_ok` attempt outcomes are insufficient by themselves. An inconclusive old-epoch row remains non-terminal under its original mutation `EffectId`, with any enclosing root retained as lineage; it cannot mutate current `tick:{tenantRegionTag}:meta` or block an otherwise evidence-permitted current-epoch terminalization, though it may still block unsafe next-tick progression, reset-scope convergence, or reopening. A terminal outcome for older or historical work remains in the durable ledger/reconciliation records under its original epoch and mutation effect identity; it must never overwrite or regress the current `tick:{tenantRegionTag}:meta`. Tick metadata updates remain limited to the current epoch's scheduler timeline; only a terminal outcome for that timeline may set `APPLIED` or `ABANDONED`. + - Treat Redis `pending` contents as an implementation detail of the hot path, not as proof of durable convergence. The durable proof that a tick is safe to move past is explicit terminal `APPLIED` or `ABANDONED` evidence for every eligible ledger row in that tick's complete expected current-epoch participant set in the PostgreSQL ledger or equivalent durable terminal records; required-versus-optional classification affects command-result aggregation, not tick commit. Reconciliation-backlog presence and `replay_ok` attempt outcomes are insufficient by themselves. An inconclusive old-epoch row remains non-terminal under its original mutation `EffectId`, with any enclosing root retained as lineage; it cannot mutate current `tick:{tenantRegionTag}:meta` or block an otherwise evidence-permitted current-epoch terminalization, though it may still block unsafe next-tick progression, reset-scope convergence, or reopening. A terminal outcome for older or historical work remains in the durable ledger/reconciliation records under its original epoch and mutation effect identity; it must never overwrite or regress the current `tick:{tenantRegionTag}:meta`. Tick metadata updates remain limited to the current epoch's scheduler timeline; only a terminal outcome for that timeline may set `APPLIED` or `ABANDONED`. - Recovery after coordination loss or reset does **not** reconstruct old ticks by silently restaging them through normal hot-path scripts. Recovery completes or abandons older work from durable manifests, ledger rows, and reconciliation backlog state only where the evidence policy permits; those historical terminal outcomes remain durable reconciliation state and do not update the current Redis tick metadata. Inconclusive old-epoch work remains non-terminal reconciliation work under its original mutation `EffectId`, with any enclosing root retained as lineage; it may prevent newer ticks from staging when that progression is unsafe, but it is not a reason to mutate or regress the current metadata or to withhold an otherwise permitted current-epoch terminalization. - Redis-local split-brain and reset consequences: - `tick-executor-lease:{tenantRegionTag}` stores only the opaque lease token; `region_epoch` is read from the separate `tick:{tenantRegionTag}:meta` view and/or the durable reset contract. Region lease and coordination Lua receives both values separately, compares them before mutation, and follows the canonical result mapping in [Redis Lua Patterns](./system-architecture-redis-lua-patterns.md#canonical-region-lease-and-tick-staging-result-mapping). @@ -656,7 +656,7 @@ If a proposed coordination pattern cannot satisfy this checklist, it should be t ### Coordination Key Examples -This table lists representative coordination keys and their responsibilities. Full semantics live in service‑specific docs and Lua descriptors, but these examples provide a quick mental model. Logical, API, and domain prose uses `regionEpoch`; the `tick:*:meta` hash and explicit storage/schema fields use `region_epoch`; serialized scheduler and event-offset payloads use `regionEpoch`. These spellings represent the same exact epoch, not alternate fields or timelines. Other serialized Redis payload examples use canonical camelCase; snake_case names denote explicit Redis hash/storage fields or SQL/domain column identifiers, not alternate payload schemas. +This table lists representative coordination keys and their responsibilities. Full semantics live in service‑specific docs and Lua descriptors, but these examples provide a quick mental model. Logical, API, and domain prose uses `regionEpoch`; the `tick:*:meta` hash and explicit storage/schema fields use `region_epoch`; serialized scheduler payloads use `regionEpoch`, while the tick-event offset record uses `region_epoch` as defined in [Tick System](./system-architecture-ticks.md#tick-commit-definition-heartbeat-watermark). These spellings represent the same exact epoch, not alternate fields or timelines. Other serialized Redis payload examples use canonical camelCase; the owner-defined offset field and explicit Redis hash/storage or SQL/domain fields retain their stated snake_case spellings, not alternate payload schemas. | Redis Key | Description | | --- | --- | @@ -677,7 +677,7 @@ This table lists representative coordination keys and their responsibilities. Fu | `remote:{tenantInstanceTag}:` | Best‑effort, TTL-bounded hint marker scoped to the complete `` identity for cross‑region follow‑ups (durable follow‑ups live in PostgreSQL). Default `remote_hint_ttl_ms = 60_000`; expiry/missing keys affect latency only. Tenant/cluster reset tooling resolves game instances from the durable scope inventory and scans one `remote:{tenantInstanceTag}:*` pattern per instance; no tenant-only remote key family exists. | | `route:{tenantRegionTag}:gamesession` | Reserved for a potential future gameplay routing view for ` → shardTarget`. Per ADR 0007, lease-aware edge admission and a client-visible shard handoff signal are not part of the current edge contract; do not implement Gateway consumption of this mapping without a dedicated sharding/routing design update. | | `tick-events:{tenantRegionTag}` | **Target-only, currently unavailable.** Best‑effort per-region tick event stream; the Game Session producer is not currently implemented/proven. Streams are retention-capped (default `tick_events_maxlen = 2048` per region); once implemented, consumers treat trimmed history as normal truncation and bootstrap from committed heartbeats/RegionStatus. | -| `tick-events-offset:{tenantRegionTag}:{consumerId}` | **Target-only, currently unavailable.** Per-consumer offset (typically Redis Stream entry ID), owned by the registered Automation consumer path. Each serialized value must include `{tenantId, gameInstanceId, regionId, consumerId, regionEpoch, latestTickId, streamOffset}`; consumers compare `regionEpoch` with the current control-plane epoch and discard that value before reuse on mismatch. Explicit hash/storage fields continue to use `region_epoch`. | +| `tick-events-offset:{tenantRegionTag}:{consumerId}` | **Target-only, currently unavailable.** Per-consumer offset (typically Redis Stream entry ID), owned by the registered Automation consumer path. Each serialized value must include `{tenantId, gameInstanceId, regionId, consumerId, region_epoch, latestTickId, streamOffset}`; consumers compare its stored `region_epoch` with the current control-plane `regionEpoch` and discard that value before reuse on mismatch. The producer and reader remain unimplemented; this row defines no current wire implementation. | | `tick-events-lease:{tenantRegionTag}` | **Target-only, currently unavailable.** Best-effort lease to avoid duplicate tick-event consumption work by registered observers. Once implemented, it is safe to drop and consumers reacquire after restarts/resets. | | `automation:timer:{tenantRegionTag}` | **Target-only, once implemented.** Reserved for the region-scoped Automation & Scripting timer index for `onInterval` and timer coordination. Stored entries must remain instance-aware in payload and durable identity (`gameInstanceId`, and plugin identifiers when applicable) even though the Redis key is region-scoped for slotting and reset targeting. No current key or reset operation is defined for this unimplemented target projection. | | `script-scheduler:{tenantRegionTag}:lastTickId` | **Target-only, once implemented.** Reserved for the Automation & Scripting derived discovery hint for “every N ticks” triggers. Its value will contain `{regionEpoch, latestTickId}` and be rejected/rebuilt when the stored epoch differs from the authoritative epoch. It will not store or own `streamOffset`; `tick-events-offset:{tenantRegionTag}:{consumerId}` is the sole event-stream offset record for each consumer. Durable automation schedules, quotas, and trigger-instance de-duplication live in PostgreSQL; this unimplemented key is not the source of truth for which scripts should eventually run or whether a due trigger was already emitted. No current key or reset operation is defined. | diff --git a/design/architecture/system-architecture-temporal-workflows.md b/design/architecture/system-architecture-temporal-workflows.md index b2c6b701d7..2590cff8cf 100644 --- a/design/architecture/system-architecture-temporal-workflows.md +++ b/design/architecture/system-architecture-temporal-workflows.md @@ -80,12 +80,12 @@ The current `businessStepKey` is an incomplete implementation encoding, not the Guidance: - `workflowFamily` is a stable design-level family such as `world-lifecycle` or `script-patch-readiness`. -- `scopeKey` is the narrow workflow scope that matters operationally, such as `world-instance`, `version`, or `game-instance`. -- `businessKey` is the stable caller-visible request identity or domain identity that makes retries idempotent. +- `scopeKey` is the narrow workflow scope that matters operationally, such as `world-instance`, `version`, or `game-instance`; for World lifecycle it is `game-instance`. +- `businessKey` is the stable caller-visible request identity or domain identity that makes retries idempotent. For World lifecycle it is `gameInstanceId`, a domain identity scoped by `tenantId` and `scopeKey`, not necessarily a globally unique token. Current adopter examples: -- `world-lifecycle` uses stable world-instance identity for its workflow business key. +- `world-lifecycle` uses `gameInstanceId` as its business key within the `tenantId` and `game-instance` scope. - full Game Design publish uses the caller-supplied `publish_request_id` from `PublishVersionRequest`, so retries converge on the same caller-visible durable workflow instead of minting a fresh internal UUID. - script-patch readiness uses the stable patch/readiness domain tuple documented in Automation Scripting. diff --git a/design/architecture/system-architecture-tick-incident-runbook.md b/design/architecture/system-architecture-tick-incident-runbook.md index 61a3e7ad7d..c83f88d0c8 100644 --- a/design/architecture/system-architecture-tick-incident-runbook.md +++ b/design/architecture/system-architecture-tick-incident-runbook.md @@ -326,7 +326,7 @@ Normal replay and re-enqueue in this section apply only to effects from the curr - For “applied but not marked” rows: - Do not update ledger rows directly to `APPLIED` from ad hoc SQL, a generic admin endpoint, or a one-off script. - Select the verifier/reconcile branch from the deployment mode; do not require target-state fields from the current-live schema or weaken the target-state gate: - - **Maintenance admission applies to both branches:** Before either verifier CAS may mutate a ledger row, validate the exact ADR 0085 external maintenance handoff, durably persist it, and pass it unchanged with the reconciliation evidence. Owner, epoch, executor, manifest, or participant proof does not replace this external admission. If the handoff is missing or unproved, make no mutation and use the existing fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) and escalate. See [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#coordination-reset-model) and [ADR 0085](./decisions/adr-0085-evidence-gated-coordination-replay-and-fenced-reset.md). + - **Maintenance admission applies to both branches:** Before a maintenance verifier CAS may mutate a ledger row, validate the exact ADR 0085 external maintenance handoff, durably persist it, and pass it unchanged with the reconciliation evidence. An owner may omit that maintenance handoff only for a specifically classified non-conflicting routine replay with durably recorded classification/evidence and applicable fence, epoch, and scope proof, as allowed by [Tick Failures & Operations](./system-architecture-tick-failures-and-operations.md); never infer this exemption from owner, epoch, executor, manifest, or participant proof alone. If neither the exact handoff nor the owner-recorded routine-replay evidence is complete, make no mutation and use the existing fail-closed [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback) and escalate. See [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#coordination-reset-model) and [ADR 0085](./decisions/adr-0085-evidence-gated-coordination-replay-and-fenced-reset.md). - **Current-live:** Run the service-owned verifier for the exact current-live ledger projection and its persisted mutation `EffectId` (retaining any enclosing root as lineage), including `effectKey` and target aggregate identity, within the narrower `` scope. Because `playableStateNamespaceId` is not persisted at this current-live boundary, this branch cannot establish namespace-complete S1/S2 binding and must not infer the namespace from `gameInstanceId`. Read `GetRuntimeOwnershipStatus` (the current instance-scoped ownership boundary) and require the current `regionEpoch` and opaque `executorFence` to match the batch/ledger ownership snapshot. Verify that the current selected-work manifest and its `manifest_digest` match the durable source and ledger projections and the expected participant evidence. This branch may be processed without `sealed_execution_context_digest` or `sealed_execution_context_ref`, which are not present at the current-live boundary. The service-owned verifier must atomically CAS the current owner/epoch/fence, require complete manifest and participant-evidence set equality, transition the matching `SCHEDULED` row(s) to `APPLIED`, and record replay-verification evidence (including the evidence digest/reference and `replay_ok` audit) in one durable transaction. Missing, extra, or conflicting evidence, or any owner/epoch/fence mismatch, affects zero rows and fails closed with no ledger mutation. The owning domain must prove the effect is already reflected in authoritative state or in its durable participant guard; a replay no-op is not a third ledger status. - **Target-state:** Read the current region authority from `RegionStatus`/`GetRegionTickStatus` and require exact current `regionEpoch`/`executorFence` equality. For S1/S2, require the complete namespace-bound projection `` and exact-compare `playableStateNamespaceId` (as well as every other immutable scope, identity, timeline, and target field) across the ledger, manifest, sealed context, and participant set. Require exactly one immutable sealed execution-context binding: either `sealed_execution_context_digest` or `sealed_execution_context_ref` resolved to its immutable digest, with the referenced context and digest matching the batch and replay request. The complete participant-projection set, sealed context, current authority/fence, and every `SCHEDULED` ledger transition must pass the same evidence-qualified CAS; a missing, stale, mismatched, incomplete, extra, or conflicting value affects zero rows and fails closed with no ledger mutation. - In either branch, replay no-op is an attempt outcome, not a third ledger status, and the verifier must not reconcile a mutation under a different persisted `EffectId` across region epochs; any enclosing `rootEffectId` remains lineage and reconciliation context rather than the effect-level identity. diff --git a/design/architecture/system-architecture-transactions.md b/design/architecture/system-architecture-transactions.md index bfc1cd8509..c772414d47 100644 --- a/design/architecture/system-architecture-transactions.md +++ b/design/architecture/system-architecture-transactions.md @@ -86,7 +86,7 @@ Tick execution is replayable: retries, failover, and Redis AOF replay can cause - **Target-state identity and guard contract:** Participant-guard durability follows the owning runtime-family classification: S1/S2 owner families use `(tenantId, playableStateNamespaceId)` plus the owning mutation identity (`EffectId`, typed operation, and target aggregate), while only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)` as its durable partition. For S1/S2, the active `gameInstanceId` remains separately exact-validated authorization/fence evidence and does not create a second guard identity; unknown or unclassified families are rejected before any participant-guard allocation or admission and are never inferred to be S3. A generated child mutation uses its persisted child `EffectId` and retains the enclosing root as lineage and reconciliation context. The guard row binds the immutable request digest and stores mutable outcome/evidence state under CAS. Matching replay returns the stored result, while a tenant, namespace, owning effect, operation, target, scope, active-instance evidence, or digest mismatch fails closed. Work explicitly outside playable-state scope must use an accepted owner-specific idempotency/partition contract; it cannot omit namespace/scope and proceed under this gameplay participant-guard contract. Command-root and generated-child allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). - **Post-abandon re-drive:** A fresh mutation identity is not an ordinary retry or replay. After conclusive `ABANDONED` evidence and source terminalization, any re-drive follows its source owner's admission and identity contract and remains linked to the prior effect lineage. Ordinary retries and replay preserve the original mutation identity. Command-root re-drive allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). -- **Command/effect boundary:** An `ACCEPTED_VOLATILE` command lost before durable staging may terminalize only at command scope as `executionOutcome = LOST_BEFORE_STAGING` and `gameplayResult = NOT_APPLIED` while its ingress status is `RECEIVED` or `ENQUEUED` and no `tickBatchId` survives; an `ACCEPTED_DURABLE` command follows its feature-specific durable replay/re-drive contract instead. No effect ledger row is invented for either command unless an effect was durably claimed or staged. A durable pre-staging source/effect claim establishes recoverability but does not itself make physical execution at least once; only a staged or otherwise dispatchable effect enters physical execution, after which its immutable identity/digest guard permits at most one logical mutation. Staged effects terminalize as `APPLIED` or `ABANDONED` only when authoritative evidence permits; inconclusive work remains `SCHEDULED`/reconciliation-required, explicitly including timeout, retry exhaustion, or missing coordination. `REPLAY_NOOP` is an `APPLIED` reason, never a third status. Command `SUCCESS`, `PARTIAL`, `FAILED`, `TIMEOUT`, and `NOT_APPLIED` remain derived player-result vocabulary under ADR 0053. See [ADR 0069](./decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md). +- **Command/effect boundary:** An `ACCEPTED_VOLATILE` command lost before durable staging may terminalize only at command scope as `executionOutcome = LOST_BEFORE_STAGING` and `gameplayResult = NOT_APPLIED` while its ingress status is `RECEIVED` or `ENQUEUED` and no `tickBatchId` survives, and authoritative evidence proves no committed batch, effect materialization, or application; ingress status or a missing batch ID alone is insufficient. Otherwise the command remains unresolved for evidence-qualified reconciliation. An `ACCEPTED_DURABLE` command follows its feature-specific durable replay/re-drive contract instead. No effect ledger row is invented for either command unless an effect was durably claimed or staged. A durable pre-staging source/effect claim establishes recoverability but does not itself make physical execution at least once; only a staged or otherwise dispatchable effect enters physical execution, after which its immutable identity/digest guard permits at most one logical mutation. Staged effects terminalize as `APPLIED` or `ABANDONED` only when authoritative evidence permits; inconclusive work remains `SCHEDULED`/reconciliation-required, explicitly including timeout, retry exhaustion, or missing coordination. `REPLAY_NOOP` is an `APPLIED` reason, never a third status. Command `SUCCESS`, `PARTIAL`, `FAILED`, `TIMEOUT`, and `NOT_APPLIED` remain derived player-result vocabulary under ADR 0053. See [ADR 0069](./decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md). - **Single propagation contract:** The coordinator sends the mutation's persisted `EffectId`, typed operation, target, immutable request digest, conditional owner-family partition, separately validated active-instance authorization/fence evidence, and required-participant context; generated children also carry their enclosing root/parent lineage binding. Participants validate the complete accepted effect binding and atomically commit their guard with effect-visible rows before acknowledging. They do not generate a fresh identity or bind a guard to mutable payload. Command-root `planOrdinal` propagation remains pending in ADR 0183. - **Current live implementation gap:** The live Game Session proto does not yet carry `commandOrdinal` or the complete applicable Command-Handoff Identity for this handoff. Plan-root manifest/allocation behavior remains proposed in ADR 0183 and is not a current implementation gap against accepted target state. `TickStagingService` derives the live `effectKey` from `commandId`; it retains a deterministic command-text-plus-slot fallback helper for selection metadata, but durable tick batching rejects any queued entry without a `commandId` before staging or effect persistence. That fallback is therefore not a live staging, replay, or recovery identity. - **Effect-key boundary:** `effectKey` remains a source-specific descriptor, ordering, or correlation field under its owning contract; it is not a substitute for persisted mutation identity. Existing source-specific validation or serialization may remain where already defined. Command-root allocation details, including the command row key and manifest binding, remain pending in ADR 0183. diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index d8766820ad..2098678881 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -1958,9 +1958,10 @@ require_contains( "design/architecture/system-architecture-tick-incident-runbook.md", [ "**Maintenance admission applies to both branches:**", - "Before either verifier CAS may mutate a ledger row, validate the exact ADR 0085 external maintenance handoff, durably persist it, and pass it unchanged with the reconciliation evidence.", - "Owner, epoch, executor, manifest, or participant proof does not replace this external admission.", - "If the handoff is missing or unproved, make no mutation and use the existing fail-closed [Current Operator Fallback]", + "Before a maintenance verifier CAS may mutate a ledger row, validate the exact ADR 0085 external maintenance handoff, durably persist it, and pass it unchanged with the reconciliation evidence.", + "An owner may omit that maintenance handoff only for a specifically classified non-conflicting routine replay with durably recorded classification/evidence and applicable fence, epoch, and scope proof", + "never infer this exemption from owner, epoch, executor, manifest, or participant proof alone.", + "If neither the exact handoff nor the owner-recorded routine-replay evidence is complete, make no mutation and use the existing fail-closed [Current Operator Fallback]", "this incident remediation is maintenance, not ordinary crash replay.", "Before its first mutation, validate the exact ADR 0085 external maintenance handoff, durably persist it, and pass it unchanged", "Missing or unproved handoff means no mutation: use the fail-closed [Current Operator Fallback]", @@ -2497,6 +2498,79 @@ require_absent( ["stale presented scope with unchanged authority may reuse the existing identity"], ) +require_contains( + "design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md", + [ + "a command root's enclosing root is its own persisted `EffectId`", + "its parent is explicitly absent (`null`)", + "retry and replay reuse the same scalar and binding", + ], +) +require_contains( + "design/architecture/microservices/automation-scripting-service/sandbox-runtime-design.md", + [ + "source tenant/game-instance ownership (`tenantId`, `gameInstanceId`) and `playableStateNamespaceId`/region identity", + "optional distinct target game-instance ownership and namespace/region identity", + "[normative Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state)", + ], +) +require_contains( + "design/architecture/microservices/world-management-service/world-creation-workflow.md", + [ + "canonical Temporal workflow ID is `world-lifecycle::game-instance:`, stable per `(tenantId, gameInstanceId)`", + ], +) +require_contains( + "design/architecture/system-architecture-temporal-workflows.md", + [ + "for World lifecycle it is `game-instance`", + "For World lifecycle it is `gameInstanceId`, a domain identity scoped by `tenantId` and `scopeKey`, not necessarily a globally unique token", + "`world-lifecycle` uses `gameInstanceId` as its business key within the `tenantId` and `game-instance` scope", + ], +) +require_contains( + "design/architecture/system-architecture-tick-incident-runbook.md", + [ + "Before a maintenance verifier CAS may mutate a ledger row, validate the exact ADR 0085 external maintenance handoff", + "An owner may omit that maintenance handoff only for a specifically classified non-conflicting routine replay with durably recorded classification/evidence and applicable fence, epoch, and scope proof", + "never infer this exemption from owner, epoch, executor, manifest, or participant proof alone", + ], +) +require_contains( + "design/architecture/system-architecture-transactions.md", + [ + "authoritative evidence proves no committed batch, effect materialization, or application", + "ingress status or a missing batch ID alone is insufficient", + "Otherwise the command remains unresolved for evidence-qualified reconciliation", + ], +) +require_contains( + "design/architecture/system-architecture-redis.md", + [ + "every eligible ledger row in that tick's complete expected current-epoch participant set", + "required-versus-optional classification affects command-result aggregation, not tick commit", + "serialized scheduler payloads use `regionEpoch`, while the tick-event offset record uses `region_epoch`", + "Each serialized value must include `{tenantId, gameInstanceId, regionId, consumerId, region_epoch, latestTickId, streamOffset}`", + "The producer and reader remain unimplemented", + ], +) +require_contains( + "design/architecture/system-architecture-gateway.md", + [ + "logical typed Gateway-owned readiness-probe operation", + "one pinned Coordination Redis connection", + "The operation and its producer/consumer proof are currently unimplemented", + ], +) +require_contains( + "design/architecture/system-architecture-redis-ops-access.md", + [ + "Gateway's typed readiness-probe operation", + "[Gateway replay readiness](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake)", + "currently unimplemented, so the checklist is not yet executable for this gate", + ], +) + print("architecture doc contracts passed") PY From fb5bc2e88f2f39016c2397de6b0ecdfc253776c2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 20:00:36 +1300 Subject: [PATCH 61/68] docs: preserve accepted persisted child identity mapping --- design/architecture/decisions/README.md | 4 +-- ...-authority-with-causal-read-composition.md | 2 +- ...ount-bounds-for-generated-effect-chains.md | 2 +- dev-tools/tests/architecture-doc-contracts.sh | 33 +++++++++++++++++++ 4 files changed, 37 insertions(+), 4 deletions(-) diff --git a/design/architecture/decisions/README.md b/design/architecture/decisions/README.md index 9311640191..6d46df38b0 100644 --- a/design/architecture/decisions/README.md +++ b/design/architecture/decisions/README.md @@ -171,7 +171,7 @@ Validation precedence is fixed: first parse every checked queue row and validate | [ADR 0072](./adr-0072-class-specific-timer-durability-and-recovery.md) | Accepted | `AS-1.4` | `GR-1.2`, `GR-2.3`, `AS-1.5`, `SF-1.4` | Class-specific timer durability and recovery | | [ADR 0073](./adr-0073-evidence-calibrated-tick-budgets-and-lock-ttls.md) | Accepted | `SF-1.4` | `GR-1.2`, `GR-1.3`, `PO-4.2`, `AR-2.3` | Evidence-calibrated tick budgets and lock TTLs | | [ADR 0074](./adr-0074-one-entity-lock-per-redis-script.md) | Accepted | `GR-1.3` | `SF-2.2`, `GR-4.1`, `PO-4.4` | One entity lock per Redis script | -| [ADR 0075](./adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md) | Accepted | `GR-4.1` | `GR-1.2`, `AS-1.2`, `PO-4.2` | Depth, cost, and count bounds for generated effect chains | +| [ADR 0075](./adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md) | Accepted | `GR-4.1` | `GR-1.2`, `AS-1.2`, `PO-4.2` | Depth, cost, and count bounds with replay-stable owner-defined child identity and lineage | | [ADR 0076](./adr-0076-failure-class-specific-durable-tick-retries.md) | Accepted | `GR-1.2` | `PO-2.4`, `PO-4.2`, `SF-2.3` | Failure-class-specific durable tick retries | | [ADR 0077](./adr-0077-durable-global-effect-fanout-and-lightweight-idle-ticks.md) | Accepted | `GR-1.2` | `GR-2.1`, `AS-1.4`, `SF-1.4`, `PO-4.2` | Durable global-effect fan-out and lightweight idle ticks | | [ADR 0078](./adr-0078-digest-bound-workflow-and-step-retry-identities.md) | Accepted | `SF-2.3` | `SF-2.4`, `SF-1.2` | Digest-bound workflow and step retry identities | @@ -277,7 +277,7 @@ Validation precedence is fixed: first parse every checked queue row and validate | [ADR 0180](./adr-0180-account-owned-hosted-terms-acceptance-gate.md) | Accepted | `AA-1.3` | `AA-1.5`, `AR-1.1`, `AR-1.4`, `AR-1.5`, `EA-3.2`, `PO-1.3`, `SF-2.3` | Account-owned hosted-terms catalog, acceptance evidence, and official-hosted creator mutation gate | | [ADR 0181](./adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md) | Accepted | `PO-1.3` | `AA-1.3`, `AA-1.4`, `AA-1.5`, `AR-1.1`, `AR-1.4`, `AR-1.5`, `EA-3.2`, `SF-2.3` | Changed hosted-terms decline, prior-terms continuity, lifecycle-reducing access, and finite transition | | [ADR 0182](./adr-0182-separated-hosted-runtime-and-certificate-identity-lifecycles.md) | Accepted | `PO-3.2` | `PO-3.1`, `PO-4.4`, `SF-1.3`, `PO-1.1` | Separated hosted runtime and certificate-identity lifecycles | -| [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) | Proposed - Pending Human Review | `GR-1.2` | `GR-1.4`, `GR-4.1`, `AS-1.2`, `AS-1.4`, `SF-1.4`, `SF-2.3`, `PO-4.2` | Pending command-plan ordering, `planOrdinal`, command-root allocation, UUIDv7 scalar, canonical serialization, and generated-child/fan-out allocation design | +| [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) | Proposed - Pending Human Review | `GR-1.2` | `GR-1.4`, `GR-4.1`, `AS-1.2`, `AS-1.4`, `SF-1.4`, `SF-2.3`, `PO-4.2` | Pending command-plan ordering, `planOrdinal`, command-root allocation, UUIDv7 scalar, canonical serialization, and additional child/fan-out allocation mechanics | | [ADR 0184](./adr-0184-emergency-tcp-proxy-identity-withdrawal.md) | Accepted | `SF-1.3` | `PO-2.1`, `PO-2.2`, `PO-3.2`, `PO-4.4` | Emergency trust cutoff for a withdrawn TCP Proxy bridge identity | Capability identifiers are defined in the [FireMUD Product Capability Taxonomy](../../product/capability-taxonomy.md). diff --git a/design/architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md b/design/architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md index ff182107c3..4ea6d9ddfc 100644 --- a/design/architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md +++ b/design/architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md @@ -50,7 +50,7 @@ For a root mutation, Game Session assigns one stable root `EffectId` to the logi - Same identity plus the same request returns the prior durable result. - Same identity with a different operation, target, or request digest fails closed. -- Derived reactions use deterministic child effect identities rather than accidental reuse. Any future allocator or replay binding remains subject to the non-authoritative [ADR 0183 proposal](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). +- Derived reactions retain their owner-defined child ordinal and durably persist the complete owner-scope/root/parent/ordinal-to-child-`EffectId` mapping before enqueue/apply; retries and replay reuse that mapping. This accepted child-identity contract is owned by [ADR 0075](./adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). Pending [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) concerns additional command-plan ordering, command-root, scalar-format, and allocation mechanics; it does not gate or redefine the accepted child mapping. - Participant acknowledgement means the guard and effect-visible domain rows committed together. - Player success waits for all declared required participants under ADR 0053. diff --git a/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md b/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md index 8d91e9401e..bfd5fcbb3e 100644 --- a/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md +++ b/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md @@ -73,7 +73,7 @@ Alerting follows the impact class: ## Consequences - Runaway depth, broad fan-out, excessive aggregate cost, and repeated concentration on one target are all bounded. -- Deterministic lineage, ordinals, digests, and accounting make admission and suppression replay-stable. +- Persisted lineage, owner-defined ordinals, digests, and accounting make admission and suppression replay-stable. - Already committed gameplay remains authoritative when a later child is suppressed. - Required and optional classifications make player outcomes and alerts reflect actual gameplay impact. - Durable per-suppression evidence supports precise investigation while bounded metrics avoid cardinality growth. diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index 2098678881..32bb354075 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -2570,6 +2570,39 @@ require_contains( "currently unimplemented, so the checklist is not yet executable for this gate", ], ) +require_contains( + "design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md", + [ + "owner-defined child ordinal allocated and persisted by the owning contract for replay-stable reuse", + "Persisted lineage, owner-defined ordinals, digests, and accounting make admission and suppression replay-stable", + "owner-scope/root/parent/ordinal mapping to each child `EffectId` is one atomic durable admission record", + ], +) +require_contains( + "design/architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md", + [ + "Derived reactions retain their owner-defined child ordinal", + "complete owner-scope/root/parent/ordinal-to-child-`EffectId` mapping before enqueue/apply", + "This accepted child-identity contract is owned by [ADR 0075]", + "Pending [ADR 0183]", + "it does not gate or redefine the accepted child mapping", + ], +) +require_contains( + "design/architecture/decisions/README.md", + [ + "Depth, cost, and count bounds with replay-stable owner-defined child identity and lineage", + "Pending command-plan ordering, `planOrdinal`, command-root allocation, UUIDv7 scalar, canonical serialization, and additional child/fan-out allocation mechanics", + ], +) +require_absent( + "design/architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md", + ["Derived reactions use deterministic child effect identities"], +) +require_absent( + "design/architecture/decisions/README.md", + ["generated-child/fan-out allocation design"], +) print("architecture doc contracts passed") PY From 28df7b2301ee85cd22546448dca68fb833c2df84 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 20:16:53 +1300 Subject: [PATCH 62/68] docs: retain atomic replay marker and tracker owner boundaries --- .../runtime-and-data.md | 2 +- ...e-session-runtime-and-tick-coordination.md | 2 +- dev-tools/tests/architecture-doc-contracts.sh | 25 +++++++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) 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 1a11105866..ff61966c20 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -10,7 +10,7 @@ This document defines Entity Management’s runtime model, persistence ownership - 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. - 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 isolated marker transaction, followed by real PostgreSQL concurrent first-apply/replay proof. Until then replay readiness remains blocked. +- 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. - Character updates are also not currently optimistic CAS: `CharacterRepository` increments `version` but updates by row ID without the old-version and tenant predicates or an affected-row conflict check. Concurrent progression/last-login writes can therefore overwrite each other. The target requires tenant- and namespace-bound version CAS with stale-write failure and focused concurrent proof; the current `@Transactional` service methods do not establish that invariant. - Current `jOOQ + Flyway` adoption and focused persistence proof remain implementation work. - The current actor-condition expiry job uses Spring fixed-delay scheduling, with a 30-second default delay after the previous invocation completes, and invokes a global, unbounded delete for rows whose `expires_at` has elapsed, without tenant/namespace/instance predicates or a batch bound. Reads filter expired rows before evaluating state, so expired gameplay effects are not restored. The deletion targets only `actor_active_conditions`; it does not delete the separate `entity_mutation_effects` receipt that `ApplyActorCondition` checks before mutation. No concrete duplicate-application or S2-loss claim is made from this path. The target still requires explicit S1/S2 classification, a replay/restore horizon, dependent-reference/hold checks, a receipt-retention guarantee, a safe watermark, and typed target, request-digest, and concurrency proof under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md); expiry is not itself disposal eligibility. diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index cdb2fd0687..deabb15fca 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -148,7 +148,7 @@ The current `remote_followup` uniqueness index on `(tenant_id, target_region_id, The complete target contract is owned by the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md), [tick failure contract](../../architecture/system-architecture-tick-failures-and-operations.md#cross-region-follow-up-record-contract-required), [scripting contract](../../architecture/system-architecture-scripting-contracts.md#2-script-work-item-vs-tick-command-boundary), [ADR 0055](../../architecture/decisions/adr-0055-durable-cross-region-effects-with-static-live-topology.md), [ADR 0066](../../architecture/decisions/adr-0066-durable-asynchronous-cross-region-result-arbitration.md), [ADR 0071](../../architecture/decisions/adr-0071-durable-tick-commit-before-fenced-coordination-cleanup.md), and [ADR 0119](../../architecture/decisions/adr-0119-epoch-fenced-per-instance-plugin-activation.md). This tracker records only current implementation and proof status; target field, identity, outcome, scope, and reconciliation requirements remain in those canonical owners. -Origin reconciliation remains target-state and is not yet fully implemented or proved: the owner must reconcile durable results before timeout, require matching scope/epoch evidence, wait for target-command convergence, and preserve the original timeout or abandonment cause. The live result-inbox path has partial late-result handling, but exact serialized arbitration, immutable terminal/retry proof, and documented compensation ownership remain unproven. Current remote due/backlog gauges use durable owned-region truth; the remaining terminalization and reconciliation proof gaps are tracked by the linked owner contracts. +Origin reconciliation remains target-state and is not yet fully implemented or proved. The live result-inbox path has partial late-result handling, but serialized result-versus-timeout arbitration, immutable terminal/retry proof, and documented compensation ownership remain unimplemented or unproved. See the canonical owner contracts immediately above for target sequencing, terminal outcomes, and compensation; this tracker records only implementation/proof status. Current remote due/backlog gauges use durable owned-region truth. ### Operator Readback and Facade Boundaries diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index 32bb354075..a36e623f6a 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -2603,6 +2603,31 @@ require_absent( "design/architecture/decisions/README.md", ["generated-child/fan-out allocation design"], ) +require_contains( + "design/architecture/microservices/entity-management-service/runtime-and-data.md", + [ + "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", + "[Entity Management Operations implementation status](./operations.md#implementation-status)", + "Real PostgreSQL concurrent first-apply/replay proof remains unavailable", + ], +) +require_absent( + "design/architecture/microservices/entity-management-service/runtime-and-data.md", + ["a conflict-safe marker insert or isolated marker transaction"], +) +require_contains( + "design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md", + [ + "The live result-inbox path has partial late-result handling", + "serialized result-versus-timeout arbitration, immutable terminal/retry proof, and documented compensation ownership remain unimplemented or unproved", + "See the canonical owner contracts immediately above for target sequencing, terminal outcomes, and compensation", + ], +) +require_absent( + "design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md", + ["the owner must reconcile durable results before timeout, require matching scope/epoch evidence"], +) print("architecture doc contracts passed") PY From 0664db774d59e5f1f098cb9024b3196b01e910ea Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 20:39:06 +1300 Subject: [PATCH 63/68] docs: fence recovery and distinguish live incident capabilities --- ...ble-idempotent-operator-write-execution.md | 6 +-- .../game-session-service/runtime-and-data.md | 2 +- ...itecture-scripting-scheduler-and-timers.md | 6 ++- ...stem-architecture-tick-incident-runbook.md | 2 +- design/project-management/ai-observations.md | 6 +++ dev-tools/tests/architecture-doc-contracts.sh | 48 +++++++++++++++++++ 6 files changed, 64 insertions(+), 6 deletions(-) diff --git a/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md b/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md index 605eea768e..9339dceab2 100644 --- a/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md +++ b/design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md @@ -41,7 +41,7 @@ The canonical complete `postAuthorizationExecutionTuple` is the immutable tuple The pre-authorization recovery lookup carries the immutable typed `targetOwner` and its schema-bound presence/absence value as part of `preAuthorizationReservationTuple`; post-authorization owner execution carries it as part of the exact canonical complete `postAuthorizationExecutionTuple`. Any later rearm is a new explicit operator request with its own authorization tuple and reference, never a pre-authorization recovery lookup, and neither path can substitute current routing or lease ownership for that value. -The reservation-owner claim is itself a durable bounded lease. The record stores `reservationOwnerId`, `reservationClaimFence`, `reservationClaimExpiresAt`, and claim state. `CAS acquire` creates the `RESERVED` record and assigns one owner with a new monotonic claim fence; `CAS renew` may extend only that bounded claim when the exact owner and fence are still current and unexpired; `CAS completion` of authorization, forwarding, or a terminal no-mutation result requires the same owner and fence; and `CAS expiry` advances the claim fence and prevents the expired owner from authorizing, forwarding, or completing. A stale owner cannot issue or redeem an Account authorization reference, forward a mutation, or write any terminal result. After claim expiry, a recovery CAS may assign exactly one fresh, unexpired reservation/recovery claim to a fenced recovery owner of the exact authenticated Logging and Admin workload. That recovery owner may perform the read-only Account lookup for `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`; if it recovers the original issued response, it may complete the atomic enrichment to `ACCOUNT_AUTHORIZATION/AUTHORIZED` under that fresh claim. A recovery CAS may complete an expired `ACCOUNT_AUTHORIZATION/RESERVED` claim to `NOT_EXECUTED_BEFORE_AUTHORIZATION` only when durable evidence proves that no Account authorization or owner-forward call can still occur. If the Account call was dispatched or its outcome is ambiguous, the record remains `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` and is non-replayable until the original response or the independent no-authorization/no-forward proof is established. An active claim is never transferred while a call may still be in flight. +The reservation-owner claim is itself a durable bounded lease. The record stores `reservationOwnerId`, `reservationClaimFence`, `reservationClaimExpiresAt`, and claim state. `CAS acquire` creates the `RESERVED` record and assigns one owner with a new monotonic claim fence; `CAS renew` may extend only that bounded claim when the exact owner and fence are still current and unexpired; `CAS completion` of authorization, forwarding, or a terminal no-mutation result requires the same owner and fence; and `CAS expiry` advances the claim fence and prevents the expired owner from authorizing, forwarding, or completing. A stale owner cannot issue or redeem an Account authorization reference, forward a mutation, or write any terminal result. After claim expiry, a recovery CAS may assign exactly one fresh, unexpired reservation/recovery claim to a fenced recovery owner of the exact authenticated Logging and Admin workload. That recovery owner may perform the read-only Account lookup for `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING`; if it recovers the original issued response, it may complete the atomic enrichment to `ACCOUNT_AUTHORIZATION/AUTHORIZED` under that fresh claim. This CAS and enrichment preserve the original reservation claim fence as immutable tuple evidence; the fresh recovery claim/fence authorizes the transition but never replaces that stored fence. A recovery CAS may complete an expired `ACCOUNT_AUTHORIZATION/RESERVED` claim to `NOT_EXECUTED_BEFORE_AUTHORIZATION` only when durable evidence proves that no Account authorization or owner-forward call can still occur. If the Account call was dispatched or its outcome is ambiguous, the record remains `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` and is non-replayable until the original response or the independent no-authorization/no-forward proof is established. An active claim is never transferred while a call may still be in flight. The durable record has an explicit `phase` and `state`; `PENDING` is never persisted or returned without its phase. `phase=ACCOUNT_AUTHORIZATION` covers `RESERVED`, `AUTHORIZATION_PENDING`, `AUTHORIZED`, and `NOT_EXECUTED_BEFORE_AUTHORIZATION`; `phase=OWNER_EXECUTION` covers `OWNER_EXECUTION_PENDING`, `FENCE_REJECTED`, `COMMITTED`, `FAILED`, and `NOT_EXECUTED_AFTER_AUTHORIZATION`. Every acquire, renew, expiry, completion, rejection, recovery, lookup, and rearm CAS compares the expected phase and state together with the phase-appropriate tuple, attempt identity, owner identity, and applicable claim/fencing token. Pre-authorization operations compare `preAuthorizationReservationTuple`; the transition to `AUTHORIZED` atomically enriches that tuple into `postAuthorizationExecutionTuple`, and every later owner execution, result lookup, and reconciliation operation compares the post-authorization tuple. Any later rearm starts a new reservation and authorization tuple with a fresh reference. A phase mismatch is an idempotency conflict or stale-fence rejection as applicable; it is never treated as an interchangeable `PENDING` state. @@ -58,13 +58,13 @@ If the redemption outcome, owner acceptance, owner commit, business mutation, de ### Fenced Reference Handoff -The original opaque reference is never stored durably by Logging and Admin, the domain owner, or the owner-result record. Account remains the source-of-truth provider and retains the reference in its protected authority record. For an `ACCOUNT_AUTHORIZATION/AUTHORIZED` record produced by a fenced recovery owner, the authorized-to-owner transition must first durably enter `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`; only then may the current domain owner receive the original reference through one bounded handoff from the exact current Logging and Admin reservation owner for the initial owner execution. The request carries the unchanged canonical complete `postAuthorizationExecutionTuple`, including immutable typed `targetOwner`, Account-returned `authorizationReferenceFingerprint`, the action-family request identity, `reservationOwnerId`, current positive `reservationClaimFence`, the current domain `ownerId` and owner/gameplay fence, and a fresh high-entropy handoff identity. +The original opaque reference is never stored durably by Logging and Admin, the domain owner, or the owner-result record. Account remains the source-of-truth provider and retains the reference in its protected authority record. For an `ACCOUNT_AUTHORIZATION/AUTHORIZED` record produced by a fenced recovery owner, the authorized-to-owner transition must first durably enter `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`; only then may the current domain owner receive the original reference through one bounded handoff from the exact current Logging and Admin reservation owner for the initial owner execution. The request carries the unchanged canonical complete `postAuthorizationExecutionTuple`, including immutable typed `targetOwner`, Account-returned `authorizationReferenceFingerprint`, the action-family request identity, `reservationOwnerId`, and the original positive `reservationClaimFence` stored in that tuple, together with the current domain `ownerId` and owner/gameplay fence and a fresh high-entropy handoff identity. If an expired `AUTHORIZATION_PENDING` claim was recovered, its fresh reservation/recovery claim and fence are separate, independently validated execution authority for the recovery CAS and handoff; they do not replace or rewrite the original tuple fence. Exact tuple comparison and current owner/fence validation remain required before evaluation, dispatch, or reference delivery. Logging and Admin is the delivery provider, not a second authority: it must hold the exact unexpired reservation owner and claim fence. Only a separately fenced replacement owner of the exact authenticated Logging and Admin mTLS workload may call Account's read-only `RecoverOperatorAuthorizationReference` with `preAuthorizationReservationTuple/v1` and that fresh fence during pre-authorization recovery. The domain owner's `recoveryOwnerId` never calls `RecoverOperatorAuthorizationReference`; it receives the original opaque reference only through this post-authorization handoff after the owner-side claim is current and fenced. When the pre-authorization recovery owner receives the original issued response, it may atomically enrich the record to `ACCOUNT_AUTHORIZATION/AUTHORIZED` under the fresh claim and invoke this bounded handoff to the current domain owner. Account checks `issuanceKind`, immutable typed `targetOwner`, authenticated workload/actor binding, automation-policy identity, authority tuple, membership version, issuance fence, all existing immutable fields, and the reservation owner/fence before returning the original reference. Logging and Admin delivers that reference only over the exact allowlisted mTLS channel to the current domain owner in a bounded, non-durable envelope bound to the handoff identity, full tuple, reference fingerprint, reservation owner/fence, current owner/fence, and an expiry no later than the Account reference expiry. The raw reference is held only in protected in-flight memory and is zeroized after successful redemption, expiry, or failed delivery; no durable recovery copy is created. This handoff is only for the initial owner execution; a consumed reference and its durable redemption result cannot start another owner attempt. If that Logging and Admin reservation claim has expired on a terminal owner-execution result, that terminal result is not eligible for rearm. A recovery owner may retain and reconcile the historical result read-only, but it cannot transfer reservation ownership, recover or deliver the original reference, redeem it for execution, or allocate a successor owner attempt. This restriction does not apply to an expired `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` claim: a fenced recovery CAS may install a fresh valid claim, recover the original issued response, atomically enrich to `AUTHORIZED`, and use the bounded handoff/fresh redemption path for the initial owner execution. Repeating a terminal owner-execution business intent requires a new explicit operator request with a new action-family request identity, fresh Account authorization, and a new opaque reference; claim expiry never turns an old reference or terminal result into authorization for another actor and never creates a duplicate issuance. -The current domain owner authenticates the delivery provider, rechecks its own current owner/gameplay fence and the unchanged reservation claim fence, and redeems the exact reference with Account before allocating the initial owner attempt. Account redemption must still validate the exact caller workload, tuple, current authority, membership, applicable privilege, and issuance fence; successful redemption consumes the reference and binds the durable redemption result to that attempt. Handoff timeout, provider/owner fence loss, tuple or fingerprint mismatch, expired or revoked reference, Account `NOT_FOUND`, delivery failure, or redemption failure after the authorized-to-owner transition remains `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` until one of the two applicable terminal-proof forms above is established durably; only then may it transition to `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION`. The original authorization and consumed reference are never reused after a failed or ambiguous post-authorization handoff. An ambiguous handoff is read-only and non-replayable; it never authorizes business execution, and any later business attempt requires a new explicit operator request, fresh Account authorization, and a new reference. +The current domain owner authenticates the delivery provider, rechecks its own current owner/gameplay fence, and validates both the unchanged original reservation claim fence in the complete post-authorization tuple and, when recovery occurred, the separately current fresh reservation/recovery claim and fence before redeeming the exact reference with Account or allocating the initial owner attempt. The fresh recovery claim is never substituted into the tuple. Account redemption must still validate the exact caller workload, tuple, current authority, membership, applicable privilege, and issuance fence; successful redemption consumes the reference and binds the durable redemption result to that attempt. Handoff timeout, provider/owner fence loss, tuple or fingerprint mismatch, expired or revoked reference, Account `NOT_FOUND`, delivery failure, or redemption failure after the authorized-to-owner transition remains `OWNER_EXECUTION/OWNER_EXECUTION_PENDING` until one of the two applicable terminal-proof forms above is established durably; only then may it transition to `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION`. The original authorization and consumed reference are never reused after a failed or ambiguous post-authorization handoff. An ambiguous handoff is read-only and non-replayable; it never authorizes business execution, and any later business attempt requires a new explicit operator request, fresh Account authorization, and a new reference. For a forwarded owner-mutation family, after the reservation owner receives the Account authorization reference, it atomically enriches the exact `preAuthorizationReservationTuple/v1` into the canonical complete `postAuthorizationExecutionTuple`. The latter contains the complete pre-authorization tuple plus `issuanceKind`, the `authorizationReferenceFingerprint` returned unchanged by Account for the exact opaque reference, exact authenticated workload and actor binding, applicable workload/policy identity, the exact applicable `authorityTuple`, independent applicable `membershipVersion`, positive `issuanceFence`, `reservationOwnerId`, positive `reservationClaimFence`, and the exact immutable `authorityEvidenceBundle/v1` defined in ADR 0047. It explicitly retains the immutable typed `targetOwner` from the reservation and every schema-bound typed presence/absence value; no declared value may be dropped during tuple completion. Logging and Admin never derives or recomputes the fingerprint or any authority evidence. Its durable post-authorization record must persist the Account-returned `authorizationReferenceFingerprint` unchanged as part of the canonical `postAuthorizationExecutionTuple`; this is required tuple evidence, not optional context. Any opaque reference held by Logging and Admin is protected, bounded in-flight delivery material only, not a recovery authority record or competing copy of Account's authority. The workload identity is the exact authenticated Logging and Admin mTLS identity; an automated request also binds `automation_policy_id` and `automation_policy_version`, while a human request has an explicit no-automation-policy value. Schema-bound absent or null values represented by the digest are stored as bound values rather than omitted during tuple completion. The reservation CAS and initial `ACCOUNT_AUTHORIZATION/RESERVED` record are prerequisites to issuance: if that pre-record commit fails, Account issuance must not be attempted, and the request uses the applicable pre-authorization outcome; `AUTHORIZATION_PENDING` is not recorded or returned because no phase record exists. If Account issuance has been dispatched or a reference may exist, but tuple completion cannot be written, the durable record remains `ACCOUNT_AUTHORIZATION/AUTHORIZATION_PENDING` under its applicable claim/recovery rules, and the original request tuple, Account response/reference fingerprint, reservation owner and claim fence, and all returned authority/evidence fields are retained in their owning durable records; the opaque reference itself remains only in Account's protected authority record and bounded in-flight delivery material. It must not be forwarded, reissued, or treated as `NOT_EXECUTED_BEFORE_AUTHORIZATION` until durable proof establishes that no authorization reference exists, cannot still be issued, and no owner-forward call occurred or can still occur. If no reference could have existed and the no-dispatch proof is complete, the pre-authorization terminal outcome may be recorded instead. The action-family request identity is canonical across HTTP, Java/domain contracts, ADRs, and audit records; its action-family mapping and moderation correlation rule are defined above. Protobuf contracts may use the language-standard wire spelling `control_plane_request_id`, which maps directly to the non-moderation identifier; it is not a second idempotency key. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 29f55ace47..c4e61237ca 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -21,7 +21,7 @@ The sections below define the target-state runtime contract. Current implementat - Durable command/effect execution currently covers movement and `PUT`, `TAKE`, `WEAR`, and `REMOVE` fully at the existing boundary. Current `GET` is the command spelling for the target `PICKUP`/`PickupVisibleRoomItem` family, and `GET` plus `DROP` also enqueue and execute on that durable command path, but their ADR 0054 spatial correctness remains incomplete until World `TargetingFactSnapshot` attestation/location-version propagation, the shared actor-lock/executor-fence critical section and durable barrier/handoff path, and stale-race proof are implemented. Current movement/item replay rows do not yet prove the ADR 0054 participant guard bound to root `EffectId`, typed operation, target, and request digest, or fail-closed changed reuse. - The target spatial/ambient reconciliation contract is not a current Game Session surface: the typed `EffectReconciliationAuthority`, durable `effect_reconciliation_backlog`/authority schema, immutable effect guards, durable action ledger/results, and list/retry/acknowledgement APIs remain unimplemented. Current persistence is limited to `tick_batch`/`tick_effect` and narrower domain/remote-follow-up reconciliation; see [Game Session API status](./api-contracts.md#implementation-status) and the normative [transaction reconciliation owner](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects). - The target remote-follow-up contract makes terminal timeout/late outcomes immutable under the original identity: exact retries return the stored terminal outcome, and a late-applied result requires a separately documented feature-specific compensation flow. The current `scheduleFollowup` replay path returns an existing retryable-timeout pair or valid terminal pair without mutation, with focused unit proof for terminal-pair replay. This does not establish exact serialized timeout/result arbitration under concurrency, complete terminal-failure mirroring, missing-coordinator recovery, or late-result compensation. The live `late_result_requires_reconciliation` path also writes `LATE_RESULT_RECONCILED`/`PARTIAL` and mirrors `APPLIED`/`PARTIAL` to the origin without a separately identified compensation/saga flow; post-abandon re-drive and compensation ownership remain unproved. -- Current tick staging has Redis-first windows that are not the target durable-first boundary: ingress pushes the queue payload before marking the durable command `STAGED`, and tick processing moves queue entries to Redis `pending` before creating the durable `tick_batch`/`tick_effect` rows. A crash or Redis loss in either window can strand a `STAGED` command with no batch/effect, while startup recovery only handles `ACCEPTED` rows with no staging timestamp and purge can classify a no-effect row as `LOST_BEFORE_STAGING`. Current crash recovery is limited to durable records that exist; there is no recovery path for a `STAGED` command without a corresponding `tick_batch`/`tick_effect`, and missing staging or effect evidence does not prove that materialization or application did not occur. Only explicitly classified volatile ingress may receive that evidence-qualified outcome; durable accepted work needs a durable source claim/materialization recovery path and its feature-specific replay/re-drive contract. The target boundary creates the durable batch/effect/source claim before `pending` staging and treats Redis-only residue as reconstructible coordination state; the current ordering and no-batch recovery are implementation drift. +- Current tick staging has Redis-first windows that are not the target durable-first boundary: ingress pushes the queue payload before marking the durable command `STAGED`, while tick processing moves queue entries to Redis `pending` before creating the durable `tick_batch`/`tick_effect` rows. Failures before the durable `STAGED` update leave the command `ACCEPTED`; failures after that update and before durable `tick_batch`/`tick_effect` creation can leave `STAGED` without a batch/effect. Startup recovery only handles `ACCEPTED` rows with no staging timestamp, and purge can classify a no-effect row as `LOST_BEFORE_STAGING`. Current crash recovery is limited to durable records that exist; there is no recovery path for a `STAGED` command without a corresponding `tick_batch`/`tick_effect`, and missing staging or effect evidence does not prove that materialization or application did not occur. Only explicitly classified volatile ingress may receive that evidence-qualified outcome; durable accepted work needs a durable source claim/materialization recovery path and its feature-specific replay/re-drive contract. The target boundary creates the durable batch/effect/source claim before `pending` staging and treats Redis-only residue as reconstructible coordination state; the current ordering and no-batch recovery are implementation drift. - The target stale-fence contract preserves a drained effect under its original mutation `EffectId` and enclosing root lineage while evidence-fenced reconciliation determines whether it is `APPLIED` or safely unapplied. A new identity may be re-driven only after authoritative participant/domain evidence conclusively terminalizes the original effect as `ABANDONED` and the owning source command/claim is terminalized; ordinary retry/replay retains the original command/effect identity. Root allocation details remain proposal-only under [ADR 0183](../../decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). The current implementation instead marks stale drained batches/effects `ABANDONED` on the fence/technical signal alone and requeues the same command, after which a later batch derives a new effect identity. This is unsafe implementation drift: a crash after participant mutation but before ledger terminalization can permit duplicate logical application or false abandonment. - `BLOCK` is also on the current durable effect replay/no-op seam; other state-changing command families still need to migrate onto it. - Current Game Session code still defaults `FIREMUD_AUTH_SESSION_EXPIRATION_MS` to one hour and does not enforce the target five-minute continuity cap. diff --git a/design/architecture/system-architecture-scripting-scheduler-and-timers.md b/design/architecture/system-architecture-scripting-scheduler-and-timers.md index 6a73a1e327..17325c5842 100644 --- a/design/architecture/system-architecture-scripting-scheduler-and-timers.md +++ b/design/architecture/system-architecture-scripting-scheduler-and-timers.md @@ -40,12 +40,14 @@ The following classification applies to Automation-owned scheduler data; it does - Durable schedule instances and due state are S2 mapping-dependent runtime state. Their durable identity uses the tenant, `playableStateNamespaceId`, and owning schedule identity; the persisted `gameInstanceId` is separately exact-validated active-instance authorization evidence. Replacement requires explicit continuity or replacement mapping, exact target validation, and that active-instance fence. A namespace transition retires the old generation before target admission and never reuses its due point implicitly. - Correctness-bearing one-shot intent is retained under its owner-defined durable identity (S1 when namespace-owned); an in-flight claim remains fenced and reconciled under its original instance, namespace, epoch, and pin evidence rather than being remapped into a new runtime. - Durable recurring candidate/claim evidence remains under its original identity until its declared firing, skip, or reconciliation outcome. Advisory/cosmetic candidate state is S3-disposable only where the authored recovery policy permits dropping it; a retained candidate audit is immutable history, not replay authority. -- Redis timer indexes, scheduler progress hints, queue pointers, and other rebuildable projections are S3 coordination state. Reset, epoch, namespace, or leader changes may discard them, but only durable owner state may rebuild or authorize scheduling. +- **Target state only:** Redis timer indexes, scheduler progress hints, queue pointers, and other rebuildable projections are S3 coordination state. Reset, epoch, namespace, or leader changes may discard them, but only durable owner state may rebuild or authorize scheduling. The current PostgreSQL schedule-definition and schedule-instance substrate, and its recovery/fence gaps, remain as recorded in [Implementation Status](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). Old-instance schedule state and correctness-bearing claims therefore block cleanup while nonterminal or reconciliation-required. A new target row or identity may admit only after the applicable old generation is fenced and the target's exact namespace, runtime, pin, and owner evidence has been validated. ### Script Timers vs Tick Timers +The end-to-end lifecycle and reload behavior in this target-state section, including rebuilding timer indexes from durable owner state, is not a description of current implementation. Current PostgreSQL schedule storage and the remaining convergence gaps are listed above and tracked by [Automation and Scheduler Runtime](../project-management/implementation-tracking/automation-and-scheduler-runtime.md#capability-status). + Plugin timer admission carries the owner lifecycle fence as evidence separate from schedule identity: the stable schedule row carries the mutable current reconciled `(pluginActivationEpoch, lifecycleRevision)` pair, while each due candidate and firing claim captures the pair as immutable evidence; a new firing requires the exact current tuple. `DRAINING` cannot authorize a new firing; only same-version/same-epoch work whose winning admission CAS durably committed the immediately preceding `ENABLED` revision before the durable Automation-owned `DRAINING` admission barrier was created may retain it under ADR 0119. A revision change alone does not create a new candidate identity. Every authored timer declares both its clock unit and recovery class. Tick/game time is the default for gameplay timers; wall clock must be explicit and is a scheduler-eligibility clock only. Timers remain layered on the authoritative runtime timeline, but not every deadline is a tick deadline: @@ -176,6 +178,8 @@ The interval admission, durable-claim, artifact-estimate reservation, and retry/ #### Script Reload +This reload sequence is target-state behavior; the current implementation status above does not establish Redis-index rebuild or end-to-end reload/recovery proof. + - During reload, leaders set `reloadState=RELOADING` for the affected runtime scope after observing that Game Session has pinned a tenant-`READY` patch for that instance. `onLoad` is not part of this instance reload path; it has already completed as part of tenant patch readiness. Existing timer entries in the region index `automation:timer:{tenantRegionTag}` and any derived per-script projections remain in Redis but are treated as pending until reconciliation completes. - Once the exact Game Session `(scriptPatchVersion, scriptPinEpoch)` is committed and reconciliation succeeds, the leader: - re-reads its heartbeat checkpoint and the current `tickId`; diff --git a/design/architecture/system-architecture-tick-incident-runbook.md b/design/architecture/system-architecture-tick-incident-runbook.md index c83f88d0c8..b09afae013 100644 --- a/design/architecture/system-architecture-tick-incident-runbook.md +++ b/design/architecture/system-architecture-tick-incident-runbook.md @@ -267,7 +267,7 @@ When this section uses target-only `tick_effects_*` replay-ledger metrics, requi - Resolve each affected scope from authoritative runtime/control-plane records and carry the complete tuple `` plus the current executor fence; the bounded metrics bucket is not sufficient evidence. - **Current-live branch:** because any deployed containment boundary is at most instance-scoped, enumerate and record every affected region and namespace/scope under the ``, obtain the broader-scope approval gate, and apply only a deployed containment/fencing control that provides authoritative scope evidence; if none is available, preserve any active broader containment, block further mutations, mark exact containment unverified, and escalate under the current-live [executor fencing/drain gate](#act-stalled-tick-region). Use `GetRuntimeOwnershipStatus` plus `ObserveRuntimeTickProgress` only as evidence-only status and forward-progress reads. Require authoritative readback of that full enumeration and fence before any cleanup action; do not describe this as an exact regional pause or reset. - **Target state only, once implemented and proven:** use the exact namespace/region-qualified pause and cleanup controls, with CAS/readback proving the carried tuple and executor fence at each mutating step. If a region remains stuck, execute the region-scoped coordination reset flow in `system-architecture-redis-reset-and-recovery.md`; missing or mismatched evidence fails closed. - - Keep current-live instances/deployments paused and non-accepting while Automation projection recovery is unavailable. Resume only after executable owner-reconciled recovery, authoritative full-scope readback, and the canonical smoke gate. If ledger backlog also accumulates, trigger ledger replay-controller remediation for the same fully resolved scope. + - Keep current-live instances/deployments paused and non-accepting while Automation projection recovery is unavailable. Resume only after executable owner-reconciled recovery, authoritative full-scope readback, and the canonical smoke gate; ledger backlog does not authorize replay-controller remediation on the current-live branch, which remains fail-closed containment and escalation. Target-state deployments may trigger replay-controller remediation only after the capability/proof gate in the canonical [Ledger Replay Controller](./system-architecture-tick-failures-and-operations.md#ledger-replay-controller) contract passes for the resolved scope. 4. **Verify convergence** - Confirm `tick_cleanup_lag_ms{scope_class}` returns to normal envelope. - Confirm `tick_coordination_cleared_total{scope_class}` catches up with durable commits for affected approved bounded scope buckets. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 8192dad296..1ca066c481 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -181,3 +181,9 @@ Entry format: - Observation: the exact contention phase and cause remain unproven. That refusal alone does not establish that CodeRabbit is reviewing, and preparation delay consumes eligible Hosted windows independently of provider duration. - Expected pattern: retain the canonical request handle and verify its actual posted or refused outcome. Investigate the narrow admission/lock boundary without bypassing duplicate-request or exact-identity safeguards; keep the other safe lane moving. - Reconsideration trigger: investigate when the controller owner can reproduce the contention or another eligible Hosted window is lost; do not silently label an unposted request as an active review. + +- `2026-10-01`: Do not infer CLI exclusion from unpublished fixes + - Context: #2839's local corrections were committed at 06:20:21 UTC and Hosted finished at 06:25:38 UTC; Gameplay made no CLI attempt during that 5m 17s interval, incorrectly assuming the unpublished corrections prevented overlap. + - Observation: the live runner permits CLI on the exact published Hosted candidate, excluding local descendant changes. An unattempted safety assumption is not a demonstrated controller hold. + - Outcome: subsequent CLI requests ran independently. A later Hosted retry encountered a closed-#2750 reservation verification error before POST; its current record and attributable terminal review were valid on one read-only reproduction, and a canonical retry posted successfully. The original exception remains unknown because the wrapper hides its phase/cause; no record was edited or safety check bypassed. + - Expected pattern: use the canonical eligible channel, retain actual refusal evidence, and keep the other lane moving. Preserve safe phase/cause diagnostics for future reservation-verification failures rather than treating an unposted request as provider activity. diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index a36e623f6a..fcee2f2dbc 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -2628,6 +2628,54 @@ require_absent( "design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md", ["the owner must reconcile durable results before timeout, require matching scope/epoch evidence"], ) +require_contains( + "design/architecture/system-architecture-scripting-scheduler-and-timers.md", + [ + "The end-to-end lifecycle and reload behavior in this target-state section", + "**Target state only:** Redis timer indexes, scheduler progress hints, queue pointers", + "This reload sequence is target-state behavior", + "current PostgreSQL schedule-definition and schedule-instance substrate", + ], +) +require_contains( + "design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md", + [ + "the original positive `reservationClaimFence` stored in that tuple", + "its fresh reservation/recovery claim and fence are separate, independently validated execution authority", + "they do not replace or rewrite the original tuple fence", + "Exact tuple comparison and current owner/fence validation remain required before evaluation, dispatch, or reference delivery", + "This CAS and enrichment preserve the original reservation claim fence as immutable tuple evidence", + "the separately current fresh reservation/recovery claim and fence before redeeming the exact reference", + ], +) +require_absent( + "design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md", + ["`reservationOwnerId`, current positive `reservationClaimFence`"], +) +require_contains( + "design/architecture/microservices/game-session-service/runtime-and-data.md", + [ + "Failures before the durable `STAGED` update leave the command `ACCEPTED`", + "failures after that update and before durable `tick_batch`/`tick_effect` creation can leave `STAGED` without a batch/effect", + "there is no recovery path for a `STAGED` command without a corresponding `tick_batch`/`tick_effect`", + ], +) +require_absent( + "design/architecture/microservices/game-session-service/runtime-and-data.md", + ["A crash or Redis loss in either window can strand a `STAGED` command"], +) +require_contains( + "design/architecture/system-architecture-tick-incident-runbook.md", + [ + "ledger backlog does not authorize replay-controller remediation on the current-live branch", + "Target-state deployments may trigger replay-controller remediation only after the capability/proof gate", + "[Ledger Replay Controller](./system-architecture-tick-failures-and-operations.md#ledger-replay-controller)", + ], +) +require_absent( + "design/architecture/system-architecture-tick-incident-runbook.md", + ["If ledger backlog also accumulates, trigger ledger replay-controller remediation"], +) print("architecture doc contracts passed") PY From c74f8892eadef1cd1abba99f4b0aa28971bd5073 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 21:40:45 +1300 Subject: [PATCH 64/68] fix: align replay recovery and reviewed runtime authority contracts --- ...gle-use-gameplay-connect-token-carriage.md | 6 +- ...terministic-fair-entity-tick-scheduling.md | 4 +- ...ution-with-one-logical-terminal-outcome.md | 2 +- ...ount-bounds-for-generated-effect-chains.md | 2 +- ...effect-id-allocation-and-replay-binding.md | 52 ++-- .../game-design-service/modding-framework.md | 2 +- .../logging-admin-service/api-contracts.md | 34 ++- .../system-architecture-gateway.md | 3 +- .../system-architecture-redis-cheatsheet.md | 3 +- .../system-architecture-redis-ops-access.md | 4 +- ...m-architecture-redis-reset-and-recovery.md | 2 +- ...m-architecture-redis-usage-and-profiles.md | 5 +- .../architecture/system-architecture-redis.md | 7 +- ...system-architecture-scripting-contracts.md | 2 +- ...e-scripting-dsl-reference-and-lifecycle.md | 2 +- ...ure-scripting-normative-contract-tables.md | 4 +- ...chitecture-tick-concepts-and-invariants.md | 2 +- ...ystem-architecture-tick-execution-flows.md | 8 +- design/project-management/ai-observations.md | 5 + dev-tools/tests/architecture-doc-contracts.sh | 222 +++++++++++++++++- .../src/main/resources/openapi.yaml | 4 +- .../controller/SessionRoleControllerTest.java | 3 +- .../src/main/resources/openapi.yaml | 2 +- 23 files changed, 314 insertions(+), 66 deletions(-) diff --git a/design/architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md b/design/architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md index 8409772119..66216321cf 100644 --- a/design/architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md +++ b/design/architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md @@ -49,14 +49,14 @@ For browser logout, Gateway exposes exactly `POST /ws/game/connect-token/revoke` - Gateway atomically consumes `jti` in the player-facing Coordination Redis deployment before attempting the upstream WebSocket connection. That deployment uses Redis 7.2 or newer with AOF enabled, `noeviction`, ACLs that prevent non-replay callers from mutating replay, deny-marker, and readiness/fence keys, and reserved capacity above the bounded maximum live marker set. Replay and browser-deny markers never share a cache/rate-limit deployment or an eviction policy. Capacity alerts and an admission-readiness threshold fail new handshakes before memory exhaustion can make marker writes unreliable. The single consume script receives `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:` in that order as one Coordination Redis atomic operation; it requires `state=OPEN`, exact fence equality, the signed-`iat` quarantine-cutoff predicate, and no deny marker, then creates the replay key with its expiry at `exp + firemud.gateway.connectTokenClockSkewMs`. It returns exactly one integer: `1` when this request wins the `jti` race, `0` when the replay marker already exists, and `-1` when the browser deny marker exists. Gateway must parse that reply as exactly one integer under both RESP2 and RESP3; null, error, wrong type, wrong arity, or any value other than `-1`, `0`, or `1` is an uncertain outcome and fails closed. A `0` or `-1` result does not create or acknowledge a replay marker. For a newly created marker, Gateway immediately executes `WAITAOF requiredLocalAofCount requiredReplicaAofCount firemud.gateway.replayConsumeAckTimeoutMs` on the same pinned Redis connection that executed the marker script, without returning it to a pool, reconnecting, or issuing an intervening write. `WAITAOF` acknowledges writes sent by the current connection, so a result from another connection cannot satisfy this contract. Its reply is an array of exactly two integers under both RESP2 and RESP3: `[localAofFsyncCount, replicaAofFsyncCount]`. Gateway must reject nulls, errors, wrong arity, wrong types, overflow, and negative counts, and accept `DURABLE_REPLAY_CONSUME_ACK` only when both counts meet their configured thresholds. Configuration validation requires `requiredLocalAofCount = 1`, `requiredReplicaAofCount >= 0`, `requiredReplicaAofCount = 0` only for the explicitly supported single-node profile and at least `1` for clustered player-facing profiles, and the canonical timeout above; impossible, negative, overflowed, or profile-inconsistent thresholds fail startup/preflight. `WAITAOF` is a Redis 7.2+ AOF-fsync acknowledgement, not a claim of protection from disk or hardware destruction. A successful `SET`, `WAIT`, read-back, or client write completion alone is not sufficient. If the marker write or `WAITAOF` result is lost, times out, is malformed, or is below threshold, the outcome is uncertain and the handshake fails closed. A player-facing profile that cannot prove the Redis version, AOF configuration, capacity headroom, and acknowledgement is not eligible to admit new handshakes. - Browser revocation and connect consumption are linearized by the Coordination Redis operation. If the deny-marker write commits first, including a revocation request racing a handshake, the consume script returns `-1`, does not create the replay marker, and Gateway denies admission. If the consume script commits first, the token was already accepted and spent; a later browser revocation records the deny marker but cannot retroactively undo that accepted handshake. No implementation may split the deny-marker check from readiness/fence validation or `jti` creation into separate Redis operations. - Consumption is final. If the backend connection or protocol upgrade subsequently fails, the client obtains a new connect token rather than retrying the spent token. -- Any Coordination Redis event that affects the shared Gateway replay-marker or replay-fence continuity domain, including a cold start, reset, unexpected replay-key eviction, failover, durability-acknowledgement timeout/failure, capacity-safety breach, or any other event that cannot prove marker continuity, atomically advances a shared `replayAdmissionFence` and records `state=QUARANTINED`, `quarantineStartedAt`, a shared signed-`iat` cutoff `quarantineCutoffIat`, and a finite `quarantineUntil` in Coordination Redis. A Cache/Rate-Limit Redis event, or a tenant/region-scoped Coordination Redis reset that does not affect this shared replay domain, does not trigger this quarantine. `quarantineCutoffIat` is the recorded detection cutoff, not a pod-local receipt time; every Gateway must reject a verified token whose signed `iat` is at or before that cutoff, and the fenced consume operation must repeat that comparison against the current shared record. Every Gateway and the Account issuance path must read that shared state and fence; a pod-local circuit breaker, cache, stale Gateway, or stale issuer cannot reopen admission or mint a credential that survives the fence change. If the shared readiness record is absent and Coordination Redis is readable, one shared compare-and-set initialization may start a new quarantine from the current detection time and persist its new cutoff. If the readiness record cannot be read, admission and issuance remain closed and no initialization is permitted. A later replay-domain loss repeats that process with a new shared cutoff and restarts the complete quarantine window; recovery and reopen preserve the current persisted cutoff until the fenced transition to `OPEN`, and never infer, clear, or shorten it from local state. The quarantine deadline is at least the detection time plus the 30-second token maximum and two `firemud.gateway.connectTokenClockSkewMs` intervals: one covers the latest tolerated future `iat`, and the other covers acceptance through `exp + skew`. When the latest affected token expiry is known, the deadline also covers that expiry plus one skew interval. Tokens from an earlier fence or issued at or before the persisted quarantine cutoff are rejected, Account cannot issue while the state is `QUARANTINED`, and a token from an issuance race carries the earlier fence and is rejected after the transition. Gateways may reopen only after the shared deadline has passed, Coordination Redis is available, configuration and capacity probes pass, and a fresh disposable marker script followed by the configured `WAITAOF` thresholds proves `DURABLE_REPLAY_CONSUME_ACK`; one compare-and-set transition then records `state=OPEN` for the current fence, after which Account may issue tokens bound to that fence. An explicitly configured local test profile may use isolated replay state with visible drift telemetry; no player-facing profile silently falls back to pod memory. +- Any Coordination Redis event that affects the shared Gateway replay-marker or replay-fence continuity domain, including a cold start, reset, unexpected replay-key eviction, failover, durability-acknowledgement timeout/failure, capacity-safety breach, or any other event that cannot prove marker continuity, atomically advances a shared `replayAdmissionFence` and records `state=QUARANTINED`, `quarantineStartedAt`, a shared signed-`iat` cutoff `quarantineCutoffIat`, and a finite `quarantineUntil` in Coordination Redis. A Cache/Rate-Limit Redis event, or a tenant/region-scoped Coordination Redis reset that does not affect this shared replay domain, does not trigger this quarantine. `quarantineCutoffIat` is the recorded detection cutoff, not a pod-local receipt time; every Gateway must reject a verified token whose signed `iat` is at or before that cutoff, and the fenced consume operation must repeat that comparison against the current shared record. Every Gateway and the Account issuance path must read that shared state and fence; a pod-local circuit breaker, cache, stale Gateway, or stale issuer cannot reopen admission or mint a credential that survives the fence change. If the shared readiness record is absent and Coordination Redis is readable, one shared compare-and-set initialization may start a new quarantine from the current detection time and persist its new cutoff. If the readiness record cannot be read, admission and issuance remain closed and no initialization is permitted. A later replay-domain loss repeats that process with a new shared cutoff and restarts the complete quarantine window; recovery and reopen preserve the current persisted cutoff until the fenced transition to `OPEN`, and never infer, clear, or shorten it from local state. The quarantine deadline is at least the detection time plus the 30-second token maximum and two `firemud.gateway.connectTokenClockSkewMs` intervals: one covers the latest tolerated future `iat`, and the other covers acceptance through `exp + skew`. When the latest affected token expiry is known, the deadline also covers that expiry plus one skew interval. Tokens from an earlier fence or issued at or before the persisted quarantine cutoff are rejected, Account cannot issue while the state is `QUARANTINED`, and a token from an issuance race carries the earlier fence and is rejected after the transition. After the shared deadline, configuration/capacity probes, exact fenced recovery-probe evidence, and every other release gate succeed, the trusted recovery coordinator authorizes reopen through Gateway's existing authenticated owner-maintenance boundary; Gateway's owner-local helper alone performs the fenced compare-and-set to `state=OPEN`. The coordinator does not receive raw Redis authority, and Account may issue only after the transition for tokens bound to the current fence. An explicitly configured local test profile may use isolated replay state with visible drift telemetry; no player-facing profile silently falls back to pod memory. ### Supported Replay Topology And Promotion Proof - Player-facing replay protection is supported only on a dedicated Coordination Redis continuity domain using either a persistent single-node AOF deployment with no failover, or a `production_clustered` primary/replica or Redis Cluster deployment whose replay-marker keys and readiness fence remain within the documented continuity domain. The single-node and clustered choices may satisfy different deployment profiles, but neither may share replay state with Cache/Rate-Limit Redis, use an eviction policy, or rely on an ephemeral no-AOF profile. - `WAITAOF` acknowledges the local and configured replica AOF-fsync positions for the marker write. It does not by itself prove that a future promoted primary will contain the marker, that a replica is eligible for promotion, or that disk/hardware loss is survivable. `DURABLE_REPLAY_CONSUME_ACK` therefore means the configured write acknowledgement only; failover durability requires the separate promotion proof below. -- Before reopening admission after a primary promotion or recovery, the recovery controller must record the continuity domain and fence, the old and new Redis identities/epochs, successful AOF load or equivalent recovery completion, the promoted node's replication/AOF position relative to the last acknowledged marker write, and read-back evidence for `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`. A clustered deployment must also prove the fixed `{gateway-connect-token-replay-v1}` tag kept all three keys in the supported continuity slot. If the promoted target or evidence cannot establish that acknowledged replay markers and the readiness/fence record are preserved, the event is uncertain and follows the full quarantine path; Gateway must not infer continuity from a promoted role, Redis availability, a new `WAITAOF`, or an isolated successful read. -- A recovery that cannot prove marker continuity does not reopen early. It waits until the affected token acceptance window is dead, then passes the fresh disposable-marker and configured `WAITAOF` readiness probe before the shared compare-and-set transition to `OPEN`. This preserves single-use admission semantics even when the underlying Redis failover lost recent marker state. +- Before reopening admission after a primary promotion or recovery, the recovery controller must record the continuity domain and fence, the old and new Redis identities/epochs, successful AOF load or equivalent recovery completion, the promoted node's replication/AOF position relative to the last acknowledged marker write, and read-back evidence for `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and the recovery-only `gateway:connect-token:{gateway-connect-token-replay-v1}:probe:*` family. A clustered deployment must also prove the fixed `{gateway-connect-token-replay-v1}` tag kept all four families in the supported continuity slot. If the promoted target or evidence cannot establish that acknowledged replay markers and the readiness/fence record are preserved, the event is uncertain and follows the full quarantine path; Gateway must not infer continuity from a promoted role, Redis availability, a new `WAITAOF`, or an isolated successful read. +- A recovery that cannot prove marker continuity does not reopen early. It waits until the affected token acceptance window is dead, then the trusted recovery coordinator invokes Gateway's separate typed recovery probe through Gateway's existing authenticated owner-maintenance boundary while shared readiness remains `QUARANTINED`. On one pinned Coordination Redis connection, Gateway conditionally writes a Gateway-generated disposable marker under `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::` only when the exact durable maintenance operation/fence, replay domain, current `replayAdmissionFence`, and quarantine state still match. The key and nonce are generated by Gateway; callers cannot supply a key, nonce, player `jti`, or marker value to redirect the probe into a normal replay/deny prefix. The probe marker has a finite bounded expiry. Gateway immediately issues the configured `WAITAOF` acknowledgement on that same pinned connection with no intervening write; readback then verifies the bound operation/fence and evidence. Only after that acknowledgement and evidence readback may cleanup run as a separate exact-fence-guarded write with readback; cleanup cannot supply or replace the acknowledgement. This probe neither accepts nor consumes a player JWT, real `jti` replay marker, or browser-deny marker, and it never writes shared readiness. Normal player consume remains `OPEN`-only and is never invoked during quarantine. A successful probe is evidence for the recovery coordinator, not admission: only the coordinator may authorize reopen after the deadline, configuration/capacity checks, all other owner release gates, and exact fenced probe evidence succeed; Gateway's owner-local helper performs the readiness compare-and-set through its authenticated maintenance boundary. If any evidence is unavailable or ambiguous, readiness remains quarantined and issuance/admission stay closed. The probe operation and its producer/consumer proof are target-only and currently unimplemented; this preserves single-use admission semantics even when the underlying Redis failover lost recent marker state. ### Scope Handoff And Proxy Exception diff --git a/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md b/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md index 3e43fd9dcd..9274e1f18d 100644 --- a/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md +++ b/design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md @@ -47,7 +47,7 @@ Within one entity's eligible queue, work uses persisted deterministic ordering: `(priority, due_tick_id, entity_enqueue_seq, source_kind, commandId_or_effectKey)` -`entity_enqueue_seq` is monotonic within the entity's current region epoch and assigned by the owning Game Session admission/scheduling path. Same-tick derived children use the persisted parent order plus deterministic child ordinals rather than completion timing. New sources map into this tuple and do not introduce private tie-breakers. +`entity_enqueue_seq` is monotonic within the entity's current region epoch and assigned by the owning Game Session admission/scheduling path. Same-tick derived children use the persisted parent order plus recorded owner-allocated child ordinals rather than completion timing. New sources map into this tuple and do not introduce private tie-breakers. The historical final tuple label `commandId_or_effectKey` is one normalized, persisted, source-specific stable identity slot: `command` uses `commandId`; `timer` uses the timer member ID; `retry` uses the persisted retry member/effect identity required by its owning contract; `remote_followup` uses the durable follow-up row ID; and `generated_effect` uses its recorded child `EffectId` as the slot value. Parent/root identity and child ordinal remain recorded audit and ordering context; they do not replace the child effect identity. The selected manifest retains the source-to-slot mapping and that context for each item; this does not introduce a second tuple or schema field. For generated children, the owner-defined ordinal and durable owner-scope/root/parent/ordinal-to-child-`EffectId` mapping are mandatory and replay-stable under accepted [ADR 0075](./adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md). Only scalar choices and additional allocator mechanics remain pending in [ADR 0183](./adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); that proposal does not defer the accepted child identity or mapping requirement. @@ -87,7 +87,7 @@ Deferred because entity locks do not prove independence from shared room or mult ## Implementation and Proof Obligations -Proof must cover one actor action plus bounded effects, per-entity ordering, deterministic child ordinals, cost-aware rotating/deficit fairness, bounded non-best-effort deferral, reserved lane budgets, source-flood resistance, crash before and after batch persistence, replay from the recorded manifest, epoch reset, scheduler-state recovery, and the prohibition on staging tick `N+1` before matching cleanup of tick `N`. +Proof must cover one actor action plus bounded effects, per-entity ordering, owner-allocated persisted child ordinals and replay-stable mappings, cost-aware rotating/deficit fairness, bounded non-best-effort deferral, reserved lane budgets, source-flood resistance, crash before and after batch persistence, replay from the recorded manifest, epoch reset, scheduler-state recovery, and the prohibition on staging tick `N+1` before matching cleanup of tick `N`. The current runtime remains narrower and game-instance scoped; this decision does not claim the region scheduler or proof exists. diff --git a/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md b/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md index 19b16510e4..a9abacab18 100644 --- a/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md +++ b/design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md @@ -36,7 +36,7 @@ Describing this as “exactly-once execution” would wrongly imply one physical ## Decision -An `ACCEPTED_VOLATILE` command still in `RECEIVED` or `ENQUEUED`, with no surviving durable `tickBatchId`, effect ledger, or source/effect claim, may terminate as lost before durable staging only when an atomic owner-defined no-batch CAS/version-fenced check wins: +An `ACCEPTED_VOLATILE` command may terminate as lost before durable staging only when an atomic owner-defined CAS/version-fenced transition on the authoritative command record wins from the eligible `RECEIVED` or `ENQUEUED` state; if concurrent staging wins, the loss transition affects zero rows. The owner must also provide positive authoritative evidence that no batch committed, no effect was materialized, and no domain application occurred; ingress status or a missing batch/effect identifier alone is insufficient. The current purge path does not prove this target boundary. See the evidence owner contracts in [Transactions](../system-architecture-transactions.md) and [Tick Failures and Operations](../system-architecture-tick-failures-and-operations.md). - `executionOutcome = LOST_BEFORE_STAGING`; and - `gameplayResult = NOT_APPLIED`. diff --git a/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md b/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md index bfd5fcbb3e..4e88cad770 100644 --- a/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md +++ b/design/architecture/decisions/adr-0075-depth-cost-and-count-bounds-for-generated-effect-chains.md @@ -55,7 +55,7 @@ Every suppression produces durable evidence containing: - root and parent identities; - authored feature, script, and version identity; -- deterministic child ordinal; +- recorded owner-allocated child ordinal, with its persisted replay-stable mapping; - limit reason: depth, count, cost, or per-target; - actual and configured limit values; - required or optional classification; and diff --git a/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md b/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md index d31768c6e4..432a1f791c 100644 --- a/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md +++ b/design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md @@ -33,15 +33,15 @@ This proposal records design options for command-plan ordering and `planOrdinal` ## Decision -### Scalar identity and allocation authority +Every clause in this Decision section is a proposal, conditional on human acceptance. In particular, the exact UUIDv7 scalar format and the additional command-plan, candidate-manifest, allocator, and fan-out-manifest mechanisms below do not extend the independently accepted owner-defined child ordinal and durable owner-scope/root/parent/ordinal-to-child-`EffectId` mapping in ADR 0069, ADR 0075, and ADR 0077. -The canonical scalar `EffectId` is an opaque, lowercase, hyphenated UUIDv7 textual value of exactly 36 characters. UUIDv7 supplies collision-resistant allocation ordering properties without giving producers semantic parsing or meaning. Producers and participants must treat the value as an opaque scalar; they must not derive it from command text, batch IDs, effect keys, participant fields, ordinals, operation names, targets, or mutable payloads. +### Proposed scalar identity and allocation authority -If accepted, Game Session would own command-root allocation, while the owner of a generated child, non-command root, or remote/fan-out leg would own its corresponding allocation boundary. Each boundary would allocate once, durably persist the value, and atomically bind it to the complete immutable owner scope, operation, exact target where applicable, request digest, enclosing root, parent, and stable ordinal. Insert-if-absent uniqueness would cover the logical mapping and scalar claim. A collision or any conflicting binding would fail closed; it would not remint or substitute an ID. +If accepted, this proposal would define the scalar `EffectId` as opaque, lowercase, hyphenated UUIDv7 text of exactly 36 characters. Producers and participants would treat it as an opaque scalar and would not derive it from command text, batch IDs, effect keys, participant fields, ordinals, operation names, targets, or mutable payloads. This exact scalar format is not an accepted cross-service requirement today. -Under this proposal, a command root's enclosing root is its own persisted `EffectId`, and its parent is explicitly absent (`null`). The first allocation durably binds that exact root mapping; retry and replay reuse the same scalar and binding. +If accepted, Game Session would own command-root allocation, while the owner of a generated child, non-command root, or remote/fan-out leg would own its corresponding allocation boundary. Each boundary would allocate once, durably persist the value, and atomically bind it to the complete immutable owner scope, operation, exact target where applicable, request digest, enclosing root, parent, and stable ordinal. Insert-if-absent uniqueness would cover the logical mapping and scalar claim. A collision or conflicting binding would fail closed without reminting or substituting an ID. -Retries, replay, failover, and reconciliation read and reuse the persisted mapping and exact scalar. Participants receive the persisted mutation identity and use it in their guard, ledger, response, and terminal outcome. The enclosing root remains lineage and reconciliation context for a child; it does not replace the child's identity or collapse siblings. A post-abandon re-drive receives a new explicitly linked identity under its own admission contract. +Under this proposal, a command root's enclosing root would be its own persisted `EffectId`, and its parent would be explicitly absent (`null`). Its first allocation would durably bind that root mapping; retry and replay would reuse the same scalar and binding. Participants would receive the persisted mutation identity for their guard, ledger, response, and terminal outcome. The enclosing root would remain lineage and reconciliation context for a child without replacing its identity or collapsing siblings. A post-abandon re-drive would receive a new explicitly linked identity under its own admission contract. ### Proposed command-root serialization refinements @@ -49,19 +49,19 @@ The proposal assigns each logical command root a stable `planOrdinal` in semanti The proposed durable allocation row is unique on `(tenantId, gameInstanceId, commandId, planOrdinal)` and binds the frozen command context and ordered plan-manifest digest. This proposal also binds the manifest schema version, serializer, canonical bytes, and exact root scalar claim, requiring exact matches on replay. Unknown, duplicate, ambiguous, noncanonical, or changed order/manifest evidence fails before staging or side effects if this design is accepted. Automation handoff identity would map exactly to one durable target command before this command-root allocation; trigger and correlation identities would not be allocation inputs. -### Generated-child candidates and suppression +### Proposed generated-child candidates and suppression -Before enqueue or apply, the owning chain boundary seals one versioned child-candidate manifest using its registered canonical serialization. Each candidate records root/parent lineage, stable ordinal, typed operation, exact target, depth, required/optional classification, immutable request or plan digest, and resolved count/cost/per-target budget revisions. The candidate manifest schema version, serializer, canonical digest, and ordered candidate set are immutable replay evidence. +If accepted, the owning chain boundary would seal a versioned child-candidate manifest before enqueue or apply. Each candidate would record root/parent lineage, stable ordinal, typed operation, exact target, depth, required/optional classification, immutable request or plan digest, and resolved count/cost/per-target budget revisions. The manifest schema version, serializer, canonical digest, and ordered candidate set would be immutable replay evidence. -Candidates receive no child `EffectId` at manifest creation. For an admitted candidate, one serializable transaction or explicitly equivalent locked multi-key atomic boundary validates the manifest, reserves the ordinal, checks and charges only the admitted candidate's count/cost/per-target budgets, allocates and persists the opaque scalar mapping together with the manifest schema version, registered serializer identifier, and canonical digest (or an immutable manifest reference resolving to those exact fields), and commits the mapping before enqueue/apply. Replay and retry must exact-compare that schema version, serializer, digest/reference, candidate ordinal, and all other immutable binding fields before reusing the mapping or enqueueing work. Concurrent sibling admission cannot double-charge, reserve two mappings for one ordinal, or leave partial budget, ordinal, mapping, or suppression state. Exact retries reuse the committed mapping. +Under this proposed mechanism, candidates would receive no child `EffectId` at manifest creation. For an admitted candidate, one serializable transaction or explicitly equivalent locked multi-key atomic boundary would validate the manifest, reserve the ordinal, check and charge only the admitted candidate's count/cost/per-target budgets, allocate and persist the scalar mapping with the manifest schema version, registered serializer identifier, and canonical digest (or an immutable reference resolving to those fields), then commit the mapping before enqueue/apply. Replay and retry would exact-compare that schema version, serializer, digest/reference, candidate ordinal, and other immutable bindings before reusing the mapping or enqueueing work. Concurrent sibling admission would not double-charge, reserve two mappings for one ordinal, or leave partial budget, ordinal, mapping, or suppression state. Exact retries would reuse the committed mapping. -An over-limit candidate is suppressed without a child ID. The same atomic boundary records immutable ID-free suppression evidence containing root/parent identity, the sealed candidate-manifest schema/serializer/digest, candidate ordinal, operation and exact target, feature/script/version, required/optional classification, reason, configured and actual limits, and outcome. Suppressed candidates are never enqueued or applied; committed parents and earlier children remain authoritative. +If accepted, an over-limit candidate would be suppressed without a child ID. The same atomic boundary would record immutable ID-free suppression evidence containing root/parent identity, the sealed candidate-manifest schema/serializer/digest, candidate ordinal, operation and exact target, feature/script/version, required/optional classification, reason, configured and actual limits, and outcome. Suppressed candidates would not be enqueued or applied; committed parents and earlier children would remain authoritative. -### Global fan-out and regional child binding +### Proposed global fan-out and regional child binding -At acceptance, the fan-out parent freezes the affected region set and topology generation. Each regional child or leg is one exact member of that sealed set and gets its own one-time allocated child `EffectId` before its wake signal. The durable child row binds root and parent lineage, child ordinal, exact operation, target region/aggregate, request digest, and the versioned child-manifest schema, registered serializer, canonical bytes/digest, and expected-participant projection. It also retains the root binding needed for reconciliation. +If accepted, the fan-out parent would freeze the affected region set and topology generation at acceptance. Each regional child or leg would be one member of that sealed set and receive its own one-time allocated child `EffectId` before its wake signal. The durable child row would bind root and parent lineage, child ordinal, exact operation, target region/aggregate, request digest, and the proposed child-manifest schema, registered serializer, canonical bytes/digest, and expected-participant projection. It would retain the root binding needed for reconciliation. -The child scalar and all binding fields are persisted before wake delivery. Retry, duplicate wake, late result, and reconciliation look up the same row and scalar. A missing, extra, duplicate, reordered, schema/serializer/digest-conflicting, target-conflicting, ordinal-conflicting, or identity-conflicting child fails closed. Wake markers remain disposable latency hints and cannot create, expand, or replace a child. +Under this proposal, the child scalar and all binding fields would be persisted before wake delivery. Retry, duplicate wake, late result, and reconciliation would look up the same row and scalar. A missing, extra, duplicate, reordered, schema/serializer/digest-conflicting, target-conflicting, ordinal-conflicting, or identity-conflicting child would fail closed. Wake markers would remain disposable latency hints and could not create, expand, or replace a child. ## Rationale @@ -71,19 +71,19 @@ The proposed exact scalar format makes wire and storage compatibility testable w ### Derive IDs from command, batch, ordinal, or payload fields -Rejected because mutable or replay-order-dependent fields can collide, change identity, or allow a participant to invent a value. Derivation also makes fan-out and generated-child reuse depend on semantics rather than durable allocation. +This proposal rejects deriving IDs from mutable or replay-order-dependent fields because they can collide, change identity, or allow a participant to invent a value. In the proposed design, derivation would also make fan-out and generated-child reuse depend on semantics rather than durable allocation. ### Permit UUID/ULID producer choice without an exact scalar contract -Rejected for the canonical cross-service boundary because callers could disagree on casing, width, textual form, or parser behavior. The selected pending proposal uses lowercase hyphenated UUIDv7 text while retaining opaque semantics. +This proposal rejects caller-selected UUID/ULID formats for its proposed cross-service boundary because callers could disagree on casing, width, textual form, or parser behavior. Its pending candidate is lowercase hyphenated UUIDv7 text with opaque semantics; this is not the accepted canonical format. ### Allocate at manifest creation for every candidate -Rejected because suppressed work would acquire an execution identity and could be mistaken for an admitted mutation. Allocation belongs to the atomic admission boundary after budget and ordinal checks. +This proposal rejects allocating at manifest creation for every candidate because suppressed work would acquire an execution identity and could be mistaken for an admitted mutation. Under the proposal, allocation would belong to the atomic admission boundary after budget and ordinal checks. ### Use a best-effort global fan-out allocator or wake message identity -Rejected because notifications can be lost or duplicated and cannot own durable correctness. The parent-owned child row and sealed manifest binding are authoritative. +This proposal rejects a best-effort global fan-out allocator or wake message identity because notifications can be lost or duplicated and cannot own durable correctness. If accepted, the parent-owned child row and sealed manifest binding would be authoritative. ## Consequences @@ -91,9 +91,9 @@ Rejected because notifications can be lost or duplicated and cannot own durable - Each generated-effect or fan-out owner would need the proposed durable allocation rows, manifest bindings, and conflict-safe atomic replay behavior if this proposal is accepted. - If accepted, this proposal would require root and child manifests to use registered schema versions and canonical serializers whose bytes and digests are stable across supported readers. - If accepted, chain admission would use a serializable or explicitly equivalent atomic boundary and retain ID-free suppression evidence. -- The proposed 36-character scalar fits existing string protobuf and database fields; current derivation, optional fields, and narrower replay guards remain gaps until independently converged on an accepted contract and proved. -- Participants, ledgers, coordinators, and operational reconciliation must carry both mutation identity and enclosing-root lineage where applicable. -- Adoption is a breaking target convergence for identity allocation; compatibility shims must not preserve semantic derivation or silently accept conflicting formats. +- The proposed 36-character scalar appears to fit existing string protobuf and database fields. Current ID derivation and replay paths are implementation facts; they do not accept or prove the pending scalar, allocator, or manifest choices. +- If accepted, participants, ledgers, coordinators, and operational reconciliation would carry both mutation identity and enclosing-root lineage where applicable. +- If accepted, adoption would be a breaking target convergence for identity allocation; compatibility shims would not preserve semantic derivation or silently accept conflicting formats. ## Reversibility and Revisit Triggers @@ -101,11 +101,11 @@ Before acceptance, human review may change the proposed command-plan ordering, ` ## Security and Privacy -Opaque UUIDv7 values must not encode tenant, account, character, target, operation, or authorization meaning. Exact scope, namespace, runtime-fence, target, and request-digest validation remains separate evidence. Collision, parser, schema, digest, or binding conflicts fail closed before domain mutation. Raw IDs remain durable audit/reconciliation fields but are excluded from bounded metric labels and player-facing messages. Suppression and replay evidence must not expose unauthorized target or tenant data across scope boundaries. +If accepted, opaque UUIDv7 values would not encode tenant, account, character, target, operation, or authorization meaning. Exact scope, namespace, runtime-fence, target, and request-digest validation would remain separate evidence. Collision, parser, schema, digest, or binding conflicts would fail closed before domain mutation. Raw IDs would remain durable audit/reconciliation fields but be excluded from bounded metric labels and player-facing messages. Suppression and replay evidence would not expose unauthorized target or tenant data across scope boundaries. ## Operations and Recovery -Game Session or the owning allocation boundary exposes durable allocation, collision, manifest-mismatch, budget-suppression, fan-out-injection, and reconciliation outcomes with bounded reason labels. Recovery retries the same persisted mapping and manifest; it never regenerates an ID or expands a frozen candidate/region set from current topology. An unresolved binding, partial participant set, or uncertain old-epoch effect remains reconciliation-required and non-terminal under the original mutation identity until the accepted evidence policy permits terminalization. +If accepted, Game Session or the owning allocation boundary would expose durable allocation, collision, manifest-mismatch, budget-suppression, fan-out-injection, and reconciliation outcomes with bounded reason labels. Recovery would retry the same persisted mapping and manifest; it would not regenerate an ID or expand a frozen candidate/region set from current topology. An unresolved binding, partial participant set, or uncertain old-epoch effect would remain reconciliation-required and non-terminal under the original mutation identity until the accepted evidence policy permits terminalization. ## Implementation and Proof Obligations @@ -114,10 +114,10 @@ Implementation and focused proof must cover: - if accepted, lowercase, hyphenated, exactly 36-character UUIDv7 scalar validation and opaque treatment at every supported wire/storage boundary; - if accepted, command-plan ordering; zero-, one-, and multi-root plans; `planOrdinal`; command-root owner/key/binding; ordered manifest digest; mismatch rejection; one-time scalar claims; insert-if-absent uniqueness; collision/conflict failure; crash recovery; concurrent allocation races; and exact replay/reconciliation reuse; - if accepted, the proposed root manifest schema version, serializer, canonical bytes, exact scalar claim, and their mismatch rejection; -- child-candidate schema version/serializer/digest, candidate ordering, depth and budget revisions, serializable sibling admission, no double charge, and no partial commit; -- ID-free suppression evidence proving no enqueue/apply and preserving committed parent/earlier-child outcomes; -- fan-out frozen region/topology set, exact child ordinal and target binding, child-manifest schema/serializer/digest, request digest, pre-wake durability, duplicate wake, late result, and topology-conflict handling; -- participant guard, ledger, coordinator, and terminal projection exactness across root/child identity and enclosing-root lineage; and -- current protobuf/database compatibility, rejected blank/invalid IDs, migration/replay behavior, bounded observability, tenant isolation, and old-epoch recovery. +- if accepted, child-candidate schema version/serializer/digest, candidate ordering, depth and budget revisions, serializable sibling admission, no double charge, and no partial commit; +- if accepted, ID-free suppression evidence proving no enqueue/apply and preserving committed parent/earlier-child outcomes; +- if accepted, fan-out frozen region/topology set, exact child ordinal and target binding, child-manifest schema/serializer/digest, request digest, pre-wake durability, duplicate wake, late result, and topology-conflict handling; +- if accepted, participant guard, ledger, coordinator, and terminal projection exactness across root/child identity and enclosing-root lineage; and +- if accepted, current protobuf/database compatibility, rejected blank/invalid IDs, migration/replay behavior, bounded observability, tenant isolation, and old-epoch recovery. The focused proof must be added only after human acceptance of this proposal and must include the existing [tick failure and operations proof obligations](../system-architecture-tick-failures-and-operations.md), [transaction contract](../system-architecture-transactions.md), [tick execution flows](../system-architecture-tick-execution-flows.md), [tick incident runbook](../system-architecture-tick-incident-runbook.md), [Entity Management API contract](../microservices/entity-management-service/api-contracts.md), and [gameplay implementation tracker](../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md). diff --git a/design/architecture/microservices/game-design-service/modding-framework.md b/design/architecture/microservices/game-design-service/modding-framework.md index 5a3b99ff73..91d5767eb1 100644 --- a/design/architecture/microservices/game-design-service/modding-framework.md +++ b/design/architecture/microservices/game-design-service/modding-framework.md @@ -178,7 +178,7 @@ The exact Trigger Identity, evaluated-descriptor recovery, Command-Handoff Ident - Each plugin trigger has one logical evaluation per full applicable Trigger Identity. Before `EVALUATED_COMMITTED`, infrastructure recovery may re-enter the DSL only under that same identity and must converge on the same durable work item and command-child identities; after that boundary, recovery replays durable descriptors without re-entering the graph. `scriptEventId` is one field of Trigger Identity, not the complete key. Each resolved live handler invocation has one `script_event_audit` row, and the current legacy materialized dry-run/test handler path likewise records one handler row for its terminal result. Target ADR 0114 command-plan previews use the isolated preview result/audit surface or return the result directly and do not create a handler audit row; command attempts and outcomes are child handoff records keyed by the complete Command-Handoff Identity. - Recurring and advisory plugin timers such as `onInterval` (or an advisory `onTimerExpire`) are **best-effort** under their declared recovery policy. Individual firings may be skipped or delayed when per-script quotas, per-tenant budgets, or cluster ceilings are reached, and skipped firings are not backfilled beyond bounded `COALESCE_ONE` behavior. A correctness-bearing one-shot timer instead persists durable intent outside Redis; physical execution may be at least once and replay-safe, while the same logical identity converges to one logical terminal outcome. -- Recurring/advisory plugin logic must therefore tolerate missed or delayed events (for example, by recomputing from current world state rather than assuming every interval executed). Every emitted command remains deduplicated and replay-selectable at child handoff under the [canonical Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state), whose source and applicable distinct target namespace/region identity is separate from the server-derived scope evidence; same-instance handoffs omit every optional target field. The complete parent Trigger Identity, including plugin `bindingId` when applicable, is retained for correlation only. Downstream authoritative effect idempotency instead uses the persisted mutation `EffectId` (the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child mutation), under the owner-declared participant-guard partition (S1/S2: tenant plus `playableStateNamespaceId`; explicitly classified S3: tenant plus `gameInstanceId`), with separately validated `playableStateScope` and active-instance fence evidence, together with the typed operation, exact target aggregate, and immutable request digest stored and compared; a conflicting operation, target, or digest fails closed. `automationDispatchId` is reused across retries but is not globally unique, and `scriptEventId` alone is insufficient for fan-out commands. +- Recurring/advisory plugin logic must therefore tolerate missed or delayed events (for example, by recomputing from current world state rather than assuming every interval executed). Every emitted command remains deduplicated and replay-selectable at child handoff under the [canonical Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state), whose source and applicable distinct target namespace/region identity is separate from the server-derived scope evidence; same-instance handoffs omit every optional target field. The complete parent Trigger Identity, including plugin `bindingId` when applicable, is retained for correlation only. Downstream authoritative effect idempotency instead uses the persisted mutation `EffectId` (the root `EffectId` for a root mutation or the generated child's persisted `EffectId` for a child mutation), under the owner-declared participant-guard partition (S1/S2: tenant plus `playableStateNamespaceId`; explicitly classified S3: tenant plus `gameInstanceId`), with separately validated `playableStateScope` and active-instance fence evidence, together with the complete owner-defined participant binding, typed operation, exact target aggregate, and immutable request digest stored and compared. Any participant-binding, operation, target, or digest conflict fails closed; the canonical [Transactions guard contract](../../system-architecture-transactions.md) and [ADR 0069](../../decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md) own the complete binding and proof. `automationDispatchId` is reused across retries but is not globally unique, and `scriptEventId` alone is insufficient for fan-out commands. - Before plugin work is evaluated and again before handoff, Automation revalidates the captured exact Game Session `(scriptPatchVersion, scriptPinEpoch)` tuple against current authoritative state for the same `(tenantId, gameInstanceId)` runtime scope, together with the exact `(pluginId, pluginVersionId, bindingId)` and scoped Automation-owned `(pluginActivationEpoch, lifecycleRevision)` fence; see [Scripting Contracts §8](../../system-architecture-scripting-contracts.md#8-plugin-version-fencing-and-control-plane-scope). Already-terminal work is unaffected; no new admission proceeds without fresh signer-policy and Game Session authority, and immediately before any final side effect the applicable execution owner revalidates the exact plugin provenance, current activation/lifecycle, component policy, capability grant, signer/publication evidence, `(pluginActivationEpoch, lifecycleRevision)`, and Game Session tuple. Routine component-policy reclassification uses the captured admission decision for already-admitted work and does not invalidate it; final-fence rejection or containment of admitted work requires the independent component-revocation fence and explicit audited emergency workflow. Missing, stale, contradictory, or unavailable authority remains a separate fail-closed condition under the stage-specific dispositions below. Specifically unavailable signer policy/evidence retains `signer_policy_unavailable` on its stage-specific response/audit surface, while an unavailable authoritative runtime/fence read keeps unresolved work fenced and retryable as `authority_unavailable`. A present-but-different activation epoch fails closed with `plugin_activation_epoch_mismatch`; a proven plugin tuple/binding or lifecycle-evidence mismatch uses `plugin_binding_mismatch`; signer or revocation mismatches remain durably terminal/ineligible with their specific canonical dispositions. See [Scripting Runtime Execution](../../system-architecture-scripting-runtime-execution.md#version-fencing-and-rollback-safety), the [scripting outcome contracts](../../system-architecture-scripting-normative-contract-tables.md#table-2-script_event_audit-stages-and-outcomes), and the [Command-Handoff Identity](../../system-architecture-scripting-normative-contract-tables.md#command-handoff-identity-target-state) owner contracts. These guarantees ensure that plugins do not rely on stronger delivery semantics than the underlying scripting engine provides and that their behavior remains predictable under load. diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 8b52915cfe..15a1dc4990 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -112,8 +112,19 @@ The internal admission-pointer service/owner paths represent exactly one of two - Replacing or rolling back `OPEN(old)` to `OPEN(new)` is a prepared cutover, not a generic open. It must use the internal `ExecutePreparedVersionCutover` control-plane operation with one durable `preparedVersionUpgradeId`; that operation revalidates the preparation, source and target identities, and CAS version before atomically swapping the route. Preparation is proof for cutover, not a substitute for route-version concurrency control. - Game Session remains the sole routing-state writer and audits the transition under the same identity and CAS result. Internal callers must not maintain a competing pointer or infer `tenantId` from `worldSlug` or `realmSlug`; Logging & Admin's public REST surface reads the resulting state and audit evidence only. +The deployed Gateway URL and listener are environment-owned; this document does not assign an HTTPS port. For an HTTPS route, set the URL to the environment's published Logging & Admin `/ping` URL and provide the issuing CA bundle so curl verifies the server certificate. The route continues to use its current privileged-JWT authentication; TLS does not imply that the target health authorization policy is implemented. + ```bash -curl -H 'Authorization: Bearer ' http://localhost:8080/ping +curl --cacert "$FIREMUD_HTTPS_CA_CERT_PATH" \ + -H 'Authorization: Bearer ' \ + "$FIREMUD_LOGGING_ADMIN_HTTPS_URL" +``` + +The current local HTTP harness listens on `localhost:8080` without TLS. Use only a disposable, non-production privileged JWT with that loopback-only harness; never send a real operator token over it. Gateway TLS termination and the current in-cluster HTTP forwarding exception are described in [Security Architecture](../../system-architecture-security.md#tls-termination-for-gateway) and [Cross-Service Trust](../../system-architecture-security.md#cross-service-trust). + +```bash +curl -H 'Authorization: Bearer ' \ + http://localhost:8080/ping ``` ## gRPC @@ -148,12 +159,23 @@ curl -H 'Authorization: Bearer ' http://localhost:8080/ping - `ToggleFeatureFlag(ToggleFeatureFlagRequest) returns (ToggleFeatureFlagResponse)` – target owner-forwarding contract, unavailable until the minimum schema/authorization gate above and the complete [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md) durable, idempotent, fenced owner-execution contract are implemented and proved. The current gRPC ingress preserves admin-role, positive-tenant, and feature-name validation, then returns an application-level `UNAVAILABLE` error without invoking a service or owner. Once enabled, Logging & Admin is the audited forwarding ingress; Game Session owns the feature-flag mutation and its durable result. - Tick-remediation is not a Logging & Admin-owned state-mutation gRPC surface. Its HTTP ingress is hard fail closed and no Logging & Admin pause/resume forwarding method remains callable internally; the target owner contract remains unavailable until the minimum schema/authorization gate above and the complete [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md) durable, idempotent, fenced owner-execution contract are implemented and proved. Once enabled, Logging & Admin audits and forwards to Game Session, which owns tick state, fencing, idempotency, and the durable result. Future recovery operations require separate named typed owner contracts; no generic `remediate` RPC is reserved. -```bash -grpcurl -plaintext -H 'Authorization: Bearer ' localhost:6565 logging_admin.v1.LoggingAdminService/Ping +Internal gRPC examples use the configured CA and workload certificate to verify the server and present a client identity. The target for the command is supplied by the environment; this transport example does not claim that current receiver-side workload/method authorization is implemented. The JWT shown for `CreateReport` reflects the current interim receiver contract and must be disposable/non-production. -# Non-production local harness only; production callers require the target internal workload/method authorization, which remains unproved by the current transport configuration. -grpcurl -plaintext -d '{"tenant_id":"1","reporter_account_id":"1","target_account_id":"2","type":"BUG","description":"example"}' \ - localhost:6565 logging_admin.v1.ReportService/CreateReport +```bash +grpcurl -cacert "$FIREMUD_GRPC_CA_CERT_PATH" \ + -cert "$FIREMUD_GRPC_CERT_CHAIN_PATH" \ + -key "$FIREMUD_GRPC_PRIVATE_KEY_PATH" \ + -H 'Authorization: Bearer ' \ + "$FIREMUD_LOGGING_ADMIN_GRPC_TARGET" \ + logging_admin.v1.LoggingAdminService/Ping + +grpcurl -cacert "$FIREMUD_GRPC_CA_CERT_PATH" \ + -cert "$FIREMUD_GRPC_CERT_CHAIN_PATH" \ + -key "$FIREMUD_GRPC_PRIVATE_KEY_PATH" \ + -H 'Authorization: Bearer ' \ + -d '{"tenant_id":"1","reporter_account_id":"1","target_account_id":"2","type":"BUG","description":"example"}' \ + "$FIREMUD_LOGGING_ADMIN_GRPC_TARGET" \ + logging_admin.v1.ReportService/CreateReport ``` ## Endpoint Authentication Classes diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index 2602768c75..5e4b57f48c 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -402,7 +402,8 @@ This section is the canonical source of truth for connect-token enforcement and - Replay and browser-revocation state use the canonical target representation defined by the Redis ownership and recovery documents, with bounded cardinality and deterministic expiry at `exp + firemud.gateway.connectTokenClockSkewMs`. The readiness/fence record and marker state must remain one script-compatible Coordination Redis atomicity domain under that contract. The legacy representation emitted by the current writer is migration-only drift and cannot be treated as target state. - The replay and deny-marker prefixes are security-critical, non-evicting coordination state. Gateway's one consume script checks readiness state, signed fence/cutoff, and deny-marker absence before creating the replay marker; consumption is successful only after that script and the configured Redis 7.2+ `WAITAOF` acknowledgement both succeed. A deny marker that linearizes before or during the consume race returns a denial without creating the replay marker; a consume already linearized is spent and cannot be retroactively undone by a later browser logout. A browser revocation is confirmed only after its deny write and same-connection durability acknowledgement succeed; an uncertain deny write remains unconfirmed. Capacity or acknowledgement failure rejects the handshake rather than accepting an uncertain marker. A crash or connection loss between marker creation and acknowledgement is treated as uncertain consumption, not as an opportunity to unconsume or retry the token. - Coordination Redis cold start, reset, unexpected eviction signal, failover, capacity-safety breach, or any other event that cannot prove replay-marker continuity starts a shared replay-protection quarantine for at least the 30-second token lifetime maximum plus two `firemud.gateway.connectTokenClockSkewMs` intervals. One interval covers a latest tolerated future `iat`; the second covers acceptance through `exp + skew`. Account stops issuing connect tokens and Gateway rejects admission until that barrier expires, configuration and capacity checks pass, and a disposable marker script followed by the configured `WAITAOF` thresholds proves `DURABLE_REPLAY_CONSUME_ACK`; tokens from the earlier fence and issuance races cannot survive reopening. Before normal release, old Gateway replay writers must be drained or authoritatively blocked and the complete tagged replay state and readiness/fence state must be authoritative, in addition to the lifetime, skew, configuration/capacity, and disposable-marker `WAITAOF` gates above. If any old-version writer or admission remains allowed, release additionally requires a separately proven cross-version guard; none is currently implemented or proven, so that mixed-version release path remains forbidden. The current replay deployment has one shared continuity domain, so an unscoped continuity failure intentionally blocks new connect-token issuance and admission platform-wide; a future partitioned deployment may narrow quarantine only when it can prove the exact affected marker and fence domain. - - Recovery obtains post-reset replay readiness through a logical typed Gateway-owned readiness-probe operation, called by trusted recovery through the existing authenticated owning-service maintenance API boundary. This is target behavior, not a new public RPC or an implemented operation. The probe is bound under the existing Redis owner contracts to the exact durable maintenance operation and fence, the shared replay domain, the expected `replayAdmissionFence`, and the authoritative quarantine/readiness, configuration, and capacity evidence. Gateway uses one pinned Coordination Redis connection for one fresh invocation of the canonical consume script with a disposable marker, then issues `WAITAOF` on that same connection. It yields `DURABLE_REPLAY_CONSUME_ACK` only when the consume returns `1`, creates the marker, the configured local and replica durability thresholds are met, and readback still proves the same operation/fence, replay domain, replay fence, quarantine state, configuration, and capacity conditions. A `0` or `-1`, connection loss, threshold timeout, malformed or uncertain result, or changed fence/quarantine/configuration/capacity fails closed; Gateway never retries an old marker to claim a new acknowledgement. Cleanup is a separate guarded write and readback, outside the acknowledgement. This operation proves neither Account projection readiness nor permission to enable normal player admission; the recovery owner still applies all other release gates. The operation and its producer/consumer proof are currently unimplemented, so the post-reset checklist is not yet executable for this gate. + - Recovery obtains post-reset replay readiness through a logical typed Gateway-owned probe, invoked automatically by the trusted recovery coordinator through the existing authenticated owning-service maintenance API boundary. This is target behavior, not a new public RPC or an implemented operation. The probe is bound under the existing Redis owner contracts to the exact durable maintenance operation and fence, the shared replay domain, expected `replayAdmissionFence`, and authoritative quarantine/readiness, configuration, and capacity evidence. While shared readiness remains `QUARANTINED`, Gateway uses one pinned Coordination Redis connection to conditionally write a Gateway-generated disposable marker at `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::` only if the exact operation/fence, replay domain, fence, and quarantine state still match, then immediately issues configured `WAITAOF` on that same connection with no intervening write. The nonce is Gateway-generated, not caller-supplied. The probe does not accept or consume a player JWT, real `jti` replay marker, or browser-deny marker, and does not write shared readiness. It succeeds only when the marker is created, configured local and replica durability thresholds are met, and subsequent readback still proves the same operation/fence, replay domain, replay fence, quarantine state, configuration, and capacity conditions. Connection loss, threshold timeout, malformed or uncertain result, or changed evidence fails closed; Gateway never retries an old marker to claim a new acknowledgement. Cleanup is a separate exact-operation/fence-guarded write and readback after acknowledgement and evidence readback; it cannot supply or replace the acknowledgement. Normal player consume remains `OPEN`-only and is never invoked during quarantine. A successful probe is evidence for the coordinator, not permission to enable player admission: only the coordinator may authorize reopening after the deadline, exact fenced probe evidence, and all other owner release gates succeed. The operation and its producer/consumer proof are currently unimplemented, so the post-reset checklist is not yet executable for this gate. Until implemented and proved under [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md), issuance and player admission remain closed. + - The probe uses only the Gateway-generated exact key family, nonce, and marker value; callers cannot supply key material or redirect a probe to player replay/deny prefixes. Its marker uses a finite bounded expiry, followed by separate exact-operation/fence-guarded cleanup and readback outside `WAITAOF`. The coordinator authorizes release only after all gates pass, then uses Gateway's existing authenticated owner-maintenance boundary; Gateway's owner-local helper performs the readiness compare-and-set. Recovery remains API-only and does not receive raw Redis authority. See [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md) for the canonical probe lifecycle. - Replay-quarantine lifecycle is a monitored security state. Gateway must emit low-cardinality `gateway.connect_token.replay_quarantine_entries_total{reason=...}`, `gateway.connect_token.replay_quarantine_exits_total{outcome=...}`, `gateway.connect_token.replay_quarantine_active`, and `gateway.connect_token.replay_quarantine_duration_seconds`, plus structured records containing the shared `replayAdmissionFence`, `state`, `quarantineStartedAt`, `quarantineUntil`, and `openedAt` values. Alertmanager must alert when a player-facing quarantine is entered, remains active past `quarantineUntil` or has no observed exit, or exits without fresh `DURABLE_REPLAY_CONSUME_ACK` proof. Dashboards must show entry/exit counts and duration. Labels must exclude `jti`, tenant identifiers, and other high-cardinality values. - Replay-cache outage behavior: - Player-facing environments (`/ws/game/**` in `enforce` mode): fail closed with HTTP `403` and `CONNECT_REPLAY_PROTECTION_UNAVAILABLE` when replay protection is unavailable. diff --git a/design/architecture/system-architecture-redis-cheatsheet.md b/design/architecture/system-architecture-redis-cheatsheet.md index 700799d57c..5adaf8e826 100644 --- a/design/architecture/system-architecture-redis-cheatsheet.md +++ b/design/architecture/system-architecture-redis-cheatsheet.md @@ -50,8 +50,9 @@ This table highlights representative prefixes and their intended Redis role. It | `session:auth:generation:issuer:`, `session:auth:generation:account:`, `session:auth:generation:tenant:`, `session:auth:generation:membership::` | **Approved global/account exception: Account durable authority with required Coordination Redis projection** | Account Service | Account advances one positive monotonic `generation` per scope transactionally in its durable store and is the sole writer of the Redis projection. Idempotent set-if-greater is permitted for a missing or lower projection only. A projection greater than durable authority is poison: Account must quarantine or replace that exact scope through an audited workflow, recreate it from durable authority, and emit immutable per-scope evidence/verification; consumers fail closed until the evidence is accepted. Region- and tenant-scoped resets preserve unaffected projections but verify affected scopes; a cluster reset may discard projections only after the Account repair/reset cutover and must rebuild and verify every affected scope before reopening. | | `session:connect-token:tenant::account::scope::request:` | **Coordination Redis — approved untagged Account legacy exception** | Account Service | Current Account-owned exact-input result-map projection. It is reset-sensitive, retained through the legacy TTL/retry horizon, and never read or promoted by target code. | | `session:connect-token:v1:tenant::account::scope::request:` | **Coordination Redis — approved untagged Account target exception** | Account Service | Target Account-owned exact-input issuance-result projection. It requires `schemaVersion: "connect-token-issuance-result-v1"`, durable SQL first-writer-wins before mint, and Redis set-if-absent/read-winner. Target readers and writers are isolated from the legacy family; exact repair comes only from the durable operation/envelope. | -| `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` | **Coordination Redis** | Spring Cloud Gateway | Target security-critical, non-evicting single-use connect-token replay and browser-denial state. The literal `{gateway-connect-token-replay-v1}` tag co-slots replay, browser-deny, and readiness/fence keys for the atomic consume script; the readiness value carries `replayAdmissionFence`. A winning consume (`1`) and a browser-deny write require the configured same-connection, threshold-satisfying `WAITAOF` durability acknowledgement; a definitive consume (`0`/`-1`) is non-mutating and has no marker acknowledgement. An unavailable, timed-out, malformed, below-threshold, lost, or otherwise ambiguous consume/deny result or durability acknowledgement is unconfirmed: fail the handshake or revocation operation closed, keep the affected admission quarantined, and enter the replay-continuity quarantine/reconciliation path for that `jti`/operation; never accept, mint, or report terminal revocation from uncertainty. This fence covers only the `/ws/game/**` gameplay-connect handshake; direct TCP/Telnet `LOGIN` does not consume this replay domain and follows its separate Account/Game Session authentication path. Region- and tenant-scoped resets preserve the shared replay domain. A replay-continuity loss trigger, including a cluster reset that invalidates this shared state, requires new gameplay handshakes to remain closed for the 30-second maximum connect-token lifetime plus two configured clock-skew intervals, followed by the required disposable-marker and durability-acknowledgement proof before readiness may admit tokens. The current generic Cache-bound writer emits only the untagged replay marker, with no deny/readiness/fence writer; that old replay key is migration-only drift and is quarantined/inventoried during cutover. This quarantine does not apply to unrelated tenant/region reset handling or Cache/Rate-Limit Redis. | +| `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` | **Coordination Redis** | Spring Cloud Gateway | Target security-critical, non-evicting single-use connect-token replay and browser-denial state. The literal `{gateway-connect-token-replay-v1}` tag co-slots replay, browser-deny, and readiness/fence keys for the atomic consume script; the readiness value carries `replayAdmissionFence`. A winning consume (`1`) and a browser-deny write require the configured same-connection, threshold-satisfying `WAITAOF` durability acknowledgement; a definitive consume (`0`/`-1`) is non-mutating and has no marker acknowledgement. An unavailable, timed-out, malformed, below-threshold, lost, or otherwise ambiguous consume/deny result or durability acknowledgement is unconfirmed: fail the handshake or revocation operation closed, keep the affected admission quarantined, and enter the replay-continuity quarantine/reconciliation path for that `jti`/operation; never accept, mint, or report terminal revocation from uncertainty. This fence covers only the `/ws/game/**` gameplay-connect handshake; direct TCP/Telnet `LOGIN` does not consume this replay domain and follows its separate Account/Game Session authentication path. Region- and tenant-scoped resets preserve the shared replay domain. A replay-continuity loss trigger, including a cluster reset that invalidates this shared state, requires new gameplay handshakes to remain closed until the later of the detection-time deadline (the 30-second maximum token lifetime plus two configured clock-skew intervals) and any later known affected-token `exp` plus one clock-skew interval. Admission remains closed until that deadline passes and the required fresh disposable-marker, durability-acknowledgement, and shared readiness proof succeeds. The exact deadline and reopen contract is owned by [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md). The current generic Cache-bound writer emits only the untagged replay marker, with no deny/readiness/fence writer; that old replay key is migration-only drift and is quarantined/inventoried during cutover. This quarantine does not apply to unrelated tenant/region reset handling or Cache/Rate-Limit Redis. | +| `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::` | **Coordination Redis** | Spring Cloud Gateway | Target-only Gateway-generated disposable recovery-probe marker in the same replay hash slot, separate from player `jti` and browser-deny markers. Gateway alone supplies its exact key/nonce/value; callers cannot redirect it to player keys. The marker has a finite bounded expiry and guarded cleanup/readback separate from the same-connection `WAITAOF`. The typed probe runs only while shared readiness is `QUARANTINED`, accepts no player JWT/`jti`/deny input, and never writes readiness. Only the recovery coordinator may authorize reopen after exact fenced probe evidence and every release gate; Gateway's owner-local helper performs the readiness CAS through its authenticated maintenance API. The probe is currently unimplemented. See [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md). | | `remote:{tenantInstanceTag}:` | **Coordination Redis** | Game Session Service / Automation & Scripting | Best-effort, TTL-bounded hint marker for remote participation scoped to the complete `` identity (typically “this entity has remote follow-ups due”). Default `remote_hint_ttl_ms = 60_000`. Region-scoped resets leave instance-scoped hints intact; tenant/cluster resets resolve every game instance from the durable scope inventory and enumerate `remote:{tenantInstanceTag}:*` per instance before removal. No tenant-only remote key family exists. | | `automation:timer:{tenantRegionTag}`, `script-scheduler:{tenantRegionTag}:lastTickId` | **Coordination Redis (target-only, once implemented)** | Automation & Scripting Service | Reserved target-only timer/checkpoint projections; they are not current runtime keys and have no current reset operation. Once implemented, they are reset-tolerant derived hints rebuilt from durable PostgreSQL schedules, trigger-instance rows, and heartbeat progress; they are never the source of truth for automation work. | | `tick-events:{tenantRegionTag}` and `tick-events-offset:{tenantRegionTag}:` | **Coordination Redis** | Game Session Service / Automation & Scripting | Best-effort tick event stream and per-consumer offsets used only as observer/wakeup hints. `tenantRegionTag` is the opaque encoding of the complete `` scope and must include `gameInstanceId`; no tenant-plus-region alias is valid. The key's `tenantRegionTag` and `` are authoritative for the event-offset scope; each offset payload stores `{tenantId, gameInstanceId, regionId, consumerId, region_epoch, latestTickId, streamOffset}` and is not a standalone scope identifier. It is discarded before reuse when `region_epoch` differs from the control-plane epoch. Stream retention is capped (default `tick_events_maxlen = 2048` per region). Correctness derives from committed heartbeats/RegionStatus plus durable schedules; missing/duplicated events must not change which schedules eventually fire. | diff --git a/design/architecture/system-architecture-redis-ops-access.md b/design/architecture/system-architecture-redis-ops-access.md index 318d61b0ed..03c442b599 100644 --- a/design/architecture/system-architecture-redis-ops-access.md +++ b/design/architecture/system-architecture-redis-ops-access.md @@ -69,7 +69,7 @@ To keep ACL usage consistent across services and documentation, Redis deployment | ACL User (example) | Intended Role | Typical Consumers | | --- | --- | --- | -| `coord_app` (logical profile; distinct principals) | Coordination application clients – may write and run Lua scripts against **Coordination Redis** only through their owner-local helper and within disjoint owner/contract key patterns | `account_coord_app` (Account-owned `session:auth:account:*`, `session:auth:tenant:*`, `session:auth:token:*`, `session:auth:generation:*`, legacy unversioned `session:connect-token:tenant:*`, and target `session:connect-token:v1:tenant:*`), `gateway_coord_app` (Gateway `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` only), `gamesession_coord_app` (Game Session `tick:*`, `timer:*`, `retry:*`, `session:game:*`, and the producer side of `tick-events:*`; stream publication uses `XADD` with bounded `MAXLEN`; any `tick-executor-lease:*` access is confined to the owner-local lease helper and its registered lease script, never to a workload-facing raw Redis path), and `automation_coord_app` (Automation-owned target coordination families such as `automation:timer:*` and `script-scheduler:*`; if a target scheduler consumes Redis Streams directly, its owner registration must bind the exact consumer-scoped `tick-events-offset:{tenantRegionTag}:` key, stream/consumer identity, caller principal, and registered script digest to one atomic compare-and-set helper. ACL/key patterns scope which keys and commands a principal may access but do not enforce compare-and-set semantics or restrict a script digest. Offset advancement must therefore go through one typed owner-local API/helper backed by that registered atomic CAS script, binding the exact consumer/key, expected current offset, monotonic next offset, script digest/version, and readback; no generic `SET` or direct Redis write call path is allowed. If direct Redis consumer access remains, its workload-facing principal is read-only (`GET`) for offset keys; the distinct owner-local executor path/principal is narrowly key-scoped and invoked only through the typed API. Its `tick-events:{tenantRegionTag}` stream pattern permits only `XREAD`/`XRANGE`, and its `tick-events-lease:{tenantRegionTag}` pattern permits only the owner-registered lease renewal/release script). Event-stream consumer identities, exact keys, and executable registrations must be complete before granting these latter permissions; absent that registration Automation uses the owner API/heartbeat contract and receives no direct stream or offset grant. Maintenance tooling is API-only and has no `coord_maintenance_app` principal. | +| `coord_app` (logical profile; distinct principals) | Coordination application clients – may write and run Lua scripts against **Coordination Redis** only through their owner-local helper and within disjoint owner/contract key patterns | `account_coord_app` (Account-owned `session:auth:account:*`, `session:auth:tenant:*`, `session:auth:token:*`, `session:auth:generation:*`, legacy unversioned `session:connect-token:tenant:*`, and target `session:connect-token:v1:tenant:*`), `gateway_coord_app` (Gateway `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:probe:*` only), `gamesession_coord_app` (Game Session `tick:*`, `timer:*`, `retry:*`, `session:game:*`, and the producer side of `tick-events:*`; stream publication uses `XADD` with bounded `MAXLEN`; any `tick-executor-lease:*` access is confined to the owner-local lease helper and its registered lease script, never to a workload-facing raw Redis path), and `automation_coord_app` (Automation-owned target coordination families such as `automation:timer:*` and `script-scheduler:*`; if a target scheduler consumes Redis Streams directly, its owner registration must bind the exact consumer-scoped `tick-events-offset:{tenantRegionTag}:` key, stream/consumer identity, caller principal, and registered script digest to one atomic compare-and-set helper. ACL/key patterns scope which keys and commands a principal may access but do not enforce compare-and-set semantics or restrict a script digest. Offset advancement must therefore go through one typed owner-local API/helper backed by that registered atomic CAS script, binding the exact consumer/key, expected current offset, monotonic next offset, script digest/version, and readback; no generic `SET` or direct Redis write call path is allowed. If direct Redis consumer access remains, its workload-facing principal is read-only (`GET`) for offset keys; the distinct owner-local executor path/principal is narrowly key-scoped and invoked only through the typed API. Its `tick-events:{tenantRegionTag}` stream pattern permits only `XREAD`/`XRANGE`, and its `tick-events-lease:{tenantRegionTag}` pattern permits only the owner-registered lease renewal/release script). Event-stream consumer identities, exact keys, and executable registrations must be complete before granting these latter permissions; absent that registration Automation uses the owner API/heartbeat contract and receives no direct stream or offset grant. Maintenance tooling is API-only and has no `coord_maintenance_app` principal. | | `entity_coord_app` | Entity Management's target Coordination Redis principal for its registered ConflictTracker entity producer; may write/run Lua only against `~conflict:entity:*` | Entity Management ConflictTracker producer scope; no `conflict:session:*` or other owner-family access | | `gamesession_coord_app` | Game Session's target Coordination Redis principal for its registered tick/session families and ConflictTracker session producer; its ConflictTracker grant is exactly `~conflict:session:*` | Game Session tick/session owner paths plus Game Session ConflictTracker producer scope; no `conflict:entity:*` access | @@ -461,7 +461,7 @@ The complete checklist and the applicable recovery release gates are mandatory f | Ledger convergence | No real tick-ledger row is created, advanced, or terminalized by smoke. The smoke check verifies that the real ledger is unchanged; `APPLIED`, `ABANDONED`, or other terminal outcomes from a synthetic durable row are not available until the separate isolation mechanism is decided. | | Cleanup | Any temporary probe lease or lock is released, no smoke-created `pending` state remains, and the sampled region is not considered in-flight. No durable batch or ledger cleanup is used as a substitute for isolation. | | Durable advancement | PostgreSQL `lastCommittedTickId`, the real tick ledger, and the real Redis tick metadata remain at their pre-smoke recovery values; real `tickId=0` is neither consumed nor authorized. | -| Replay-domain readiness | When the workflow affects the shared replay domain, trusted recovery calls Gateway's typed readiness-probe operation through the existing authenticated owning-service maintenance API boundary. The operation must return `DURABLE_REPLAY_CONSUME_ACK` before recovery reaches `AWAITING_RESUME`; Gateway's ownership, fence binding, consume, and durability contract is defined in [Gateway replay readiness](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake). This is target-only and currently unimplemented, so the checklist is not yet executable for this gate. Its result is distinct from `post_reset_replacement_verification/v1` and Account projection evidence, and does not itself enable normal player admission. | +| Replay-domain readiness | When the workflow affects the shared replay domain, trusted recovery invokes Gateway's typed readiness-probe operation through the existing authenticated owning-service maintenance API boundary. The probe runs while shared readiness remains `QUARANTINED`, conditionally writes a distinct Gateway-generated disposable probe marker on one pinned connection, and immediately issues configured `WAITAOF` on that connection with no intervening write; guarded cleanup/readback follows the acknowledgement. It returns `DURABLE_REPLAY_CONSUME_ACK` only after the acknowledgement and exact evidence readback; it neither consumes player credentials nor writes shared readiness. Only the recovery coordinator may authorize reopening after the deadline, exact fenced probe evidence, and every other release gate, with Gateway's owner-local helper performing the readiness CAS. Gateway's ownership and proof contract is defined in [Gateway replay readiness](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake). This is target-only and currently unimplemented, so the checklist is not yet executable for this gate. Its result is distinct from `post_reset_replacement_verification/v1` and Account projection evidence, and does not itself enable normal player admission. | | Scope sampling | For tenant- or cluster-scoped resets, the smoke check samples at least one representative region per affected executor/shard group rather than only one global region. | The high-level recovery workflow must compose these phases without inventing alternate write paths or omitting required steps such as command-record convergence. diff --git a/design/architecture/system-architecture-redis-reset-and-recovery.md b/design/architecture/system-architecture-redis-reset-and-recovery.md index f5598553b9..5d734fa9a3 100644 --- a/design/architecture/system-architecture-redis-reset-and-recovery.md +++ b/design/architecture/system-architecture-redis-reset-and-recovery.md @@ -247,7 +247,7 @@ A region- or tenant-scoped reset parent cannot claim global account- or issuer-i | `session:connect-token:v1:tenant::account::scope::request:` | Coordination | **Target exact-result projection; unavailable and not currently proven** | Region- and tenant-scoped coordination resets preserve this Account-owned projection once the target operation/envelope cutover is implemented. For a planned destructive cluster reset, Account’s durable issuance operation/response-envelope authority and immutable pre-wipe evidence must complete before the wipe; after reset, Account repairs and durably reads back the exact projection. For unexpected cold-start loss, handshakes remain fenced until Account performs exact repair and readback. Missing or untrusted results fail closed until the applicable identity expires; they must not be reconstructed from a JWT or silently reminted. | The target value requires `schemaVersion: "connect-token-issuance-result-v1"`; `scopeHash` and `requestHash` are fixed-length lowercase hexadecimal SHA-256 of canonical UTF-8 `connectScopeId` and `requestId`, respectively; the target reader/writer is isolated to this versioned prefix, uses durable SQL first-writer-wins before mint, and installs Redis with set-if-absent/read-winner. Exact repair only is permitted. See the [Account connect-token persistence contract](./microservices/account-service/runtime-and-data.md#connect-token-issuance-persistence-and-retention). | | `session:auth:generation:issuer:`, `session:auth:generation:account:`, `session:auth:generation:tenant:`, and `session:auth:generation:membership::` | Coordination | **Reset-sensitive, fail-closed by scope** | Region- and tenant-scoped coordination resets do not reset these untagged Account-owned projections; they leave unaffected scopes intact and re-project/verify every affected exact scope. A missing or lower Redis projection may be repaired with Account-owned idempotent set-if-greater. If that projection mutation is unavailable, the same Account-owned durable generation-mutation/repair operation is the fallback; an unavailable or ambiguous durable result keeps the scope fenced. A projection greater than Account durable authority is poisoned and must be quarantined or replaced through an Account-owned audited workflow, recreated from durable authority, and accompanied by immutable per-scope repair evidence before protected traffic reopens. A cluster-scoped reset may discard projections only after protected admission is closed and Account advances the issuer authority generation; Account then rebuilds and verifies every affected projection and current issued-token record before reopen. | Account's durable transactional generation is the sole authority. Redis is only a bounded projection/cache and must never become an alternate writer or reset baseline. No scoped coordination reset advances, deletes, or recreates these projection families; they remain outside gameplay session policy. | | `session:game:auth:issuer-generation:v1:` | Coordination | **Reset-sensitive, fail-closed by scope** | Region- and tenant-scoped coordination resets do not reset the Game Session issuer-generation consumer projection; affected scopes are reinstalled or reconciled from the exact Account-owned issuer checkpoint and read back before issuer-gated admission, reconnect, or revocation consumption. A cluster-scoped reset may discard it only after the Account repair/reset cutover and issuer-generation projection gates close protected admission; Game Session then installs the exact derived projection and verifies its complete source checkpoint before reopen. | Game Session owns only this derived consumer projection; Account's durable issuer generation and `session:auth:generation:issuer:` remain authoritative. No scoped coordination reset advances or recreates this projection from local state. | -| `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` | Coordination | **Reset-sensitive, fail-closed** | These shared Gateway replay-domain keys are an explicit exception to tenant/region key tagging and are untouched by region- or tenant-scoped resets. The readiness value carries `replayAdmissionFence` and all three keys share the literal hash tag `{gateway-connect-token-replay-v1}` for one Redis Cluster slot. If replay markers or browser-revocation deny markers are dropped or become untrusted, or fence/readiness continuity is uncertain, the reset advances the fence and rejects all new first-party gameplay handshakes for at least the maximum gameplay-connect lifetime (`30 seconds`) plus two configured clock-skew intervals. Reopen requires the same quarantine and disposable-marker proof: one fresh invocation of the canonical consume script must return `1` and create a disposable replay marker, followed by one same-connection `WAITAOF` local/replica durability acknowledgement meeting the configured thresholds. A `0` or `-1` result is non-mutating and cannot supply a second write acknowledgement; any cleanup is a separate guarded cleanup write/readback and is not part of `DURABLE_REPLAY_CONSUME_ACK`. This gate covers loss of either replay or deny markers and is in addition to, and cannot bypass, the Account cutover, issuer-generation projection rebuild/proof, and post-reset smoke ordering. The current generic Cache-bound writer emits only the untagged replay marker; it has no current deny-marker, readiness, or replay-fence writer. Migration requires quarantine, exact old replay-prefix inventory/readback, named Coordination client/ACL cutover, target-key readback, and retention or explicit cleanup of old markers through their original acceptance window. Resetting this replay state alone does not close already admitted WebSockets. A cluster reset closes affected gameplay sockets under its required explicit invalidation policy. | Consumed replay and deny markers are security-critical and non-evicting. The fence is advanced only after old marker state is dropped or rejected; quarantine and the single durability acknowledgement must complete before the readiness record reopens admission. Existing admitted WebSockets are unaffected by replay-state reset alone. | +| `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::` | Coordination | **Reset-sensitive, fail-closed** | These shared Gateway replay-domain keys are an explicit exception to tenant/region key tagging and are untouched by region- or tenant-scoped resets. The readiness value carries `replayAdmissionFence`; all four key families share the literal hash tag `{gateway-connect-token-replay-v1}` for one Redis Cluster slot. If replay markers or browser-revocation deny markers are dropped or become untrusted, or fence/readiness continuity is uncertain, the reset advances the fence and rejects all new first-party gameplay handshakes for at least the maximum gameplay-connect lifetime (`30 seconds`) plus two configured clock-skew intervals. While readiness remains `QUARANTINED`, the trusted recovery coordinator invokes Gateway's separate typed probe: Gateway conditionally writes its own disposable probe marker on one pinned connection, then obtains the configured same-connection `WAITAOF` acknowledgement. Gateway owns the probe key, nonce, and marker value; callers cannot redirect it to a player `jti` or deny prefix. The probe marker has a finite bounded expiry. The probe does not call the normal `OPEN`-only consume script or write shared readiness. Only the recovery coordinator may authorize reopening after the deadline, exact fenced probe evidence, and every other owner release gate; Gateway's owner-local helper performs the readiness CAS through the existing authenticated maintenance API. Exact-operation/fence-guarded cleanup and readback are separate from `DURABLE_REPLAY_CONSUME_ACK`. This gate covers loss of either replay or deny markers and is in addition to, and cannot bypass, the Account cutover, issuer-generation projection rebuild/proof, and post-reset smoke ordering. The current generic Cache-bound writer emits only the untagged replay marker; it has no current deny-marker, readiness, replay-fence, or recovery-probe writer. Migration requires quarantine, exact old replay-prefix inventory/readback, named Coordination client/ACL cutover, target-key readback, and retention or explicit cleanup of old markers through their original acceptance window. Resetting this replay state alone does not close already admitted WebSockets. A cluster reset closes affected gameplay sockets under its required explicit invalidation policy. | Consumed replay and deny markers are security-critical and non-evicting. The fence is advanced only after old marker state is dropped or rejected; quarantine and the recovery coordinator's separately gated release must complete before the readiness record reopens admission. Existing admitted WebSockets are unaffected by replay-state reset alone. See [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md) for the canonical probe and reopen contract. | | `remote:{tenantInstanceTag}:` | Coordination | **Reset-tolerant** | Cross-region follow-ups rely solely on durable tables; hints may be temporarily missing, increasing latency only. Region-scoped coordination resets leave instance-scoped hints intact; tenant- and cluster-scoped resets enumerate every affected game instance from the durable scope inventory and remove each instance's `remote:{tenantInstanceTag}:*` keys. | The complete key scope is `` because durable remote follow-up identity is instance-aware. These are best-effort cross-region wake-up hints only; dropping them affects latency, not correctness. Hint keys are TTL-bounded (default `remote_hint_ttl_ms = 60_000`) so stale hints age out automatically. | | `ratelimit:::*` and separately declared shared heuristics | Cache/Rate-Limit | **Reset-tolerant** | Rate-limit counters reset; future requests rebuild subject or shared-policy state from zero. | Each limiter declares whether reset temporarily weakens or tightens its heuristic and its unavailable-store behavior. Hard authorization, financial, durable-quota, or security invariants remain outside evictable Redis. | | `inventory:::*` | Cache/Rate-Limit | **Reset-tolerant** | Namespace-backed cached inventory/container aggregates are flushed; subsequent reads recompute views from PostgreSQL and repopulate Redis. | The cache scope is `(tenantId, playableStateNamespaceId, containerId)`; `playableStateScope` is separately validated evidence and is not inferred from the key. Inventories remain authoritative in PostgreSQL; cache loss affects latency only. | diff --git a/design/architecture/system-architecture-redis-usage-and-profiles.md b/design/architecture/system-architecture-redis-usage-and-profiles.md index d458ce8185..2bc168cc26 100644 --- a/design/architecture/system-architecture-redis-usage-and-profiles.md +++ b/design/architecture/system-architecture-redis-usage-and-profiles.md @@ -46,7 +46,7 @@ Scope-key convention: `{tenantRegionTag}` is the canonical opaque tag for the co - Automation coordination structures that participate in tick timelines under Automation & Scripting ownership and Game Session enqueue contracts. - Characteristics: - Treated as a long-running **coordination buffer with bounded tail-loss** in persistent environments; durable history for tick effects and gameplay outcomes lives in PostgreSQL tick effect ledgers and domain stores. - - Game Session owns its tick/session coordination prefixes and registered scripts, as well as the live and recent presence projection responsibility: gameplay coordination families such as `tick:*`, `timer:*`, `retry:*`, `tick-executor-lease:*`, and the target-only, once-implemented `tick-events:*` stream, plus the canonical `session:game:{tenantGameplayTag}::` records and their derived `session:game:index:*` projections. The separately approved `session:game:auth:issuer-generation:v1:*` consumer projection is a distinct family with its own ownership and recovery rules. Automation & Scripting is the target registered consumer owner for the corresponding `tick-events-offset:*` and `tick-events-lease:*` records; live integration uses `ObserveRuntimeTickProgress`. See the [tick event contract](./system-architecture-ticks.md#tick-events--heartbeat-stream). Account Service retains ownership of the current legacy `session:auth:account:*` and `session:auth:tenant:*` projections, the explicit `session:auth:token:*` and `session:auth:generation:*` families, legacy unversioned `session:connect-token:tenant:*`, and target `session:connect-token:v1:tenant:*` prefixes, and Automation & Scripting Service retains ownership of its other automation-specific prefixes and scripts as documented below; Game Session invokes those contracts but does not write them. + - Game Session owns its tick/session coordination prefixes and registered scripts, as well as the live and recent presence projection responsibility: gameplay coordination families such as `tick:*`, `timer:*`, `retry:*`, `tick-executor-lease:*`, and the target-only, once-implemented `tick-events:*` stream, plus the canonical `session:game:{tenantGameplayTag}::` records and their derived `session:game:index:*` projections. This projection responsibility does not assign the current physical `gameplaypresence:session:` or `accountrecentpresence::` prefixes to the Coordination Redis role; their storage-role classification and target key contract remain unproven. See the [Game Session runtime and data status](./microservices/game-session-service/runtime-and-data.md#implementation-status) and the [Redis owner and reset catalog](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). The separately approved `session:game:auth:issuer-generation:v1:*` consumer projection is a distinct family with its own ownership and recovery rules. Automation & Scripting is the target registered consumer owner for the corresponding `tick-events-offset:*` and `tick-events-lease:*` records; live integration uses `ObserveRuntimeTickProgress`. See the [tick event contract](./system-architecture-ticks.md#tick-events--heartbeat-stream). Account Service retains ownership of the current legacy `session:auth:account:*` and `session:auth:tenant:*` projections, the explicit `session:auth:token:*` and `session:auth:generation:*` families, legacy unversioned `session:connect-token:tenant:*`, and target `session:connect-token:v1:tenant:*` prefixes, and Automation & Scripting Service retains ownership of its other automation-specific prefixes and scripts as documented below; Game Session invokes those contracts but does not write them. - AOF enabled in `dev_local`, `hobby_self_hosted`, and `production_clustered`–like profiles. - Subject to tail‑loss SLOs and replay guarantees described in the Redis hub doc. - Example prefixes: @@ -281,7 +281,8 @@ Coordination and Cache/Rate‑Limit Redis are sized and configured differently. ### Coordination Redis - **Goal:** predictable restart behavior and bounded memory usage for coordination keys. -- **Recommendations:** +- **Requirements and recommendations:** + - Every non-ephemeral Coordination Redis profile must configure an explicit finite positive Redis `maxmemory` bound. Container and pod resource limits do not satisfy this Redis-level requirement. - `maxmemory-policy=noeviction` is mandatory for every non-ephemeral Coordination Redis profile. The only permitted deviation is an explicitly labelled ephemeral one-shot test/CI stack; any non-ephemeral deviation or observed eviction is fail-closed incident evidence. - Keep peak memory for coordination prefixes (`tick:*`, `timer:*`, `retry:*`, `session:game:*`, `session:auth:token:*`, `session:auth:generation:*`, `tick-executor-lease:*`, etc.) within the canonical Coordination Redis budget from `system-architecture-redis-operations.md` (normally **≤ 30–40% of `maxmemory`**). - Use AOF preamble and rewrite settings that keep AOF size within the budgets described in **Redis Operations & Migrations**. diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index fca3f6dfef..202909edbf 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -99,7 +99,7 @@ Redis coordination keys form a long-running, measured-exposure **coordination bu - Every issuer-generation projection, including the canonical `session:auth:generation:issuer:` projection and the Game Session `session:game:auth:issuer-generation:v1:` consumer projection, atomically stores `lastAppliedSourceOutboxSequence` (the accepted source `outboxSequence`) and `lastAppliedIssuerGeneration` for its exact canonical `outboxStreamKey`, plus `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` as derived source-checkpoint evidence for every nonzero sequence. These `lastAppliedSource*` fields are projection evidence associated with the canonical `outboxStreamKey`/`outboxSequence` and the applicable `outboxCheckpoints`; they are not authority-tuple fields or JWT claims. For sequence `0`, the two source-event fields are omitted from the projection, not serialized as JSON `null`, an empty string, a zero digest, or another sentinel; the Account-owned zero-sequence checkpoint is the only evidence. For every positive sequence, both source-event fields are required non-null values in their canonical formats. Ordinary delivered events may apply only the next contiguous sequence. A higher delivered sequence is a gap and must quarantine the affected projection and reconcile from Account before advancing the watermark or generation. The sole exception is one Account-owned authoritative snapshot/reconciliation installation, which may atomically install the exact Account checkpoint and generation at its latest sequence without consuming skipped events; that installation must carry the exact snapshot/checkpoint evidence and operation identity, and the next delivered event must be exactly one greater than the installed sequence. For each stream, the projection also retains bounded duplicate evidence for the most recent accepted sequences, at minimum `{outboxStreamKey, outboxSequence, eventId, eventDigest}`; each evidence entry has a required non-null `eventDigest`, and no entry represents the zero-sequence baseline. An equal or lower sequence is a no-op only when that bounded evidence matches or an authoritative Account lookup for the exact `(outboxStreamKey, outboxSequence)` proves the same event identity and digest; a high-water mark alone is never duplicate proof. If the evidence has aged out, the lookup is unavailable, or same-sequence evidence conflicts, the projection is quarantined. A valid next event advances the complete persisted checkpoint even when set-if-greater generation semantics leave the generation unchanged. The gameplay binding's separate `{outboxStreamKey, outboxSequence}` freshness set does not replace this projection-local replay evidence. Projection recovery fails closed while the checkpoint is missing, stale, regressed, ambiguous, or quarantined, including any invalid omitted/null/sentinel representation. - An empty Game Session issuer projection is an uninstalled and quarantined state, not an implicit zero-authority state and not permission to consume live events. Game Session, not Account, must install `session:game:auth:issuer-generation:v1:` from one Account-owned authoritative snapshot/reconciliation transaction for the exact `issuer/` scope and read back that installed derived projection. That transaction returns the exact checkpoint: `outboxStreamKey = account:auth-authority:v1:issuer/`, `lastAppliedSourceOutboxSequence` equal to the Account checkpoint's exact latest `outboxSequence`, and source `issuerAuthGeneration` from the same snapshot. For a nonzero sequence it also returns the exact source `eventId` and `eventDigest`; for sequence `0`, permitted only when the stream has no committed event, `lastAppliedSourceEventId` and `lastAppliedSourceEventDigest` are absent, and the Account-owned zero-sequence checkpoint itself is the evidence. The result also carries the source transaction or immutable bundle version, the exact checkpoint evidence, and the reconciliation operation identity; Game Session must not invent bootstrap event IDs, digests, sequences, or authority values locally. Before consuming events, Game Session atomically persists that complete checkpoint with the exact `issuerAuthGeneration` mapped to canonical persisted `lastAppliedIssuerGeneration`, stores matching `{outboxStreamKey, outboxSequence, eventId, eventDigest}` duplicate evidence only for a nonzero checkpoint, and reads back the installed projection. For a zero-sequence baseline, duplicate evidence is empty and the first consumable event must be sequence `1`; for a nonzero baseline, the next consumable event must be exactly `lastAppliedSourceOutboxSequence + 1`. Until the atomic installation and exact readback succeed, or if any applicable snapshot, source-checkpoint, event-identity/digest, or authority value is missing, stale, regressed, contradictory, or ambiguous, the projection remains quarantined and issuer-gated admission, reconnect, and revocation consumption fail closed. - Canonical issuer snapshot mapping is exact across bootstrap, persistence, readback, replay, and recovery: Account's authoritative snapshot field `issuerAuthGeneration` maps one-to-one to the projection field `lastAppliedIssuerGeneration`. The latter is the only persisted projection field used for comparison and replay advancement; `issuerAuthGeneration` is the source snapshot/authority name and is not a second persisted alias or a local fallback. Every bootstrap install, event replay, exact readback, set-if-greater repair decision, and recovery acknowledgement must compare the mapped value together with the exact `outboxStreamKey`, `lastAppliedSourceOutboxSequence`, source event evidence, and operation/checkpoint evidence. -- Spring Cloud Gateway has one narrow Coordination Redis authority: one-use connect-token replay consumption under `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, browser-revocation deny markers under `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, and the shared replay-readiness record under `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`. The readiness value carries the shared `replayAdmissionFence`. The Gateway fails closed when that replay authority is unavailable, owns the marker TTLs and reset contract, and must not expand this exception into ownership of gameplay sessions, Account auth state, or general coordination policy. +- Spring Cloud Gateway has one narrow Coordination Redis authority: one-use connect-token replay consumption under `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, browser-revocation deny markers under `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, the shared replay-readiness record under `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and a separate Gateway-generated disposable recovery-probe marker under `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`. The readiness value carries the shared `replayAdmissionFence`. Any marker-loss or reset event that can break replay continuity keeps shared readiness quarantined under an advanced `replayAdmissionFence` until the canonical [ADR 0029 readiness proof](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md) permits reopening; during that quarantine, an absent `jti` marker alone never proves first use. The probe marker is not a player `jti` or deny marker: its typed probe runs only in `QUARANTINED`, does not accept player credentials or write shared readiness, and returns evidence to the recovery coordinator. Normal player consume remains `OPEN`-only; only the coordinator may reopen after every release gate passes. The Gateway fails closed when that replay authority is unavailable, owns marker TTLs and reset contract, and must not expand this exception into ownership of gameplay sessions, Account auth state, or general coordination policy. These probe and release contracts are target-only and currently unimplemented. Game Session owns the live and recent account-presence projections described in [Game Session Runtime and Data](./microservices/game-session-service/runtime-and-data.md), but their current Redis shapes are implementation drift rather than accepted target authority. The live `gameplaypresence:session:`, `gameplaypresence:::sessions`, and `gameplaypresence::account::sessions` families, and the recent `accountrecentpresence::` family, currently use direct untagged writes with separate value/index mutations. Their exact owner scope, storage role, partial-write behavior, reset policy, rebuild/readback evidence, and private-by-failure semantics are not proven. These shapes must remain outside the accepted target key contract: the target owner projection requires an exact scope, atomic owner-controlled mutation, and a missing, stale, partial, or ambiguous projection must make presence private/unavailable rather than expose stale or cross-scope presence. The current families are cataloged in the reset matrix only to prevent an operator from treating an unregistered legacy shape as safe to delete, preserve, or use as authority. @@ -519,9 +519,9 @@ Gateway connect-token replay state is a narrow security-critical exception to th - **Canonical replay-domain pin:** Gateway owns the shared domain identity and carries it through the non-secret `FIREMUD_GATEWAY_REPLAY_DOMAIN` configuration value. The only accepted value is the versioned literal `gateway-connect-token-replay-v1`; it is not generated per pod, tenant, region, deployment attempt, or reset. This fixed literal is the complete shared replay namespace: tenant, game, and region identifiers are intentionally not additional key components. Target Gateway startup and deployment preflight must reject a missing, unknown, or mismatched value, and every target key helper, ACL/prefix declaration, migration, reset, and recovery tool must use the exact hash tag `{gateway-connect-token-replay-v1}`. -- The target key shapes are `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`. The readiness value carries `replayAdmissionFence`, state, cutoff, and quarantine fields. All three keys contain the same literal `{gateway-connect-token-replay-v1}` hash tag and therefore share one Redis Cluster slot; matching [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md), the consume script receives `KEYS[1]=readiness`, `KEYS[2]=replay jti`, and `KEYS[3]=deny jti` and **must atomically validate readiness state, the signed fence and cutoff, and deny-marker absence, then create the replay marker in that same operation**. Replay and deny marker expiries are absolute at `token.exp + firemud.gateway.connectTokenClockSkewMs`; neither marker is refreshed, extended from consumption time, or replaced with a fixed 30-second TTL. The deployed clock-skew setting is the single `FIREMUD_GATEWAY_CONNECT_TOKEN_CLOCK_SKEW_MS` value, default `5000` ms and bounded to `0..5000` ms. +- The target key shapes are `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`. The readiness value carries `replayAdmissionFence`, state, cutoff, and quarantine fields. All four key families contain the same literal `{gateway-connect-token-replay-v1}` hash tag and therefore share one Redis Cluster slot; matching [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md), the normal consume script receives `KEYS[1]=readiness`, `KEYS[2]=replay jti`, and `KEYS[3]=deny jti` and **must atomically validate `OPEN` readiness, the signed fence and cutoff, and deny-marker absence, then create the replay marker in that same operation**. Normal consume is never called during quarantine. The separate recovery probe uses only the Gateway-generated disposable probe marker while readiness remains `QUARANTINED`, does not consume player JWT/`jti`/deny state, and cannot mutate shared readiness; the recovery coordinator alone may reopen after exact fenced proof and all owner gates. Replay and deny marker expiries are absolute at `token.exp + firemud.gateway.connectTokenClockSkewMs`; neither marker is refreshed, extended from consumption time, or replaced with a fixed 30-second TTL. The deployed clock-skew setting is the single `FIREMUD_GATEWAY_CONNECT_TOKEN_CLOCK_SKEW_MS` value, default `5000` ms and bounded to `0..5000` ms. See [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md) for the canonical recovery-probe binding and reopen sequence. - The target deployment has one shared replay-continuity domain, so replay markers, deny markers, and the shared `replayAdmissionFence` are not tenant- or region-partitioned even though their physical keys use the fixed slot tag. Region- and tenant-scoped coordination resets must leave the Gateway replay and deny-marker prefixes and readiness record untouched and must not invalidate connect tokens solely because gameplay coordination in that narrower scope was reset. If either reset cannot prove that the shared replay domain was untouched and continuous, it escalates to the same shared quarantine rather than attempting a narrower fence. The current writer emits only the untagged replay marker `gateway:connect-token:jti:` through the generic Cache-bound client; it has no current deny-marker, readiness, or replay-fence writer. These are migration-only implementation gaps, not target state. Migration and recovery use the owner-defined quarantine, exact old-prefix inventory/readback of `gateway:connect-token:jti:*`, named Coordination client/ACL cutover, target-key readback, and retention or explicit cleanup of old markers through their original acceptance window before reopening admission; the broad `gateway:connect-token:*` selector is forbidden for migration, reset, and ACL boundaries because it also matches tagged target keys; see [Redis Reset & Recovery](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary). -- A cluster-scoped Coordination Redis reset, loss of replay or deny-marker continuity, uncertain failover, eviction, capacity breach, or durability-acknowledgement failure invalidates the shared replay domain. The reset drops or makes untrusted all replay markers, deny markers, and readiness state, advances the shared fence, rejects new first-party handshakes for at least the maximum gameplay-connect lifetime (`30 seconds`) plus two configured clock-skew intervals after the recorded detection cutoff, and reopens only after the configured disposable-marker plus `WAITAOF` proof establishes `DURABLE_REPLAY_CONSUME_ACK`. Existing WebSockets are not closed by replay-state reset alone; the broader cluster reset separately requires explicit gameplay-session invalidation. +- A cluster-scoped Coordination Redis reset, loss of replay or deny-marker continuity, uncertain failover, eviction, capacity breach, or durability-acknowledgement failure invalidates the shared replay domain. The reset drops or makes untrusted all replay markers, deny markers, probe markers, and readiness state, advances the shared fence, and rejects new first-party handshakes for at least the maximum gameplay-connect lifetime (`30 seconds`) plus two configured clock-skew intervals after the recorded detection cutoff. While readiness remains `QUARANTINED`, the separate Gateway-owned probe must establish configured `WAITAOF` durability; only the recovery coordinator may reopen after exact fenced probe evidence and every other release gate. The probe alone never reopens admission. Existing WebSockets are not closed by replay-state reset alone; the broader cluster reset separately requires explicit gameplay-session invalidation. - A future partitioned replay deployment may narrow quarantine to a proven marker/fence domain only after its topology and reset contract establish that isolation. It must not be inferred from a tenant or region label in the current shared deployment. --- @@ -627,6 +627,7 @@ Key principles: - **Coordination vs cache prefixes** - Canonical coordination prefixes (for example `tick:*`, `timer:*`, `retry:*`, `session:game:*`, `session:auth:token:*`, `session:auth:generation:*`, the target exact-result `session:connect-token:v1:tenant::account::scope::request:` family, `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and `tick-executor-lease:*`) live **only** on Coordination Redis. The current legacy Account result map remains at the separate unversioned `session:connect-token:tenant::account::scope::request:` family and is not parsed as target. The shared `replayAdmissionFence` is a field in `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, not a physical prefix. The current generic Cache-bound writer's untagged `gateway:connect-token:*` replay marker is migration-only implementation drift, not a current canonical Coordination Redis prefix or authority. + - Gateway's recovery-only disposable marker family `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::` is a separately registered Coordination Redis prefix owned by Gateway. Its ACL and reset inventories are distinct from player `jti`, deny, and readiness data; see the target-only probe contract in [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md). - Cache and rate‑limit prefixes (for example `inventory:*`, `view:room-look:*`, `ratelimit:*`) live **only** on Cache/Rate‑Limit Redis. - Coordination prefix ownership is normative: Account owns the live legacy `session:auth:account:*` and `session:auth:tenant:*` projections, the target `session:auth:token:*` exact-token registry, the target `session:auth:generation:*` authority-generation projections, and the target `session:connect-token:*` exact-input issuance-result projections. Gateway owns only the shared replay-domain exception: `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` carrying `replayAdmissionFence`; this does not grant gameplay-session, Account-auth, or general coordination ownership. Game Session owns the separately approved gameplay families under `session:game:*`, including `session:game:auth:issuer-generation:v1:`; it never owns the Account auth or connect-token issuance prefixes, and no wildcard `session:auth:*` grant is implied. Game Session also owns `tick:*`, `timer:*`, `retry:*`, and `tick-executor-lease:*`; it does not own or mutate the target-only, unimplemented Automation & Scripting families `automation:timer:*` or `script-scheduler:*`. The retired `automation:tick:*` staging path is not part of the live design or active prefix inventory. Automation & Scripting owns its current automation prefixes and the reserved target families once implemented, while its Cache/Rate-Limit families `automation:queue:*`, `automation:quota:*`, `automation:tenant-budget:*`, `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` remain separate; non-owner participation is contract-bound through approved helpers. The shared `conflict:*` diagnostic family is Coordination-only, reset-tolerant, and non-authoritative: `common-data-runtime` owns the mutation helper, while Game Session and Entity Management own the producer scopes that call it. Its target deployed principals are distinct: `entity_coord_app` has the exact `~conflict:entity:*` grant and no `conflict:session:*` or other owner-family grant, while `gamesession_coord_app` has the exact `~conflict:session:*` grant in addition to its separately registered Game Session families and no `conflict:entity:*` grant. No shared principal, generic maintenance principal, or helper-library identity may cross those producer-owner boundaries. Current `conflict:entity::` and `conflict:session::` writes use the generic Redis client and separate `INCR`/`EXPIRE` calls with warning-only expiry failure; both endpoint placement and mutation shape are implementation drift. The target accepts only those registered producer kinds and canonical scope identifiers, permits one key per admitted producer scope, enforces a finite deployment key-cardinality cap with overflow sampled or aggregated rather than creating arbitrary keys, and uses a 300-second inactivity TTL unless an owner-approved profile states a shorter bound. The target uses named Coordination clients and these distinct `coord_app` principals only, never cache ACLs, and converges the mutation through a registered single-key atomic helper/script that performs both `INCR` and `PEXPIRE` on every accepted increment so the inactivity TTL is refreshed atomically. The existing `RedisAtomicOperations.incrementWithTtl` helper sets expiry only when the count is first created and therefore does not satisfy this sliding-inactivity contract unless it is extended; this is target guidance, not a claim that the current tracker implements it. The live Entity `TickLockServiceImpl` `tick:lock::` family is an unscoped implementation-drift writer, not a second Game Session authority; it remains fenced/unregistered for target reset and admission until routed through the canonical full-runtime-scope helper. See `design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md`, with later canonical owner contracts including ADR 0029 defining the Gateway replay carrier. diff --git a/design/architecture/system-architecture-scripting-contracts.md b/design/architecture/system-architecture-scripting-contracts.md index dfee640d45..ca6a5544ff 100644 --- a/design/architecture/system-architecture-scripting-contracts.md +++ b/design/architecture/system-architecture-scripting-contracts.md @@ -49,7 +49,7 @@ To make script patch rollback meaningful: - On execution, Game Session must enforce a **version fence**: - If a command’s `scriptPatchVersion` does not match the game instance’s currently pinned `scriptPatchVersion`, Game Session must not execute it. - If a command’s `scriptPinEpoch` does not match the game instance’s current epoch, Game Session must not execute it, even when the patch version is identical. - - **Target state:** rejection must retain the complete applicable parent event-scope/Trigger Identity (`tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`, `entityId`, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch`, `scriptEventId`, `isDryRun`, plus producer-derived `sourceService` when the event is custom or service-specific, and plugin/binding and scheduler fields when applicable), together with the paired `scriptPinControlPlaneRequestId` as required owner evidence/correlation and the complete Command-Handoff Identity, including `outboxWorkItemId` as parent correlation and optional distinct target fields (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, `targetRegionEpoch`). The server-derived source and target `playableStateScope` values remain separately persisted, exact-validated policy/routing/authorization/fence evidence and are not identity fields. This evidence lets operators diagnose exactly which fan-out command was dropped; a child rejection must not be reduced to one handler-level disposition. The live fallback records the narrower work-item, command, and available dispatch fields in the current handoff/audit surfaces until `AS-1.5` is complete. + - **Target state:** rejection must retain the complete applicable parent event-scope/Trigger Identity (`tenantId`, `gameInstanceId`, `playableStateNamespaceId`, `regionId`, `regionEpoch`, `entityId`, `scriptId`, `eventType`, `eventSchemaVersion`, `scriptPatchVersion`, `scriptPinEpoch`, `scriptEventId`, `isDryRun`, plus producer-derived `sourceService` when the event is custom or service-specific, and plugin/binding and scheduler fields when applicable), together with the paired `scriptPinControlPlaneRequestId` as required owner evidence/correlation. It must separately retain the complete Command-Handoff Identity: required source runtime fields, dispatch/ordinal, and applicable distinct target runtime fields (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, `targetRegionEpoch`); parent `outboxWorkItemId` is retained only as correlation and is not part of that identity. The server-derived source and target `playableStateScope` values remain separately persisted, exact-validated policy/routing/authorization/fence evidence and are not identity fields. This evidence lets operators diagnose exactly which fan-out command was dropped; a child rejection must not be reduced to one handler-level disposition. The live fallback records the narrower work-item, command, and available dispatch fields in the current handoff/audit surfaces until `AS-1.5` is complete. The canonical [Table 2 identity owner](./system-architecture-scripting-normative-contract-tables.md#table-2-command-handoff-identity) defines the exact identity fields. - Parent `outboxWorkItemId` and Trigger Identity fields are correlation-only; they are excluded from child uniqueness, deduplication, and replay selection (see the [normative identity tables](./system-architecture-scripting-normative-contract-tables.md#table-2-command-handoff-identity)). - Rejected entries must be removed or moved to a bounded dead-letter store with explicit `maxAge`/`maxRows` and alert-backed cleanup cadence. - Before schedule admission resumes under a new `scriptPinEpoch`, durable or resumable-idempotent reconciliation must fence or terminalize pending old-epoch occurrences and claims, and every old-epoch enqueue attempt must fail. Rollback may still cancel or purge displaced rows asynchronously for bounded resource use, but that cleanup is not the admission or mutation correctness barrier. The epoch fence at each persistence, handoff, staging, replay, and final effect boundary remains authoritative; ordinary player commands and ticks continue unless an explicitly declared unfenced effect requires an exceptional pause. 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 545ab5de52..e09114a7c6 100644 --- a/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md +++ b/design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md @@ -101,7 +101,7 @@ The required Trigger Identity fields and target-scope exceptions are defined in | 3 | **Script work item** | For each admitted resolved handler, one durable parent work item owns the applicable Trigger Identity and pre-DSL lifecycle; when it reaches `EVALUATED_COMMITTED`, it gains immutable evaluated command descriptor/child-dispatch rows, one per emitted command, with version metadata. A handler denied before work-item materialization has no parent work item. The descriptor rows have independent handoff statuses while the parent marker remains the recovery boundary. | **Target state only:** each work item/descriptor and queue-index pointer retains and exact-validates authoritative `playableStateNamespaceId`, with `playableStateScope` separately exact-validated; an `outboxWorkItemId` alone is not isolation evidence. The displayed `automation:queue:{tenantInstanceTag}:` is the current pointer-key shape, not a target identity contract. **Current implementation:** that queue is only a derived pre-DSL parent-work pointer projection for `PENDING_EVALUATION`/`EVALUATING`, not an evaluated-command descriptor index or proof of namespace isolation. | | 4 | **Tick command** | A concrete command that the Game Session Service executes during game ticks under its normal locking and idempotency rules. | Enqueued into `tick:{tenantRegionTag}:queue:` for consumption by the tick loop. | -Admitted triggers lead to durable parent work items, and their DSL runs execute within those parents. **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. +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. diff --git a/design/architecture/system-architecture-scripting-normative-contract-tables.md b/design/architecture/system-architecture-scripting-normative-contract-tables.md index a88dc3b01f..2641275542 100644 --- a/design/architecture/system-architecture-scripting-normative-contract-tables.md +++ b/design/architecture/system-architecture-scripting-normative-contract-tables.md @@ -83,7 +83,7 @@ Additional required fields for scheduler/timer triggers: Plugin-owned schedule rows, due candidates, firing claims, candidate audits, and timer-derived work retain the captured `lifecycleRevision` alongside `pluginActivationEpoch`. The revision is fence evidence only: before a new firing claim or handler admission, the scheduler must observe the exact current lifecycle tuple and require the current revision in `ENABLED`; it may not use the `DRAINING` predecessor exception for a new firing. A same-epoch lifecycle revision change fences the old candidate under its existing identity and does not mint a fresh candidate identity merely because the revision changed. Already-admitted work may use the narrowly retained immediately preceding `ENABLED` revision only with ADR 0119's durable pre-`DRAINING` admission/fence evidence and same-version/same-epoch rule. -Before handler resolution, a scheduler/timer firing claim is keyed by the complete durable logical schedule/event identity: the stable logical schedule continuity fields together with exact `scriptPatchVersion` and `scriptPinEpoch`, `isDryRun`, applicable runtime scope, target selector, trigger mode, and tagged due point; when `triggerMode=CATCH_UP`, `resumeWindowId` is additionally required and participates in claim uniqueness and `scriptEventId` derivation, and it is absent otherwise. The physical `scheduleInstanceId` is retained only as immutable row-generation metadata for durable lookup and reconciliation; it is explicitly excluded from `scheduleCandidateId`, firing-claim uniqueness, and `scriptEventId` derivation. The logical identity therefore includes schedule-owned `scriptId` and any schedule-owned `pluginId`, `pluginVersionId`, and `bindingId`; for plugin-owned candidates, the captured `pluginActivationEpoch` is an additional tagged field in the local `scheduleCandidateId`/firing-claim uniqueness key, while core-script candidates omit it. Same-epoch retries reuse that candidate identity only while the complete captured fence evidence remains current; for plugin-owned schedules, a same-version disable/re-enable derives a fresh candidate identity from the newer `pluginActivationEpoch`. `pluginActivationEpoch` is not a separate handler Trigger Identity field: it is included in the candidate, firing-claim, and candidate-audit identities and is an input to the scheduler-derived `scriptEventId`, so a fresh activation epoch yields a fresh event ID transitively in every resolved handler identity. Core schedule transition identity changes only through the accepted exact `scriptPatchVersion`/`scriptPinEpoch` contract; no separate core epoch is implied. It must not fabricate fields absent from the durable schedule. Candidate audits use that same complete due-candidate identity, including the exact patch and epoch, `isDryRun`, captured plugin activation epoch when applicable, and `resumeWindowId` only for `CATCH_UP`. This owner-known firing identity is distinct from the ordinary producer event-ingress key below and derives the one event-scope `scriptEventId` propagated to resolved handlers. After resolution, each plugin child uses the captured handler execution identity above; only scheduler candidate/firing-claim/audit identities include activation epoch directly, while the scheduler-derived `scriptEventId` makes it differ transitively in the handler Trigger Identity. `lifecycleRevision` is retained and revalidated alongside it as non-identity fence evidence and is not added to those identities. Neither lifecycle value is part of Command-Handoff Identity, stable schedule-row identity, or the stable continuity key. Durable schedule rows, due candidates, firing claims, candidate audits, and list/read projections persist and expose the exact plugin activation epoch and captured lifecycle revision as fence evidence; `scriptPinEpoch` remains execution/fence metadata and is excluded from the stable continuity key. +Before handler resolution, a scheduler/timer firing claim is keyed by the complete durable logical schedule/event identity: the stable logical schedule continuity fields together with exact `scriptPatchVersion` and `scriptPinEpoch`, `isDryRun`, applicable runtime scope, target selector, trigger mode, and tagged due point; when `triggerMode=CATCH_UP`, `resumeWindowId` is additionally required and participates in claim uniqueness and `scriptEventId` derivation, and it is absent otherwise. The physical `scheduleInstanceId` is retained only as immutable row-generation metadata for durable lookup and reconciliation; it is explicitly excluded from `scheduleCandidateId`, firing-claim uniqueness, and `scriptEventId` derivation. Core-owned schedules include their schedule-owned `scriptId`; plugin-owned schedules use their schedule-owned `pluginId`, `pluginVersionId`, and `bindingId` without adding a synthetic `scriptId`. For plugin-owned candidates, the captured `pluginActivationEpoch` is an additional tagged field in the local `scheduleCandidateId`/firing-claim uniqueness key, while core-script candidates omit it. Same-epoch retries reuse that candidate identity only while the complete captured fence evidence remains current; for plugin-owned schedules, a same-version disable/re-enable derives a fresh candidate identity from the newer `pluginActivationEpoch`. `pluginActivationEpoch` is not a separate handler Trigger Identity field: it is included in the candidate, firing-claim, and candidate-audit identities and is an input to the scheduler-derived `scriptEventId`, so a fresh activation epoch yields a fresh event ID transitively in every resolved handler identity. Core schedule transition identity changes only through the accepted exact `scriptPatchVersion`/`scriptPinEpoch` contract; no separate core epoch is implied. It must not fabricate fields absent from the durable schedule. Candidate audits use that same complete due-candidate identity, including the exact patch and epoch, `isDryRun`, captured plugin activation epoch when applicable, and `resumeWindowId` only for `CATCH_UP`. This owner-known firing identity is distinct from the ordinary producer event-ingress key below and derives the one event-scope `scriptEventId` propagated to resolved handlers. After resolution, each plugin child uses the captured handler execution identity above; only scheduler candidate/firing-claim/audit identities include activation epoch directly, while the scheduler-derived `scriptEventId` makes it differ transitively in the handler Trigger Identity. `lifecycleRevision` is retained and revalidated alongside it as non-identity fence evidence and is not added to those identities. Neither lifecycle value is part of Command-Handoff Identity, stable schedule-row identity, or the stable continuity key. Durable schedule rows, due candidates, firing claims, candidate audits, and list/read projections persist and expose the exact plugin activation epoch and captured lifecycle revision as fence evidence; `scriptPinEpoch` remains execution/fence metadata and is excluded from the stable continuity key. For scheduler/timer identities, the applicable `playableStateNamespaceId` is the durable playable-state identity component carried in the schedule instance, due candidate, firing claim, candidate audit, and derived `scriptEventId`. The server-derived `playableStateScope` is retained alongside those records as separately persisted exact-validated policy/routing/authorization/migration-fence evidence; it is not added to schedule, candidate, firing-claim, event-scope, or handler uniqueness. Missing or mismatched scope evidence fails closed and fences admission until authoritative reconciliation. Only a stale or incorrect presented scope with unchanged authoritative scope may resume the existing namespace-keyed identity; an authority-proven scope transition starts a new playable-state lifecycle and namespace before fresh schedule state is admitted. @@ -339,7 +339,7 @@ The exact resume formula, modulo-zero boundary behavior, and runtime scope/epoch ### Version-Owned Durable Schedule Migration (Normative) -- `scheduleDefinitionId` participates in the stable logical continuity key but is not the durable row or trigger-claim identity. For a playable-state-scoped schedule, the continuity key is `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}`; `playableStateScope` is separately persisted exact-validated policy/routing/authorization/migration-fence evidence and is not a continuity-key component. `pluginId` is the stable plugin owner while `pluginVersionId`, `scriptPatchVersion`, and `scriptPinEpoch` remain provenance and exact execution-fence metadata. +- `scheduleDefinitionId` participates in the stable logical continuity key and the complete durable row/trigger-claim identity, but is never sufficient as a standalone row or claim identity. For a playable-state-scoped schedule, the continuity key is `{stableOwnerKind, stableOwnerId, scheduleDefinitionId, playableStateNamespaceId, targetScopeType, targetScopeId}`; `playableStateScope` is separately persisted exact-validated policy/routing/authorization/migration-fence evidence and is not a continuity-key component. `pluginId` is the stable plugin owner while `pluginVersionId`, `scriptPatchVersion`, and `scriptPinEpoch` remain provenance and exact execution-fence metadata. - By default, a version transition tombstones the displaced interval and creates a target interval with fresh due state when a validated target definition exists. When authoritative reconciliation proves the target definition is absent, reconciliation follows the [scheduler owner rule](./system-architecture-scripting-scheduler-and-timers.md#explicit-continuity-across-script-transitions): it fences admission and atomically tombstones the displaced interval, terminalizes any proven-displaced candidates under their original identities as applicable, creates no replacement row, due state, firing claim, or `scriptEventId`, and never rebinds existing candidates or claims. If target-definition or other required authority is unavailable, contradictory, or ambiguous, reconciliation must not tombstone or create replacement state; it retains the displaced row, candidates, and claims fenced and nonterminal until authority reconciles. Only a later validated target reconciliation may create fresh state and identities. Carrying due state requires explicit compatible continuity declarations on both sides, `source.isDryRun == target.isDryRun`, typed interval/cadence/target/playable-scope checks, and an exact pin/epoch transition: validate the prior/source `(scriptPatchVersion, scriptPinEpoch)` tuple and target tuple independently; they may differ across the transition, and both remain provenance and execution-fence metadata rather than members of the stable continuity key. A same-version repin is still a new epoch transition: the transition must atomically or resumably reconcile the stable row and retire or rewrite all displaced mutable schedule state, due candidates, and current list/read projections before admission resumes. Old-epoch firing claims retain their original exact `(scriptPatchVersion, scriptPinEpoch)` and `resumeWindowId`, and only pending claims may be fenced or terminal-marked; claims already in handoff reconcile the downstream outcome under their original exact fence. Neither pending-claim fencing/terminalization nor in-handoff reconciliation creates a new firing claim, handler identity, or `scriptEventId`. Immutable candidate-audit identity, outcome, exact tuple, and `resumeWindowId` are never rewritten. A transient due-candidate state/claim keyed by `scheduleCandidateId` may remain fenced while reconciliation is pending. It may settle into the one firing path only while its original exact `(scriptPatchVersion, scriptPinEpoch)` tuple and every applicable authoritative binding, runtime-scope, owner, and plugin lifecycle fence (including the captured `(pluginActivationEpoch, lifecycleRevision)` pair when applicable) remain current, or into one immutable terminal candidate audit. If authoritative evidence proves any applicable fence displaced, terminalize the candidate under its original identity with the applicable bounded terminal outcome/reason and create no firing claim or `scriptEventId`; if authority is unavailable, contradictory, or ambiguous, retain the fenced candidate as nonterminal until reconciled. It is never rebound to a new scope or epoch. `scheduleSemanticsHash` is diagnostic evidence only; equality cannot grant continuity. Replacement creation and retirement are one atomic durable result or a resumable, idempotent operation keyed by `controlPlaneRequestId`. - The preceding playable-scope checks validate separately persisted server-derived policy/routing/authorization/fence evidence; they do not add `playableStateScope` to continuity, candidate, or Trigger Identity. A presented scope mismatch remains fenced until authoritative reconciliation; only unchanged authoritative scope permits the existing namespace-keyed identity, while an authority-proven scope-policy transition starts a new playable-state lifecycle and namespace. - A new version/namespace-owned entry, or a target entry created after a namespace transition, must derive a new scheduler trigger claim and `scriptEventId`; a matching `scheduleDefinitionId`, due point, handler, or old `playableStateNamespaceId` must never be used to reuse a Trigger Identity across the migration. A presented `playableStateScope` mismatch remains an admission/migration fence requiring authoritative reconciliation and exact evidence validation; an authority-proven transition must allocate the new namespace before fresh identity, and no path may silently reuse the old identity while fenced. diff --git a/design/architecture/system-architecture-tick-concepts-and-invariants.md b/design/architecture/system-architecture-tick-concepts-and-invariants.md index 903d2b2b89..233b0423cf 100644 --- a/design/architecture/system-architecture-tick-concepts-and-invariants.md +++ b/design/architecture/system-architecture-tick-concepts-and-invariants.md @@ -132,7 +132,7 @@ Timer sources (including cooldowns, regeneration, and delayed effects) carry exa - Per-region projections such as `timer:{tenantRegionTag}` must preserve the tag and value for each member; a sorted-set score or other index representation must not imply a shared numeric domain. Tick IDs and epoch-millisecond values are never compared or aliased. - Wall-clock eligibility uses one consistent application time source (NTP-synchronized wall clock); tick eligibility uses the committed region heartbeat/timeline. Redis server time is not used for either comparison. - Drained with bounded work per tick (for example, up to `game.tick-max-timers` timers per region per tick) so delayed or bursty timers do not turn a single tick into unbounded work. -- Implemented using deterministic, idempotent Lua scripts that accept explicit caller-supplied `currentTickId` and, when evaluating a wall-clock source, `now_ms` values as `ARGV`; scripts must not call Redis `TIME`, and AOF replay reuses the same arguments. +- Implemented using deterministic, idempotent Lua scripts that accept explicit caller-supplied `currentTickId` and, when evaluating a wall-clock source, `now_ms` values as `ARGV`; scripts must not call Redis `TIME`. Under Redis 7.2+ effect-based script replication, the AOF records the script's write effects and restart replays those recorded commands; it does not rerun the Lua script with the original `ARGV` values. `ARGV` fixes the time/tick inputs for the original execution. See the official [Redis scripting and effects-replication documentation](https://redis.io/docs/latest/develop/interact/programmability/eval-intro/). All writes to timer keys (`timer:{tenantRegionTag}`) are performed under the same region lease and Lua scripts as tick processing; domain services must not modify timer keys via ad-hoc Redis commands. This keeps timers and command queues in the same concurrency domain. diff --git a/design/architecture/system-architecture-tick-execution-flows.md b/design/architecture/system-architecture-tick-execution-flows.md index d949c86eec..2dd505f784 100644 --- a/design/architecture/system-architecture-tick-execution-flows.md +++ b/design/architecture/system-architecture-tick-execution-flows.md @@ -63,10 +63,10 @@ Within a region’s tick, root actor commands and their effects proceed through - Writers must persist `target_region_epoch` and `due_tick_id` from the same status read so retries and failover cannot shift eligibility non-deterministically. - Optionally writes a best-effort Redis hint marker such as `remote:{tenantInstanceTag}:` (for the target entity, with the tag derived from the target ``) to reduce latency when the target region drains follow-ups. - If the command needs to wait for remote completion, the origin region creates or updates a separate durable cross-region coordinator record. This waiting state is **not** kept as a non-terminal row inside the origin tick batch. - - The target `ScheduleRequest`, coordinator, follow-up, and origin-addressed result projections share the complete target scope `(targetGameInstanceId, targetPlayableStateNamespaceId, targetPlayableStateScope, targetRegionId, targetRegionEpoch, dueTickId)` and the immutable request digest covering that scope, exact target identity, operation, and sealed manifest binding. Each projection preserves these fields for exact replay/result equality checks; a missing, conflicting, or mismatched namespace, scope, target, or digest fails closed. - - Minimum coordinator fields include durable `coordinatorId`, `tenantId`, `originCommandId`, `originGameInstanceId`, `originRegionId`, `originRegionEpoch`, `originTickId`, target scope (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`, `dueTickId`), exact target aggregate (`targetAggregateType`, `targetAggregateId`), the originating `originEffectId` and distinct target-leg `targetEffectId`, target-leg `typedOperation`, immutable `requestDigest`, and the sealed required-participant manifest (or immutable manifest reference plus digest). These identity/binding fields are compared on replay and a missing or conflicting value fails closed. The lifecycle is (`PENDING_REMOTE`, `REMOTE_APPLIED`, `REMOTE_ABANDONED`, `REMOTE_TIMEOUT_ABANDONED`, `LATE_RESULT_IGNORED`, `LATE_RESULT_RECONCILED`), with origin-timeline deadline (`originDeadlineRegionEpoch`, `originDeadlineTickId`; storage may use names such as `remote_deadline_region_epoch` / `remote_deadline_tick_id`), final player-facing/result-facing projection fields when applicable (`executionOutcome`, `gameplayResult`), and `updatedAt`. - - Target completion is returned through one durable origin-owned result path, not an unspecified transient message: - - the target leg writes an origin-addressed result or inbox row keyed to `coordinatorId` and repeats `originCommandId`, `originGameInstanceId`, origin region/epoch/tick, target game instance, `targetPlayableStateNamespaceId`, `targetPlayableStateScope`, target region/epoch and `dueTickId`, the distinct target `targetEffectId`, typed operation, exact target aggregate, and one immutable follow-up binding/digest reference that binds the request digest and sealed-manifest context, + - The target `ScheduleRequest`, coordinator, follow-up, and origin-addressed result projections share the complete target scope `(targetGameInstanceId, targetPlayableStateNamespaceId, targetPlayableStateScope, targetRegionId, targetRegionEpoch, dueTickId)` and the immutable request digest covering that scope, exact target identity, operation, and sealed manifest binding. The coordinator and origin-addressed result also retain the complete original source scope `(tenantId, originGameInstanceId, originPlayableStateNamespaceId, originPlayableStateScope, originRegionId, originRegionEpoch, originTickId)`. `playableStateNamespaceId` is stable playable-state identity; `playableStateScope` is separately exact-validated evidence, as defined by [Multi-Tenancy](./system-architecture-multi-tenancy.md). Each projection preserves the applicable source and target fields for exact replay/result equality checks; missing, conflicting, or mismatched namespace, scope, target, or digest evidence fails closed. + - Minimum coordinator fields include durable `coordinatorId`, `tenantId`, `originCommandId`, `originGameInstanceId`, `originPlayableStateNamespaceId`, `originPlayableStateScope`, `originRegionId`, `originRegionEpoch`, `originTickId`, target scope (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetPlayableStateScope`, `targetRegionId`, `targetRegionEpoch`, `dueTickId`), exact target aggregate (`targetAggregateType`, `targetAggregateId`), the originating `originEffectId` and distinct target-leg `targetEffectId`, target-leg `typedOperation`, immutable `requestDigest`, and the sealed required-participant manifest (or immutable manifest reference plus digest). These identity/binding fields are compared on replay and a missing or conflicting value fails closed. The lifecycle is (`PENDING_REMOTE`, `REMOTE_APPLIED`, `REMOTE_ABANDONED`, `REMOTE_TIMEOUT_ABANDONED`, `LATE_RESULT_IGNORED`, `LATE_RESULT_RECONCILED`), with origin-timeline deadline (`originDeadlineRegionEpoch`, `originDeadlineTickId`; storage may use names such as `remote_deadline_region_epoch` / `remote_deadline_tick_id`), final player-facing/result-facing projection fields when applicable (`executionOutcome`, `gameplayResult`), and `updatedAt`. + - Target completion is returned through one durable origin-owned result path, not an unspecified transient message. The current live coordinator and result projection schemas do not yet carry the complete source and target tuples described here; this remains target-state contract, not a claim of schema implementation: + - the target leg writes an origin-addressed result or inbox row keyed to `coordinatorId` and repeats `originCommandId`, `tenantId`, `originGameInstanceId`, `originPlayableStateNamespaceId`, `originPlayableStateScope`, origin region/epoch/tick, target game instance, `targetPlayableStateNamespaceId`, `targetPlayableStateScope`, target region/epoch and `dueTickId`, the distinct target `targetEffectId`, typed operation, exact target aggregate, and one immutable follow-up binding/digest reference that binds the request digest and sealed-manifest context, - the row records the target terminal outcome and any command-specific result payload needed by origin reconciliation; it is not correlated only by the target `gameInstanceId` or a transient message ID, - origin-side processing claims and applies that result idempotently when advancing the coordinator lifecycle. Acceptance of a result that has a dependent child effect is crash-safe: the durable acceptance transition cannot commit without a deterministic child-effect intent. The result acceptance and child intent commit in one durable transaction where they share an owner, or a resumable durable acceptance intent records both before either is treated as accepted. Replays reuse the child identity and the exact accepted-result digest; missing, extra, partial, or conflicting intent/projection evidence fails closed. This is an acceptance/intent durability invariant, not another coordinator outcome. Exact opaque allocation remains non-authoritative in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). - The target region later drains these follow-ups into its own tick pipeline and applies them under its lease and locks. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 1ca066c481..4d9b1e19cd 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -187,3 +187,8 @@ Entry format: - Observation: the live runner permits CLI on the exact published Hosted candidate, excluding local descendant changes. An unattempted safety assumption is not a demonstrated controller hold. - Outcome: subsequent CLI requests ran independently. A later Hosted retry encountered a closed-#2750 reservation verification error before POST; its current record and attributable terminal review were valid on one read-only reproduction, and a canonical retry posted successfully. The original exception remains unknown because the wrapper hides its phase/cause; no record was edited or safety check bypassed. - Expected pattern: use the canonical eligible channel, retain actual refusal evidence, and keep the other lane moving. Preserve safe phase/cause diagnostics for future reservation-verification failures rather than treating an unposted request as provider activity. + +- `2026-10-01`: Closed-PR history must not retain a Hosted execution slot + - Context: the repository-wide Hosted admission sweep reread the complete review history of merged #2750; an exception became an admission hold even though the live open-PR inventory had already excluded it. + - Outcome: the repair is published in #2916 and installed as a separately tested writer-build-5 backport. Confirmed closed PRs no longer require that historical network read. An exact, attributable, locally archived rate-limit response still holds the repository until its proven reset time, including a response whose terminal edit occurred after creation. No historical record, count, or taper decision was removed. + - Proof: 118 focused runtime tests, 883 tests against the compatible live-controller baseline, and 920 tests on the owning child passed. The original transient exception's underlying network cause remains unknown; the reproduced failure mode is now covered without weakening open-PR request safety or promoting an unmerged record schema. diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index fcee2f2dbc..5fa7724ccb 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -2501,9 +2501,9 @@ require_absent( require_contains( "design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md", [ - "a command root's enclosing root is its own persisted `EffectId`", - "its parent is explicitly absent (`null`)", - "retry and replay reuse the same scalar and binding", + "Under this proposal, a command root's enclosing root would be its own persisted `EffectId`", + "its parent would be explicitly absent (`null`)", + "retry and replay would reuse the same scalar and binding", ], ) require_contains( @@ -2557,8 +2557,18 @@ require_contains( require_contains( "design/architecture/system-architecture-gateway.md", [ - "logical typed Gateway-owned readiness-probe operation", + "logical typed Gateway-owned probe", "one pinned Coordination Redis connection", + "While shared readiness remains `QUARANTINED`", + "disposable marker at `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`", + "then immediately issues configured `WAITAOF` on that same connection with no intervening write", + "Cleanup is a separate exact-operation/fence-guarded write and readback after acknowledgement and evidence readback", + "does not accept or consume a player JWT, real `jti` replay marker, or browser-deny marker", + "Normal player consume remains `OPEN`-only and is never invoked during quarantine", + "only the coordinator may authorize reopening after the deadline, exact fenced probe evidence, and all other owner release gates succeed", + "callers cannot supply key material or redirect a probe to player replay/deny prefixes", + "Its marker uses a finite bounded expiry", + "Gateway's owner-local helper performs the readiness compare-and-set", "The operation and its producer/consumer proof are currently unimplemented", ], ) @@ -2568,6 +2578,63 @@ require_contains( "Gateway's typed readiness-probe operation", "[Gateway replay readiness](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake)", "currently unimplemented, so the checklist is not yet executable for this gate", + "The probe runs while shared readiness remains `QUARANTINED`", + "Only the recovery coordinator may authorize reopening after the deadline, exact fenced probe evidence, and every other release gate", + ], +) +require_contains( + "design/architecture/decisions/adr-0029-single-use-gameplay-connect-token-carriage.md", + [ + "trusted recovery coordinator invokes Gateway's separate typed recovery probe through Gateway's existing authenticated owner-maintenance boundary while shared readiness remains `QUARANTINED`", + "Gateway-generated disposable marker under `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`", + "This probe neither accepts nor consumes a player JWT, real `jti` replay marker, or browser-deny marker, and it never writes shared readiness", + "Gateway's owner-local helper alone performs the fenced compare-and-set to `state=OPEN`", + "The coordinator does not receive raw Redis authority", + "callers cannot supply a key, nonce, player `jti`, or marker value", + "The probe marker has a finite bounded expiry", + "Gateway immediately issues the configured `WAITAOF` acknowledgement on that same pinned connection with no intervening write", + "Only after that acknowledgement and evidence readback may cleanup run as a separate exact-fence-guarded write with readback", + "The probe operation and its producer/consumer proof are target-only and currently unimplemented", + ], +) +require_contains( + "design/architecture/system-architecture-redis-reset-and-recovery.md", + [ + "`gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`", + "While readiness remains `QUARANTINED`, the trusted recovery coordinator invokes Gateway's separate typed probe", + "Only the recovery coordinator may authorize reopening after the deadline, exact fenced probe evidence, and every other owner release gate", + "Gateway owns the probe key, nonce, and marker value; callers cannot redirect it to a player `jti` or deny prefix", + "The probe marker has a finite bounded expiry", + "no current deny-marker, readiness, replay-fence, or recovery-probe writer", + ], +) +require_contains( + "design/architecture/system-architecture-redis-ops-access.md", + [ + "`gateway:connect-token:{gateway-connect-token-replay-v1}:probe:*` only", + "it neither consumes player credentials nor writes shared readiness", + "immediately issues configured `WAITAOF` on that connection with no intervening write", + "guarded cleanup/readback follows the acknowledgement", + ], +) +require_contains( + "design/architecture/system-architecture-redis-cheatsheet.md", + [ + "`gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`", + "The typed probe runs only while shared readiness is `QUARANTINED`", + "Gateway alone supplies its exact key/nonce/value; callers cannot redirect it to player keys", + "The marker has a finite bounded expiry", + "Gateway's owner-local helper performs the readiness CAS through its authenticated maintenance API", + "The probe is currently unimplemented", + ], +) +require_contains( + "design/architecture/system-architecture-redis.md", + [ + "a separate Gateway-generated disposable recovery-probe marker", + "The probe marker is not a player `jti` or deny marker", + "Normal consume is never called during quarantine", + "the recovery coordinator alone may reopen after exact fenced proof and all owner gates", ], ) require_contains( @@ -2578,6 +2645,50 @@ require_contains( "owner-scope/root/parent/ordinal mapping to each child `EffectId` is one atomic durable admission record", ], ) +require_contains( + "design/architecture/decisions/adr-0065-deterministic-fair-entity-tick-scheduling.md", + [ + "recorded owner-allocated child ordinals", + "owner-defined ordinal and durable owner-scope/root/parent/ordinal-to-child-`EffectId` mapping are mandatory and replay-stable under accepted [ADR 0075]", + "Only scalar choices and additional allocator mechanics remain pending in [ADR 0183]", + "owner-allocated persisted child ordinals and replay-stable mappings", + ], +) +require_contains( + "design/architecture/system-architecture-scripting-dsl-reference-and-lifecycle.md", + [ + "Only after all applicable handler-scoped gates pass does each admitted resolved handler create a durable parent work item", + "A trigger with no admitted handlers creates no parent work items", + "The exact per-handler gates remain owned by [Normative Table 2]", + ], +) +require_contains( + "design/architecture/system-architecture-tick-execution-flows.md", + [ + "The coordinator and origin-addressed result also retain the complete original source scope", + "originPlayableStateNamespaceId", + "originPlayableStateScope", + "The current live coordinator and result projection schemas do not yet carry the complete source and target tuples", + "this remains target-state contract, not a claim of schema implementation", + ], +) +require_contains( + "services/spring-cloud-gateway/src/main/resources/openapi.yaml", + [ + "Current REST route mutations require a Bearer JWT accepted by the gateway's", + "privileged-role predicate, which currently accepts global or tenant-scoped", + "acceptance of tenant-scoped roles is implementation drift", + "The target management contract requires exact operator authentication and", + "global privileged authorization on an internal dev/test-only surface", + ], +) +require_contains( + "design/architecture/system-architecture-redis-usage-and-profiles.md", + [ + "This projection responsibility does not assign the current physical `gameplaypresence:session:` or `accountrecentpresence::` prefixes to the Coordination Redis role", + "their storage-role classification and target key contract remain unproven", + ], +) require_contains( "design/architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md", [ @@ -2676,6 +2787,109 @@ require_absent( "design/architecture/system-architecture-tick-incident-runbook.md", ["If ledger backlog also accumulates, trigger ledger replay-controller remediation"], ) +require_contains( + "design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md", + [ + "atomic owner-defined CAS/version-fenced transition on the authoritative command record", + "if concurrent staging wins, the loss transition affects zero rows", + "positive authoritative evidence that no batch committed, no effect was materialized, and no domain application occurred", + "ingress status or a missing batch/effect identifier alone is insufficient", + "[Transactions](../system-architecture-transactions.md)", + "[Tick Failures and Operations](../system-architecture-tick-failures-and-operations.md)", + ], +) +require_absent( + "design/architecture/decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md", + ["with no surviving durable `tickBatchId`, effect ledger, or source/effect claim"], +) +require_contains( + "design/architecture/microservices/game-design-service/modding-framework.md", + [ + "complete owner-defined participant binding", + "Any participant-binding, operation, target, or digest conflict fails closed", + "[Transactions guard contract](../../system-architecture-transactions.md)", + "[ADR 0069](../../decisions/adr-0069-at-least-once-effect-execution-with-one-logical-terminal-outcome.md)", + ], +) +require_contains( + "design/architecture/system-architecture-redis-cheatsheet.md", + [ + "the later of the detection-time deadline (the 30-second maximum token lifetime plus two configured clock-skew intervals) and any later known affected-token `exp` plus one clock-skew interval", + "Admission remains closed until that deadline passes and the required fresh disposable-marker, durability-acknowledgement, and shared readiness proof succeeds", + "[ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md)", + ], +) +require_contains( + "design/architecture/system-architecture-redis.md", + [ + "shared readiness quarantined under an advanced `replayAdmissionFence`", + "during that quarantine, an absent `jti` marker alone never proves first use", + "[ADR 0029 readiness proof](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md)", + ], +) +require_contains( + "design/architecture/system-architecture-scripting-contracts.md", + [ + "parent `outboxWorkItemId` is retained only as correlation and is not part of that identity", + "applicable distinct target runtime fields (`targetGameInstanceId`, `targetPlayableStateNamespaceId`, `targetRegionId`, `targetRegionEpoch`)", + "[Table 2 identity owner](./system-architecture-scripting-normative-contract-tables.md#table-2-command-handoff-identity)", + ], +) +require_absent( + "design/architecture/system-architecture-scripting-contracts.md", + ["complete Command-Handoff Identity, including `outboxWorkItemId` as parent correlation"], +) +require_contains( + "design/architecture/system-architecture-scripting-normative-contract-tables.md", + [ + "Core-owned schedules include their schedule-owned `scriptId`; plugin-owned schedules use their schedule-owned `pluginId`, `pluginVersionId`, and `bindingId` without adding a synthetic `scriptId`", + "`scheduleDefinitionId` participates in the stable logical continuity key and the complete durable row/trigger-claim identity, but is never sufficient as a standalone row or claim identity", + ], +) +require_absent( + "design/architecture/system-architecture-scripting-normative-contract-tables.md", + ["The logical identity therefore includes schedule-owned `scriptId` and any schedule-owned `pluginId`"], +) +require_contains( + "design/architecture/system-architecture-tick-concepts-and-invariants.md", + [ + "accept explicit caller-supplied `currentTickId`", + "the AOF records the script's write effects and restart replays those recorded commands", + "it does not rerun the Lua script with the original `ARGV` values", + "[Redis scripting and effects-replication documentation](https://redis.io/docs/latest/develop/interact/programmability/eval-intro/)", + ], +) +require_absent( + "design/architecture/system-architecture-tick-concepts-and-invariants.md", + ["AOF replay reuses the same arguments"], +) +require_contains( + "design/architecture/system-architecture-gateway.md", + [ + "While shared readiness remains `QUARANTINED`", + "Normal player consume remains `OPEN`-only and is never invoked during quarantine", + "only the coordinator may authorize reopening after the deadline, exact fenced probe evidence, and all other owner release gates succeed", + "issuance and player admission remain closed", + "not a new public RPC or an implemented operation", + ], +) +require_contains( + "design/architecture/system-architecture-redis-usage-and-profiles.md", + [ + "The checked Coordination configurations", + "do not set an internal Redis `maxmemory` bound", + "Every non-ephemeral Coordination Redis profile must configure an explicit finite positive Redis `maxmemory` bound", + ], +) +require_contains( + "design/architecture/decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md", + [ + "Proposed - Pending Human Review", + "Every clause in this Decision section is a proposal, conditional on human acceptance", + "do not extend the independently accepted owner-defined child ordinal and durable owner-scope/root/parent/ordinal-to-child-`EffectId` mapping", + "This exact scalar format is not an accepted cross-service requirement today", + ], +) print("architecture doc contracts passed") PY diff --git a/services/game-session-service/src/main/resources/openapi.yaml b/services/game-session-service/src/main/resources/openapi.yaml index b1f030b8eb..db419a6961 100644 --- a/services/game-session-service/src/main/resources/openapi.yaml +++ b/services/game-session-service/src/main/resources/openapi.yaml @@ -79,7 +79,9 @@ components: type: string example: refreshed error: - $ref: '#/components/schemas/ErrorDetail' + oneOf: + - $ref: '#/components/schemas/ErrorDetail' + - type: 'null' paths: /ping: get: diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/SessionRoleControllerTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/SessionRoleControllerTest.java index fca180be06..9a25c31569 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/SessionRoleControllerTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/SessionRoleControllerTest.java @@ -48,7 +48,8 @@ void refreshRolesReturnsOk() throws Exception { HttpHeaders.AUTHORIZATION, "Bearer " + PlatformAdminJwtTestSupport.privilegedToken(jwtUtil))) .andExpect(status().isOk()) - .andExpect(jsonPath("$.data").value("refreshed")); + .andExpect(jsonPath("$.data").value("refreshed")) + .andExpect(jsonPath("$.error").value(org.hamcrest.Matchers.nullValue())); } @Test diff --git a/services/spring-cloud-gateway/src/main/resources/openapi.yaml b/services/spring-cloud-gateway/src/main/resources/openapi.yaml index 32674961a1..916009491d 100644 --- a/services/spring-cloud-gateway/src/main/resources/openapi.yaml +++ b/services/spring-cloud-gateway/src/main/resources/openapi.yaml @@ -4,7 +4,7 @@ info: description: >- Current REST route mutations require a Bearer JWT accepted by the gateway's privileged-role predicate, which currently accepts global or tenant-scoped - privileged roles; global-role-only enforcement is implementation drift. + privileged roles; acceptance of tenant-scoped roles is implementation drift. The target management contract requires exact operator authentication and global privileged authorization on an internal dev/test-only surface. version: 1.0.0 From 1e6ab8a50961fb2645a25957eb5a17b259f9dc17 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 22:13:42 +1300 Subject: [PATCH 65/68] Align reviewed recovery authority and owning contract references --- ...ting-event-ingress-idempotency-identity.md | 4 ++ ...9-coordination-redis-ownership-boundary.md | 1 + ...-session-front-end-and-region-execution.md | 4 ++ .../game-design-service/operations.md | 2 +- .../system-architecture-gateway.md | 2 +- ...system-architecture-identifier-glossary.md | 2 +- .../system-architecture-redis-ops-access.md | 2 +- .../architecture/system-architecture-redis.md | 4 +- .../system-architecture-transactions.md | 4 +- design/project-management/ai-observations.md | 2 + dev-tools/tests/architecture-doc-contracts.sh | 70 +++++++++++++++++++ 11 files changed, 89 insertions(+), 8 deletions(-) diff --git a/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md b/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md index 0ebba5fc38..c5d2e5092a 100644 --- a/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md +++ b/design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md @@ -33,6 +33,10 @@ Retry identity and handler materialization follow the current Trigger Identity a Current implementation and proof obligations are owned by [ADR 0172](./adr-0172-parent-event-and-frozen-handler-execution-identity.md) and the canonical identity matrix and scheduler-preimage requirements in [Scripting Normative Contract Tables](../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). Select and report checks under [Validation and Runtime Proof](../../developer-workflows/validation-and-runtime-proof.md); this superseded ADR is not an independent proof authority. +## Supersession + +- Replacement ADR: [ADR 0172](./adr-0172-parent-event-and-frozen-handler-execution-identity.md) + ## References - `design/architecture/system-architecture-scripting-contracts.md` diff --git a/design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md b/design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md index e657f76f6c..98cff8f111 100644 --- a/design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md +++ b/design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md @@ -22,6 +22,7 @@ Coordination Redis ownership is explicit and narrow: - Game Session Service owns gameplay coordination keyspace and schema (for example `tick:*`, `timer:*`, `retry:*`, `session:game:*`, and lease-related prefixes). - Account Service owns the exact authentication/session-auth families recorded by the Redis hub: `session:auth:account:*`, `session:auth:tenant:*`, `session:auth:token:*`, and `session:auth:generation:*`, together with their lifecycle semantics. It also owns the separate exact-input `session:connect-token:tenant::account::scope::request:` issuance-result/idempotency family defined by [ADR 0029](./adr-0029-single-use-gameplay-connect-token-carriage.md). No wildcard `session:auth:*` ACL or authority grant is implied. +- Gateway Service owns the exact connect-token replay, browser-deny, readiness/fence, and recovery-probe key families in the pinned `gateway-connect-token-replay-v1` domain: `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`, as defined by [ADR 0029](./adr-0029-single-use-gameplay-connect-token-carriage.md). These are bounded Gateway-owned replay and recovery records, not wildcard access or a broader non-owner participation grant. - Automation & Scripting Service owns automation coordination and cache families with an explicit current-versus-target split: - Coordination Redis: it owns the target scheduler/checkpoint boundary represented by `automation:timer:*` and `script-scheduler:*` once implemented. These are reset-tolerant projections rebuilt from durable schedules, trigger-instance rows, and heartbeat progress; durable schedules and trigger-instance de-duplication remain PostgreSQL authority. They are target-state names, not current runtime guarantees. The former `automation:tick:*` staging path is retired, not live, and is not an active owned prefix. - Cache/Rate-Limit Redis: `automation:queue:*` discovery pointers, `automation:quota:*`, `automation:tenant-budget:*`, `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` best-effort buffers/counters and owner-token leases; queue pointers are disposable indexes, not work truth. The test and readiness families remain unsupported for target adoption until each is centrally registered and has slot-safe keying. These remain distinct from the target Coordination Redis `automation:timer:*` and `script-scheduler:*` projections. diff --git a/design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md b/design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md index e4b7b43177..c1070e718d 100644 --- a/design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md +++ b/design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md @@ -4,6 +4,10 @@ Superseded by [ADR 0170](./adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md) +## Supersession + +- Replacement ADR: [ADR 0170](./adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md) + ## Context FireMUD already makes two high-level decisions: diff --git a/design/architecture/microservices/game-design-service/operations.md b/design/architecture/microservices/game-design-service/operations.md index fe81283160..1a1ebe9174 100644 --- a/design/architecture/microservices/game-design-service/operations.md +++ b/design/architecture/microservices/game-design-service/operations.md @@ -24,7 +24,7 @@ The target attempt record must immutably bind the normalized preallocation reque The target publication boundary treats object-store export as a durable candidate operation: persist `STAGED` export intent before any write, retain a deterministic candidate manifest or incremental durable key evidence, make writes and deletes idempotent, and use a durable cleanup retry/outbox with exact object/readback verification. An ambiguous external result remains nonterminal and reconciliation-required until the candidate and release state are proven; it must not be reported as terminal `FAILED` merely because a storage call timed out. `version_asset_artifact` and the immutable release attestation remain the Game Design authorities; object-store listings alone cannot authorize publication or purge. -**Current implementation gap:** `AssetExportServiceImpl` writes directly to S3-compatible storage before the artifact row receives the exported manifest. If an asset or manifest write fails, `VersionPublishCommandServiceImpl` has no manifest to record or clean up; if later cleanup fails, it is only logged. The Temporal activity catches these failures and returns terminal `FAILED`, so ambiguous partial exports have no durable recovery authority. The current direct-prefix implementation is therefore not proof of the target `STAGED`/candidate/reconciliation contract described in [Asset Storage](./asset-storage.md). +**Current implementation gap:** `AssetExportServiceImpl` writes directly to S3-compatible storage before the artifact row receives the exported manifest. If an asset or manifest write fails, `VersionPublishCommandServiceImpl` has no manifest to record or clean up; if later cleanup fails, it is only logged. `VersionPublishCommandServiceImpl` normally records terminal `FAILED` and returns the attempt snapshot for publication failures; `TemporalVersionPublishActivitiesImpl` catches only `PendingReconciliationException` and returns `PENDING`. A partial export before manifest persistence can therefore lack durable cleanup and failure evidence. The current direct-prefix implementation is not proof of the target `STAGED`/candidate/reconciliation contract described in [Asset Storage](./asset-storage.md). ## Local Development Notes diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index 5e4b57f48c..77862649dc 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -401,7 +401,7 @@ This section is the canonical source of truth for connect-token enforcement and - Replay checks must be backed by the player-facing Coordination Redis deployment (not Cache/Rate-Limit Redis or per-pod memory) so `jti` replay decisions are consistent across horizontally scaled gateway pods and cannot be selectively evicted. The deployment requires Redis 7.2+ with AOF enabled, `noeviction`, replay-key ACL isolation, and admission-blocking capacity thresholds. The atomic marker script is followed by `WAITAOF requiredLocalAofCount requiredReplicaAofCount timeout`; `DURABLE_REPLAY_CONSUME_ACK` succeeds only when the reported AOF-fsync counts meet the configured thresholds, with at least one local AOF acknowledgement. The browser-deny write uses the same pinned Coordination connection and configured timeout/threshold after the write; if a valid marker already exists, reassert it with its unchanged original absolute expiry before `WAITAOF`, or withhold the durable acknowledgement until the original write's durability is proven. Never extend its expiry; malformed or conflicting marker state stays non-mutating and fails closed. Its propagation remains in the default `redis.REPL_ALL` mode. An unavailable, timed-out, malformed, below-threshold, or otherwise ambiguous deny write is unconfirmed and cannot be reported as terminal revocation. `WAIT`, read-back, or a successful client write is not a substitute, and this contract does not claim protection from disk or hardware destruction. - Replay and browser-revocation state use the canonical target representation defined by the Redis ownership and recovery documents, with bounded cardinality and deterministic expiry at `exp + firemud.gateway.connectTokenClockSkewMs`. The readiness/fence record and marker state must remain one script-compatible Coordination Redis atomicity domain under that contract. The legacy representation emitted by the current writer is migration-only drift and cannot be treated as target state. - The replay and deny-marker prefixes are security-critical, non-evicting coordination state. Gateway's one consume script checks readiness state, signed fence/cutoff, and deny-marker absence before creating the replay marker; consumption is successful only after that script and the configured Redis 7.2+ `WAITAOF` acknowledgement both succeed. A deny marker that linearizes before or during the consume race returns a denial without creating the replay marker; a consume already linearized is spent and cannot be retroactively undone by a later browser logout. A browser revocation is confirmed only after its deny write and same-connection durability acknowledgement succeed; an uncertain deny write remains unconfirmed. Capacity or acknowledgement failure rejects the handshake rather than accepting an uncertain marker. A crash or connection loss between marker creation and acknowledgement is treated as uncertain consumption, not as an opportunity to unconsume or retry the token. - - Coordination Redis cold start, reset, unexpected eviction signal, failover, capacity-safety breach, or any other event that cannot prove replay-marker continuity starts a shared replay-protection quarantine for at least the 30-second token lifetime maximum plus two `firemud.gateway.connectTokenClockSkewMs` intervals. One interval covers a latest tolerated future `iat`; the second covers acceptance through `exp + skew`. Account stops issuing connect tokens and Gateway rejects admission until that barrier expires, configuration and capacity checks pass, and a disposable marker script followed by the configured `WAITAOF` thresholds proves `DURABLE_REPLAY_CONSUME_ACK`; tokens from the earlier fence and issuance races cannot survive reopening. Before normal release, old Gateway replay writers must be drained or authoritatively blocked and the complete tagged replay state and readiness/fence state must be authoritative, in addition to the lifetime, skew, configuration/capacity, and disposable-marker `WAITAOF` gates above. If any old-version writer or admission remains allowed, release additionally requires a separately proven cross-version guard; none is currently implemented or proven, so that mixed-version release path remains forbidden. The current replay deployment has one shared continuity domain, so an unscoped continuity failure intentionally blocks new connect-token issuance and admission platform-wide; a future partitioned deployment may narrow quarantine only when it can prove the exact affected marker and fence domain. + - Coordination Redis cold start, reset, unexpected eviction signal, failover, capacity-safety breach, or any other event that cannot prove replay-marker continuity starts a shared replay-protection quarantine for at least the 30-second token lifetime maximum plus two `firemud.gateway.connectTokenClockSkewMs` intervals. One interval covers a latest tolerated future `iat`; the second covers acceptance through `exp + skew`. When the latest expiry of an affected token is known, the quarantine deadline also covers that token's `exp + firemud.gateway.connectTokenClockSkewMs`; the deadline is the later of these bounds, and admission must never reopen before it. This deadline rule is defined by [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md). Account stops issuing connect tokens and Gateway rejects admission until that barrier expires, configuration and capacity checks pass, and a disposable marker script followed by the configured `WAITAOF` thresholds proves `DURABLE_REPLAY_CONSUME_ACK`; tokens from the earlier fence and issuance races cannot survive reopening. Before normal release, old Gateway replay writers must be drained or authoritatively blocked and the complete tagged replay state and readiness/fence state must be authoritative, in addition to the lifetime, skew, configuration/capacity, and disposable-marker `WAITAOF` gates above. If any old-version writer or admission remains allowed, release additionally requires a separately proven cross-version guard; none is currently implemented or proven, so that mixed-version release path remains forbidden. The current replay deployment has one shared continuity domain, so an unscoped continuity failure intentionally blocks new connect-token issuance and admission platform-wide; a future partitioned deployment may narrow quarantine only when it can prove the exact affected marker and fence domain. - Recovery obtains post-reset replay readiness through a logical typed Gateway-owned probe, invoked automatically by the trusted recovery coordinator through the existing authenticated owning-service maintenance API boundary. This is target behavior, not a new public RPC or an implemented operation. The probe is bound under the existing Redis owner contracts to the exact durable maintenance operation and fence, the shared replay domain, expected `replayAdmissionFence`, and authoritative quarantine/readiness, configuration, and capacity evidence. While shared readiness remains `QUARANTINED`, Gateway uses one pinned Coordination Redis connection to conditionally write a Gateway-generated disposable marker at `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::` only if the exact operation/fence, replay domain, fence, and quarantine state still match, then immediately issues configured `WAITAOF` on that same connection with no intervening write. The nonce is Gateway-generated, not caller-supplied. The probe does not accept or consume a player JWT, real `jti` replay marker, or browser-deny marker, and does not write shared readiness. It succeeds only when the marker is created, configured local and replica durability thresholds are met, and subsequent readback still proves the same operation/fence, replay domain, replay fence, quarantine state, configuration, and capacity conditions. Connection loss, threshold timeout, malformed or uncertain result, or changed evidence fails closed; Gateway never retries an old marker to claim a new acknowledgement. Cleanup is a separate exact-operation/fence-guarded write and readback after acknowledgement and evidence readback; it cannot supply or replace the acknowledgement. Normal player consume remains `OPEN`-only and is never invoked during quarantine. A successful probe is evidence for the coordinator, not permission to enable player admission: only the coordinator may authorize reopening after the deadline, exact fenced probe evidence, and all other owner release gates succeed. The operation and its producer/consumer proof are currently unimplemented, so the post-reset checklist is not yet executable for this gate. Until implemented and proved under [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md), issuance and player admission remain closed. - The probe uses only the Gateway-generated exact key family, nonce, and marker value; callers cannot supply key material or redirect a probe to player replay/deny prefixes. Its marker uses a finite bounded expiry, followed by separate exact-operation/fence-guarded cleanup and readback outside `WAITAOF`. The coordinator authorizes release only after all gates pass, then uses Gateway's existing authenticated owner-maintenance boundary; Gateway's owner-local helper performs the readiness compare-and-set. Recovery remains API-only and does not receive raw Redis authority. See [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md) for the canonical probe lifecycle. - Replay-quarantine lifecycle is a monitored security state. Gateway must emit low-cardinality `gateway.connect_token.replay_quarantine_entries_total{reason=...}`, `gateway.connect_token.replay_quarantine_exits_total{outcome=...}`, `gateway.connect_token.replay_quarantine_active`, and `gateway.connect_token.replay_quarantine_duration_seconds`, plus structured records containing the shared `replayAdmissionFence`, `state`, `quarantineStartedAt`, `quarantineUntil`, and `openedAt` values. Alertmanager must alert when a player-facing quarantine is entered, remains active past `quarantineUntil` or has no observed exit, or exits without fresh `DURABLE_REPLAY_CONSUME_ACK` proof. Dashboards must show entry/exit counts and duration. Labels must exclude `jti`, tenant identifiers, and other high-cardinality values. diff --git a/design/architecture/system-architecture-identifier-glossary.md b/design/architecture/system-architecture-identifier-glossary.md index da8d6d57f6..8a8fd9e781 100644 --- a/design/architecture/system-architecture-identifier-glossary.md +++ b/design/architecture/system-architecture-identifier-glossary.md @@ -87,7 +87,7 @@ Tick-driven, cross-service mutations are at-least-once and must be idempotent. - `EffectId` – the persisted mutation identity for one logical effect. Retries, replay, and reconciliation must preserve the same mutation identity and validate the immutable request digest under the accepted effect contract. A generated child has its own persisted child `EffectId` while retaining enclosing-root and parent lineage where applicable. Current Entity replay looks up by `(tenantId, effectId)` but does not validate a request digest, so it does not prove this target contract. Command-root allocation details remain pending in [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md). - `deterministic effect plan` – a proposed ordered set of command-root effects described in pending [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); it is not an accepted canonical term or requirement. - `planOrdinal` – a proposed command-root allocation field described in pending [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md); it is not an accepted identity or ordering contract. -- **Participant guard identity** – a deterministic uniqueness identity under the owning runtime-family contract. For owner-classified S1/S2 families, the durable guard partition is `(tenantId, playableStateNamespaceId)` plus the owning identity/effect (`EffectId`, typed operation, and target aggregate); `gameInstanceId` is not a uniqueness dimension and is carried and exact-validated separately as active-runtime authorization/fence evidence. Only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)` as its durable partition; an unknown or unclassified family is rejected before any participant-guard allocation or admission and is never treated as S3 by default. A root effect uses its root `EffectId`; a generated child mutation uses its persisted child `EffectId`, while the enclosing root remains lineage and reconciliation context rather than collapsing sibling guards. The child ordinal participates in deterministic child-ID derivation under the owning contract but is not a second guard-key field. For S1/S2, `playableStateNamespaceId` is the uniqueness partition; `playableStateScope` and `gameInstanceId` are separately persisted, exact-validated routing/authorization/fence evidence and are not additional uniqueness dimensions. Same family-partitioned guard identity with the same request and evidence returns the prior result; a changed tenant, namespace, owning effect, operation, target, scope, digest, or separately validated active-instance fence fails closed. Work explicitly outside playable-state scope must use an accepted owner-specific idempotency/partition contract; it cannot omit namespace/scope and proceed under this gameplay participant-guard contract. The durable outcome and other evidence/reconciliation fields are mutable guard-row state protected by CAS, not part of uniqueness identity. A conserved multi-participant operation normally shares one effect identity but still follows [ADR 0053](./decisions/adr-0053-command-atomicity-by-invariant-class.md)'s atomicity/co-location/reservation semantics. +- **Participant guard identity** – a deterministic uniqueness identity under the owning runtime-family contract. For owner-classified S1/S2 families, the durable guard partition is `(tenantId, playableStateNamespaceId)` plus the owning identity/effect (`EffectId`, typed operation, and target aggregate); `gameInstanceId` is not a uniqueness dimension and is carried and exact-validated separately as active-runtime authorization/fence evidence. Only an explicitly owner-classified S3 family uses `(tenantId, gameInstanceId)` as its durable partition; an unknown or unclassified family is rejected before any participant-guard allocation or admission and is never treated as S3 by default. A root effect uses its root `EffectId`; a generated child mutation uses its persisted child `EffectId`, while the enclosing root remains lineage and reconciliation context rather than collapsing sibling guards. The owner must allocate and durably persist each generated child's ordinal and owner-scope/root/parent/ordinal-to-child-`EffectId` mapping under the accepted owner contract; deterministic child-ID derivation is only proposed by pending [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) and is not current target. The ordinal is not a second guard-key field. For S1/S2, `playableStateNamespaceId` is the uniqueness partition; `playableStateScope` and `gameInstanceId` are separately persisted, exact-validated routing/authorization/fence evidence and are not additional uniqueness dimensions. Same family-partitioned guard identity with the same request and evidence returns the prior result; a changed tenant, namespace, owning effect, operation, target, scope, digest, or separately validated active-instance fence fails closed. Work explicitly outside playable-state scope must use an accepted owner-specific idempotency/partition contract; it cannot omit namespace/scope and proceed under this gameplay participant-guard contract. The durable outcome and other evidence/reconciliation fields are mutable guard-row state protected by CAS, not part of uniqueness identity. A conserved multi-participant operation normally shares one effect identity but still follows [ADR 0053](./decisions/adr-0053-command-atomicity-by-invariant-class.md)'s atomicity/co-location/reservation semantics. - The root effect identity, required participant set, and participant outcomes are Game Session reconciliation data. The durable plan allocation and guard/effect behavior are owned by [Transaction Strategies](./system-architecture-transactions.md) and must not be replaced with an ad-hoc service-local key. ## Cross-Service Causal-Read Fence Identity diff --git a/design/architecture/system-architecture-redis-ops-access.md b/design/architecture/system-architecture-redis-ops-access.md index 03c442b599..3c1aab037d 100644 --- a/design/architecture/system-architecture-redis-ops-access.md +++ b/design/architecture/system-architecture-redis-ops-access.md @@ -10,7 +10,7 @@ The target control-plane and maintenance contract in this document is ahead of t - The live implementation supports the current `{tenantId, gameInstanceId}` queue boundary; `regionId` is present in the proto contract but is currently rejected by the service implementation. - The bounded `coordination-maintenance ...` public surface remains target state, not a description of fully implemented repo-local tooling today. No public recovery scope is currently implemented and proven; recovery phases may be implemented and tested behind the high-level operation without becoming separate public commands. - The owning-service typed maintenance API, role-bound Redis helper surface, aggregated registry, descriptor validators, and ownership-enforcement checks described below are target state and are not implemented; current direct access remains subject to the generic runtime seam and the incident-only fallback. -- Reset-smoke isolation is a separate mechanism decision: the existing [Game Session readiness-only identity contract](./microservices/game-session-service/operations.md#readiness-and-liveness) and [synthetic player-flow canary contract](./system-architecture-logging-monitoring.md#synthetic-player-flow-canaries-target-state-prod-like-contract) do not define an isolated reset-smoke namespace or durable synthetic identity that can safely map to tick staging and ledger rows. Automation's separate [`isDryRun=true` namespace](./system-architecture-scripting-contracts.md#6-dry-run--test-traffic-safety) is explicitly non-committing and cannot reach tick queues, so it is not a reset-smoke identity. Until a reset-smoke mechanism decision is accepted and implemented, `RunPostResetSmokeCheck` is non-mutating for real PostgreSQL tick state, real Redis tick metadata/staging/pending, and real tick-ledger rows. It may perform only bounded sampled lease acquire/renew/release probes and, when the workflow affects the shared replay domain, a fresh canonical replay-consume invocation on the same pinned Redis connection. The invocation must return `1` and create a disposable replay marker through the target `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `jti`, and `deny:jti` keys, followed by one same-connection `WAITAOF` local/replica durability acknowledgement meeting configured thresholds. A `0` or `-1` result is non-mutating and cannot supply a second write acknowledgement; any cleanup is a separate guarded cleanup write/readback and is not part of `DURABLE_REPLAY_CONSUME_ACK`. The current writer's untagged replay marker remains migration-only drift and is not target proof. The probe must fail closed on timeout, malformed, below-threshold, or uncertain results and must not enter real staging or ledger paths. +- Reset-smoke isolation is a separate mechanism decision: the existing [Game Session readiness-only identity contract](./microservices/game-session-service/operations.md#readiness-and-liveness) and [synthetic player-flow canary contract](./system-architecture-logging-monitoring.md#synthetic-player-flow-canaries-target-state-prod-like-contract) do not define an isolated reset-smoke namespace or durable synthetic identity that can safely map to tick staging and ledger rows. Automation's separate [`isDryRun=true` namespace](./system-architecture-scripting-contracts.md#6-dry-run--test-traffic-safety) is explicitly non-committing and cannot reach tick queues, so it is not a reset-smoke identity. Until a reset-smoke mechanism decision is accepted and implemented, `RunPostResetSmokeCheck` is non-mutating for real PostgreSQL tick state, real Redis tick metadata/staging/pending, and real tick-ledger rows. It may perform only bounded sampled lease acquire/renew/release probes and, when the workflow affects the shared replay domain, require Gateway's typed recovery probe through the existing authenticated owning-service maintenance API boundary while shared readiness remains `QUARANTINED`. Normal player consume remains `OPEN`-only and is not invoked for this recovery proof. The probe's durability acknowledgement and fenced evidence must satisfy [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md), [Gateway replay readiness](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake), and the [reset policy matrix](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary); timeout, malformed, below-threshold, or uncertain results fail closed, and successful probe evidence does not bypass any other recovery gate or authorize reopening by itself. This probe remains target-only and unimplemented, so the checklist is not yet executable for this gate. The current writer's untagged replay marker remains migration-only drift and is not target proof, and reset-smoke must not enter real staging or ledger paths. Use this doc as the canonical target-state contract for later reset/replay tooling, but do not assume every operation below is already available in the running codebase. Current operators, runbooks, Helm hooks, Jobs, and dashboards must not invoke the `coordination-maintenance` commands described below until that surface is implemented and end-to-end proven. diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index 202909edbf..a2d8d7cc07 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -89,7 +89,7 @@ FireMUD uses Redis as a **transient, high‑performance coordination layer**, no Redis coordination keys form a long-running, measured-exposure **coordination buffer**, not the durable log of record for gameplay effects: -- Durable history for tick-driven outcomes lives in PostgreSQL via the tick effect ledger and domain idempotency tables described in `system-architecture-tick-failures-and-operations.md` and `system-architecture-transactions.md`. Each durable tick-outcome row retains the complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId)` projection; `playableStateNamespaceId` is the durable namespace identity and `playableStateScope` is separately exact-validated evidence. Durable participant/replay authority is each mutation's persisted root-or-child `EffectId` (the root identity for a root mutation or the child's own identity for a generated child) plus typed operation, exact target, and immutable request digest. The enclosing root `EffectId` remains lineage and reconciliation context for child mutations and cannot collapse siblings beneath one participant identity. `effectKey` and the remaining scope/tick facts are descriptor, projection, or evidence, not ledger uniqueness. `APPLIED`/`ABANDONED` are recorded only when that existing evidence policy permits terminalization, while inconclusive old-epoch work remains reconciliation-required under its original mutation `EffectId` with the enclosing root retained as lineage. +- Durable history for tick-driven outcomes lives in PostgreSQL via the tick effect ledger and domain idempotency tables described in `system-architecture-tick-failures-and-operations.md` and `system-architecture-transactions.md`. Each durable tick-outcome row retains the complete `(tenantId, gameInstanceId, playableStateNamespaceId, playableStateScope, regionId, regionEpoch, tickId)` projection; `playableStateNamespaceId` is the durable namespace identity and `playableStateScope` is separately exact-validated evidence. Durable participant/replay authority is each mutation's persisted root-or-child `EffectId` (the root identity for a root mutation or the child's own identity for a generated child) plus typed operation, exact target, and immutable request digest. Participant-guard uniqueness also includes the owner-declared runtime-family partition: S1/S2 use `(tenantId, playableStateNamespaceId)`, while only explicitly declared S3 uses `(tenantId, gameInstanceId)`; unknown or unclassified families fail closed. The immutable `requestDigest` binds that identity but is not a uniqueness field or partition substitute; other scope and tick values remain exact evidence. The enclosing root `EffectId` remains lineage and reconciliation context for child mutations and cannot collapse siblings beneath one participant identity. See [Transaction Strategies](./system-architecture-transactions.md#tick-effects-are-at-least-once-idempotency-is-mandatory) and the [Identifier Glossary](./system-architecture-identifier-glossary.md#cross-service-effect-identity). `effectKey` and the remaining scope/tick facts are descriptor, projection, or evidence, not ledger uniqueness. `APPLIED`/`ABANDONED` are recorded only when that existing evidence policy permits terminalization, while inconclusive old-epoch work remains reconciliation-required under its original mutation `EffectId` with the enclosing root retained as lineage. - Coordination Redis holds volatile structures such as tick queues, `pending` sets, timers, region leases, tick event streams, and scheduler offsets; these structures are subject to measured unreplicated-write exposure and scoped resets as defined in this document and the Redis reset/runbook docs. - Application and ops designs must not treat AOF contents or Redis key history as the primary log for audits, analytics, or long-term effect replay; those concerns belong in PostgreSQL-backed ledgers and domain stores. - Redis Streams, lists, queue pointers, and wake signals are not durable event authority. Durable event capture, per-consumer delivery state, replay/reconstruction, retention, and backpressure remain owned by each flow's PostgreSQL outbox and worker/API contract; this hub records only the volatile Redis consequence. @@ -630,7 +630,7 @@ Key principles: - Gateway's recovery-only disposable marker family `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::` is a separately registered Coordination Redis prefix owned by Gateway. Its ACL and reset inventories are distinct from player `jti`, deny, and readiness data; see the target-only probe contract in [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md). - Cache and rate‑limit prefixes (for example `inventory:*`, `view:room-look:*`, `ratelimit:*`) live **only** on Cache/Rate‑Limit Redis. -- Coordination prefix ownership is normative: Account owns the live legacy `session:auth:account:*` and `session:auth:tenant:*` projections, the target `session:auth:token:*` exact-token registry, the target `session:auth:generation:*` authority-generation projections, and the target `session:connect-token:*` exact-input issuance-result projections. Gateway owns only the shared replay-domain exception: `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness` carrying `replayAdmissionFence`; this does not grant gameplay-session, Account-auth, or general coordination ownership. Game Session owns the separately approved gameplay families under `session:game:*`, including `session:game:auth:issuer-generation:v1:`; it never owns the Account auth or connect-token issuance prefixes, and no wildcard `session:auth:*` grant is implied. Game Session also owns `tick:*`, `timer:*`, `retry:*`, and `tick-executor-lease:*`; it does not own or mutate the target-only, unimplemented Automation & Scripting families `automation:timer:*` or `script-scheduler:*`. The retired `automation:tick:*` staging path is not part of the live design or active prefix inventory. Automation & Scripting owns its current automation prefixes and the reserved target families once implemented, while its Cache/Rate-Limit families `automation:queue:*`, `automation:quota:*`, `automation:tenant-budget:*`, `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` remain separate; non-owner participation is contract-bound through approved helpers. The shared `conflict:*` diagnostic family is Coordination-only, reset-tolerant, and non-authoritative: `common-data-runtime` owns the mutation helper, while Game Session and Entity Management own the producer scopes that call it. Its target deployed principals are distinct: `entity_coord_app` has the exact `~conflict:entity:*` grant and no `conflict:session:*` or other owner-family grant, while `gamesession_coord_app` has the exact `~conflict:session:*` grant in addition to its separately registered Game Session families and no `conflict:entity:*` grant. No shared principal, generic maintenance principal, or helper-library identity may cross those producer-owner boundaries. Current `conflict:entity::` and `conflict:session::` writes use the generic Redis client and separate `INCR`/`EXPIRE` calls with warning-only expiry failure; both endpoint placement and mutation shape are implementation drift. The target accepts only those registered producer kinds and canonical scope identifiers, permits one key per admitted producer scope, enforces a finite deployment key-cardinality cap with overflow sampled or aggregated rather than creating arbitrary keys, and uses a 300-second inactivity TTL unless an owner-approved profile states a shorter bound. The target uses named Coordination clients and these distinct `coord_app` principals only, never cache ACLs, and converges the mutation through a registered single-key atomic helper/script that performs both `INCR` and `PEXPIRE` on every accepted increment so the inactivity TTL is refreshed atomically. The existing `RedisAtomicOperations.incrementWithTtl` helper sets expiry only when the count is first created and therefore does not satisfy this sliding-inactivity contract unless it is extended; this is target guidance, not a claim that the current tracker implements it. The live Entity `TickLockServiceImpl` `tick:lock::` family is an unscoped implementation-drift writer, not a second Game Session authority; it remains fenced/unregistered for target reset and admission until routed through the canonical full-runtime-scope helper. See `design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md`, with later canonical owner contracts including ADR 0029 defining the Gateway replay carrier. +- Coordination prefix ownership is normative: Account owns the live legacy `session:auth:account:*` and `session:auth:tenant:*` projections, the target `session:auth:token:*` exact-token registry, the target `session:auth:generation:*` authority-generation projections, and the target `session:connect-token:*` exact-input issuance-result projections. Gateway owns only the shared replay-domain exception: `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and the separately registered recovery-only `gateway:connect-token:{gateway-connect-token-replay-v1}:probe:*`; this does not grant gameplay-session, Account-auth, or general coordination ownership. Game Session owns the separately approved gameplay families under `session:game:*`, including `session:game:auth:issuer-generation:v1:`; it never owns the Account auth or connect-token issuance prefixes, and no wildcard `session:auth:*` grant is implied. Game Session also owns `tick:*`, `timer:*`, `retry:*`, and `tick-executor-lease:*`; it does not own or mutate the target-only, unimplemented Automation & Scripting families `automation:timer:*` or `script-scheduler:*`. The retired `automation:tick:*` staging path is not part of the live design or active prefix inventory. Automation & Scripting owns its current automation prefixes and the reserved target families once implemented, while its Cache/Rate-Limit families `automation:queue:*`, `automation:quota:*`, `automation:tenant-budget:*`, `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` remain separate; non-owner participation is contract-bound through approved helpers. The shared `conflict:*` diagnostic family is Coordination-only, reset-tolerant, and non-authoritative: `common-data-runtime` owns the mutation helper, while Game Session and Entity Management own the producer scopes that call it. Its target deployed principals are distinct: `entity_coord_app` has the exact `~conflict:entity:*` grant and no `conflict:session:*` or other owner-family grant, while `gamesession_coord_app` has the exact `~conflict:session:*` grant in addition to its separately registered Game Session families and no `conflict:entity:*` grant. No shared principal, generic maintenance principal, or helper-library identity may cross those producer-owner boundaries. Current `conflict:entity::` and `conflict:session::` writes use the generic Redis client and separate `INCR`/`EXPIRE` calls with warning-only expiry failure; both endpoint placement and mutation shape are implementation drift. The target accepts only those registered producer kinds and canonical scope identifiers, permits one key per admitted producer scope, enforces a finite deployment key-cardinality cap with overflow sampled or aggregated rather than creating arbitrary keys, and uses a 300-second inactivity TTL unless an owner-approved profile states a shorter bound. The target uses named Coordination clients and these distinct `coord_app` principals only, never cache ACLs, and converges the mutation through a registered single-key atomic helper/script that performs both `INCR` and `PEXPIRE` on every accepted increment so the inactivity TTL is refreshed atomically. The existing `RedisAtomicOperations.incrementWithTtl` helper sets expiry only when the count is first created and therefore does not satisfy this sliding-inactivity contract unless it is extended; this is target guidance, not a claim that the current tracker implements it. The live Entity `TickLockServiceImpl` `tick:lock::` family is an unscoped implementation-drift writer, not a second Game Session authority; it remains fenced/unregistered for target reset and admission until routed through the canonical full-runtime-scope helper. See `design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md`, with later canonical owner contracts including ADR 0029 defining the Gateway replay carrier. - New prefixes must be registered in the canonical catalogs: - Coordination prefixes and their reset policies belong in the reset policy matrix and any extended catalogs in `system-architecture-redis-reset-and-recovery.md`. diff --git a/design/architecture/system-architecture-transactions.md b/design/architecture/system-architecture-transactions.md index c772414d47..a9e1554bf1 100644 --- a/design/architecture/system-architecture-transactions.md +++ b/design/architecture/system-architecture-transactions.md @@ -125,7 +125,7 @@ To prevent cross-instance collisions and make retries safe, spatial tick effects Game Session renews the actor-lock lease with that same opaque Redis lock token through Entity's commit acknowledgement and passes the attestation unchanged to Entity; the durable `executorFence` is validated separately at the barrier and Entity commit gates. Entity verifies the attestation's exact binding, including `regionId`, exact `playableStateNamespaceId`, and exact `playableStateScope`, against the request, participant guard, and canonical unchanged `requestDigest` for the same root `EffectId` in its local transaction before changing the holder. A missing, mismatched, or stale attestation (including a changed region, namespace, scope, epoch, or fence) commits no Entity mutation; the Game Session orchestrator invokes Game Logic to re-resolve the targeting facts under that same root `EffectId`, preserving the unchanged `requestDigest`, namespace, scope, and `regionId`. A changed request is rejected under the participant guard rather than reusing the root. Barrier creation, renewal, replay, terminalization, and reconciliation are durable, fence-checked transitions; each preserves and exact-compares the namespace and scope evidence, and Redis lock expiry cannot clear or terminalize the barrier. A lock-renewal failure or fence change fences the old orchestrator and leaves the durable barrier `RECONCILIATION_REQUIRED`. Handoff/recovery must drain or reconcile that barrier from durable guard/holder evidence, including the exact namespace and scope; a new owner may reconcile the exact root `EffectId`, but MOVE admission cannot authorize a conflicting actor move merely because the Redis lock expired, and must wait for terminal barrier evidence. Every `MOVE` for the actor must acquire the same actor lock and pass the barrier gate, so it cannot interleave between World validation and Entity commit. After Entity commits, the acknowledgement is recorded, and the barrier and lock are released, a later valid `MOVE` is permitted. This is serialization, durable barrier evidence, and fencing across local transactions, not a distributed World/Entity transaction. -Any handoff or recovery path that performs maintenance mutation on this barrier must first carry the unchanged ADR-0085 external maintenance handoff: exact `operationId`, external maintenance fence/lock binding, classifier, immutable evidence digest, and complete affected scope. The only alternative is an explicitly owner-recorded non-conflicting routine-replay or reconciliation exemption with its classification and evidence. The actor Redis lock and durable `executorFence` remain separate execution aids and never substitute for either authorization; a missing or mismatched handoff or exemption leaves the barrier `RECONCILIATION_REQUIRED` and fails closed. These controls do not alter the accepted `(tenantId, gameInstanceId, EffectId)` identity or its exact request/namespace/scope evidence. +Any handoff or recovery path that performs maintenance or reset mutation on this barrier must carry the unchanged [ADR 0085](./decisions/adr-0085-evidence-gated-coordination-replay-and-fenced-reset.md) external maintenance handoff: exact `operationId`, external maintenance fence/lock binding, classifier, immutable evidence digest, and complete affected scope. `OwnerRoutineReplayExemption` is available only for explicitly classified, non-conflicting ordinary owner-local routine replay or reconciliation outside maintenance and reset; it cannot authorize these mutations. The actor Redis lock and durable `executorFence` remain separate execution aids and never substitute for the handoff. A missing or mismatched handoff leaves the barrier `RECONCILIATION_REQUIRED` and fails closed. These controls do not alter the accepted `(tenantId, gameInstanceId, EffectId)` identity or its exact request/namespace/scope evidence. Focused proof must exercise stale location/version evidence, root/actor/room/namespace/scope/epoch/fence or request-digest mismatches, Entity rejection before holder mutation, actor-lock lease expiry while the barrier is in flight, an owner crash after World validation and before Entity acknowledgement, lock-renewal failure, executor-fence change fencing the old orchestrator, handoff/recovery reconciliation of the exact root, an old Entity commit racing a new MOVE, and a valid `MOVE` after terminal barrier evidence. For `PICKUP`, a previously moved item is replay only when the stored participant guard matches the same root `EffectId`, immutable request digest, and exact destination container for that actor; another holder or a different destination is a conflict/stale/reconciliation outcome, never a generic replay. Select validation through the shared [Validation and Runtime Proof](../developer-workflows/validation-and-runtime-proof.md) workflow. @@ -198,7 +198,7 @@ Required control-plane interfaces: - `ExternalMaintenanceHandoff` is the unchanged ADR-0085 handoff: exact `operationId`, external maintenance fence/lock binding, classifier, immutable evidence digest, and complete affected scope. The handoff also contains either a sealed exact-effect manifest or an immutable selection predicate plus a frozen owner-resolved member manifest and digest. For each action, the owner atomically resolves the handoff and compares its operation/fence/classifier/evidence digest/affected scope and member membership with the selected effect's immutable guard and current backlog revision/status. A handoff authorizes only its bounded sealed member set; it is not globally single-use, and each member action is independently idempotent through `actionRequestId`/`actionDigest`. Scope widening, stale revision or fence, absent membership, or any mismatch fails closed. The handoff evidence digest does not replace the effect's request digest. - `OwnerRoutineReplayExemption` is an owner-issued, durably recorded non-conflicting exemption. It carries the stable owner-recorded `exemptionId` (and the existing owner authorization/audit record link where applicable), the exact effect identity, exact target, complete affected scope, classification, and immutable evidence digest. The owner persists this record before the request and atomically reads it back and exact-compares those fields with `(tenantId, gameInstanceId, effectId)`, the target, and the requested scope before allowing replay or reconciliation. A caller cannot self-label a request as routine or supply an unverified exemption. -For spatial or ambient maintenance, recovery, or reset mutations invoked through either API, exactly one authority branch must resolve and match before mutation. The selected authority must also pass the common atomic effect-guard and backlog revision/status comparison; an authority that is valid for another effect, target, scope, or revision cannot authorize this action. Ordinary owner-local replay/reconciliation that satisfies the owner exemption may preserve the original `EffectId`; missing, ambiguous, or contradictory handoff/exemption evidence fails closed. Existing operator authorization issuance and redemption policy remains owned by its canonical Account/Logging & Admin contract; this carrier links to that owner evidence rather than redefining it here. +For spatial or ambient maintenance, recovery, or reset mutations invoked through either API, the unchanged ADR 0085 `ExternalMaintenanceHandoff` is always required and must resolve and match before mutation; `OwnerRoutineReplayExemption` cannot authorize maintenance or reset. The handoff must also pass the common atomic effect-guard and backlog revision/status comparison; an authority valid for another effect, target, scope, or revision cannot authorize this action. Ordinary owner-local routine replay or reconciliation outside maintenance and reset may preserve the original `EffectId` only when the owner has explicitly classified it as non-conflicting and the recorded exemption matches. Missing, ambiguous, or contradictory handoff or exemption evidence fails closed. Existing operator authorization issuance and redemption policy remains owned by its canonical Account/Logging & Admin contract; this carrier links to that owner evidence rather than redefining it here. Operational SLOs and alerts: diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 4d9b1e19cd..c48e2c7a85 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -192,3 +192,5 @@ Entry format: - Context: the repository-wide Hosted admission sweep reread the complete review history of merged #2750; an exception became an admission hold even though the live open-PR inventory had already excluded it. - Outcome: the repair is published in #2916 and installed as a separately tested writer-build-5 backport. Confirmed closed PRs no longer require that historical network read. An exact, attributable, locally archived rate-limit response still holds the repository until its proven reset time, including a response whose terminal edit occurred after creation. No historical record, count, or taper decision was removed. - Proof: 118 focused runtime tests, 883 tests against the compatible live-controller baseline, and 920 tests on the owning child passed. The original transient exception's underlying network cause remains unknown; the reproduced failure mode is now covered without weakening open-PR request safety or promoting an unmerged record schema. + - Observation: the Hosted admission inventory must distinguish active candidates from historical closed PRs before any history-dependent slot decision. + - Expected pattern: exclude confirmed closed PRs before reserving a Hosted execution slot; retain only exact, attributable rate-limit evidence as a repository-wide hold through its verified reset time. diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index 5fa7724ccb..5a43fb0de4 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -2572,6 +2572,76 @@ require_contains( "The operation and its producer/consumer proof are currently unimplemented", ], ) +require_contains( + "design/architecture/system-architecture-redis-ops-access.md", + [ + "require Gateway's typed recovery probe through the existing authenticated owning-service maintenance API boundary while shared readiness remains `QUARANTINED`", + "Normal player consume remains `OPEN`-only and is not invoked for this recovery proof", + "timeout, malformed, below-threshold, or uncertain results fail closed", + "This probe remains target-only and unimplemented, so the checklist is not yet executable for this gate", + "[ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md)", + "[Gateway replay readiness](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake)", + "[reset policy matrix](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary)", + ], +) +require_absent( + "design/architecture/system-architecture-redis-ops-access.md", + ["a fresh canonical replay-consume invocation on the same pinned Redis connection"], +) +require_contains( + "design/architecture/system-architecture-redis.md", + [ + "Gateway owns only the shared replay-domain exception: `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and the separately registered recovery-only `gateway:connect-token:{gateway-connect-token-replay-v1}:probe:*`", + "Participant-guard uniqueness also includes the owner-declared runtime-family partition: S1/S2 use `(tenantId, playableStateNamespaceId)`, while only explicitly declared S3 uses `(tenantId, gameInstanceId)`; unknown or unclassified families fail closed.", + "The immutable `requestDigest` binds that identity but is not a uniqueness field or partition substitute; other scope and tick values remain exact evidence.", + ], +) +require_contains( + "design/architecture/decisions/adr-0011-gameplay-session-front-end-and-region-execution.md", + [ + "## Supersession\n\n- Replacement ADR: [ADR 0170](./adr-0170-fenced-command-forwarding-and-authoritative-region-transition.md)", + ], +) +require_contains( + "design/architecture/decisions/adr-0001-scripting-event-ingress-idempotency-identity.md", + [ + "## Supersession\n\n- Replacement ADR: [ADR 0172](./adr-0172-parent-event-and-frozen-handler-execution-identity.md)", + ], +) +require_contains( + "design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md", + [ + "Gateway Service owns the exact connect-token replay, browser-deny, readiness/fence, and recovery-probe key families in the pinned `gateway-connect-token-replay-v1` domain: `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::`, as defined by [ADR 0029](./adr-0029-single-use-gameplay-connect-token-carriage.md).", + "These are bounded Gateway-owned replay and recovery records, not wildcard access or a broader non-owner participation grant.", + ], +) +require_contains( + "design/architecture/microservices/game-design-service/operations.md", + [ + "`VersionPublishCommandServiceImpl` normally records terminal `FAILED` and returns the attempt snapshot for publication failures; `TemporalVersionPublishActivitiesImpl` catches only `PendingReconciliationException` and returns `PENDING`.", + ], +) +require_contains( + "design/architecture/system-architecture-gateway.md", + [ + "When the latest expiry of an affected token is known, the quarantine deadline also covers that token's `exp + firemud.gateway.connectTokenClockSkewMs`; the deadline is the later of these bounds, and admission must never reopen before it.", + "This deadline rule is defined by [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md).", + ], +) +require_contains( + "design/architecture/system-architecture-identifier-glossary.md", + [ + "The owner must allocate and durably persist each generated child's ordinal and owner-scope/root/parent/ordinal-to-child-`EffectId` mapping under the accepted owner contract; deterministic child-ID derivation is only proposed by pending [ADR 0183](./decisions/adr-0183-deterministic-effect-id-allocation-and-replay-binding.md) and is not current target.", + ], +) +require_contains( + "design/architecture/system-architecture-transactions.md", + [ + "Any handoff or recovery path that performs maintenance or reset mutation on this barrier must carry the unchanged [ADR 0085](./decisions/adr-0085-evidence-gated-coordination-replay-and-fenced-reset.md) external maintenance handoff: exact `operationId`, external maintenance fence/lock binding, classifier, immutable evidence digest, and complete affected scope.", + "`OwnerRoutineReplayExemption` is available only for explicitly classified, non-conflicting ordinary owner-local routine replay or reconciliation outside maintenance and reset; it cannot authorize these mutations.", + "A missing or mismatched handoff leaves the barrier `RECONCILIATION_REQUIRED` and fails closed.", + ], +) require_contains( "design/architecture/system-architecture-redis-ops-access.md", [ From 1dd0ff8b132bb0d89b3dd6da54c40b7704a3378d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 22:32:39 +1300 Subject: [PATCH 66/68] Clarify script pin evidence and fail-closed replay cutover --- .../system-architecture-redis-lua-patterns.md | 2 ++ ...em-architecture-scripting-observability-contract.md | 2 +- ...stem-architecture-scripting-scheduler-and-timers.md | 2 +- dev-tools/tests/architecture-doc-contracts.sh | 10 ++++++++++ 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/design/architecture/system-architecture-redis-lua-patterns.md b/design/architecture/system-architecture-redis-lua-patterns.md index 0d9dac1c17..a8cc68a8b4 100644 --- a/design/architecture/system-architecture-redis-lua-patterns.md +++ b/design/architecture/system-architecture-redis-lua-patterns.md @@ -47,6 +47,8 @@ Automation queue-pointer enqueue and rebuild are a separate Cache/Rate-Limit des The Gateway replay-consume descriptor is `gateway-connect-token-replay-consume/v1`: `redis_role=coordination`, `KEYS[1]=gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, `KEYS[2]=gateway:connect-token:{gateway-connect-token-replay-v1}:jti:`, and `KEYS[3]=gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`. The descriptor must require the literal `{gateway-connect-token-replay-v1}` tag on every key, reject the untagged current-drift replay marker, and declare the stable outcomes `1` (marker created), `0` (already replayed), and `-1` (browser denied), with no mutation for `0` or `-1`. Focused contract tests must prove the three keys resolve to one Redis Cluster slot, reject any missing or different tag, preserve readiness/fence and deny-marker race ordering, and keep the same `KEYS` order under RESP2 and RESP3. Migration tests separately inventory/read back the current untagged replay prefix under quarantine and prove that it cannot be accepted by the target descriptor. Select and report implementation and runtime proof using [Validation and Runtime Proof](../developer-workflows/validation-and-runtime-proof.md). +While an untagged legacy `jti` marker may still represent a token accepted in its original window, replay admission remains blocked. Legacy-marker continuity requires proven exact transfer to canonical tagged authority or expiry/quarantine release gates proving the marker unusable; absence of a tagged target key alone never proves the legacy token unused. Resolving that continuity condition does not release quarantine: all ADR 0029 deadline, exact fenced probe, old-writer, and owner release gates still apply. + Browser revocation has a separate descriptor, `gateway-connect-token-browser-revoke/v1`, because its deny-marker mutation and durability acknowledgement are not the three-key replay-consume script contract. It uses `redis_role=coordination`, `KEYS[1]=gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:`, and the token's absolute expiry (including the configured clock-skew allowance) as the bounded marker TTL. A newly created marker may return `1`. An existing marker may return `0` only as an observation; it is not by itself proof on the current connection. Before `WAITAOF`, the existing-marker path must reassert the valid marker with its unchanged original absolute expiry on the same pinned connection, or withhold `DURABLE_BROWSER_REVOKE_ACK` until durability of the original write is proven. It must never extend the expiry. Malformed or conflicting marker state is non-mutating and fails closed. Gateway must immediately issue `WAITAOF requiredLocalAofCount requiredReplicaAofCount firemud.gateway.replayConsumeAckTimeoutMs` on the same pinned connection, with the same exact two-integer threshold validation as replay consumption; only that acknowledgement yields `DURABLE_BROWSER_REVOKE_ACK`. This descriptor must require the literal `{gateway-connect-token-replay-v1}` tag and must not be folded into, or represented as, the replay-consume descriptor's three-key invocation. The current implementation provides neither this deny-marker write nor its `WAITAOF` proof: it is replay-only, untagged, and Cache-bound migration drift. Entity-lock hard rule: each Redis tick Lua invocation may acquire at most one `tick:{tenantRegionTag}:lock:`. Piecemeal acquisition across invocations, a multi-lock whitelist, and a configurable multi-lock count are prohibited. A script fails closed when its declared or supplied key set would require more than one entity lock. Multi-entity invariants belong to an owning transaction or durable effect/workflow path, not Redis lock lifetime. See [ADR 0074](./decisions/adr-0074-one-entity-lock-per-redis-script.md). diff --git a/design/architecture/system-architecture-scripting-observability-contract.md b/design/architecture/system-architecture-scripting-observability-contract.md index 5534b6ce52..8de4d55624 100644 --- a/design/architecture/system-architecture-scripting-observability-contract.md +++ b/design/architecture/system-architecture-scripting-observability-contract.md @@ -78,7 +78,7 @@ The following is the canonical target `script_event_audit` field list (with the - `eventSchemaVersion` (admitted event and payload contract version, including tenant-readiness `onLoad`; see [normative Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields)) - `scriptPatchVersion` - `scriptPinEpoch` (required for gameplay/runtime and scheduler triggers; absent for tenant-readiness `onLoad`) - - `scriptPinControlPlaneRequestId` (retained immutable owner/audit evidence, required with a positive `scriptPinEpoch` for every instance-scoped gameplay/runtime and scheduler trigger; absent with the entire pin tuple for pre-instance requests such as tenant-readiness `onLoad`; epoch-zero records represent explicitly unpinned state only on contracts that support that state and are not valid instance-scoped trigger admission) + - `scriptPinControlPlaneRequestId` (retained immutable owner/audit evidence, required with a positive `scriptPinEpoch` for every instance-scoped gameplay/runtime and scheduler trigger; absent with `scriptPinEpoch` for pre-instance requests such as tenant-readiness `onLoad`, while `scriptPatchVersion` remains required; epoch-zero records represent explicitly unpinned state only on contracts that support that state and are not valid instance-scoped trigger admission) - `scriptEventId` - `isDryRun` (boolean) - `sourceService` (derived from authenticated producer/workload identity for custom/service-specific events; the same value used in ingress dedupe and persisted unchanged in ingress and handler audit; omitted for built-in events that originate entirely within Automation & Scripting) diff --git a/design/architecture/system-architecture-scripting-scheduler-and-timers.md b/design/architecture/system-architecture-scripting-scheduler-and-timers.md index 17325c5842..ac2205ce3a 100644 --- a/design/architecture/system-architecture-scripting-scheduler-and-timers.md +++ b/design/architecture/system-architecture-scripting-scheduler-and-timers.md @@ -113,7 +113,7 @@ When an explicitly preserved tick-aligned interval keeps a logical timer alive a ### End-to-End `onInterval` Timer Lifecycle -This section summarizes how a single `onInterval` timer behaves across normal operation, leader changes, and script reloads, and which Redis keys are authoritative at each step. +This section summarizes how a single `onInterval` timer behaves across normal operation, leader changes, and script reloads. Durable `script_schedule_instances` rows in PostgreSQL are authoritative schedule state; Redis keys are rebuildable coordination projections, as defined by [ADR 0072](./decisions/adr-0072-class-specific-timer-durability-and-recovery.md). Timer, schedule, firing, and catch-up identities must be instance-aware even when Redis keys are region-scoped for slotting and locality. The per-region scheduler runtime-progress hint is intentionally namespace-independent: its opaque key tag carries the full tenant/game/region scope, while its payload carries only `{regionEpoch, latestTickId}`; it is derived progress, never timer, due, or admission identity. diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index 5a43fb0de4..7aa0773363 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -1819,6 +1819,7 @@ require_contains( "`eventType`", "`eventSchemaVersion` (admitted event and payload contract version, including tenant-readiness `onLoad`; see [normative Table 1](./system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields))", "`scriptPatchVersion`", + "absent with `scriptPinEpoch` for pre-instance requests such as tenant-readiness `onLoad`, while `scriptPatchVersion` remains required", ], ) require_contains( @@ -2020,6 +2021,7 @@ require_absent( require_contains( "design/architecture/system-architecture-scripting-scheduler-and-timers.md", [ + "Durable `script_schedule_instances` rows in PostgreSQL are authoritative schedule state; Redis keys are rebuildable coordination projections, as defined by [ADR 0072](./decisions/adr-0072-class-specific-timer-durability-and-recovery.md).", "resume-window record per ``", "its `resumeWindowId` is ``", "The server-derived `playableStateScope` is persisted separately as immutable policy/routing/authorization/migration-fence evidence and is exact-validated; it is not part of the window identity.", @@ -2818,6 +2820,14 @@ require_contains( "current PostgreSQL schedule-definition and schedule-instance substrate", ], ) +require_contains( + "design/architecture/system-architecture-redis-lua-patterns.md", + [ + "While an untagged legacy `jti` marker may still represent a token accepted in its original window, replay admission remains blocked.", + "absence of a tagged target key alone never proves the legacy token unused", + "Resolving that continuity condition does not release quarantine: all ADR 0029 deadline, exact fenced probe, old-writer, and owner release gates still apply.", + ], +) require_contains( "design/architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md", [ From 9e9d7eeca93b7a85ec4d5d3ecfd2eb6575beaa05 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 22:48:32 +1300 Subject: [PATCH 67/68] Clarify per-entity sequencing and bounded maintenance scope --- .../system-architecture-redis-ops-access.md | 2 +- ...chitecture-tick-failures-and-operations.md | 2 +- .../system-architecture-transactions.md | 2 +- design/project-management/ai-observations.md | 5 ++++ dev-tools/tests/architecture-doc-contracts.sh | 25 +++++++++++++++++++ 5 files changed, 33 insertions(+), 3 deletions(-) diff --git a/design/architecture/system-architecture-redis-ops-access.md b/design/architecture/system-architecture-redis-ops-access.md index 3c1aab037d..b9ddbe77ea 100644 --- a/design/architecture/system-architecture-redis-ops-access.md +++ b/design/architecture/system-architecture-redis-ops-access.md @@ -69,7 +69,7 @@ To keep ACL usage consistent across services and documentation, Redis deployment | ACL User (example) | Intended Role | Typical Consumers | | --- | --- | --- | -| `coord_app` (logical profile; distinct principals) | Coordination application clients – may write and run Lua scripts against **Coordination Redis** only through their owner-local helper and within disjoint owner/contract key patterns | `account_coord_app` (Account-owned `session:auth:account:*`, `session:auth:tenant:*`, `session:auth:token:*`, `session:auth:generation:*`, legacy unversioned `session:connect-token:tenant:*`, and target `session:connect-token:v1:tenant:*`), `gateway_coord_app` (Gateway `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:probe:*` only), `gamesession_coord_app` (Game Session `tick:*`, `timer:*`, `retry:*`, `session:game:*`, and the producer side of `tick-events:*`; stream publication uses `XADD` with bounded `MAXLEN`; any `tick-executor-lease:*` access is confined to the owner-local lease helper and its registered lease script, never to a workload-facing raw Redis path), and `automation_coord_app` (Automation-owned target coordination families such as `automation:timer:*` and `script-scheduler:*`; if a target scheduler consumes Redis Streams directly, its owner registration must bind the exact consumer-scoped `tick-events-offset:{tenantRegionTag}:` key, stream/consumer identity, caller principal, and registered script digest to one atomic compare-and-set helper. ACL/key patterns scope which keys and commands a principal may access but do not enforce compare-and-set semantics or restrict a script digest. Offset advancement must therefore go through one typed owner-local API/helper backed by that registered atomic CAS script, binding the exact consumer/key, expected current offset, monotonic next offset, script digest/version, and readback; no generic `SET` or direct Redis write call path is allowed. If direct Redis consumer access remains, its workload-facing principal is read-only (`GET`) for offset keys; the distinct owner-local executor path/principal is narrowly key-scoped and invoked only through the typed API. Its `tick-events:{tenantRegionTag}` stream pattern permits only `XREAD`/`XRANGE`, and its `tick-events-lease:{tenantRegionTag}` pattern permits only the owner-registered lease renewal/release script). Event-stream consumer identities, exact keys, and executable registrations must be complete before granting these latter permissions; absent that registration Automation uses the owner API/heartbeat contract and receives no direct stream or offset grant. Maintenance tooling is API-only and has no `coord_maintenance_app` principal. | +| `coord_app` (logical profile; distinct principals) | Coordination application clients – may write and run Lua scripts against **Coordination Redis** only through their owner-local helper and within disjoint owner/contract key patterns | `account_coord_app` (Account-owned `session:auth:account:*`, `session:auth:tenant:*`, `session:auth:token:*`, `session:auth:generation:*`, legacy unversioned `session:connect-token:tenant:*`, and target `session:connect-token:v1:tenant:*`), `gateway_coord_app` (Gateway `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and `gateway:connect-token:{gateway-connect-token-replay-v1}:probe:*` only), `gamesession_coord_app` (Game Session `tick:*`, `timer:*`, `retry:*`, `session:game:*`, and the producer side of `tick-events:*`; stream publication uses `XADD` with bounded `MAXLEN` as a best-effort coordination hint, not durable stream or work authority (see [Tick Events & Heartbeat Stream](./system-architecture-ticks.md#tick-events--heartbeat-stream)); any `tick-executor-lease:*` access is confined to the owner-local lease helper and its registered lease script, never to a workload-facing raw Redis path), and `automation_coord_app` (Automation-owned target coordination families such as `automation:timer:*` and `script-scheduler:*`; if a target scheduler consumes Redis Streams directly, its owner registration must bind the exact consumer-scoped `tick-events-offset:{tenantRegionTag}:` key, stream/consumer identity, caller principal, and registered script digest to one atomic compare-and-set helper. ACL/key patterns scope which keys and commands a principal may access but do not enforce compare-and-set semantics or restrict a script digest. Offset advancement must therefore go through one typed owner-local API/helper backed by that registered atomic CAS script, binding the exact consumer/key, expected current offset, monotonic next offset, script digest/version, and readback; no generic `SET` or direct Redis write call path is allowed. If direct Redis consumer access remains, its workload-facing principal is read-only (`GET`) for offset keys; the distinct owner-local executor path/principal is narrowly key-scoped and invoked only through the typed API. Its `tick-events:{tenantRegionTag}` stream pattern permits only `XREAD`/`XRANGE`, and its `tick-events-lease:{tenantRegionTag}` pattern permits only the owner-registered lease renewal/release script). Event-stream consumer identities, exact keys, and executable registrations must be complete before granting these latter permissions; absent that registration Automation uses the owner API/heartbeat contract and receives no direct stream or offset grant. Maintenance tooling is API-only and has no `coord_maintenance_app` principal. | | `entity_coord_app` | Entity Management's target Coordination Redis principal for its registered ConflictTracker entity producer; may write/run Lua only against `~conflict:entity:*` | Entity Management ConflictTracker producer scope; no `conflict:session:*` or other owner-family access | | `gamesession_coord_app` | Game Session's target Coordination Redis principal for its registered tick/session families and ConflictTracker session producer; its ConflictTracker grant is exactly `~conflict:session:*` | Game Session tick/session owner paths plus Game Session ConflictTracker producer scope; no `conflict:entity:*` access | diff --git a/design/architecture/system-architecture-tick-failures-and-operations.md b/design/architecture/system-architecture-tick-failures-and-operations.md index b44941fd7c..ad00ecf5a1 100644 --- a/design/architecture/system-architecture-tick-failures-and-operations.md +++ b/design/architecture/system-architecture-tick-failures-and-operations.md @@ -102,7 +102,7 @@ To make replays observable and bounded, Game Session maintains a **tick effect l - optional `pending_digest` or equivalent Redis-pending integrity field; it is not a substitute for the required immutable exact pending envelope or the sealed execution-context binding above - `created_at`, `updated_at` - The selected-work manifest is required for deterministic replay and source cleanup. At minimum it records, per selected source item: - - the tick-batch identity `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)`; separately, its entity-local `entity_enqueue_seq` is allocated monotonically within the complete allocation scope `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch)`. `playableStateScope` is not part of either identity. A reset that bumps `regionEpoch` and restarts `tickId` at `0` starts a new entity-local sequence domain, while old-epoch ordering identities remain immutable and are never rebound even if a numeric sequence value is reused. + - the tick-batch identity `(tenantId, gameInstanceId, regionId, regionEpoch, tickId)`; separately, its entity-local `entity_enqueue_seq` is allocated monotonically within the complete allocation scope `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch, entityId)`. `playableStateScope` is not part of either identity. A reset that bumps `regionEpoch` and restarts `tickId` at `0` starts a new entity-local sequence domain, while old-epoch ordering identities remain immutable and are never rebound even if a numeric sequence value is reused. - `source_kind` - declared `phase`, `lane`, and `cost_class` - source item identity diff --git a/design/architecture/system-architecture-transactions.md b/design/architecture/system-architecture-transactions.md index a9e1554bf1..db374b6d8d 100644 --- a/design/architecture/system-architecture-transactions.md +++ b/design/architecture/system-architecture-transactions.md @@ -198,7 +198,7 @@ Required control-plane interfaces: - `ExternalMaintenanceHandoff` is the unchanged ADR-0085 handoff: exact `operationId`, external maintenance fence/lock binding, classifier, immutable evidence digest, and complete affected scope. The handoff also contains either a sealed exact-effect manifest or an immutable selection predicate plus a frozen owner-resolved member manifest and digest. For each action, the owner atomically resolves the handoff and compares its operation/fence/classifier/evidence digest/affected scope and member membership with the selected effect's immutable guard and current backlog revision/status. A handoff authorizes only its bounded sealed member set; it is not globally single-use, and each member action is independently idempotent through `actionRequestId`/`actionDigest`. Scope widening, stale revision or fence, absent membership, or any mismatch fails closed. The handoff evidence digest does not replace the effect's request digest. - `OwnerRoutineReplayExemption` is an owner-issued, durably recorded non-conflicting exemption. It carries the stable owner-recorded `exemptionId` (and the existing owner authorization/audit record link where applicable), the exact effect identity, exact target, complete affected scope, classification, and immutable evidence digest. The owner persists this record before the request and atomically reads it back and exact-compares those fields with `(tenantId, gameInstanceId, effectId)`, the target, and the requested scope before allowing replay or reconciliation. A caller cannot self-label a request as routine or supply an unverified exemption. -For spatial or ambient maintenance, recovery, or reset mutations invoked through either API, the unchanged ADR 0085 `ExternalMaintenanceHandoff` is always required and must resolve and match before mutation; `OwnerRoutineReplayExemption` cannot authorize maintenance or reset. The handoff must also pass the common atomic effect-guard and backlog revision/status comparison; an authority valid for another effect, target, scope, or revision cannot authorize this action. Ordinary owner-local routine replay or reconciliation outside maintenance and reset may preserve the original `EffectId` only when the owner has explicitly classified it as non-conflicting and the recorded exemption matches. Missing, ambiguous, or contradictory handoff or exemption evidence fails closed. Existing operator authorization issuance and redemption policy remains owned by its canonical Account/Logging & Admin contract; this carrier links to that owner evidence rather than redefining it here. +For spatial or ambient maintenance or reset mutations invoked through either API, the unchanged ADR 0085 `ExternalMaintenanceHandoff` is always required and must resolve and match before mutation, including in recovery paths that perform maintenance or reset mutations; `OwnerRoutineReplayExemption` cannot authorize maintenance or reset. The handoff must also pass the common atomic effect-guard and backlog revision/status comparison; an authority valid for another effect, target, scope, or revision cannot authorize this action. Ordinary owner-local routine replay or reconciliation outside maintenance and reset may preserve the original `EffectId` only when the owner has explicitly classified it as non-conflicting and the recorded exemption matches. Missing, ambiguous, or contradictory handoff or exemption evidence fails closed. Existing operator authorization issuance and redemption policy remains owned by its canonical Account/Logging & Admin contract; this carrier links to that owner evidence rather than redefining it here. Operational SLOs and alerts: diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index c48e2c7a85..e61395ce50 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -194,3 +194,8 @@ Entry format: - Proof: 118 focused runtime tests, 883 tests against the compatible live-controller baseline, and 920 tests on the owning child passed. The original transient exception's underlying network cause remains unknown; the reproduced failure mode is now covered without weakening open-PR request safety or promoting an unmerged record schema. - Observation: the Hosted admission inventory must distinguish active candidates from historical closed PRs before any history-dependent slot decision. - Expected pattern: exclude confirmed closed PRs before reserving a Hosted execution slot; retain only exact, attributable rate-limit evidence as a repository-wide hold through its verified reset time. + +- 2026-10-01: Keep validation-script inputs stable during execution. + - Context: an architecture-contract run passed its test cases but then read a truncated final command after the same shell script was edited while its process was still running. A complete rerun against the finished script passed. + - Observation: a shell process may continue reading its script after earlier commands finish; editing that script during execution can invalidate the run independently of the corrected contract. + - Expected pattern: finish script edits before starting its validation, or discard the affected run as proof and rerun the complete named check after edits settle. Do not diagnose the resulting partial command as a missing repository tool without checking the input race. diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index 7aa0773363..ffe4826ab0 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -2231,6 +2231,7 @@ require_contains( "bounded batches per complete recovery scope ``", "fairness cursors and deficit/cost accounting are keyed by the complete recovery scope", "service startup for each complete recovery scope", + "`entity_enqueue_seq` is allocated monotonically within the complete allocation scope `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch, entityId)`", ], ) require_absent( @@ -2239,6 +2240,7 @@ require_absent( "bounded batches per ``", "scheduling across regions rather than draining one region completely", "service startup for each region to converge", + "complete allocation scope `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, regionEpoch)`", ], ) for tick_commit_path in ( @@ -2546,6 +2548,29 @@ require_contains( "Otherwise the command remains unresolved for evidence-qualified reconciliation", ], ) +require_contains( + "design/architecture/system-architecture-transactions.md", + [ + "For spatial or ambient maintenance or reset mutations invoked through either API", + "including in recovery paths that perform maintenance or reset mutations", + "Ordinary owner-local routine replay or reconciliation outside maintenance and reset may preserve the original `EffectId` only when the owner has explicitly classified it as non-conflicting and the recorded exemption matches.", + ], +) +require_absent( + "design/architecture/system-architecture-transactions.md", + [ + "For spatial or ambient maintenance, recovery, or reset mutations invoked through either API", + ], +) +require_contains( + "design/architecture/system-architecture-redis-ops-access.md", + [ + "stream publication uses `XADD` with bounded `MAXLEN` as a best-effort coordination hint, not durable stream or work authority", + "[Tick Events & Heartbeat Stream](./system-architecture-ticks.md#tick-events--heartbeat-stream)", + "its workload-facing principal is read-only (`GET`) for offset keys", + "absent that registration Automation uses the owner API/heartbeat contract and receives no direct stream or offset grant", + ], +) require_contains( "design/architecture/system-architecture-redis.md", [ From ad467b03d270dd7b2217c294a60db1bb0c620393 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 1 Oct 2026 23:20:51 +1300 Subject: [PATCH 68/68] docs(runtime): distinguish current safety seams from target recovery proof --- .../api-contracts.md | 2 +- .../runtime-and-data.md | 2 +- .../world-creation-workflow.md | 2 +- ...tem-architecture-redis-incident-runbook.md | 3 +- .../system-architecture-redis-ops-access.md | 2 +- .../architecture/system-architecture-redis.md | 2 +- design/project-management/ai-observations.md | 2 +- dev-tools/tests/architecture-doc-contracts.sh | 33 ++++++++++++++++++- 8 files changed, 40 insertions(+), 8 deletions(-) diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md index b85785acca..6839cc3dc8 100644 --- a/design/architecture/microservices/automation-scripting-service/api-contracts.md +++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md @@ -86,7 +86,7 @@ On the current public Automation & Scripting API, `workItemId` and `workItemIds` Domain services such as Game Session and Game Logic deliver automation events through event-ingress RPCs (for example `TriggerScriptEvent`). The required identity fields, endpoint ownership, and audit behavior are defined in the [normative scripting contract tables](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields); the following list describes the service-local wire envelope: - The current `TriggerScriptEventRequest` carries `tenantId`, `gameInstanceId`, `regionId`, and `entityId` when applicable. `playableStateNamespaceId` is part of the target runtime identity but is absent from the current proto; see the canonical [normative scripting contract tables](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields) for target identity requirements. -- `playableStateScope` is carried for gameplay-originated events as separately persisted, exact-validated policy/routing/authorization/migration-fence evidence. Current scope evidence does not prove the complete target namespace/scope tuple. It stays explicit for handler/work fencing and operator read models but is excluded from Trigger Identity, timer-follow-up identity, uniqueness, and deduplication keys; see the [normative identity tables](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). +- `playableStateScope` is carried for gameplay-originated events and persisted in ingress and work records as policy/routing/authorization/migration-fence evidence. Current ingress compares the request scope with runtime-owner state only when both values are present, so this evidence does not prove the complete target namespace/scope tuple or owner binding. It stays explicit for handler/work fencing and operator read models but is excluded from Trigger Identity, timer-follow-up identity, uniqueness, and deduplication keys; see the [normative identity tables](../../system-architecture-scripting-normative-contract-tables.md#table-1-trigger-identity-required-fields). - `regionEpoch` for gameplay/runtime triggers and scheduler triggers so Trigger Identity is fenced across scoped coordination resets. - `scriptEventId` in the normalized applicable Trigger Identity. Its wire requirement follows the [ingress ownership matrix](../../system-architecture-scripting-normative-contract-tables.md#table-1a-event-ingress-scripteventid-ownership-matrix), and it is not a complete idempotency key by itself. - `isDryRun` so live and dry-run/test traffic are always in separate idempotency namespaces. 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 ff61966c20..b9eaa2b9eb 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -73,7 +73,7 @@ Entity Management must classify its runtime persistence surface for cutover and - `S3` entity-owned ephemeral state: - synthetic room-ground containers and their contents keyed by `(tenantId, gameInstanceId, roomInstanceId)`; - transient containment, encounter-specific entities, corpses, summons, or equivalent rows whose lifecycle is tied to the source `gameInstanceId`; - - Target-only `entity_tick_state` watermark rows keyed by `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, targetAggregateType, entityId)` for the concrete instance/region timeline; `playableStateScope` is separately persisted and exact-validated evidence, not a key dimension. No such live table or projection is currently implemented: the live schema has `entity_mutation_effects` for narrower effect/operation replay instead. Entity exact-validates the owner-resolved `playableStateNamespaceId` and immutable `playableStateScope` pair before reading or writing this future disposable watermark; neither value is inferred from an entity or instance id. Replay reads that exact row and compares `(last_region_epoch, last_tick_id)`, while durable S1/S2 effect replay continues to use the stable namespace plus structured `EffectId`/operation/target/request-digest guard rather than this watermark; + - Target-only `entity_tick_state` watermark rows keyed by `(tenantId, gameInstanceId, playableStateNamespaceId, regionId, targetAggregateType, entityId)` for the concrete instance/region timeline; `playableStateScope` is separately persisted and exact-validated evidence, not a key dimension. No such live table or projection is currently implemented: the live schema has `entity_mutation_effects` for narrower effect/operation replay instead. Entity exact-validates the owner-resolved `playableStateNamespaceId` and immutable `playableStateScope` pair before reading or writing this future disposable watermark; neither value is inferred from an entity or instance id. Replay reads that exact row and compares `(last_region_epoch, last_tick_id)`, while current durable effect replay uses the `{tenantId, effectId}` table with operation-name-only matching; the namespace/scope/fence, typed-target, and request-digest guard remains target-only; - any row family explicitly documented as instance-scoped only. ### Conservative Current Implementation Inventory 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 40bfe0b055..742fb1afaa 100644 --- a/design/architecture/microservices/world-management-service/world-creation-workflow.md +++ b/design/architecture/microservices/world-management-service/world-creation-workflow.md @@ -176,7 +176,7 @@ Temporal owns orchestration and workflow progress using the canonical `world-lif The target workflow must represent each activate, fail, or terminate request as a durable queued signal/update envelope carrying a stable operation identity, normalized request digest, and expected lifecycle epoch/status. Owner-generated CAS evidence is recorded in the result only after the local lifecycle CAS commits as the winner; it is not request-envelope authority. Exact retries read back one logical result; changed identity, digest, status, or epoch fails closed, and conflicting lifecycle operations follow explicit precedence/conflict rules rather than last-writer-wins behavior. A signal may not be combined with or overwrite another logical operation whose outcome is still unresolved. -**Current implementation gap:** `TemporalWorldLifecycleWorkflowImpl` stores only one pending epoch/reason per signal type and has no operation identity or digest. Repeated same-type signals overwrite one another, while an activate and terminate received together are both processed sequentially; termination then reuses the pre-activation epoch after activation has advanced it and can retry until the workflow fails. The current `TemporalWorldLifecycleOrchestrator`/workflow path therefore does not provide one durable lifecycle result for concurrent or lost signal requests. This is in addition to the existing `AlreadyStarted` identity-comparison gap above and remains unproved until the queued envelope, owner lifecycle CAS, conflict handling, and readback result are implemented. +**Current implementation gap:** `TemporalWorldLifecycleWorkflowImpl` stores only one pending epoch/reason per signal type and has no operation identity or digest. Repeated same-type signals overwrite one another, while an activate and terminate received together are both processed sequentially; termination then reuses the pre-activation epoch after activation has advanced it, with stale-epoch retries bounded to five termination-activity attempts. The current `TemporalWorldLifecycleOrchestrator`/workflow path therefore does not provide one durable lifecycle result for concurrent or lost signal requests. This is in addition to the existing `AlreadyStarted` identity-comparison gap above and remains unproved until the queued envelope, owner lifecycle CAS, conflict handling, and readback result are implemented. See [World Management Service](README.md) for additional service context. diff --git a/design/architecture/system-architecture-redis-incident-runbook.md b/design/architecture/system-architecture-redis-incident-runbook.md index af39a2cbab..85ba33cdc7 100644 --- a/design/architecture/system-architecture-redis-incident-runbook.md +++ b/design/architecture/system-architecture-redis-incident-runbook.md @@ -154,7 +154,8 @@ Before entering this measured-SLO detect/decide path, verify that the affected d 3. The recovery workflow runs its internal ledger and command-convergence phases, converging lingering epoch-13 `SCHEDULED` rows to `APPLIED` or `ABANDONED` without bumping `region_epoch` only where durable evidence permits; inconclusive rows remain reconciliation-required, and command records follow the canonical terminal vocabulary. 4. If pending age and stalled signals recover within one emitted budget window, the region stays on epoch `13`; otherwise the controller upgrades the same operation and maintenance lock to `reset_first`. 2. If the controller-validated classification is `reset_first`: - - Execute the [Canonical Coordination Reset Sequence](./system-architecture-redis-operations.md#canonical-coordination-reset-sequence) for the same scope. + - **Target state only, once the canonical gated coordination-maintenance operation is implemented and proven:** Execute the [Canonical Coordination Reset Sequence](./system-architecture-redis-operations.md#canonical-coordination-reset-sequence) for the same scope. + - **Current deployments:** Do not execute the reset or mutate raw coordination keys. Preserve evidence, keep the affected scope fenced or stopped, use only the shipped `PauseTicksForScope` / `GetRuntimeOwnershipStatus` boundary and `coord_ops_ro` read-only inspection, then follow the [Current Operator Fallback](./system-architecture-redis-reset-and-recovery.md#current-operator-fallback). - Keep only the incident-specific choices local to this runbook: scope selection, whether `replay_first` was exhausted first, whether gameplay sessions are preserved, and what evidence justified escalation. 3. Verify region health returns to `RUNNING` or bounded `DEGRADED` and eligible-profile measured exposure, including `redis_unreplicated_write_window_ms{scope}`, returns within `redis_unreplicated_write_window_slo_ms` for the same deployment/environment/ruleset scope after the controller-validated recovery classification completes. If replay cannot complete before `RESUME_AUTHORIZED`, the operation remains paused and quarantined until reset escalation or audited `release-lock`. A failure after `RESUME_AUTHORIZED` is reconciled only through the same operation's internal release worker; `release-lock` is prohibited. diff --git a/design/architecture/system-architecture-redis-ops-access.md b/design/architecture/system-architecture-redis-ops-access.md index b9ddbe77ea..b7c15d415a 100644 --- a/design/architecture/system-architecture-redis-ops-access.md +++ b/design/architecture/system-architecture-redis-ops-access.md @@ -10,7 +10,7 @@ The target control-plane and maintenance contract in this document is ahead of t - The live implementation supports the current `{tenantId, gameInstanceId}` queue boundary; `regionId` is present in the proto contract but is currently rejected by the service implementation. - The bounded `coordination-maintenance ...` public surface remains target state, not a description of fully implemented repo-local tooling today. No public recovery scope is currently implemented and proven; recovery phases may be implemented and tested behind the high-level operation without becoming separate public commands. - The owning-service typed maintenance API, role-bound Redis helper surface, aggregated registry, descriptor validators, and ownership-enforcement checks described below are target state and are not implemented; current direct access remains subject to the generic runtime seam and the incident-only fallback. -- Reset-smoke isolation is a separate mechanism decision: the existing [Game Session readiness-only identity contract](./microservices/game-session-service/operations.md#readiness-and-liveness) and [synthetic player-flow canary contract](./system-architecture-logging-monitoring.md#synthetic-player-flow-canaries-target-state-prod-like-contract) do not define an isolated reset-smoke namespace or durable synthetic identity that can safely map to tick staging and ledger rows. Automation's separate [`isDryRun=true` namespace](./system-architecture-scripting-contracts.md#6-dry-run--test-traffic-safety) is explicitly non-committing and cannot reach tick queues, so it is not a reset-smoke identity. Until a reset-smoke mechanism decision is accepted and implemented, `RunPostResetSmokeCheck` is non-mutating for real PostgreSQL tick state, real Redis tick metadata/staging/pending, and real tick-ledger rows. It may perform only bounded sampled lease acquire/renew/release probes and, when the workflow affects the shared replay domain, require Gateway's typed recovery probe through the existing authenticated owning-service maintenance API boundary while shared readiness remains `QUARANTINED`. Normal player consume remains `OPEN`-only and is not invoked for this recovery proof. The probe's durability acknowledgement and fenced evidence must satisfy [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md), [Gateway replay readiness](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake), and the [reset policy matrix](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary); timeout, malformed, below-threshold, or uncertain results fail closed, and successful probe evidence does not bypass any other recovery gate or authorize reopening by itself. This probe remains target-only and unimplemented, so the checklist is not yet executable for this gate. The current writer's untagged replay marker remains migration-only drift and is not target proof, and reset-smoke must not enter real staging or ledger paths. +- Reset-smoke isolation is a separate mechanism decision: the existing [Game Session readiness-only identity contract](./microservices/game-session-service/operations.md#readiness-and-liveness) and [synthetic player-flow canary contract](./system-architecture-logging-monitoring.md#synthetic-player-flow-canaries-target-state-prod-like-contract) do not define an isolated reset-smoke namespace or durable synthetic identity that can safely map to tick staging and ledger rows. Automation's separate [`isDryRun=true` namespace](./system-architecture-scripting-contracts.md#6-dry-run--test-traffic-safety) is explicitly non-committing and cannot reach tick queues, so it is not a reset-smoke identity. Until a reset-smoke mechanism decision is accepted and implemented, `RunPostResetSmokeCheck` is non-mutating for real PostgreSQL tick state, real Redis tick metadata/staging/pending, and real tick-ledger rows. It may perform bounded sampled lease acquire/renew/release probes and, when the workflow affects the shared replay domain, require Gateway's typed recovery probe over the existing authenticated owning-service transport boundary only; that boundary provides authenticated transport, but no recovery endpoint is implemented while shared readiness remains `QUARANTINED`. Existing ACL-denial probes may also run through the documented isolated disposable/protected harness: key-scoped denials use a protected probe namespace that cannot contain shared deployment data, while `FLUSHALL`, `FLUSHDB`, and `SCRIPT FLUSH` denials run only against an isolated disposable target with required cleanup/readback and never real tick state. Normal player consume remains `OPEN`-only and is not invoked for this recovery proof. The probe's durability acknowledgement and fenced evidence must satisfy [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md), [Gateway replay readiness](./system-architecture-gateway.md#tenant-aware-edge-connect-token-gameplay-handshake), and the [reset policy matrix](./system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary); timeout, malformed, below-threshold, or uncertain results fail closed, and successful probe evidence does not bypass any other recovery gate or authorize reopening by itself. This probe remains target-only and unimplemented, so the checklist is not yet executable for this gate. The current writer's untagged replay marker remains migration-only drift and is not target proof, and reset-smoke must not enter real staging or ledger paths. Use this doc as the canonical target-state contract for later reset/replay tooling, but do not assume every operation below is already available in the running codebase. Current operators, runbooks, Helm hooks, Jobs, and dashboards must not invoke the `coordination-maintenance` commands described below until that surface is implemented and end-to-end proven. diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index a2d8d7cc07..7e8799f5db 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -630,7 +630,7 @@ Key principles: - Gateway's recovery-only disposable marker family `gateway:connect-token:{gateway-connect-token-replay-v1}:probe::` is a separately registered Coordination Redis prefix owned by Gateway. Its ACL and reset inventories are distinct from player `jti`, deny, and readiness data; see the target-only probe contract in [ADR 0029](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md). - Cache and rate‑limit prefixes (for example `inventory:*`, `view:room-look:*`, `ratelimit:*`) live **only** on Cache/Rate‑Limit Redis. -- Coordination prefix ownership is normative: Account owns the live legacy `session:auth:account:*` and `session:auth:tenant:*` projections, the target `session:auth:token:*` exact-token registry, the target `session:auth:generation:*` authority-generation projections, and the target `session:connect-token:*` exact-input issuance-result projections. Gateway owns only the shared replay-domain exception: `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and the separately registered recovery-only `gateway:connect-token:{gateway-connect-token-replay-v1}:probe:*`; this does not grant gameplay-session, Account-auth, or general coordination ownership. Game Session owns the separately approved gameplay families under `session:game:*`, including `session:game:auth:issuer-generation:v1:`; it never owns the Account auth or connect-token issuance prefixes, and no wildcard `session:auth:*` grant is implied. Game Session also owns `tick:*`, `timer:*`, `retry:*`, and `tick-executor-lease:*`; it does not own or mutate the target-only, unimplemented Automation & Scripting families `automation:timer:*` or `script-scheduler:*`. The retired `automation:tick:*` staging path is not part of the live design or active prefix inventory. Automation & Scripting owns its current automation prefixes and the reserved target families once implemented, while its Cache/Rate-Limit families `automation:queue:*`, `automation:quota:*`, `automation:tenant-budget:*`, `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` remain separate; non-owner participation is contract-bound through approved helpers. The shared `conflict:*` diagnostic family is Coordination-only, reset-tolerant, and non-authoritative: `common-data-runtime` owns the mutation helper, while Game Session and Entity Management own the producer scopes that call it. Its target deployed principals are distinct: `entity_coord_app` has the exact `~conflict:entity:*` grant and no `conflict:session:*` or other owner-family grant, while `gamesession_coord_app` has the exact `~conflict:session:*` grant in addition to its separately registered Game Session families and no `conflict:entity:*` grant. No shared principal, generic maintenance principal, or helper-library identity may cross those producer-owner boundaries. Current `conflict:entity::` and `conflict:session::` writes use the generic Redis client and separate `INCR`/`EXPIRE` calls with warning-only expiry failure; both endpoint placement and mutation shape are implementation drift. The target accepts only those registered producer kinds and canonical scope identifiers, permits one key per admitted producer scope, enforces a finite deployment key-cardinality cap with overflow sampled or aggregated rather than creating arbitrary keys, and uses a 300-second inactivity TTL unless an owner-approved profile states a shorter bound. The target uses named Coordination clients and these distinct `coord_app` principals only, never cache ACLs, and converges the mutation through a registered single-key atomic helper/script that performs both `INCR` and `PEXPIRE` on every accepted increment so the inactivity TTL is refreshed atomically. The existing `RedisAtomicOperations.incrementWithTtl` helper sets expiry only when the count is first created and therefore does not satisfy this sliding-inactivity contract unless it is extended; this is target guidance, not a claim that the current tracker implements it. The live Entity `TickLockServiceImpl` `tick:lock::` family is an unscoped implementation-drift writer, not a second Game Session authority; it remains fenced/unregistered for target reset and admission until routed through the canonical full-runtime-scope helper. See `design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md`, with later canonical owner contracts including ADR 0029 defining the Gateway replay carrier. +- Coordination prefix ownership is normative: Account owns the live legacy `session:auth:account:*` and `session:auth:tenant:*` projections, the target `session:auth:token:*` exact-token registry, the target `session:auth:generation:*` authority-generation projections, and the target `session:connect-token:v1:*` exact-input issuance-result projections. The current legacy result map remains a separate unversioned `session:connect-token:*` family and is owner-cleaned only after its TTL/retry horizon; both families remain Account-owned. Gateway owns only the shared replay-domain exception: `gateway:connect-token:{gateway-connect-token-replay-v1}:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:deny:jti:*`, `gateway:connect-token:{gateway-connect-token-replay-v1}:readiness`, and the separately registered recovery-only `gateway:connect-token:{gateway-connect-token-replay-v1}:probe:*`; this does not grant gameplay-session, Account-auth, or general coordination ownership. Game Session owns the separately approved gameplay families under `session:game:*`, including `session:game:auth:issuer-generation:v1:`; it never owns the Account auth or connect-token issuance prefixes, and no wildcard `session:auth:*` grant is implied. Game Session also owns `tick:*`, `timer:*`, `retry:*`, and `tick-executor-lease:*`; it does not own or mutate the target-only, unimplemented Automation & Scripting families `automation:timer:*` or `script-scheduler:*`. The retired `automation:tick:*` staging path is not part of the live design or active prefix inventory. Automation & Scripting owns its current automation prefixes and the reserved target families once implemented, while its Cache/Rate-Limit families `automation:queue:*`, `automation:quota:*`, `automation:tenant-budget:*`, `automation:test:quota:*`, `automation:test:capacity:*`, and `automation:readiness:capacity:*` remain separate; non-owner participation is contract-bound through approved helpers. The shared `conflict:*` diagnostic family is Coordination-only, reset-tolerant, and non-authoritative: `common-data-runtime` owns the mutation helper, while Game Session and Entity Management own the producer scopes that call it. Its target deployed principals are distinct: `entity_coord_app` has the exact `~conflict:entity:*` grant and no `conflict:session:*` or other owner-family grant, while `gamesession_coord_app` has the exact `~conflict:session:*` grant in addition to its separately registered Game Session families and no `conflict:entity:*` grant. No shared principal, generic maintenance principal, or helper-library identity may cross those producer-owner boundaries. Current `conflict:entity::` and `conflict:session::` writes use the generic Redis client and separate `INCR`/`EXPIRE` calls with warning-only expiry failure; both endpoint placement and mutation shape are implementation drift. The target accepts only those registered producer kinds and canonical scope identifiers, permits one key per admitted producer scope, enforces a finite deployment key-cardinality cap with overflow sampled or aggregated rather than creating arbitrary keys, and uses a 300-second inactivity TTL unless an owner-approved profile states a shorter bound. The target uses named Coordination clients and these distinct `coord_app` principals only, never cache ACLs, and converges the mutation through a registered single-key atomic helper/script that performs both `INCR` and `PEXPIRE` on every accepted increment so the inactivity TTL is refreshed atomically. The existing `RedisAtomicOperations.incrementWithTtl` helper sets expiry only when the count is first created and therefore does not satisfy this sliding-inactivity contract unless it is extended; this is target guidance, not a claim that the current tracker implements it. The live Entity `TickLockServiceImpl` `tick:lock::` family is an unscoped implementation-drift writer, not a second Game Session authority; it remains fenced/unregistered for target reset and admission until routed through the canonical full-runtime-scope helper. See `design/architecture/decisions/adr-0009-coordination-redis-ownership-boundary.md`, with later canonical owner contracts including ADR 0029 defining the Gateway replay carrier. - New prefixes must be registered in the canonical catalogs: - Coordination prefixes and their reset policies belong in the reset policy matrix and any extended catalogs in `system-architecture-redis-reset-and-recovery.md`. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index e61395ce50..c781f02d55 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -195,7 +195,7 @@ Entry format: - Observation: the Hosted admission inventory must distinguish active candidates from historical closed PRs before any history-dependent slot decision. - Expected pattern: exclude confirmed closed PRs before reserving a Hosted execution slot; retain only exact, attributable rate-limit evidence as a repository-wide hold through its verified reset time. -- 2026-10-01: Keep validation-script inputs stable during execution. +- `2026-10-01`: Keep validation-script inputs stable during execution - Context: an architecture-contract run passed its test cases but then read a truncated final command after the same shell script was edited while its process was still running. A complete rerun against the finished script passed. - Observation: a shell process may continue reading its script after earlier commands finish; editing that script during execution can invalidate the run independently of the corrected contract. - Expected pattern: finish script edits before starting its validation, or discard the affected run as proof and rerun the complete named check after edits settle. Do not diagnose the resulting partial command as a missing repository tool without checking the input race. diff --git a/dev-tools/tests/architecture-doc-contracts.sh b/dev-tools/tests/architecture-doc-contracts.sh index ffe4826ab0..8fac6f243a 100644 --- a/dev-tools/tests/architecture-doc-contracts.sh +++ b/dev-tools/tests/architecture-doc-contracts.sh @@ -2602,7 +2602,10 @@ require_contains( require_contains( "design/architecture/system-architecture-redis-ops-access.md", [ - "require Gateway's typed recovery probe through the existing authenticated owning-service maintenance API boundary while shared readiness remains `QUARANTINED`", + "require Gateway's typed recovery probe over the existing authenticated owning-service transport boundary only; that boundary provides authenticated transport, but no recovery endpoint is implemented while shared readiness remains `QUARANTINED`", + "Existing ACL-denial probes may also run through the documented isolated disposable/protected harness", + "key-scoped denials use a protected probe namespace that cannot contain shared deployment data", + "`FLUSHALL`, `FLUSHDB`, and `SCRIPT FLUSH` denials run only against an isolated disposable target with required cleanup/readback and never real tick state", "Normal player consume remains `OPEN`-only and is not invoked for this recovery proof", "timeout, malformed, below-threshold, or uncertain results fail closed", "This probe remains target-only and unimplemented, so the checklist is not yet executable for this gate", @@ -2932,6 +2935,34 @@ require_contains( "[ADR 0029 readiness proof](./decisions/adr-0029-single-use-gameplay-connect-token-carriage.md)", ], ) +require_contains( + "design/architecture/system-architecture-redis.md", + [ + "the target `session:connect-token:v1:*` exact-input issuance-result projections", + "The current legacy result map remains a separate unversioned `session:connect-token:*` family", + "both families remain Account-owned", + "Gateway owns only the shared replay-domain exception", + "it never owns the Account auth or connect-token issuance prefixes", + ], +) +require_absent( + "design/architecture/system-architecture-redis.md", + ["the target `session:connect-token:*` exact-input issuance-result projections"], +) +require_contains( + "design/architecture/system-architecture-redis-incident-runbook.md", + [ + "**Target state only, once the canonical gated coordination-maintenance operation is implemented and proven:** Execute the [Canonical Coordination Reset Sequence]", + "**Current deployments:** Do not execute the reset or mutate raw coordination keys. Preserve evidence, keep the affected scope fenced or stopped, use only the shipped `PauseTicksForScope` / `GetRuntimeOwnershipStatus` boundary and `coord_ops_ro` read-only inspection, then follow the [Current Operator Fallback]", + ], +) +require_contains( + "design/architecture/system-architecture-redis-ops-access.md", + [ + "require Gateway's typed recovery probe over the existing authenticated owning-service transport boundary only; that boundary provides authenticated transport, but no recovery endpoint is implemented", + "This probe remains target-only and unimplemented", + ], +) require_contains( "design/architecture/system-architecture-scripting-contracts.md", [