PR #3269 review history
Unit 1A · identity, Account and public JOIN
Review rounds
Three-number pills mean: found (raw) / accepted here (useful) / routed
Recorded review history
Reviews and findings
- Hosted Review 1 CompletedRuntime 10m 45sFound: 8 Accepted: 0/3/4 Routed: 1
- Preserve terminal-read status codes in Account settlement.Minor
Both settlement paths map every owner error except
FAILED_PRECONDITIONtoUNAVAILABLE. A missing receipt can therefore bypass Account’s “not committed” handling, whileALREADY_EXISTSandDATA_LOSScan appear retryable.Preserve these owner statuses for both Automation and Entity, then add boundary tests for the absent, conflicting, and corrupt receipt cases.
if (failure.getStatus().getCode() == Status.Code.FAILED_PRECONDITION) { throw Status.FAILED_PRECONDITION .withDescription("Automation terminal evidence is not committed") .asRuntimeException(); } + Status.Code code = failure.getStatus().getCode(); + if (code == Status.Code.NOT_FOUND + || code == Status.Code.ALREADY_EXISTS + || code == Status.Code.DATA_LOSS) { + throw failure; + } throw Status.UNAVAILABLE .withDescription("Automation terminal evidence is unavailable") .asRuntimeException();Apply the same status-preservation block to the Entity catch path.
Route · PR #3269 → PR #3249 Accepted/FixedVerified both Account settlement catch paths hide NOT_FOUND/ALREADY_EXISTS/DATA_LOSS as UNAVAILABLE. Account implementation is owned by parent #3249; route there for exact status propagation and boundary cases. View routed finding - Use the base-class lifecycle helpers here as well.Trivial
This client has the same duplicated
closed/initializedstate asGrpcAutomationSelectedSourceIntakeCommandClient(Lines 36-66 and 119-137 of that file). It also overridesclose()the same way. Replaceinit()withinitOnce(...)andrequireStub()withrequireInitializedStub(...). Then remove theclose()override. Share the mTLS file checks and the workload-context checks with the Automation client through one helper. The full diff is in the Automation client comment.Also applies to: 118-136
- Accepted Entity duplicates same base lifecycle and sibling mTLS/workload guards. Include in one shared scoped client fix; preserve exact peer and namespace checks.
- Replace the PR-process narrative with current-state status, and reconcile the qualification SHA.Minor
This section records PR-workflow history, not canonical current state:
- "receiving parent
a929" is an abbreviated, unresolvable SHA. - The text says the 56 postimages were "preserved byte-for-byte".
- The text says "No CodeRabbit review or new GitHub CI pass is claimed".
- The text describes a single PostgreSQL container that was "independently confirmed absent".
Line 13 cites source
f9e3f879…for the 1,105-case gate. The PR description cites2ffbe651…for the same 1,105-case, 224-suite result. Make the tracker name the one commit that the proof actually ran at. Remove or move the transitional merge and review commentary to the PR. Keep only the scoped proof result, its commit, and the remaining gap: the fresh whole-service Entity and Automation gate. As per path instructions: "Flag obsolete transitional guidance".- Accepted Tracker/current PR cite different SHAs for same 1105 cases and include obsolete carry/review narrative. Verify archived execution SHA; record bounded current status and preserve failed aggregate attribution in PR.
- "receiving parent
- Close the stale-snapshot gap in the Entity reservation guard.Minor
The guard reads
entity_empty_source_numeric_key_reservationwith the caller's snapshot. Consider a writer that runs at REPEATABLE READ or SERIALIZABLE and takes its snapshot before a founder commits:- The writer waits for the founder's SHARE locks to release.
- The writer then inserts into
itemsand other source tables. - Its trigger does not see the new
CANONICAL_EMPTY_SOURCErow, so it accepts a row inside the reserved scope.
The receipt then claims an empty scope that is no longer empty. The Automation guard in V1003 already rejects this case: it checks
transaction_isolation, andstaleRepeatableReadWritersCannotMissACommittedCanonicalReservationtests it. Entity has no equivalent check.Apply the same isolation check here and in
entity_reject_source_truncate. Also add a matching stale-snapshot PostgreSQL test.🔒️ Proposed fix
BEGIN + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Entity source row writes require READ COMMITTED isolation'; + END IF; IF requested_key IS NULL OR requested_key <= 0 THEN RETURN; END IF;- Accepted Entity reservation and TRUNCATE guards consult old caller snapshot without READ COMMITTED requirement. Match Automation guard before lookup and add actual stale-snapshot PostgreSQL refusal proof.
- Extract the duplicated digest and parsing helpers into one shared helper.Trivial
The following code is byte-for-byte identical in
EntitySelectedEmptyPublicationDigestService:contentDigest,appendSegment,canonicalUuid,canonicalPositiveLong, andrequireOriginalPublicationRequest. The only differences are the domain string, the schema constant, and the message prefix. The two services claim one shared framing recipe, so a fix to one copy can silently drift from the other. Move a parameterizedframedSha256(domain, schema, segments...)helper and the canonical parsers intocommon-platform-core, for example next toPublicationDigestRequestBinding.Also applies to: 169-199
- Accepted Verified owner digest services duplicate identical framing, canonical parsers and original-freeze join. Share only that recipe, preserving owner domains/schema/prefixes and exact preimages.
- Use the base-class lifecycle helpers instead of duplicating
closedandinitializedstate.TrivialAbstractReloadingBlockingGrpcClientalready provides this lifecycle:initOnce(closedMessage, unavailableMessage)checksclosed, skips repeated initialization, callsinitReloadingClient(), checks for a null stub, and setsexplicitlyInitialized.requireInitializedStub(unavailableMessage)checksclosed,explicitlyInitialized, and the stub.close()already setsclosed = trueandexplicitlyInitialized = false.
This class has its own
volatilefields namedclosedandinitialized. They hide the base fields with the same names, and the overriddenclose()updates both copies. The current behavior matches the base class. However, the subclass and the base class now track the same lifecycle separately, and a future change to one copy can make them disagree.GrpcEntitySelectedSourceIntakeCommandClienthas the same duplication. The two clients also repeatrequireWorkloadOnlyContext,requireFileBackedMtls, andrequireReadableFilealmost line for line. The only differences are the label strings. The base class already hasrequireNoAmbientSqlfor the SQL part.Delegate to the base helpers. Move the shared mTLS and workload-context checks into one package-private helper with a label parameter.
♻️ Proposed refactor
private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; @@ - public synchronized void init() throws SSLException, IOException { - if (closed) { - throw new IllegalStateException("Automation selected-source command client is closed"); - } - if (initialized) return; - initReloadingClient(); - if (stub() == null) { - throw new IllegalStateException("Automation selected-source command stub unavailable"); - } - initialized = true; - } + public void init() throws SSLException, IOException { + initOnce( + "Automation selected-source command client is closed", + "Automation selected-source command stub unavailable"); + } @@ - @Override - public void close() throws IOException { - synchronized (this) { - closed = true; - initialized = false; - } - super.close(); - } - private AutomationSelectedSourceIntakeCommandServiceGrpc .AutomationSelectedSourceIntakeCommandServiceBlockingStub requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) { - throw new IllegalStateException( - "Automation selected-source command client is not initialized and available"); - } - return currentStub; + return requireInitializedStub( + "Automation selected-source command client is not initialized and available"); }Also applies to: 119-137
- Accepted Subclass duplicates existing base initialized/closed/initOnce/requireInitializedStub/close. Reuse base lifecycle and shared scoped mTLS/workload guards without changing fail-closed semantics.
- Extend the
AR-1.5Capability Status row to cover the selected Entity/Automation intake prerequisite.MinorAR-1.5is primarily owned by this tracker, but its row does not identify the Entity/Automation intake implementation or focused proof. Add the canonical contract links, owner implementation anchors, and focused test anchors. Scopeprovento the bounded intake/digest slice and retain the existing full-publication and attestation gaps. A fresh whole-service rerun is not required for a bounded status.- Accepted AR-1.5 omits selected Entity/Automation intake owner contracts, implementation and focused proof anchors. Add bounded anchors, preserving full-publication and attestation gaps.
- Add transport-level and namespace-mismatch tests for the Automation client.Trivial
The Entity client has a loopback mTLS test in
GrpcEntitySelectedSourceIntakeCommandClientMtlsTest. That test covers the exact request and receipt round trip, the bounded deadline, and rejection of a wrong server identity. The Automation client has no matching test. This file covers only constructor checks and checks that run before transport. Nothing tests thatretainsendsretainSelectedSourceto the server URI.../sa/automation-scripting-service. Nothing tests that it mapsfromResponsefailures toIllegalStateException. This file also never tests thetargetNamespacemismatch rejection at Lines 72-75 of the client. The Entity test covers that path withwrongNamespaceClient.The Automation client is a separate class with its own peer URI and its own codec. Proof for the Entity client does not cover it. Add an Automation version of the loopback mTLS test, and add a namespace-mismatch test.
- Accepted Automation has constructor/pretransport tests but lacks independent loopback mTLS roundtrip/deadline/peer and malformed response proof; Entity transport proof cannot qualify distinct Automation class.
- Hosted Review 2 CompletedRuntime 9m 52sFound: 9 Accepted: 3/3/3 Routed: 0
- Map Entity storage outages to
UNAVAILABLE, notDATA_LOSS.MajorThis code has the same defect as the Automation terminal-read service.
catch (RuntimeException corrupt)also catches jOOQ and SpringDataAccessExceptioninstances fromrepository.read, for example connection loss or a pool timeout. Account receivesDATA_LOSSunchanged, so it treats a temporary Entity database failure as permanent receipt corruption.Map data-access failures to
UNAVAILABLE. KeepDATA_LOSSonly for receipt validation exceptions. Add a unit case in whichrepository.readthrows aDataAccessException.Proposed fix
--- "a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java" +++ "b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java" @@ -59,13 +59,18 @@ repository .read(namespace, request.binding().intakeRequestId()) .orElseThrow(() -> Status.NOT_FOUND.asRuntimeException()); } catch (StatusRuntimeException denied) { throw denied; - } catch (RuntimeException corrupt) { + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Entity receipt storage is unavailable") + .asRuntimeException(); + } catch (IllegalArgumentException | IllegalStateException corrupt) { throw Status.DATA_LOSS .withDescription("Entity committed receipt is invalid") .asRuntimeException(); } if (!Arrays.equals(request.binding().canonicalBytes(), receipt.authorizationBindingBytes())) { throw Status.ALREADY_EXISTS- Accepted Valid retry-status bug: jOOQ/Spring storage failure is not receipt corruption. Sanitized UNAVAILABLE before narrow validation DATA_LOSS; focused unit outage proof preserving other statuses.
- Confirm the intended per-tenant cardinality. The current guard allows only one Automation receipt per tenant.Major
requireNoPriorScopeOrOperationrejects any existing row with the samecanonical_tenant_id, so a second Game Design Version for the same tenant can fail withIntakeConflictException(ALREADY_EXISTS). This conflicts withreadPublicationScope, which reads tenant associations and selects the requestedgameDesignVersionRowId.If receipt uniqueness is intended per tenant and version, use the same scope as the Entity implementation:
- + " WHERE target_namespace = ? AND (canonical_tenant_id = ? " - + "OR canonical_version_id = ? OR operation_id = ?)", + + " WHERE target_namespace = ? AND ((canonical_tenant_id = ? " + + "AND canonical_version_id = ?) OR operation_id = ?) LIMIT 1",- Accepted Valid scope bug: Automation intake is namespace plus canonical tenant/version, independently unique operation. Restrict paired scope predicate and bound result; prove same-tenant second Version and conflicts in PostgreSQL.
- Bound the prior-scope lookup so that a multi-row match still maps to a conflict.Minor
The predicate
(canonical_tenant_id = ? AND canonical_version_id = ?) OR operation_id = ?can match two different associations. One row can match the scope and a different row can match the operation. In that case jOOQfetchOnethrowsTooManyRowsException, notIntakeConflictException.EntitySelectedSourceIntakeCommandGrpcServicethen maps theRuntimeExceptiontoINTERNAL, notFAILED_PRECONDITION. The caller then sees a server fault for a deterministic conflict.🐛 Proposed fix
- + "(canonical_tenant_id = ? AND canonical_version_id = ?) OR operation_id = ?) ", + + "(canonical_tenant_id = ? AND canonical_version_id = ?) OR operation_id = ?) " + + "LIMIT 1",- Accepted Valid deterministic conflict bug: scope row plus independent operation row can make fetchOne throw TooManyRowsException. LIMIT1 preserves predicate and intended IntakeConflictException; prove multi-match.
- Bind the Automation owner to its configured namespace, as Entity does.Minor
EntityEmptySelectedSourceIntakeServicerejects anytargetNamespacethat differs from its configured owner namespace before any read.AutomationEmptySelectedSourceIntakeServicehas no configured namespace. It only checks that the peer namespace equals the caller-suppliedtargetNamespace. Today onlyAutomationSelectedSourceIntakeCommandGrpcServiceenforces the namespace binding. Suppose another caller invokes this service, or the service is wired behind a different receiver. A Game Design peer from namespaceothercould then retain a receipt forotherin this Automation database. Add the constructor parameter and the check so that the owner boundary does not depend on its caller.🛡️ Proposed fix
+ private final String configuredNamespace; private final AutomationEmptySelectedSourceIntakeRepository repository; @@ public AutomationEmptySelectedSourceIntakeService( + String configuredNamespace, AutomationEmptySelectedSourceIntakeRepository repository, @@ + if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) { + throw new IllegalArgumentException("Configured Automation namespace is required"); + } + this.configuredNamespace = configuredNamespace; @@ WorldSelectedDraftPublicationFreezeEvidence exactFreeze) { + if (!configuredNamespace.equals(targetNamespace)) { + throw new SecurityException( + "Selected Automation intake namespace differs from the configured owner namespace"); + } requireAuthenticatedGameDesignCaller(targetNamespace);- Accepted Valid owner boundary gap: bind Automation service to validated configured namespace and reject mismatched target before storage/remote reads; update actual callers and denial proof.
- Move the duplicated
TestPkikeytool harness into a shared test fixture.TrivialLines 358-581 repeat Lines 298-520 of
GrpcEntitySelectedSourceIntakeCommandClientMtlsTestalmost line for line. The repeated code includesTestIdentity,TestPki.create,clientProperties,issueIdentity,runKeytool,readCertificate, andwritePem. The copy also keeps Entity-specific names in the Automation test:entity-command-test-ca.p12,entity-server,wrong-entity-server, andentity-command-client-ca.crt. These names show that the copies already differ in meaning. A future fix to one copy, such as the keytool timeout or the SAN/EKU flags, can miss the other copy.This PR already adds
testFixtures(project(":common-test-support"))to this module. Extract one parameterized helper, for exampleSyntheticWorkloadPki.create(dir, serverUri, wrongServerUri, clientUri), into thecommon-test-supporttest fixtures or into a package-private class in this test package. Use that helper from both mTLS tests.- Accepted Useful test consolidation: share identical keytool/PKI mechanics between both actual mTLS tests with parameterized workload URIs, retaining SAN/EKU/timeout and all loopback denial cases.
- Add the patch-scope
UNSUPPORTED_SCOPEcase to the Entity receiver test.TrivialThe Entity API contract says Entity "supports
versionIdscope only and must returnUNSUPPORTED_SCOPEforscriptPatchVersion". The Automation receiver test covers this withpatchScopeIsUnsupportedAndDoesNotReadTheSelectedEmptyReceipt. The Entity receiver test has no equivalent case, so the Entity branch atEntitySelectedEmptyPublicationDigestGrpcReceiverLine 42 has no test. Add the same test, usingPublicationDigestRequestBinding.patch(...)andverifyNoInteractions(digestService).🧪 Proposed test
+ @Test + void patchScopeIsUnsupportedAndDoesNotReadTheSelectedEmptyReceipt() { + SessionContext.clear(); + EntitySelectedEmptyPublicationDigestService digestService = + Mockito.mock(EntitySelectedEmptyPublicationDigestService.class); + EntitySelectedEmptyPublicationDigestGrpcReceiver receiver = + new EntitySelectedEmptyPublicationDigestGrpcReceiver( + digestService, NAMESPACE, new SimpleMeterRegistry()); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.patch(TENANT, VERSION_ROW, "patch-1", "request-7"); + GetDraftDesignDigestRequest request = + GetDraftDesignDigestRequest.newBuilder() + .setTenantId(binding.tenantId()) + .setBaseVersionId(binding.baseVersionId()) + .setScriptPatchVersion(binding.scriptPatchVersion()) + .setPublishRequestId(binding.publishRequestId()) + .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity()) + .setRequestDigest(binding.requestDigest()) + .build(); + + GetDraftDesignDigestResponse response = invokeAsGameDesign(receiver, request); + + assertEquals("UNSUPPORTED_SCOPE", response.getError().getCode()); + verifyNoInteractions(digestService); + }- Accepted Valid missing contract proof: Entity supports version scope only. Add patch-scope UNSUPPORTED_SCOPE test and verify no digest service interaction; production branch unchanged.
- Do not report infrastructure failures as
DATA_LOSS.MajorreadValidatedperforms the jOOQ query before it decodes the stored receipt. The broad runtime catch can therefore map database outages and query timeouts toDATA_LOSSinstead ofUNAVAILABLE, preventing callers from applying retry handling.Map storage-access failures to
UNAVAILABLE. KeepDATA_LOSSfor receipt decoding and validation failures. Add a unit case for a jOOQDataAccessException.--- "a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java" +++ "b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java" @@ -59,15 +59,21 @@ .orElseThrow(() -> Status.NOT_FOUND.asRuntimeException()); } catch (StatusRuntimeException denied) { throw denied; } catch (AutomationEmptySelectedSourceIntakeRepository.IntakeConflictException changed) { throw Status.ALREADY_EXISTS .withDescription("Automation receipt differs from the complete original authorization") .asRuntimeException(); - } catch (RuntimeException corrupt) { + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.TransientDataAccessException + | org.springframework.jdbc.CannotGetJdbcConnectionException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Automation receipt storage is unavailable") + .asRuntimeException(); + } catch (IllegalArgumentException | IllegalStateException corrupt) { throw Status.DATA_LOSS .withDescription("Automation committed receipt is invalid") .asRuntimeException(); } try { return new AutomationSelectedSourceIntakeTerminalReadEvidence(request, receipt);- Accepted Valid retry-status bug: jOOQ/Spring storage access exceptions currently enter broad corruption catch. Map sanitized UNAVAILABLE, retain DATA_LOSS for receipt validation; focused outage unit proof.
- Extract the shared request validation and correlation logic.Trivial
AutomationSelectedSourceIntakeCommandEvidence.RequestandEntitySelectedSourceIntakeCommandEvidence.Requestare line-for-line copies. The copies differ only in owner, schema and purpose constants. This covers the following logic:collidesWithRetainedIdentity- the
createretry loop - the
equals/hashCodeoverrides - the freeze-binding checks
If one owner's identity set changes, the other owner's copy can silently drift from it. Move the shared logic to one package-private helper in
common.publicationorcommon.account.sourceintake. Pass the expectedOwner, schema and purpose as parameters.- Accepted Useful consolidation: shared identical request validation, freeze/correlation/collision and equality mechanics prevent owner drift. Preserve exact owner/schema/purpose/wire behavior in smallest shared internal helper.
- Do not attribute digest-slice proof to
f9e3. Add focused digest proof anchors.MinorThe
AR-1.5row says the "intake, terminal read and digest slice has focused source/storage/transport proof atf9e3f879…". Two facts do not support this for the digest part:- Line 13 says the
f9e3gate covered Common, Common Security, fiveEntityRetainedAuthoredActorCoreSourceServicecases, and oneAutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTestcase. None of these runs the digest readers or receivers. - The digest readers now delegate to
SelectedEmptyPublicationDigestSupport. That shared helper was extracted atbc10f8bb…, afterf9e3, sof9e3did not run the current digest code.
The row lists
EntitySelectedEmptyPublicationDigestService.javaandAutomationSelectedEmptyPublicationDigestService.javaas implementation anchors. It does not list any digest proof anchor. The tracker contract says: "Aprovenrow must also name focused executable proof." To fix this:- Add
EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java,AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java, andEntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.javaas proof anchors. - Give the digest slice the revision that each case actually ran at.
- If no digest case has run on the current helper, mark the digest slice as unproven.
As per coding guidelines: "A
provenrow must also name focused executable proof."- Accepted Valid attribution gap: f9e3 gate did not run digest receivers/current shared digest helper. Correct tracker scope, add owning digest executable anchors and record current focused proof only after actual execution.
- Line 13 says the
- Hosted Review 3 CompletedRuntime 11m 26sFound: 6 Accepted: 0/3/3 Routed: 0
- Replace the abbreviated
bc10revision with the full commit SHA.MinorLine 13 attributes the shared digest helper to
bc10. TheAR-1.5row at Line 271 usesbc10ande2c38ecin the same way. Every other revision in this section uses a full 40-character SHA. An earlier review asked the author to replace the unresolvable abbreviationa929with a full SHA, and these abbreviations have the same problem. The full SHA forbc10isbc10f8bb9dd1596e5271b1be0f40e7ede0be534e. Use the full SHA fore2c38ecas well, so that each proof scope points to exactly one commit.As per path instructions: "Review docs for canonical-current-state consistency."
📝 Proposed fix
-The shared selected-source digest helper was added later at `bc10`; its subsequent current-source execution is attributed below, not to this gate. +The shared selected-source digest helper was added later at `bc10f8bb9dd1596e5271b1be0f40e7ede0be534e`; its subsequent current-source execution is attributed below, not to this gate.- Accepted Use verified full proof SHAs at the tracker owner; preserve historical source scopes and no new qualification claim.
- Map storage outages to
UNAVAILABLEand corrupt receipts toDATA_LOSS.Minorowner.retain(...)reachesAutomationEmptySelectedSourceIntakeRepository.readandretainFresh, which use jOOQ.- A database outage or timeout throws
org.jooq.exception.DataAccessExceptionor a SpringDataAccessException. Neither type extendsIllegalStateException, so the generic catch returnsINTERNAL. - A corrupt stored receipt makes
readValidatedorfromStoredthrowIllegalStateExceptionorIllegalArgumentException. The current catch returnsFAILED_PRECONDITION.
GrpcAutomationSelectedSourceIntakeCommandClientforwards the status code to Game Design. The caller therefore cannot tell a retryable outage from a permanent integrity fault.AutomationEmptySelectedSourceIntakeTerminalReadServicein this layer already maps the same repository failures toUNAVAILABLEandDATA_LOSS. Use the same mapping here.IllegalStateExceptionalso covers the Account and World echo mismatches inAutomationEmptySelectedSourceIntakeService. KeepFAILED_PRECONDITIONfor those cases. Put the data-access catch before theIllegalArgumentException | IllegalStateExceptioncatch. To report a corrupt receipt asDATA_LOSS, add a dedicated exception type in the repository so the service can tell it apart from an echo mismatch.🐛 Proposed minimal fix for storage outages
--- "a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcService.java" +++ "b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcService.java" @@ -72,10 +72,13 @@ observer.onError(Status.fromCode(denied.getStatus().getCode()).asRuntimeException()); } catch (SecurityException denied) { observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); } catch (AutomationEmptySelectedSourceIntakeRepository.IntakeConflictException conflict) { observer.onError(Status.ALREADY_EXISTS.asRuntimeException()); + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); } catch (IllegalArgumentException | IllegalStateException unavailable) { observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); } catch (RuntimeException failure) { observer.onError(Status.INTERNAL.asRuntimeException()); }- Accepted Valid command boundary gap: retryable jOOQ/Spring storage failures map UNAVAILABLE; narrowly typed corrupt stored receipt maps DATA_LOSS, while Account/World echo mismatch stays FAILED_PRECONDITION.
- A database outage or timeout throws
- Optional: reuse one shared test PKI harness instead of a third keytool copy.Trivial
The nested
Pkirecord repeats the keytool harness inSelectedSourceIntakeCommandTestPkialmost line for line: the CA,-certreq/-gencertwith SAN/EKU, the PKCS12 import, and the PEM writer. The two copies have already started to differ. This copy callswaitForbefore it reads the output. The shared copy reads the output first. If you move the harness into thecommon-test-supporttest fixtures, both modules can depend on it. A later SAN/EKU or timeout fix then applies to all mTLS proofs.- Accepted Shared test PKI consolidates duplicated keytool/PEM mechanics at common-test-support, preserving workload-specific SAN/EKU and bounded timeout behavior.
- Map Entity storage failures to
UNAVAILABLE, notINTERNAL.Minorowner.retaincallsrepository.readandrepository.retainFresh. These can throw a jOOQDataAccessExceptionor a SpringDataAccessException. Examples are connection loss, a pool timeout, or a lock or deadlock failure under theLOCK TABLEsequence. Neither exception type extendsIllegalStateException, so the finalcatch (RuntimeException)maps them toINTERNAL.GrpcEntitySelectedSourceIntakeCommandClientpasses the status code through unchanged. Game Design therefore sees a transient storage fault as a server defect, not as a retryable outage.The terminal-read service already maps these exceptions to
UNAVAILABLE. Use the same mapping here, and add a unit case where the owner throws aDataAccessException.Proposed fix
} catch (SecurityException denied) { observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); } catch (IllegalArgumentException | IllegalStateException unavailable) { observer.onError(Status.FAILED_PRECONDITION.asRuntimeException());- Accepted Entity command must classify jOOQ/Spring storage outages as retryable UNAVAILABLE instead of generic INTERNAL, with sanitized focused tests.
- The
versionIdcheck compares the request against itself.TrivialretainedPublicationRequesttakes its version from thegameDesignVersionRowIdargument. Both callers parse that argument frompublicationRequest.versionId(). Line 81 therefore compares the requestedversionIdwith a canonical copy of the same value. TherequestDigestandderivedWorkflowIdentitycomparisons share this dependency. No retained World value takes part in these checks.The callers in
AutomationSelectedEmptyPublicationDigestServiceandEntitySelectedEmptyPublicationDigestServicecomparetarget.gameDesignVersionRowId()with the requested row before they call this helper, so the current paths are safe. The helper is public, though, and its Javadoc says it checks the request against the retained freeze. A future caller that skips the separate target check would get no row binding from this helper.To fix this, pass the retained row from
receipt.authorizationBinding().selected().target().gameDesignVersionRowId()and compare it here. Alternatively, rename the parameter and document that the caller must bind the row first.♻️ Proposed change
--- "a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedEmptyPublicationDigestSupport.java" +++ "b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedEmptyPublicationDigestSupport.java" @@ -57,21 +57,26 @@ } /** Requires the original publication request identity retained in the selected World freeze. */ public static void requireOriginalPublicationRequest( PublicationDigestRequestBinding requested, UUID canonicalTenantId, - long gameDesignVersionRowId, + long retainedGameDesignVersionRowId, UUID canonicalVersionId, UUID selectedCommitId, WorldSelectedDraftPublicationFreezeEvidence retainedFreeze, String ownerLabel) { var freezeRequest = retainedFreeze.request(); var retainedSelection = freezeRequest.accountBinding().input().selection(); + if (retainedGameDesignVersionRowId + != retainedSelection.selectedCommit().target().gameDesignVersionRowId()) { + throw new IllegalStateException( + ownerLabel + " publication request differs from the original retained World freeze"); + } var retainedPublicationRequest = PublicationDigestRequestBinding.full( freezeRequest.canonicalTenantId().toString(), - Long.toString(gameDesignVersionRowId), + Long.toString(retainedGameDesignVersionRowId), freezeRequest.publicationRequestId()); if (!canonicalTenantId.equals(freezeRequest.canonicalTenantId()) || !canonicalVersionId.equals(freezeRequest.canonicalVersionId()) || !selectedCommitId.equals(retainedSelection.selectedCommit().commitId())Also applies to: 81-81
- Accepted Current callers already compare row identity, but public helper promises retained freeze binding. Check retained target row within helper and reconstruct from retained row, with focused mismatch proof.
- Make the stale-snapshot test prove the reservation check, not only the isolation check.Trivial
repeatableReadSnapshot()opens aREPEATABLE READtransaction.automation_require_source_numeric_key_unreservedandautomation_reject_authored_source_truncateboth reject every non-read committedtransaction before they readautomation_empty_source_numeric_key_reservation. As a result, bothassertThatThrownBy(...).isInstanceOf(SQLException.class)assertions pass even when no canonical reservation is committed. The test name says that a stale writer cannot miss a committed reservation, but the assertions do not show this.Add one or both of these changes:
- Assert the specific message, for example
hasMessageContaining("require READ COMMITTED isolation"). The test then documents the mechanism it covers. - Add a
READ COMMITTEDcase. Open the writer transaction, commit the canonical fixture from a second connection, and then run the insert in the writer transaction. AsserthasMessageContaining("reserved by an immutable empty-source receipt").
♻️ Proposed assertion tightening
- .isInstanceOf(SQLException.class); + .isInstanceOf(SQLException.class) + .hasMessageContaining("require READ COMMITTED isolation");- Accepted Assertions currently prove isolation refusal only. Tighten exact diagnostic and test name; preserve separate READ COMMITTED reservation proof.
- Assert the specific message, for example
- CLI Review 1 CompletedRuntime 3m 50sFound: 4 Accepted: 0/2/0 Routed: 0
- Check that cascading deletes of characters and recipes still work after V1011.Major
V1011 installs
entity_guard_character_template_referenceoninventoryandcharacter_equipment. It installsentity_guard_recipe_ingredient_referenceoncrafting_ingredients. OnDELETE, each trigger looks up the parent row (charactersorcrafting_recipes). If the parent is missing, the trigger raises'... reference owner is unavailable'.Some foreign keys may be
ON DELETE CASCADEinV1__baseline.sql, for example frominventory,character_equipmentorcrafting_ingredients. PostgreSQL runs cascades from an AFTER RI trigger, after the parent row is already deleted. TheBEFORE DELETErow trigger on the child then does not find the parent, and the whole parent delete fails. This affects every existing live tenant, not only canonical reservations. Ordinary character deletion would break, and so would recipe deletion with ingredients.Verify:
- the
ON DELETEactions of these three foreign keys inV1__baseline.sql; - whether any production code path deletes a character or recipe that has child rows.
If a cascade exists, skip the check when the parent is already gone. The parent's own trigger has already enforced the reservation check on the parent row.
🐛 Possible fix (character trigger; apply the same change to the recipe trigger)
IF TG_OP IN ('UPDATE', 'DELETE') THEN old_character_id := (to_jsonb(OLD)->>'character_id')::BIGINT; SELECT tenant_id INTO referenced_tenant FROM %I.characters WHERE id = old_character_id; - IF NOT FOUND THEN + IF NOT FOUND AND TG_OP = 'UPDATE' THEN RAISE EXCEPTION 'Entity character reference owner is unavailable'; END IF; - PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant); + IF FOUND THEN + PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant); + END IF; END IF;Also applies to: 817-826
- Rejected All three actual baseline foreign keys (inventory/character_equipment to characters, crafting_ingredients to recipes) use default NO ACTION, not CASCADE. No later migration changes them. The proposed parent-missing cascade path does not exist; retain fail-closed guards.
- the
- Do not count a mocked test as PostgreSQL proof in the
AR-1.5row.MinorThe row counts "12 repository/service PostgreSQL" Automation cases. The Automation PostgreSQL classes have 9 cases: 6 in
AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTestand 3 inAutomationEmptySelectedSourceIntakePostgresIntegrationTest. The other 3 cases come fromAutomationEmptySelectedSourceIntakeServiceIntegrationTest. That class uses only Mockito mocks. Its Javadoc says it is "Mocked service ordering proof". It does not touch PostgreSQL.The row also says there are 17 Automation unit cases. The changed unit classes in the source contain 20
@Testmethods:AutomationEmptySelectedSourceIntakeValueTesthas 7,AutomationSelectedEmptyPublicationDigestGrpcReceiverTesthas 4,AutomationSelectedSourceIntakeCommandGrpcServiceTesthas 3 andAutomationSelectedSourceIntakeTerminalReadServiceTesthas 6.Split the 12 cases into 9 physical PostgreSQL cases and 3 mocked service cases. Confirm which unit classes the gate ran, then correct the unit count. The tracker contract requires proof to be described exactly: "
implementeddoes not implyproven, and a historical broad test run does not substitute for focused proof."As per coding guidelines: a
provenrow "must also name focused executable proof".- Accepted AR-1.5 combines nine real Automation PostgreSQL cases with three mocked service cases under PostgreSQL proof. Separate these categories and verify unit totals against source-attributed execution XML before correcting them.
- Verify that this framing is the ADR 0047 framing that the contracts cite.Minor
appendSegmentwrites each segment as an ASCII decimal length, then':', then the UTF-8 bytes. The Entity and Automation contracts say this schema-3/schema-6 preimage uses "ADR 0047 byte-length framing". The Entity contract describes its other length-framed digest as "prefixed by its byte length as a four-byte big-endian integer". The repository also has a sharedDraftAuthorizationFenceBinding.framehelper. The new fixtures use that helper for selected-source content.If ADR 0047 requires the four-byte big-endian prefix, the documented schema-6 and schema-3 preimages differ from the implemented bytes. An independent recipient that follows the contract then computes a different
contentDigest. The tests do not catch this. BothexpectedSelectedEmptyDigesthelpers use the same decimal-colon encoding.Check ADR 0047. If the ADRs differ, change this helper and the two test helpers to the ADR encoding, for example by delegating to
DraftAuthorizationFenceBinding.frame. If decimal-colon is the ADR 0047 encoding, no change is necessary.♻️ Possible change if ADR 0047 is the shared frame
private static void appendSegment(ByteArrayOutputStream output, String value) { - byte[] bytes = value.getBytes(StandardCharsets.UTF_8); - output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); - output.write(':'); - output.writeBytes(bytes); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame(output, value); }- Rejected ADR0047 explicitly specifies segment(bytes)=ASCII canonical decimal byte length + colon + bytes (lines130-147). Current appendSegment implements it exactly. Four-byte DraftAuthorization framing is a different contract and must not replace this encoding.
- Map Entity intake conflicts to
ALREADYEXISTS, as Automation does.MinorMap Entity intake conflicts to `ALREADY_EXISTS`, as Automation does.
EntityEmptySelectedSourceIntakeRepository.IntakeConflictExceptionis private and extendsIllegalStateException. As a result, the catch at Line 81 maps these failures toFAILED_PRECONDITION:- a prior scope or operation association;
- a census that is not freshly empty;
requireSameInputsdivergence on retry.
Automation exposes a public
IntakeConflictException.AutomationSelectedSourceIntakeCommandGrpcServicemaps it toALREADY_EXISTS. The shared Game Design caller therefore gets different status codes for the same conflict, depending on the owner. A conflict on Entity also looks the same as a transient remote-echo precondition failure, so a retry policy can resend a request that is permanently conflicted.Make the Entity exception public. Catch it before the generic
IllegalStateExceptionhandler, as Automation does.🐛 Proposed fix
} catch (EntityEmptySelectedSourceIntakeRepository.CorruptReceiptException corrupt) { observer.onError(Status.DATA_LOSS.asRuntimeException()); + } catch (EntityEmptySelectedSourceIntakeRepository.IntakeConflictException conflict) { + observer.onError(Status.ALREADY_EXISTS.asRuntimeException()); } catch (org.jooq.exception.DataAccessExceptionIn
EntityEmptySelectedSourceIntakeRepository:- private static final class IntakeConflictException extends IllegalStateException { - private IntakeConflictException(String message) { + public static final class IntakeConflictException extends IllegalStateException { + public IntakeConflictException(String message) {- Accepted Entity repository conflicts are a distinct private subtype but currently fall through to FAILED_PRECONDITION. Expose that subtype and map only it to sanitized ALREADY_EXISTS; retain generic preconditions and add focused status regression.
- CLI Review 2 CompletedRuntime 3m 02sFound: 8 Accepted: 1/1/2 Routed: 0
- Verify that the decimal
len:framing is the ADR 0047 framing.MajorappendSegmentwritesInteger.toString(length), then:, then the UTF-8 bytes. Both contract documents say the schema-6 Automation and schema-3 Entity preimages use "ADR 0047 byte-length framing". Elsewhere in the codebase, framing goes throughDraftAuthorizationFenceBinding.frame, and the Entity intent-digest contract specifies a four-byte big-endian length prefix. Suppose ADR 0047, or the Game Design recipient that independently validates retained recipient evidence, uses a different encoding. Then every selected-empty participant digest differs from the recipient's recomputation, and the selected-full profile fails closed. The integration tests copy this same encoding, so they cannot detect the mismatch. Confirm the ADR 0047 encoding. If it differs, delegate to the canonical framer, for exampleDraftAuthorizationFenceBinding.frame, instead of keeping a second implementation.- Rejected Repeated CLI1 framing hypothesis: ADR0047 lines130-147 explicitly specifies ASCII canonical decimal UTF8-byte length plus colon and bytes. Current appendSegment matches. Four-byte authoring framing is a separate contract.
- Wrap freeze and binding decode failures the same way as the Entity codec.Trivial
EntitySelectedSourceIntakeCommandGrpcCodec.fromRequestwraps the World freeze decode and theRequestconstructor intryblocks. Those blocks convert anyRuntimeException, including an NPE from a missing nested field, intoIllegalArgumentException. The Automation codec lets those exceptions escape without conversion. The current receiver catches everyRuntimeException, so it still maps them toINVALID_ARGUMENT. Other callers, such as the client'sfromResponsepath, rely onIllegalArgumentExceptionto classify invalid evidence. Align the two codecs so that both have the same failure contract.♻️ Proposed alignment
- var freezeRequest = - WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest(wire.getFreezeRequest()); - WorldSelectedDraftPublicationFreezeEvidence freezeEvidence = - WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( - freezeRequest, wire.getFreezeAcknowledgement()); - Request request = - new Request( - wire.getSchemaVersion(), - wire.getTargetNamespace(), - transportRequestId, - authorization, - freezeEvidence); + final WorldSelectedDraftPublicationFreezeEvidence freezeEvidence; + try { + var freezeRequest = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest(wire.getFreezeRequest()); + freezeEvidence = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, wire.getFreezeAcknowledgement()); + } catch (RuntimeException malformed) { + throw invalid("Complete original World freeze evidence is invalid", malformed); + } + final Request request; + try { + request = + new Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + transportRequestId, + authorization, + freezeEvidence); + } catch (RuntimeException malformed) { + throw invalid("Automation selected-source command binding is invalid", malformed); + }- Accepted Align the closed Automation command decoder with Entity: normalize malformed nested World-freeze and command-binding runtime failures to IllegalArgumentException while preserving exact echoes and existing receiver status behavior.
- The reference guard raises an error when a cascaded child delete runs after its parent row is gone.Major
On DELETE,
entity_guard_character_template_referencelooks up the parentcharactersrow and raises 'Entity character reference owner is unavailable' when it finds no row.entity_guard_recipe_ingredient_referenceuses the same pattern forcrafting_recipes. Supposeinventory,character_equipment, orcrafting_ingredientsreference their parent withON DELETE CASCADE. PostgreSQL runs the cascaded child DELETE after it removes the parent row, so the BEFORE DELETE child trigger cannot find the parent. Every delete of a character with inventory or equipment, and of a recipe with ingredients, then fails. Legacy, unreserved tenants are affected too. Check the V1 baseline FK actions. If any FK cascades, return OLD without the check when the parent row is already gone. The deleted parent row was already checked by its own row trigger.🐛 Proposed change (character guard; apply the same pattern to the recipe guard)
IF TG_OP IN ('UPDATE', 'DELETE') THEN old_character_id := (to_jsonb(OLD)->>'character_id')::BIGINT; SELECT tenant_id INTO referenced_tenant FROM %I.characters WHERE id = old_character_id; - IF NOT FOUND THEN + IF NOT FOUND AND TG_OP = 'UPDATE' THEN RAISE EXCEPTION 'Entity character reference owner is unavailable'; END IF; - PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant); + IF FOUND THEN + PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant); + END IF; END IF;- Rejected Repeated cascade hypothesis: all three actual inventory/equipment/ingredient parent foreign keys use default NO ACTION, not CASCADE; no later migration changes them. Proposed missing-parent bypass would relax guards for a nonexistent path.
- Reserved canonical keys can collide with the future
entitytenantidentitiesrow IDs that canonical actor assignment writes intocharacters.tenantid.MajorReserved canonical keys can collide with the future `entity_tenant_identities` row IDs that canonical actor assignment writes into `characters.tenant_id`.
maximumOccupiedSourceKeyreservesmax + 1asTENANTandmax + 2asVERSION. It computesmaxonly from reservations and rows that already exist. It does not includeentity_tenant_identities.entity_tenant_row_idor its sequence. Canonical preseeded assignment storescharacters.tenant_id = entity_tenant_row_id, asPreseededActorAssignmentIntegrationTestshows. V1011'strg_entity_character_source_reservationthen rejects any write whose tenant key matches aCANONICAL_EMPTY_SOURCEreservation.Example: on a fresh database with no actor rows, the first founding reserves TENANT=1 and VERSION=2. When a tenant receives
entity_tenant_row_id = 1, or already has it without actors, every actor assignment for that tenant fails with "reserved by an immutable empty-source receipt". The same failure applies toVERSIONkeys and Game Design Version row IDs written later intoitems.version_id. The allocator must reserve a key space that no external allocator can produce, or it must also include the external allocator's current and future values. Confirm the sequence or allocation source forentity_tenant_row_idand for the version numbers.- Accepted Confirmed existing canonical tenant mapping row1 can precede source reservation key1; actual canonical actor assignment then hits the unrelated authored-source reservation. Separate canonical runtime provenance from authored-key guards; max-only allocation changes cannot prevent future collisions.
- V1011 makes every gameplay-table write fail outside READ COMMITTED, including writes for unreserved legacy tenants.Major
entity_require_source_numeric_key_unreservedraises an error when the isolation level is not READ COMMITTED. It does this before it checks whether the key is null or reserved. The triggers attach this function tocharacters,items,inventory,character_equipment,item_instances,item_stacks,container_instances,room_ground_inventory,item_transfer_audits,entity_mutation_effects,actor_resource_states,actor_active_conditions, and other tables. Any existing Entity writer that runs at REPEATABLE READ or SERIALIZABLE now fails on every write. Candidates are the stack, transfer, and effect-replay paths, or a configured default isolation level. The tracker says "Legacy adapters and consumers retain develop behavior", and this change breaks that statement. Every write on these hot gameplay tables also runs a SECURITY DEFINER plpgsql function withto_jsonb(NEW/OLD)and a lookup in the reservation table.Confirm that no Entity writer or
TransactionTemplatesets an isolation level above READ COMMITTED. If you keep the isolation fence, apply it only when a reserved canonical key is actually possible. Also measure the trigger cost on the inventory and effect paths.- Rejected Full scoped Entity writer/config scan found no raised-isolation production writer or configured override. Guard-first is intentional and tested against stale RR snapshots; checking reservation visibility first can miss a committed reservation. No current regression or measured cost established.
- The isolation check rejects all source-row writes outside READ COMMITTED, including writes with unreserved keys.Major
automation_require_source_numeric_key_unreservedcheckstransaction_isolationbefore it checksrequested_key. After V1003, every INSERT, UPDATE, or DELETE onscripts,script_event_bindings, orscript_patch_base_bindingsfails inside a REPEATABLE READ or SERIALIZABLE transaction, even when no canonical reservation exists. If any current Automation writer, such as script-patch publication or event-binding sync, runs at a stricter isolation level, it starts to fail after this migration. That contradicts the statement that existing rows and writers stay legacy and unqualified. Confirm that no existing writer runs above READ COMMITTED. Otherwise, apply the isolation check only when a key matches aCANONICAL_EMPTY_SOURCEreservation. A writer at a stricter level cannot safely tell whether such a reservation exists, so it needs a different fence for that case.- Rejected Full scoped Automation writer/config scan found no higher-isolation writer: founding explicitly READ COMMITTED, publication RR READ ONLY, other writers DEFAULT and no deployment override. Guard-first rejects stale RR snapshots as proven; reservation-first lookup is unsafe.
readValidateddoes not compare several stored association columns with the receipt.MinorREAD_RECEIPTdoes not selectselected_commit_id,source_revision_id, orsource_revision_order.insertAssociationpersists these three columns, and the Automation repository compares the same three columns in its readback. If a stored association differs from its receipt in one of these columns, Entity does not detect the difference. Add the columns to the query and to the equality check, so that Entity and Automation apply the same immutable-readback contract.🛡️ Proposed change
- + "r.request_digest, r.schema_digest, r.receipt_digest, r.receipt_bytes, r.retained_at " + + "r.request_digest, r.schema_digest, r.receipt_digest, r.receipt_bytes, r.retained_at, " + + "a.selected_commit_id, a.source_revision_id, a.source_revision_order "In
readValidated, add these checks:|| !Objects.equals(row.get(23, UUID.class), receipt.selectedCommitId()) || !Objects.equals(row.get(24, UUID.class), receipt.sourceRevisionId()) || !Objects.equals(row.get(25, String.class), receipt.sourceRevisionOrder())- Accepted Entity persists selected_commit_id/source_revision_id/source_revision_order but omits them from immutable receipt readback comparison. Select and compare all three; verify per-column valid-but-different corruption against native PostgreSQL.
- The test copies the framing it should verify.Trivial
expectedSelectedEmptyDigestandappendDigestSegmentrepeat the same decimallen:bytesframing asSelectedEmptyPublicationDigestSupport. The test therefore proves only that the two copies agree. It does not prove that the digest conforms to ADR 0047. After you confirm the canonical framing, build the expected value from a fixed known-answer vector taken from the ADR. Do not re-derive it with the same algorithm.- Accepted Add an independent fixed known-answer vector at the shared framer owner using literal ADR0047 UTF8 preimage bytes, including multibyte, empty and colon segments. Retain integration expectations for separate owner-identity/segment-order proof; no production framing change.
- CLI Review 3 CompletedRuntime 3m 06sFound: 4 Accepted: 0/0/1 Routed: 0
- Check that no existing writer to
scripts,scripteventbindings, orscriptpatchbasebindingsruns above READ COMMITTED.MajorCheck that no existing writer to `scripts`, `script_event_bindings`, or `script_patch_base_bindings` runs above READ COMMITTED.
automation_require_source_numeric_key_unreservedchecks the isolation level before it checks for a reserved key.automation_guard_authored_source_rowcalls it on every INSERT, UPDATE, and DELETE. As a result, any write to these three tables under REPEATABLE READ or SERIALIZABLE now fails as soon as V1003 is applied, even when no canonical reservation exists. Existing script-patch publication orUpdateScriptpaths would fail with "Automation authored-source row writes require READ COMMITTED isolation".Confirm that all current writers (JPA, jOOQ, Spring
@Transactional(isolation = …), Temporal activities) use READ COMMITTED. If any writer uses a higher level, apply the isolation check only when aCANONICAL_EMPTY_SOURCEreservation matches the requested key, or change that writer first.- Rejected Repeated CLI2 hypothesis. Full current writer/config review found source founding explicitly READ COMMITTED, publication RR READ ONLY, all other production writers default with no higher isolation configured. No writer/config change in17c. Reservation-first lookup breaks stale-snapshot fence.
- Replace the restated V1011 guard contract with a link to the canonical Entity contract.Trivial
This paragraph repeats the V1011 storage-guard rules: owner-resolved provenance, tenant UUID to private-row mapping, namespace/scope tuple, reserved-key denial, and the READ COMMITTED fence. The [Entity API contract](../../architecture/microservices/entity-management-service/api-contracts.md) already defines these rules in its "Current selected-empty status" section. The tracker should record only implementation status and link to that definition. Keep only the status sentence ("does not enable child writers or gameplay admission") and add the link.
Based on learnings: "do not duplicate canonical technical contracts that are already defined by the owning ADRs or architecture contracts … use this documentation only to track implementation-specific status, decisions, or links to the canonical definitions."
♻️ Proposed rewrite
-The local Entity V1011 guard distinguishes a character with complete owner-resolved provenance, an exact tenant UUID/private-row mapping, and an enrolled namespace/scope tuple from authored-source TENANT rows, so its private mapping ID may coincide with the selected-empty reservation. Legacy rows at reserved keys remain denied under the READ COMMITTED fence. The current non-admitting assignment writes no character children; this does not enable child writers or gameplay admission. +The local Entity V1011 owner-resolved character guard follows the [Entity selected-empty storage contract](../../architecture/microservices/entity-management-service/api-contracts.md#digest-input-manifest). The current non-admitting assignment writes no character children; this does not enable child writers or gameplay admission.- Accepted Useful tracker alignment: replace repeated V1011 contract predicates with link to canonical Entity Digest Input Manifest; retain actual local implementation consequence and child-writer/admission limits. No runtime change.
- Check whether parent-row cascades now fail in the child reference guards.Major
On DELETE,
entity_guard_character_template_referenceselects the parentcharactersrow and raises 'Entity character reference owner is unavailable' when that row isNOT FOUND.entity_guard_recipe_ingredient_reference(lines 878-887) does the same forcrafting_recipes. PostgreSQL runsON DELETE CASCADEchild deletes after the parent row is already deleted in the same transaction. Ifinventory.character_id,character_equipment.character_id, orcrafting_ingredients.recipe_idcascades, the parent lookup returns no row and the guard raises. The whole parent delete then rolls back. Deleting a legacy character that owns inventory or equipment, or deleting a recipe with ingredients, would then fail permanently.Check the foreign key
ON DELETEactions inV1__baseline.sql. If any of them cascade, skip the parent lookup forTG_OP = 'DELETE'when the parent row no longer exists. The parent's ownentity_guard_source_owner_rowtrigger already checks the reserved TENANT/VERSION key.🐛 Possible fix if cascades exist
IF TG_OP IN ('UPDATE', 'DELETE') THEN old_character_id := (to_jsonb(OLD)->>'character_id')::BIGINT; SELECT tenant_id INTO referenced_tenant FROM %I.characters WHERE id = old_character_id; - IF NOT FOUND THEN + IF NOT FOUND AND TG_OP = 'UPDATE' THEN RAISE EXCEPTION 'Entity character reference owner is unavailable'; END IF; - PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant); + IF FOUND THEN + PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant); + END IF; END IF;- Rejected Conditional cascade premise is false: actual inventory/equipment character and crafting_ingredients recipe FKs are default NO ACTION, no later override. Other character-child cascades are different families without these parent lookup guards. Do not weaken reserved-source protection.
- Check that no existing Entity runtime writer runs above READ COMMITTED.Major
entity_require_source_numeric_key_unreservedchecks the isolation level before any reservation lookup.entity_guard_source_owner_rowcalls it on every row write tocharacters,item_instances,item_stacks,container_instances,room_ground_inventory,item_transfer_audits,entity_mutation_effects,actor_resource_states,actor_active_conditions, and the authored template tables. Oncharacters, the guard makes this call with aNULLkey only to enforce isolation. As a result, every gameplay mutation under REPEATABLE READ or SERIALIZABLE (for example DROP/PICKUP holder moves,UpdateEntity, orApplyActorCondition) fails as soon as V1011 is applied. This happens even with no canonical reservation. Every per-row write on these hot tables also now runsto_jsonband up to three extra lookups.Confirm that no Entity
@Transactional, jOOQ, or JDBC writer on these tables uses a higher isolation level. If any does, apply the isolation check only after aCANONICAL_EMPTY_SOURCErow matches the requested key. The fence protects only reserved keys, so non-reserved writes do not need it.- Rejected Repeated CLI2 hypothesis. Current Entity writers/config default READ COMMITTED; explicit RR path is READ ONLY.17c changes no writer isolation. Guard-first deliberately rejects stale higher-isolation snapshots; moving lookup first is unsafe. No concrete hot-path regression evidence supplied.
- CLI Review 4 CompletedRuntime 3m 13sFound: 4 Accepted: 0/2/0 Routed: 0
- Check the schema-2 claim against the unchanged manifest notes.Minor
Line 108 says retained schema-2 Entity participant evidence keeps its original meaning. This means schema 2 is the deployed baseline. The unchanged implementation notes in the same section contradict that:
- Line 116 describes the move from
1to2as a target bump. The current item projection still omitsequipmentSlotGroupKey. - Line 129 describes
v1as unsupported only "oncev2is deployed".
If the registered reader still emits schema 1, the new text claims that schema-2 evidence exists when it does not. Check what
digestSchemaVersionthe registered Entity reader emits today. Then make lines 108, 116 and 129 agree. For example, write "retained schema-1/2 participant evidence", or update the implementation note if v2 has shipped.As per path instructions: "Review docs for canonical-current-state consistency. Flag ... conflicts between architecture docs."
- Accepted Useful current-state explicitness: registered EntityDraftDesignDigestServiceImpl emits schema1, slot-group schema2 remains target, selected-empty unregistered reader emits3. Clarify retained evidence sentence without claiming schema2 deployed or changing runtime.
- Line 116 describes the move from
- Apply the same key-allocation fix here as in Automation.Major
This is the same root cause as the comment on
AutomationEmptySelectedSourceIntakeRepositorylines 191-199.max(local keys) + 1/2is reserved permanently. V1011's guards then block every legacyitems,npcs,crafting_recipes,equipment_slot_definitionsorbody_layout_slot_definitionswrite that uses the reserved value. If Game Design assigns thosetenant_id/version_idvalues, a later legitimate tenant or version can collide with the reservation. The block is irreversible. Fix both owners together after you confirm who assigns these IDs.- Rejected No supported GDS→Entity template writer assigns these numeric keys. Saves found are unsupported legacy adapters/opt-in hardcoded dev seeding. Entity keys are private; canonical-character collision was separately fixed. Keep reserved-key denial, no speculative allocator redesign.
- Separate the proof attribution for the two digest-reader test methods.Minor
The proof cell first describes the Automation gate at
f2d3142…. It then states that the earlier Entity evidence ata5d501c…"is not part of this Automation aggregate". The next sentence says "It exercised the real digest helper … throughselectedEmptyPublicationReaderResolvesOnlyTheValidatedReceiptForTenantAndGameDesignRowandselectedEmptyPublicationReaderUsesTheRetainedTargetProofAndReturnsSchemaSixDigest."- The first method is in
EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest. - The second method is in
AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.
"It" cannot refer to both runs. Each reading attributes one method to a run that did not execute it. The tracker also says the digest helper arrived at
bc10f8b…. Ifa5d501c…comes before that commit, the Entity run cannot have exercised the helper at all.Give each method its own sentence with the exact source commit that executed it. Remove any claim that a run cannot support.
As per coding guidelines: "Evidence targets must be repository-local and resolvable ... a historical broad test run does not substitute for focused proof."
- Accepted Useful proof-attribution correction: current AR1.5 It sentence conflates Entity and Automation methods/runs. Replace with separately source-pinned statements supported by retained XML; preserve failed/historical gate limits.
- The first method is in
- Reserved keys can collide with numeric IDs that Game Design assigns later.Major
retainFreshsetslocalTenantKey/localVersionKeytomax(observed) + 1and+ 2. The value is computed only from Automation's own reservation and source tables. It then reserves both values asCANONICAL_EMPTY_SOURCE. After that, V1003'sautomation_guard_authored_source_rowrejects every INSERT, UPDATE or DELETE onscripts,script_event_bindingsandscript_patch_base_bindingsthat uses either value.The legacy columns
scripts.tenant_id,script_event_bindings.base_version_idandscript_patch_base_bindings.base_version_idappear to hold Game Design numeric tenant and version IDs. The fixtureTargetProofusesgameDesignVersionRowId = 23, and the patch-base binding refers to a Game Design base version. If Game Design assigns these IDs, Automation does not own that number space. The local maximum then gives no protection:- A tenant or version that Game Design creates later can receive the same number.
- All legacy script writes for that tenant or version then fail permanently.
- The reservation and association rows are immutable, so the block cannot be removed.
Entity has the same root cause:
EntityEmptySelectedSourceIntakeRepository.retainFresh, lines 203-205, withitems.tenant_id/version_id.PreseededActorAssignmentIntegrationTestalready showslocalTenantKey == 1colliding withentity_tenant_row_id == 1. V1011 needed a specialOWNER_RESOLVEDexception for that collision.The slice is unregistered today, so no production founding happens yet. Resolve this before registration:
- Confirm which component assigns the numeric IDs stored in these columns.
- If Game Design assigns them, take keys from a range that cannot collide. One option is negative or high-offset keys that legacy writers never use.
- Alternatively, reserve the keys in Game Design's own ID space.
- Rejected No supported cross-owner write shown. UpdateScript takes raw IDs but is bootstrap/dev-only. Current GDS Notify passes List.of(); Automation returns before reads/writes for empty scripts. Reserved-key denial is intentional; hypothetical future producers do not justify a new ID scheme.
- CLI Review 5 CompletedRuntime 3m 29sFound: 4 Accepted: 0/0/0 Routed: 0
- Verify that the child-reference guards do not block cascaded parent deletes.Major
On DELETE,
entity_guard_character_template_referencereads the parentcharactersrow. It raises'Entity character reference owner is unavailable'when the row is not found.entity_guard_recipe_ingredient_reference(lines 878-887) does the same forcrafting_recipes.Assume that
inventory.character_id,character_equipment.character_id, orcrafting_ingredients.recipe_idis declaredON DELETE CASCADE. PostgreSQL then runs the cascaded child DELETE after it deletes the parent row in the same transaction. When the child BEFORE DELETE trigger runs, the parent row is no longer visible, so the guard raises an exception. A character or recipe delete that has child rows then fails completely. For a legacy, unreserved character, this is a new regression.Check the V1 baseline FK actions for these three columns. If any of them cascades, return without error on DELETE when the parent is missing. A deleted parent cannot claim a reserved key, and the parent row's own trigger already checked that key.
🐛 Proposed DELETE-path change
IF TG_OP IN ('UPDATE', 'DELETE') THEN old_character_id := (to_jsonb(OLD)->>'character_id')::BIGINT; SELECT tenant_id INTO referenced_tenant FROM %I.characters WHERE id = old_character_id; - IF NOT FOUND THEN + IF NOT FOUND AND TG_OP = 'UPDATE' THEN RAISE EXCEPTION 'Entity character reference owner is unavailable'; END IF; - PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant); + IF FOUND THEN + PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant); + END IF; END IF;Apply the same change to the recipe-ingredient guard.
- Rejected V1 inventory.character_id, character_equipment.character_id and crafting_ingredients.recipe_id FKs use NO ACTION; no later CASCADE override. Assumed cascades cannot reach these guards. Actual resource/condition CASCADE paths use a different guard.
- Verify that Automation rejects World automation references before it records an empty receipt.Minor
EntityEmptySelectedSourceIntakeService.requireEmptyWorldEntityClosurechecks two things before retention:- all seven World inbound-closure family counts are zero;
- the World spawn bindings are absent.
The Automation path has no matching check. It depends only on
new SelectedOwnerEmptySourceInputs(...). The comment at line 101 says that this value validates "complete supported inbound World closure". The comment does not say that the value requiresWORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK,..._AUTOMATION_SCRIPT_REFERENCE, and..._AUTOMATION_TARGET_BINDINGto be zero.Assume the shared value checks only that the closure is complete. Then a World freeze with automation hooks still produces a
COMMITTED_EMPTYAutomation receipt and a schema-6 digest. The selected release would then contain World references to scripts that Automation never retained.Confirm that
SelectedOwnerEmptySourceInputsenforces zero counts for the three automation families. If it does not, add an explicit check here, the same as the Entity service does.♻️ Proposed guard
SelectedOwnerEmptySourceInputs inputs = new SelectedOwnerEmptySourceInputs(originalBinding, worldEvidence); + var closure = + worldEvidence.inventory().publicEvidence().sourceModel().inboundSourceClosure(); + if (closure == null + || closure.familyCounts().stream() + .filter(f -> f.family().startsWith("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_")) + .anyMatch(f -> f.count() != 0)) { + throw new IllegalArgumentException( + "Automation empty-source intake cannot retain World automation references"); + }- Accepted Shared inputs check complete closure but not zero Automation families; retainFresh/receipt add no denial. Add owner-local pre-retention hook/script/target zero-count guard and regression; preserve exact binding, HELD and stored-retry behavior.
- Verify that no existing Entity runtime writer runs above READ COMMITTED.Major
entity_require_source_numeric_key_unreservedchecks the isolation level before it checks the key.entity_guard_source_owner_rowcalls it for every row on 16 tables, including on theNULL::BIGINTpath forcharacters. These tables include hot runtime tables:characters,item_instances,item_stacks,container_instances,room_ground_inventory,actor_resource_states,actor_active_conditions,entity_mutation_effects, anditem_transfer_audits. After this migration, any INSERT, UPDATE, or DELETE on these tables fails under REPEATABLE READ or SERIALIZABLE. This applies even when no canonical reservation exists.The evidence is in the changed tests.
staleRepeatableReadWritersCannotMissACommittedCanonicalReservationshows that a REPEATABLE READ character insert is rejected. Assume that any gameplay or item-transfer path, for example a@Transactional(isolation = REPEATABLE_READ)service or a jOOQSET TRANSACTION, writes these tables. That path breaks in production after deployment.Confirm the isolation level of all current writers to these tables. If any writer uses a higher isolation level, apply the isolation check only when the row key matches a
CANONICAL_EMPTY_SOURCEreservation, or only after at least one canonical reservation exists.- Rejected Current Entity founding is READ COMMITTED; higher-isolation source path is READ ONLY. No supported higher-isolation runtime writer found; repeats CLI2/3. Guard-first isolation prevents stale-snapshot reservation bypass; conditional lookup weakens it.
- Verify that no existing writer to the script tables runs above READ COMMITTED.Major
The isolation check runs before the
requested_key IS NULL OR <= 0early return. As a result, every INSERT, UPDATE, and DELETE onscripts,script_event_bindings, andscript_patch_base_bindingsfails unless the transaction isolation is exactlyread committed. This applies to legacy rows that will never touch a reserved key. It also applies before any canonical reservation exists, because V1003 installs the triggers unconditionally.Assume an existing path writes these tables under REPEATABLE READ or SERIALIZABLE, for example through
@Transactional(isolation = ...), jOOQSET TRANSACTION, or a pool-level default. That path starts to fail after this migration. The script publication path and bootstrap tooling are the most likely to be affected.Confirm the isolation level of every current writer to these three tables. If some writers must keep a higher isolation level, apply the isolation check only when a
CANONICAL_EMPTY_SOURCEreservation exists, or only when the key matches a reservation.- Rejected Current founding writes explicitly READ COMMITTED; higher-isolation path is READ ONLY publication read. No supported higher-isolation script writer found; prior CLI2/3 evidence unchanged. Conditional lookup can miss a new reservation in a stale snapshot and weakens the fence.
- CLI Review 6 CompletedRuntime 3m 27sFound: 1 Accepted: 0/0/0 Routed: 0
- Verify that the local tenant-key allocator cannot alias another tenant's canonical Entity tenant row ID.Major
maximumOccupiedSourceKeyderiveslocalTenantKeyfromMAX(...) + 1. The calculation covers reservation rows and thetenant_idcolumns of source and runtime tables. It does not includeentity_tenant_identities.entity_tenant_row_id.That mapping table allocates row IDs independently. Assume this sequence:
- A canonical roster capture creates mapping row
1for tenant A. Tenant A has no characters yet. - A selected-empty intake for tenant B runs. The allocator selects
localTenantKey = 1and reserves it asCANONICAL_EMPTY_SOURCE.
The reverse order produces the same collision. The mapping sequence can later issue a row ID that is already reserved.
The consequences:
- The V1011 guard accepts tenant A's owner-resolved characters with
tenant_id = 1, because the mapping matches tenant A. Tenant A's runtime rows then share tenant B's reserved numeric scope. - Every legacy or authored write that tenant A makes with key
1is rejected as "reserved by an immutable empty-source receipt".
PreseededActorAssignmentIntegrationTestassertsentityTenantRowId == sourceReceipt.localTenantKey()(Line 735 there). This equality holds only because the same tenant takes the first key in both allocators. The code does not establish this binding.Confirm that the design guarantees one tenant per Entity database. If it does not, use one of these fixes:
- Include
entity_tenant_identities.entity_tenant_row_idin the occupied-key union. Also make the mapping allocator skip reserved keys. - Or bind
localTenantKeyexplicitly to the canonical tenant's mapping row, and fail closed if that row belongs to a different tenant.
Partial fix: treat mapped tenant row IDs as occupied
+ " UNION ALL SELECT tenant_id FROM actor_active_conditions WHERE tenant_id > 0" + + " UNION ALL SELECT entity_tenant_row_id FROM entity_tenant_identities" + + " WHERE entity_tenant_row_id > 0" + " UNION ALL SELECT version_id FROM items WHERE version_id > 0"- Rejected Private mapping IDs and authored-source keys are distinct by contract. Canonical writes require exact UUID/mapping/namespace provenance; receipt/digest reads bind canonical tenant+Version. Legacy collisions remain denied; no supported leak is established.
- A canonical roster capture creates mapping row
- Hosted Review 4 CompletedRuntime 8m 44sFound: 1 Accepted: 0/1/0 Routed: 0
- Update the tracker anchor on line 9.Minor
The tracker does not define
#selected-full-owner-publication-preparation. Link to the existing#selected-entity-and-automation-intake-prerequisiteheading.--- "a/design/architecture/microservices/entity-management-service/api-contracts.md" +++ "b/design/architecture/microservices/entity-management-service/api-contracts.md" @@ -6,7 +6,7 @@ ## Implementation Status -The prepared selected-source command and immutable receipt/digest reads remain standalone, unregistered and unqualified. Forward V1011 adds the empty selected source catalogue over the current combined Entity/Saga parent, retaining explicit family and equipment evidence; this does not enable arbitrary authored templates, placement or gameplay admission. Its publication consumption follows the [canonical Game Design profile](../game-design-service/version-control.md#selected-full-publication-profile); current controlled-input proof limits and pending cross-owner qualification belong to the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation). +The prepared selected-source command and immutable receipt/digest reads remain standalone, unregistered and unqualified. Forward V1011 adds the empty selected source catalogue over the current combined Entity/Saga parent, retaining explicit family and equipment evidence; this does not enable arbitrary authored templates, placement or gameplay admission. Its publication consumption follows the [canonical Game Design profile](../game-design-service/version-control.md#selected-full-publication-profile); current controlled-input proof limits and pending cross-owner qualification belong to the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-entity-and-automation-intake-prerequisite). Entity V1003–V1010 and the manually composed, unregistered assignment/receipt/roster services are passive source and storage preparation. The canonical roster proto has no runtime handler, authenticated client, peer interceptor, or bean registration in this boundary. Legacy adapters and consumers retain develop behavior. The qualified immutable donor contains the complete migration tail; focused qualification of this recut, including the default combined Entity/Saga locations and actual-parent upgrade, is recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). Neither storage fixtures nor discovery references establish actual owner provenance, fresh Account eligibility, gameplay admission, or PLAY. Authenticated owner handoff and real caller/execution replacement remain required.- Accepted Verified Entity API status links to a removed tracker heading; correct only the fragment to the existing intake-prerequisite status section.
- Hosted Review 5 CompletedRuntime 6m 07sFound: 1 Accepted: 0/1/0 Routed: 0
- Update the tracker anchor on Line 15.Minor
The target heading is
### Selected Entity and Automation intake prerequisite, so the current link does not resolve to the owning status section.-... belong to the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation). +... belong to the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-entity-and-automation-intake-prerequisite).- Accepted Automation status still links to the removed selected-full heading. Its owning intake-prerequisite section exists; change only that tracker fragment.
Routed Findings
Route 1 · PR #3269 → PR #3249 Accepted/FixedMinorPreserve terminal-read status codes in Account settlement.
Both settlement paths map every owner error except
FAILED_PRECONDITIONtoUNAVAILABLE. A missing receipt can therefore bypass Account’s “not committed” handling, whileALREADY_EXISTSandDATA_LOSScan appear retryable.Preserve these owner statuses for both Automation and Entity, then add boundary tests for the absent, conflicting, and corrupt receipt cases.
if (failure.getStatus().getCode() == Status.Code.FAILED_PRECONDITION) { throw Status.FAILED_PRECONDITION .withDescription("Automation terminal evidence is not committed") .asRuntimeException(); } + Status.Code code = failure.getStatus().getCode(); + if (code == Status.Code.NOT_FOUND + || code == Status.Code.ALREADY_EXISTS + || code == Status.Code.DATA_LOSS) { + throw failure; + } throw Status.UNAVAILABLE .withDescription("Automation terminal evidence is unavailable") .asRuntimeException();Apply the same status-preservation block to the Entity catch path.
Outcome: Published19907273a7509fbc6d59ea4b4aada9188364f045 preserves three terminal codes for both owners, strips poisoned details. Fresh11Accountcases/20status-matrix combinations0fail/error/skip;MainTestCheckstyle/SpotBugs/SpotlessPASS85.9s. Proof:3249-routed-terminal-statuses/qualified-proof.json.
Earlier routing and proof
Earlier decisions
- Routed Verified both Account settlement catch paths hide NOT_FOUND/ALREADY_EXISTS/DATA_LOSS as UNAVAILABLE. Account implementation is owned by parent #3249; route there for exact status propagation and boundary cases.
Unlinked items
no items unlinked