PR #3134 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 13m 30sFound: 14 Accepted: 5/6/2 Routed: 0
- Allow Account-local fences to differ from Account-scope generations.Major
AccountAuthorityGenerationRepository.advanceInternaladvances the shared Account issuance fence for both Account and membership scopes, but it advances only the selected scope's generation. A membership advance can therefore produce Account generation/source2/2with fence4/3. The password-reset test constructs and accepts exactly this state.requireRetainedEventpasses those receipt fence values toRetainedEventEvidence, which then throws because of the equality checks. Remove only those checks.- || issuanceFence != accountAuthorityGeneration - || issuanceFenceSourceVersion != sourceVersion || accountSecurityCutoff == null- Accepted Accepted independent positive issuance fence/source coordinates rather than artificial Account generation equality; retain exact receipt and cutoff binding. Implemented7a with unit divergent4/3 vs2/2 proof; genuine membership-fence production closure is not claimed.
- Handle non-
ACTIVEfresh Accounts before enrolling platform birth sources.MajorAccountRepository.saveaccepts everyAccountLifecycleState, but fresh source initialization rejects any state other thanactive. The transaction then rolls back.AccountRepositoryIntegrationTestcreates fresh Accounts with every enum value, so its non-ACTIVEcases fail.If non-
ACTIVEfresh Accounts are unsupported, reject them before the insert with a clear error. If they are supported, skip only platform-restriction birth enrollment for those rows while retaining Account authority baseline initialization. Keep the V81 guard for any birth row.- Accepted Accepted clear non-ACTIVE fresh insertion rejection before mutation. Do not skip restriction birth guards or invent authority; retained non-ACTIVE ordinary update proof remains.
- Update the
AA-1.3capability row to match the new reset prose.MinorLine 35 states that password-reset token consumption is now implemented atomically. The
AA-1.3row at Line 51 still says "Recovery token consumption and reset-driven revocation remain incomplete." The same row also omits the new production anchors and the focused proof anchor:- Production anchors to add:
AccountPasswordResetOperationRepository.java,AccountPasswordResetDraftSourceChangeRepository.java,AccountAuthoritySourceEventReadback.java,V77__account_password_reset_operation_receipts.sql,V89__account_password_reset_pending_draft_source_changes.sql. - Proof anchor to add:
PasswordResetAuthorityProducerPostgresIntegrationTest.java.
Update the gap text so it says token consumption is implemented and only reset-driven revocation and PostgreSQL execution proof remain pending. Keep the
Verificationvalue unchanged, because the PostgreSQL cases were skipped.As per coding guidelines: "Keep its status, implementation record, validation, gaps, decisions, and service-map sections aligned when a domain boundary changes" and "
implementedandpartialrows name concrete production anchors."- Accepted Accepted tracker anchors/gap correction, shared with CLI#4. Keep partial status and passing physical proof, revocation and remaining recovery gaps explicit.
- Production anchors to add:
- Describe the pending-intent path as a retryable denial, not a wait.Minor
Both documents say the reset "waits" for the owner-fence outcome.
AccountServiceImpl.completePasswordResetdoes not wait. It commits theWAITINGintent, throwsSourceEvidenceUnavailableException(retryableAUTH_UNAVAILABLE), and depends on a same-token retry to settle.design/architecture/microservices/account-service/runtime-and-data.md#L11-L11: replace "the request waits for its owner-fence outcome before mutating the token or password" with "the request records its exact intent without token/password mutation and returns retryableAUTH_UNAVAILABLEuntil a same-token retry observes the settled owner-fence outcome".design/project-management/implementation-tracking/player-access-and-session.md#L33-L33: replace "token/password mutation waits for its owner-fence outcome" with the same retryable-denial wording.
As per path instructions: "Review docs for canonical-current-state consistency."
📍 Affects 2 files
design/architecture/microservices/account-service/runtime-and-data.md#L11-L11(this comment)design/project-management/implementation-tracking/player-access-and-session.md#L33-L33
- Accepted Accepted exact retryable AUTH_UNAVAILABLE wording; WAITING persists original intent without token/password mutation, never blocks the request waiting for owners.
- Return a token denial for a
SOURCE_ABORTEDintent instead of an internal error.MinorA
DEFINITIVE_ABORT(Lines 2507-2523) marks the journal rowSOURCE_ABORTEDand leaves thepassword_reset_tokenrow in place. On any retry with the same token:findAccountIdByTokenHashfinds the row, soresolvedTokenstays empty.pendingholds the abortedIntent, sooriginalIntent != null.- The flow reads authority and calls
participate. participatethrowsIllegalStateException("Terminal password-reset source intent has no receipt")at Lines 100-102 ofAccountPasswordResetDraftSourceChangeRepository.
token_hashis the V89 primary key, so no new intent can ever be created for that token. The token stays readable but can never be used, and every retry returns an internal error rather than "Invalid token". This is reachable when a capture mismatch occurs while the intent waits.Check the terminal status before reading authority or calling
participate. Map it to the original denial.🐛 Proposed fix
Intent originalIntent = pending.orElse(null); if (originalIntent != null && (originalIntent.accountId() != account.getId() || !originalIntent.accountUuid().equals(account.getAccountUuid()))) { throw new IllegalStateException("Password-reset Draft intent Account binding changed"); } + if (originalIntent != null && "SOURCE_ABORTED".equals(originalIntent.status())) { + return PasswordResetAttempt.aborted( + originalIntent.tokenExpiresAt().isAfter(LocalDateTime.now()) + ? "Invalid token" + : "Token expired"); + }Also delete or expire the token row in the same transaction as
markSourceAborted. Then the user is prompted to request a new reset link.- Accepted Accepted terminal aborted intent client denial with exact owner/request binding. Same-transaction token invalidation must preserve receipt/FK and rollback guarantees; no terminal intent server error.
- Preserve password-reset and logout-all branches in both V80 guards.Major
V80 replaces both shared guards but accepts only
ACCOUNT_AUTHORITY_CHANGEDandACCOUNT_SECURITY_STATE_CHANGED.Password-reset completion updates the locked Account password hash, advances Account authority, and appends a
PASSWORD_RESET_COMMITTEDevent. The Account update guard then cannot use its security-state branch and falls through to the legacy branch, which requiresACCOUNT_AUTHORITY_CHANGEDandmutationKinds. The deferred Account trigger can therefore reject the reset transaction.Logout-all advances the Account source state and appends a
LOGOUT_ALL_COMMITTEDevent as the latest source event. The source-record guard rejects that event withUnsupported Account source event type.Add explicit password-reset and logout-all branches to both guards. Bind each branch to its matching immutable operation receipt, Account identity, event identity and payload, authority counters, and issuance-fence values. The Account update branches must also validate the permitted Account state changes.
V79’s acceptance of these schemas as prior checkpoints does not make them valid current events for the V80 guards.
- Accepted Accepted exact reset/logout receipt branches in both V80 source/Account mutation guards; retain legacy/security and immutable payload, identity, counter, fence and permitted-state checks.
- Use
Propagation.MANDATORYforfindByIdForUpdate.MinorfindByIdForUpdateuses@Transactional, which means REQUIRED propagation. If a caller has no surrounding transaction, the method opens its own transaction. The method returns after the row lock is already released, and the caller receives no serialization. The sibling methodsfindByAccountUuidForUpdateandupdatePasswordHashForLockedAccountrequire a writable owner transaction. Apply the same contract here.Proposed fix
--- "a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java" +++ "b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java" @@ -55,11 +55,12 @@ } /** Locks one exact persisted Account row before an owner-local authority mutation. */ - @Transactional + @Transactional(propagation = Propagation.MANDATORY) public Optional<Account> findByIdForUpdate(Long id) { if (id == null || id <= 0L) { throw new IllegalArgumentException("A positive persisted Account ID is required"); } + requireWritableOwnerTransaction(); return Optional.ofNullable( dsl.selectFrom(ACCOUNTS).where(ACCOUNTS.ID.eq(id)).forUpdate().fetchOne(this::toEntity)); }- Accepted Accepted mandatory writable owner transaction for findByIdForUpdate; prove outside/read-only transaction denies before locking.
- Keep generic Account updates readable by LOGIN source reads.Major
AccountRepository.saverecords generic source events for changes topasswordHash,emailVerified,loginAuthModes, androle.readCurrentIssuerAccountSourcesnow validates every retained event throughrequireRetainedEvent, whileverifyEventaccepts only password-reset, logout-all, and security-state schemas. A generic Account event is therefore rejected withSourceEvidenceUnavailableException. Later closed events cannot repair the stream because the generic event remains in retained history.Accept and project validated legacy
AccountEventheads, or stop generic saves from changing fields that this reader must support.- Rejected Reject promotion of generic Account events to closed currentness: they lack operation-specific receipt/readback evidence, intentionally denied by current source contract. Keep exact retained history; typed AUTH_UNAVAILABLE and truthful gaps handled by4233551592.
- Use the configured jOOQ ignore terminator.Minor
The repository uses jOOQ
DDLDatabasedefaults, where the closing token is[jooq ignore stop].[jooq ignore end]is not configured, so it does not close the ignore region at line 90. Replace it with:--- [jooq ignore end] +-- [jooq ignore stop]- Accepted Accepted configured jOOQ stop terminator; shared with CLI#5. Regenerate jOOQ and retain protected baseline SQL.
- Account source reads now replay the full retained history on every call.Trivial
readCurrentSourcepreviously verified only the head event, and the comment at Lines 677-679 still describes that design. ForScopeKind.ACCOUNT, it now callsverifyEventHistory. That method loads and verifies every event from sequence 1 to the head. For each closed event, it also builds a newAccountAuthoritySourceEventReadbackand runs its receipt queries.readCurrentSourcealso runs acount(*)query on the event table.This path runs on every
recordAccountUpdate,readCurrentIssuerAccountSources,prepareClosedAccountAdvance, andadvanceClosedAccountHead.advanceClosedAccountHeadruns it twice. The cost is O(n) queries per call, and n grows with each reset, logout-all, or security update. These calls also holdFOR SHARE/FOR UPDATElocks.Possible fixes:
- Persist a verified-through checkpoint and verify only the events appended after it.
- Make the DB guards enforce the receipt invariant, as V38/V40 do for contiguity.
Also update the stale comment in
verifyLatestEvent.- Accepted Partially accepted stale comment correction, shared with CLI#3. Reject unproved latest-only/marker shortcut: closed-prefix and mixed history validation must remain. No performance optimization is claimed.
- Map legacy Account event readback failures to
AUTH_UNAVAILABLE.MajorWhen
emailVerifiedchanges fromfalsetotrue,verifyEmailcallsAccountRepository.save, which appends anaccount-auth-authority-source-event/v1event.requireCurrentLatestlater sends that event toverifyEvent, which supports only password-reset, logout-all, and security-state schemas. The generic event reachesIllegalStateException("Account source event schema is unsupported").This can prevent later password resets before token processing. The gRPC handler then returns
INVALID_ARGUMENTinstead of the intendedAUTH_UNAVAILABLE. Account source reads can fail in the same way.Map the unsupported generic schema to
SourceEvidenceUnavailableException. Keep the fail-closed behavior, and update the integration expectation and tracker text to state that Accounts with retained generic history cannot complete a reset until the history has a closed operation-specific readback contract.- default -> throw new IllegalStateException("Account source event schema is unsupported"); + default -> + throw new AccountAuthoritySourceEvidenceRepository + .SourceEvidenceUnavailableException();- Accepted Accepted unsupported generic history maps typed SourceEvidenceUnavailableException/AUTH_UNAVAILABLE, preserving closed-receipt-only currentness and exact retained evidence.
- Create the missing disclosure and settlement objects before using these checks.Major
DraftAuthorizationFenceRepositoryqueries the disclosure tables and the publication/Game Logic settlement tables and functions, but no migration through V89 defines them. Calls that reach these checks can fail before enforcing the fence. Add the required Flyway DDL, and update the staleV99Javadoc reference. Do not remove the checks.- Accepted Accepted complete nonactivating disclosure/publication/GameLogic storage closure and exact settlement checks; retain checks, no empty stubs or missing-dependency approval. Final forward map coordinated with Document.
- Enforce the settled Draft source change for environment binding updates.Trivial
V86 requires
source_change_bindingfor predecessor updates, but it does not require the matching Draft source change to beSOURCE_COMMITTEDor to contain the exact environment-binding scope. A committed publication can therefore advance the binding head while its Draft source change remainsWAITING.Add the deferred fence used by V85:
♻️ Suggested deferred fence trigger
+CREATE FUNCTION account_hosted_terms_environment_binding_fence_complete_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +DECLARE predecessor UUID; +BEGIN + IF NEW.status = 'COMMITTED' THEN + SELECT predecessor_binding_id INTO predecessor + FROM account_hosted_terms_environment_bindings + WHERE environment_boundary = NEW.environment_boundary + AND binding_id = NEW.candidate_binding_id; + IF predecessor IS NOT NULL AND (NEW.source_change_binding IS NULL OR NOT EXISTS ( + SELECT 1 FROM account_draft_authorization_source_changes change + JOIN account_draft_authorization_changed_scopes changed USING (change_id) + WHERE change.change_id = NEW.request_id + AND change.binding = NEW.source_change_binding + AND change.status = 'SOURCE_COMMITTED' + AND changed.source_key = + 'HOSTED_TERMS:environment-boundary/' || NEW.environment_boundary)) THEN + RAISE EXCEPTION 'Updated environment binding requires fully settled exact Draft source change'; + END IF; + END IF; + RETURN NULL; +END; +$$; +CREATE CONSTRAINT TRIGGER account_hosted_terms_environment_binding_fence_complete + AFTER INSERT OR UPDATE ON account_hosted_terms_environment_binding_publications + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_hosted_terms_environment_binding_fence_complete_guard();- Accepted Accepted deferred exact committed predecessor environment-source fence and exact changed-scope check; prove WAITING/wrong scope rejected, initial binding unaffected.
- Replace the self-comparison with a check of
affirmative_action_digest.MinorThe record is built from
row.get("affirmative_action_evidence", byte[].class). Line 527-529 then compares the record's copy with the same column, so the comparison is always true. The method never checks the storedaffirmative_action_digestagainst the stored evidence bytes. A row with mismatched action evidence and digest therefore reads back as valid. Compare the digest, as the code already does for the party source.Proposed fix
--- "a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java" +++ "b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsRepository.java" @@ -524,11 +524,10 @@ row.get("affirmative_action_evidence", byte[].class), row.get("affirmative_action_digest", String.class), row.get("accepted_at", OffsetDateTime.class)); - if (!Arrays.equals( - acceptance.affirmativeActionEvidence(), - row.get("affirmative_action_evidence", byte[].class)) + if (!HostedTermsEncoding.digest(acceptance.affirmativeActionEvidence()) + .equals(row.get("affirmative_action_digest", String.class)) || !HostedTermsEncoding.digest(acceptance.individualPartySource()) .equals(row.get("individual_party_source_digest", String.class))) { throw new IllegalStateException("Stored acceptance evidence digest conflicts"); } return acceptance;- Accepted Accepted validate affirmative action evidence digest instead of tautological byte self-comparison; prove corruption rejection without activating hosted terms.
- CLI Review 1 CompletedRuntime 3m 30sFound: 5 Accepted: 1/3/1 Routed: 0
- Avoid replaying the full Account event history on every source read.Trivial
readCurrentSourcenow callsverifyEventHistoryfor every Account scope. That method decodes every event from sequence 1 to the checkpoint. For each closed event,requireRetainedEventadds receipt lookups and, for security-state events, more shared row locks and readbacks.readCurrentSourceruns several times per operation. Examples arerecordAccountUpdate(before and after the append),readCurrentIssuerAccountSources,prepareClosedAccountAdvance, andadvanceClosedAccountHead. Each Account stream grows with every security-relevant update, so the cost of each read grows without bound. The comment inverifyLatestEvent(lines 677-679) still says the read path avoids "replaying an ever-growing retained history". That statement is now true only for issuer scopes.Choose one of these options:
- Validate history once, at append time. Persist a verified-history marker, such as a closed or legacy flag on the source head. Then verify only the latest event on read.
- Rely on the V38/V40 immutability guards and verify only the event at the checkpoint.
Update the stale comment in either case.
- Accepted Partially accepted stale-comment correction. Reject latest-only shortcut: mixed legacy/closed history supplies retained legacy Account state and last security cutoff, absent from that shortcut. Performance optimization is not implemented or claimed.
- Do not keep superseded password hashes in the source-change journal.Major
participatestores the Argon2 hash of the new password inaccount_password_reset_draft_source_changes.password_verifier.markSourceCommittedandmarkSourceAbortednever clear it, so the row keeps the hash after the operation ends. The row is also never deleted.Consequence: after a later password change, the old hash still sits in a second table. Over time each Account collects every reset hash in a store that is not the credential table. Old hashes are offline-cracking material for the user's earlier passwords.
The verifier is needed only while the intent is
WAITING, to finish the deferred reset. Clearpassword_verifierwhen the intent becomesSOURCE_COMMITTEDorSOURCE_ABORTED. Keeppassword_verifier_digestfor receipt binding. Then relax thesha256Hex(intent.passwordVerifier())check inrequireIntentfor terminal rows. Also define a retention horizon for terminal journal rows.- Accepted Accepted terminal verifier clearing with WAITING recovery and exact digest/receipt binding preserved; add SQL/readback proof. Reject invented numeric retention horizon; owner terminal receipt lifecycle remains incomplete.
- Map a terminal pending intent to
Invalid tokeninstead of a server error.MinorThe capture-mismatch abort path (lines 2507-2514) marks the intent
SOURCE_ABORTEDbut leaves the reset token unconsumed. On the next retry with the same token,findByTokenHashreturns the aborted intent.participatethen throwsIllegalStateException("Terminal password-reset source intent has no receipt")(line 101 ofAccountPasswordResetDraftSourceChangeRepository.java).The first response was
IllegalArgumentException("Invalid token"). Every later retry gets an unhandled 500 instead. The token also stays readable until the cleanup job removes it, but the user can never use it.When
originalIntent.status()isSOURCE_ABORTED, fail with the same client error before callingparticipate.Proposed fix
Intent originalIntent = pending.orElse(null); + if (originalIntent != null && "SOURCE_ABORTED".equals(originalIntent.status())) { + throw new IllegalArgumentException("Invalid token"); + } if (originalIntent != null- Accepted Accepted: a same-Account SOURCE_ABORTED reset retry must return the existing Invalid token client denial rather than an unhandled terminal-intent server error, without weakening Account/request binding.
- Align the
AA-1.3capability row with the new password-reset status.MinorLines 33-35 say that password-reset completion now claims and consumes its token atomically. The unchanged
AA-1.3row (line 51) still says "Recovery token consumption and reset-driven revocation remain incomplete". That row also has no anchors for the new production code:AccountPasswordResetOperationRepository.java,AccountPasswordResetDraftSourceChangeRepository.java,PasswordResetTokenRepository.java, V77, and V89. Its proof anchors also omitPasswordResetAuthorityProducerPostgresIntegrationTest.javaandAccountPasswordResetOperationRepositoryTest.java.The Capability Status row is the scan-first status surface, so it now contradicts the narrative above it. Add the anchors to the
AA-1.3row. Replace its gap text with the remaining work: reset-driven revocation, other recovery workflows, and physical PostgreSQL proof.As per coding guidelines: "Keep its status, implementation record, validation, gaps, decisions, and service-map sections aligned when a domain boundary changes", and "
implementedandpartialrows name concrete production anchors."- Accepted Accepted: update AA-1.3 production/proof anchors and gap wording for atomic reset-token consumption; keep capability partial and physical PostgreSQL, revocation and other recovery gaps explicit.
- Close the jOOQ ignore blocks with
[jooq ignore stop].MinorV77 and V78 close their ignore blocks with
-- [jooq ignore end]. jOOQ does not recognizeendas a stop token. Every other migration in this change uses-- [jooq ignore stop]. If the jOOQ DDL simulation carries the open ignore state into later scripts, later migrations drop out of jOOQ code generation.services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql#L91-L91: replace-- [jooq ignore end]with-- [jooq ignore stop].services/account-service/src/main/resources/db/migration/V78__account_logout_all_operation_receipts.sql#L90-L90: replace-- [jooq ignore end]with-- [jooq ignore stop].
- Accepted Accepted: use recognized jOOQ ignore stop terminators in unreleased V77/V78; preserve SQL bodies and protected migration baseline, regenerate jOOQ and run owning validation.
- CLI Review 2 CompletedRuntime 4m 24sFound: 8 Accepted: 0/5/1 Routed: 0
- Account source reads now scale with the full event history.Trivial
verifyEventHistoryloads and verifies every event from sequence 1 to the head on every Account source read. For each closed event,closedEventReadback().requireRetainedEventadds more queries: the receipt lookup, the checkpoint read, and for security-state eventsreadOperation/requireReceiptNotAhead.readCurrentIssuerAccountSourcesthen callsrequireCurrentLatest, which walks the same history again (AccountAuthoritySourceEventReadbackLines 117-124).This affects live paths.
AccountRepository.save→recordAccountUpdate→readCurrentSourceruns on every security-relevant save, for exampleverifyEmail. Password reset adds two more full passes (before and after commit). The number of queries per call grows without bound as an Account accumulates events.Consider storing a verified prefix checkpoint. For example, keep a durable "history verified through sequence N" marker that the same owner transaction advances, and verify only events after N. Database guards already make events immutable.
- Rejected A persistent verified-prefix cache adds an unproved authority mechanism: immutable event rows alone do not preserve current receipt/fence/operation readback. Linear verification is real but no measured failure/SLO establishes this proposed cache as necessary; preserve full currentness proof.
- Enforce the initial state on INSERT for the state-machine tables.Minor
Both guards fire only
BEFORE UPDATE OR DELETE. Each table CHECK accepts terminal states. An INSERT can therefore create a row that is alreadyCOMMITTEDorDISCLOSED, without the transition and readback rules. The other new journals (V83, V85, V86, V88, V89) reject non-initial inserts.services/account-service/src/main/resources/db/migration/V90__account_control_ui_committed_issuance.sql#L107-L109: addINSERTto the trigger. Requirestatus = 'PREPARED'with null candidate and result columns.services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql#L142-L144: addINSERTto the trigger. Requirestatus = 'PREPARED',dispatch_attempts = 0and null result columns.
- Accepted V90 and V98 UPDATE/DELETE-only state guards allow initial inserts directly into terminal states satisfying table checks. Enforce initial PREPARED insert and null candidate/result/zero-attempt invariants with positive and negative PostgreSQL fixtures.
- Use
IS DISTINCT FROMin the publication completeness guard.MinorThese checks use
<>on JSON extractions. A missing field givesNULL.NULLinside theORchain does not raise. Two concrete cases:- If the selection frame has no
intent.canonicalTenantIdor nointent.publishRequestId, the frame passes "Changed publication selection identity" (lines 94-95). - If the bundle has no
issuanceFence, or the source payload has noaccountIdortenantId, the guard does not check them (lines 61, 65-66).
V95 fixed the same guard with
IS DISTINCT FROM. Apply that fix here too.Proposed fix
- IF convert_from(parsed, 'UTF8')::JSONB->'intent'->>'canonicalTenantId' <> NEW.tenant_uuid::TEXT - OR convert_from(parsed, 'UTF8')::JSONB->'intent'->>'publishRequestId' <> NEW.publish_request_id THEN + IF convert_from(parsed, 'UTF8')::JSONB->'intent'->>'canonicalTenantId' IS DISTINCT FROM NEW.tenant_uuid::TEXT + OR convert_from(parsed, 'UTF8')::JSONB->'intent'->>'publishRequestId' IS DISTINCT FROM NEW.publish_request_id THENApply the same change to lines 58-66 and to the
source_count/decodecomparisons at lines 100-106.Also applies to: 94-95
- Accepted V91 JSON identity/vector comparisons using <> permit missing fields via SQL NULL. Use null-safe IS DISTINCT FROM and fail closed on absent source/count fields, with malformed JSON/vector negatives.
- If the selection frame has no
- Password reset now fails permanently for any Account that has an older-format source event.Major
requireCurrentLatestpasses every earlier event throughrequireRetainedEvent→verifyEvent.verifyEventaccepts only the reset, logout-all, and security-state schemas. For any otherschemaVersionit reachesdefault -> throw new SourceEvidenceUnavailableException()(Line 468).AccountRepository.savestill writes events in the olderAccountAuthoritySourceEventV1Codecformat throughrecordAccountUpdate. A common trigger:verifyEmailchangesemail_verified.recordAccountUpdateappends anEMAIL_LOGIN_ELIGIBILITY_CHANGEDevent in the older format.- After that,
completePasswordResetcallsrequireCurrentLatestand always throwsSourceEvidenceUnavailableException, which callers see as retryableAUTH_UNAVAILABLE.
Consequences:
- Reset regression. Most verified accounts can no longer reset their password. Before this PR, the reset path went through
save/recordAccountUpdate, which accepts these events. - Endless retries. The error says "retry", but no retry can succeed, so clients loop.
- Other blocked paths. The same check now runs inside
AccountAuthoritySourceEvidenceRepository.readCurrentIssuerAccountSources. That blocks first-JOIN membership production and creator bootstrap (AccountCreatorMembershipSourceReader.readCurrentUpstreamSourceEvidence) for these Accounts.
The tracker states that generic events "fail closed as
AUTH_UNAVAILABLE". It does not say that this covers nearly every verified Account.Either:
- accept older-format Account events in the history walk, as
AccountAuthoritySourceEvidenceRepository.verifyEventHistoryalready does, while requiring a closed receipt only for closed schemas; or - return a terminal, non-retryable error and record the limitation in the AA-1.3 gap.
- Rejected Deliberate tested fail-closed currentness: generic history lacks exact owner receipts. Tracker Retained Account Source Prerequisite records AUTH_UNAVAILABLE and incomplete closure. Accepting generic digests or changing that outcome weakens the owning contract; full producer closure remains required.
- Lock source rows in the canonical sort-key order.Minor
The comment says the guard uses "Same sorted original source locks as Account's producer/source writers". The query orders by
l.source_key, which uses the database collation. V76, V93 and V97 order byaccount_publication_authorization_source_sort_key(source_key), which is UTF-16 code-unit order. If the two orders disagree for a key pair, this guard and a V76 readback guard can lock the same rows in opposite order. PostgreSQL then aborts one of the transactions with a deadlock error.Proposed fix
- WHERE s.operation_id = NEW.operation_id ORDER BY l.source_key FOR UPDATE OF l; + WHERE s.operation_id = NEW.operation_id + ORDER BY account_publication_authorization_source_sort_key(l.source_key) FOR UPDATE OF l;- Accepted V96 currently orders locks by database collation while V76/V93/V97 use canonical UTF-16 sort keys. Align settlement to shared sort-key function and add focused guard proof.
- Add the missing
;separators in theAA-1.3anchor cells.MinorThe implementation-anchor cell joins two links with a double space and no separator:
...V40__account_authority_source_baselines.sql) [AccountPasswordResetOperationRepository.java]. The proof-anchor cell has the same defect before[PasswordResetAuthorityProducerPostgresIntegrationTest.java]. Every other anchor list in this table uses;. Strict anchor parsing (for example,dev-tools/tests/architecture-doc-contracts.sh) can merge or misread these links. Readers also see the cell as one run-on value.Proposed fix
-...V40__account_authority_source_baselines.sql) [AccountPasswordResetOperationRepository.java]... +...V40__account_authority_source_baselines.sql); [AccountPasswordResetOperationRepository.java]... -...AccountAuthoritySourceEvidencePersistenceIntegrationTest.java) [PasswordResetAuthorityProducerPostgresIntegrationTest.java]... +...AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java]...As per coding guidelines: "Evidence targets must be repository-local and resolvable".
- Accepted Repair two missing semicolon separators in AA-1.3 implementation/proof anchor cells; documentation-only fix assigned.
- Use the shared 2048-character source-key width in every source table.Minor
V76 widened
account_draft_authorization_source_locks.source_keyto 2048 because keys are shared. V91 and V98 narrow the width to 512 again. Hosted-terms environment keys are'HOSTED_TERMS:environment-boundary/' || environment_boundary, with a boundary of up to 512 characters, so these keys can reach 546 characters. Inserts with such keys fail.services/account-service/src/main/resources/db/migration/V91__account_selected_publication_authorization.sql#L24-L24: declaresource_key VARCHAR(2048).services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql#L7-L7: declareVARCHAR(2048)and change the CHECK tooctet_length(source_key) <= 2048.services/account-service/src/main/resources/db/migration/V98__account_hosted_terms_disclosure_handoffs.sql#L42-L43: declaresource_key VARCHAR(2048).
- Accepted V91 and V98 use narrower 512-character source keys than the V76 shared 2048-byte contract, rejecting legitimate max environment-derived keys. Align columns/checks and prove long valid key and oversized denial.
- Keep earlier codec failures as suppressed exceptions in
verifyAccountSource.TrivialThe nested
catch (IllegalArgumentException ...)chain dropscurrentSchemaMismatch,resetFailure, andlogoutFailure. The caller sees only the exception fromAccountSecurityStateAuthorityEventV1Codec.verify. This can mislead operators. Example: a realPasswordResetAuthorityEventV1Codecevent with a tamperedeventDigestis reported as a security-state schema error, and the digest error is lost. Add the earlier failures to the final exception withaddSuppressed. As an alternative, select the codec byeventTypebefore verifying.♻️ Proposed change
- } catch (IllegalArgumentException logoutFailure) { - var security = - AccountSecurityStateAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); + } catch (IllegalArgumentException logoutFailure) { + AccountSecurityStateAuthorityEventV1Codec.SecurityStateEvent security; + try { + security = + AccountSecurityStateAuthorityEventV1Codec.verify(supplied.canonicalEventJson()); + } catch (IllegalArgumentException securityFailure) { + securityFailure.addSuppressed(currentSchemaMismatch); + securityFailure.addSuppressed(resetFailure); + securityFailure.addSuppressed(logoutFailure); + throw securityFailure; + }The
securityvariable type is an assumption. Use the actual return type ofverify, orvarwith a helper method.- Accepted Preserve prior codec verification errors as suppressed diagnostics without changing evidence acceptance. Bounded fix and malformed reset-digest regression assigned.
- CLI Review 3 CompletedRuntime 3m 42sFound: 4 Accepted: 0/3/1 Routed: 0
- Align the PostgreSQL proof status with the companion docs.Minor
Line 9 says "physical PostgreSQL proof remains pending." The other two docs give a more specific status:
runtime-and-data.mdLine 13 says physical PostgreSQL execution at7a665c83e81f5cec85fcd7ec9a205c291bc0eba2"established partial evidence": fresh install through V97, the V73 upgrade, and selected V80/V86 cases passed, while other cases failed.- The tracker (Line 11) records 92 executed cases with three failures.
A reader of the README can conclude that no physical execution happened. State the partial result, the failures, and the unrun V98 proof, or link only to the tracker section.
Proposed wording
-... Focused checks and integration-source compilation pass; physical PostgreSQL proof remains pending. ... +... Focused checks and integration-source compilation pass; physical PostgreSQL execution at 7a established only partial evidence (some cases failed, and V98 remains unrun). ...As per path instructions: "Review docs for canonical-current-state consistency. Flag ... conflicts between architecture docs".
- Accepted Accepted README status correction; link owning physical-proof status rather than implying no execution occurred.
- Replace the stale migration numbers in the migration comments and the operator-facing error text.Minor
These migrations name versions that no longer match the objects they describe: "V57" for the Draft source change (V75/V76), "V78" for security-state (V79), and "V107" for the publication guard (V91). Operators who read these failure messages will look in the wrong migration.
services/account-service/src/main/resources/db/migration/V80__account_security_event_source_guard.sql#L423-L424: replace "V78 security-state" with "V79 security-state" or "security-state" in thisRAISEmessage and in the otherV78 security-statemessages in this function.services/account-service/src/main/resources/db/migration/V80__account_security_event_source_guard.sql#L116-L118: change "V78 deliberately omits" to name V79.services/account-service/src/main/resources/db/migration/V93__account_selected_publication_settlement.sql#L151-L160: replace "V107" with "V91" in the comment and theRAISEtext.services/account-service/src/main/resources/db/migration/V79__account_security_state_operations.sql#L236-L236: replace "V57" with the V75/V76 source-change name in the message and in the related comment at Line 208.services/account-service/src/main/resources/db/migration/V88__account_logout_all_pending_draft_source_changes.sql#L152-L152: replace "V57" with "V76", matching the V89 wording, here and in Line 224.
- Accepted Accepted stale migration references in V79/V80/V88/V93 operator diagnostics/comments; retain correct operation references.
- Move the duplicated strict-codec helpers into one shared package-private helper.Trivial
requireExactFields,requireExactText,requireText,requireUuid,requirePositiveDecimal,digest,canonicalJson, the cutoff-binding checks, and the strictObjectMappersetup appear twice. One copy is in this file. The other copy is inservices/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/PasswordResetAuthorityEventV1Codec.java(Lines 181-264). The two copies are nearly identical.AccountSecurityStateAuthorityEventV1CodecandRuntimeMembershipAuthorityEvidenceValidatoralso each redefine the same UUID, positive-decimal, and nil-UUID patterns.These codecs define the security-event wire contract that
RuntimeMembershipAuthorityEvidenceValidator.verifyAccountSourceaccepts. If someone later fixes a validation rule in one copy only, the copies will diverge. Each event schema would then accept different inputs. Keep only the schema-specific field sets and bindings in each codec.♻️ Sketch of a shared helper
// package-private, same package final class StrictAuthorityEventSupport { static final Pattern UUID_PATTERN = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]*"); static final Pattern DIGEST_PATTERN = Pattern.compile("sha256:[0-9a-f]{64}"); static final ObjectMapper JSON = /* strict duplicate + trailing-token mapper */; static void requireExactFields(ObjectNode object, Set<String> required, String path) { ... } static String requireText(ObjectNode object, String field, String path) { ... } static String requireUuid(ObjectNode object, String field, String path) { ... } static String requirePositiveDecimal(ObjectNode object, String field, String path) { ... } static void requireAccountCutoffBinding(ObjectNode event, String streamKey) { ... } static String digest(ObjectNode preimage) { ... } static String canonicalJson(ObjectNode wire) { ... } }- Accepted Accepted shared strict-codec support to prevent validation drift; preserve schema-specific bindings, wire bytes and errors.
- Require
resultdigestto equal the SHA-256 ofresultpayload.MinorRequire `result_digest` to equal the SHA-256 of `result_payload`.
The table checks only that
result_digesthas the correct format. A terminal update can store a digest that does not match the payload, and the trigger accepts it. V85 and V86 enforceresult_digest = 'sha256:' || encode(sha256(result_payload), 'hex')for the same kind of terminal result. Add the same constraint here.Proposed fix
result_digest VARCHAR(71) CHECK (result_digest ~ '^sha256:[0-9a-f]{64}$'), + CHECK (result_digest IS NULL + OR result_digest = 'sha256:' || encode(sha256(result_payload), 'hex')),- Accepted Accepted V98 terminal result digest/payload integrity constraint with mismatch and valid-transition PostgreSQL regression.
- Hosted Review 2 CompletedRuntime 10m 03sFound: 5 Accepted: 0/3/2 Routed: 0
- Fix the stale Javadoc on
markSourceAborted: a mixed commit-order outcome stays pending.TrivialThe Javadoc says a commit-order abort needs two terminal owner readbacks, "including a mixed vector". The code does not do this.
settlement()returnsPENDINGfor a mixedCOMMIT_ORDERvector, soallAffectedSettledrejects the abort. The V76account_draft_authorization_is_settledcheck also requirescount(DISTINCT outcome) = 1. A future owner verifier that relies on this Javadoc would expect a mixed result to settle the change, but the abort would always be rejected.Proposed fix
- * source commit applies: revoke order requires two definitive aborts; commit order requires two - * exact terminal owner readbacks, including a mixed vector. + * source commit applies: revoke order requires every required owner to report a definitive + * abort; commit order requires every required owner to report one uniform exact terminal + * outcome. A mixed vector remains pending.- Accepted Accepted Javadoc correction: COMMIT_ORDER requires uniform terminal owner outcome; mixed vector stays pending.
- Reuse one shared
JsonMapperin all three canonical encoders.TrivialEach
canonicalhelper callsJsonMapper.builder().build()every time it runs. A single currentness or publication request runs many encodings: party, catalog, acceptance, currentness source, and binding receipt. A built mapper is thread-safe and has no per-call configuration here. Build it once and reuse it.services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/CreatorPartyEncoding.java#L99-L107: addprivate static final JsonMapper JSON = JsonMapper.builder().build();and callJSON.writeValueAsString(fields).services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEncoding.java#L240-L247: make the same change with a staticJsonMapper.services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingEncoding.java#L79-L86: make the same change with a staticJsonMapper.
♻️ Proposed refactor (pattern for each file)
+ private static final JsonMapper JSON = JsonMapper.builder().build(); @@ - return Rfc8785CanonicalJson.canonicalizeUtf8( - JsonMapper.builder().build().writeValueAsString(fields)); + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(fields));📍 Affects 3 files
services/account-service/src/main/java/net/firedevops/firemud/accountservice/creatorparty/CreatorPartyEncoding.java#L99-L107(this comment)services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEncoding.java#L240-L247services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingEncoding.java#L79-L86
- Accepted Accepted reuse immutable JsonMapper per canonical encoder; preserve exact bytes and validation.
- Make the local integration-run count match the latest recorded run, or name the run it describes.Minor
Line 11 says the local integration run "executed two cases and skipped 83 without Docker." The PR description says the corrected V98 batch's local integration run reported 86 cases: two executed and 84 skipped. The tracker does not say which run its 85-case figure comes from. A reader will treat it as the current local result. Either update the counts to the latest run (2 executed, 84 skipped) or name the head/batch that produced 83 skips.
As per path instructions: "Review docs for canonical-current-state consistency." As per coding guidelines: keep the tracker's "status, implementation record, validation, gaps … aligned".
- Accepted Accepted qualify historical85-case result and corrected86-case scope by exact batch; do not imply unrun physical proof is complete.
- Add
TRUNCATEguards to the three creator-party tables.MinorThe immutable guard covers only
UPDATE OR DELETE. ATRUNCATEonaccount_tenant_creator_party_historyremoves all prior history. Thenaccount_creator_party_history_insert_guardaccepts a newFRESH_INITIALrow for the same tenant. That breaks the stated rule "All history counts as prior state". The other immutable tables added in this PR (V74, V79, V81, V90, V91, V98) have statement-levelTRUNCATEguards. Add the same guards here.🔒️ Proposed fix
CREATE TRIGGER account_creator_party_operation_immutable BEFORE UPDATE OR DELETE ON account_fresh_creator_party_association_operations FOR EACH ROW EXECUTE FUNCTION account_creator_party_immutable_guard(); +CREATE TRIGGER account_individual_creator_party_no_truncate + BEFORE TRUNCATE ON account_individual_creator_party_sources + FOR EACH STATEMENT EXECUTE FUNCTION account_creator_party_immutable_guard(); +CREATE TRIGGER account_creator_party_history_no_truncate + BEFORE TRUNCATE ON account_tenant_creator_party_history + FOR EACH STATEMENT EXECUTE FUNCTION account_creator_party_immutable_guard(); +CREATE TRIGGER account_creator_party_operation_no_truncate + BEFORE TRUNCATE ON account_fresh_creator_party_association_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_creator_party_immutable_guard();- Accepted Accepted V84 statement-level TRUNCATE guards preserving creator source/history/receipts with retained-history rejection proof.
- Map a pending source change to
AUTH_UNAVAILABLE.MinorWhen a new password-reset change overlaps a waiting source change,
requestSourceChangethrowsIllegalStateException.completePasswordResethandles onlySourceEvidenceUnavailableExceptionas unavailable; the generic path returnsINVALID_ARGUMENT.Map only this pending-change condition and rethrow other
IllegalStateExceptioninstances.--- "a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java" +++ "b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java" @@ -133,8 +133,16 @@ nextSequence, requestId, eventId); SourceChange change = new SourceChange(UUID.randomUUID(), List.of(source), mutation); - fences.requestSourceChange(change); + try { + fences.requestSourceChange(change); + } catch (IllegalStateException pending) { + if ("Another authority source change is already pending".equals(pending.getMessage())) { + throw new net.firedevops.firemud.accountservice.repository + .AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException(); + } + throw pending; + } dsl.execute( "INSERT INTO "- Accepted Accepted typed pending-source condition mapped only to retryable SourceEvidenceUnavailable; preserve unrelated failures and rollback.
- CLI Review 4 CompletedRuntime 3m 29sFound: 3 Accepted: 1/0/1 Routed: 0
- Every Account source read now runs one query round per retained event.Trivial
readCurrentSourcecounts the stream events. For Account scope, it then callsverifyEventHistory. That method loads every event from sequence 1 to the head. For each closed event, it also builds a freshAccountAuthoritySourceEventReadbackand runs receipt lookups.readCurrentIssuerAccountSourcesrepeats a full history walk throughrequireCurrentLatest. The cost of each read grows with the number of Account security mutations. The walk runs on every source read, including reads that happen while the Account row lock is held. History has no bound, because receipt retention is unresolved.Before this path serves LOGIN or JOIN traffic:
- Add a verified history watermark, for example the last fully verified sequence and digest on
account_authority_source_records. - Verify only the events after that watermark.
- Add a latency metric for history length.
Also applies to: 756-857
- Rejected Repeated optional watermark proposal, with no measured latency defect. Current owner proof requires full immutable history/receipt verification; persisting a cache changes provenance and tamper guarantees. This passive slice does not justify skipping older evidence.
- Add a verified history watermark, for example the last fully verified sequence and digest on
- V97 rejects this intake authorization at commit, so the test fails.Major
V97 adds the deferred constraint trigger
account_game_logic_intake_source_read_finalize_validateonaccount_game_logic_intake_authorizations. That trigger runsaccount_game_logic_intake_source_read_terminal_guard(), and the guard runs:SELECT * INTO STRICT original FROM account_game_logic_intake_source_read_reservations WHERE operation_id = NEW.operation_id FOR UPDATE;This fixture inserts the authorization and its sources without a matching
account_game_logic_intake_source_read_reservationsrow. When theexecuteWithoutResulttransaction commits,STRICTraisesNO_DATA_FOUND.gameLogicSettlementAcceptsCompleteTerminalAndUsesCanonicalSourceLockOrdertherefore never reaches the settlement insert.Fix the fixture so the run is valid under V97. In the same transaction, insert a reservation with matching identity fields, issuance evidence, and source rows. The reservation's 7th
scope_bytesframe must equal the snapshot'sbindingJson. Also seed aCOMMIT_ORDER, settled Draft fence for that selection, becauseaccount_game_logic_intake_source_read_complete_guardrequires it.- Accepted V97 deferred terminal guard requires the exact source-read reservation and settled original Draft fence; the new canonical-order fixture omits them and will fail at commit. Correct fixture only; preserve all guards and assertions.
- Run Argon2 hashing before you take the Account row lock.Trivial
completePasswordResetInOwnerTransactionrunsfindByIdForUpdatefirst. While the Account row stays locked, it then runs:verifyPassword(Line 2446)hashPassword(Line 2462)
Each call is Argon2 with 64 MiB of memory and 2 iterations. During that time the transaction holds the
accountsrow lock and a pooled connection. Concurrent resets, retries, and other writers to the same Account must wait for this work. The new-intent path does not need the lock to computehashPassword(request.newPassword()). Compute the hash beforepasswordResetOwnerTransaction.execute(...)and pass it in. If an existing intent is found, discard the precomputed hash.- Accepted Fresh reset hashes its replacement password while holding the Account lock. Precompute only the new candidate verifier before the owner transaction; retain locked receipt/intent rechecks, original retry verifier and exact conflict checks.
- CLI Review 5 CompletedRuntime 3m 50sFound: 6 Accepted: 0/3/2 Routed: 0
- Bind the original
globalRolesfrom the receipt, not from the current role source.Majorexpected_before_stateandexpected_after_stateboth readglobalRolesfromrole_source_row.global_roles. As a result,before_state->'globalRoles'must always equalafter_state->'globalRoles'. For a V79 receipt withGLOBAL_ROLE_CHANGED, the storedbefore_statehas the old roles, so the guard raises at line 497.V79 allows
mutation_kindsto containGLOBAL_ROLE_CHANGEDtogether with up to three other kinds. A role change alone does not touch protectedaccountscolumns, so this trigger returns early. A combined change, for example role plus lifecycle, always fails, andchanged_kindscan never containGLOBAL_ROLE_CHANGED.Use the receipt's original roles for the before image. Keep the current role source for the after image.
🐛 Proposed fix
expected_before_state := jsonb_build_object( 'emailVerified', OLD.email_verified, - 'globalRoles', to_jsonb(role_source_row.global_roles), + 'globalRoles', before_state->'globalRoles', 'lifecycleState', upper(OLD.lifecycle_state), 'loginAuthModes', expected_old_modes);- Rejected Current V74 enforces empty immutable global roles; no migration74-98 or service registers a role writer. Combined role changes cannot occur. V79 checks original locked preimage; do not loosen V80 to self-asserted roles for an unimplemented future producer.
- Require the exact source evidence before
DISPATCHAUTHORIZED.MinorRequire the exact source evidence before `DISPATCH_AUTHORIZED`.
The
PREPARED→DISPATCH_AUTHORIZEDtransition does not check thataccount_hosted_terms_disclosure_sourcescontains a row forNEW.source_key. After this transition,account_hosted_terms_disclosure_source_insert_guardrejects all new source rows. A handoff authorized with no source row is therefore permanent. That handoff carries no source evidence, so the exact-source fence ("Exact hosted terms source has authorized disclosure") cannot apply to it. Add the check to the transition branch.🛡️ Proposed fix
IF OLD.status = 'PREPARED' AND NEW.status = 'DISPATCH_AUTHORIZED' AND OLD.dispatch_attempts = 0 AND NEW.dispatch_attempts = 1 AND NEW.result_outcome IS NULL AND NEW.result_payload IS NULL - AND NEW.result_digest IS NULL AND NEW.result_recorded_at IS NULL THEN + AND NEW.result_digest IS NULL AND NEW.result_recorded_at IS NULL + AND EXISTS (SELECT 1 FROM account_hosted_terms_disclosure_sources s + WHERE s.handoff_id = NEW.handoff_id AND s.source_key = NEW.source_key) THEN RETURN NEW;- Accepted V98 currently authorizes dispatch with no exact source row then prevents insertion. Require matching handoff/source before dispatch and prove missing or unrelated sources rejected.
- Every Account source read now does work that grows with the full event history.Trivial
verifyEventHistoryreads every event from sequence 1 to the checkpoint on eachreadCurrentSourcecall. For each closed event it also callsclosedEventReadback(). That call builds a newAccountAuthoritySourceEventReadbackand new operation repositories, then runs the receipt lookups.recordAccountUpdatecallsreadCurrentSourcetwice for each update.advanceClosedAccountHeadcalls it several times. The query count per Account mutation therefore grows linearly with the stream length, and the stream has no bound.Do these two things:
- Create the readback once per call and reuse it outside the loop.
- Persist a verified-history watermark, for example the last fully verified sequence on
account_authority_source_records. Then reads verify only the events after that watermark.
- Accepted Partially accepted: reuse one closed-event readback per history verification. Reject persisted watermark: no latency proof; skipping immutable old receipts changes current tamper/provenance verification.
- Deny TRUNCATE on every immutable evidence table.Minor
Several "immutable" tables block only row-level
UPDATEandDELETE.TRUNCATEdoes not fire row triggers, so it removes all retained evidence. Later guards depend on this evidence: V80 and V88 read the receipts, V84 reads the bootstrap rows, and V86 reads the catalog. V79, V81, V84, and V88–V98 already add statement-level truncate guards. Apply the same pattern here.services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql#L88-L90: addBEFORE TRUNCATE ... FOR EACH STATEMENT EXECUTE FUNCTION account_password_reset_operation_immutable_guard().services/account-service/src/main/resources/db/migration/V78__account_logout_all_operation_receipts.sql#L87-L89: add the same statement trigger that runsaccount_logout_all_operation_immutable_guard().services/account-service/src/main/resources/db/migration/V83__account_tenant_creation_bootstrap.sql#L186-L188: add a statement trigger that runsaccount_tenant_creation_bootstrap_no_delete().services/account-service/src/main/resources/db/migration/V85__account_hosted_terms_acceptance_workflow.sql#L124-L129: add statement triggers that runaccount_hosted_terms_immutable_guard()for catalog versions, acceptances, and publication operations. The V87 truncate trigger only holds source locks and does not deny the truncate.services/account-service/src/main/resources/db/migration/V86__account_hosted_terms_environment_binding.sql#L105-L107: add statement triggers foraccount_hosted_terms_environment_bindingsandaccount_hosted_terms_environment_binding_publications.
- Accepted Add statement-level TRUNCATE denial for immutable V77/V78 receipts, V83 bootstrap and V85/V86 terms evidence; retain normal protected transitions and prove preservation.
- Use one current physical PostgreSQL and V98 proof status in all three documents.Minor
The tracker records a current-head physical run at
c69fa364…. That run executed 98 cases with one V97 settlement-fixture failure, and its fresh V98 coverage passed. Other passages still say that V98 is unrun or that the replacement physical run is pending. Readers get contradictory proof status.design/project-management/implementation-tracking/player-access-and-session.md#L11-L11: Keep this line as the single source of the exact current-head counts and failures.design/project-management/implementation-tracking/player-access-and-session.md#L37-L39: Replace "V98 disclosure persistence proof is unrun" and "V98 remains unexecuted" with the current-head result. Alternatively, mark the 7a statements as historical.design/architecture/microservices/account-service/runtime-and-data.md#L13-L13: Remove "V98 and its disclosure persistence proof remain unrun", or update it to the current-head result. Then link to the tracker.design/architecture/microservices/account-service/README.md#L9-L9: Replace "remains pending" with "executed with one failure (see tracker)", or keep only the link to the tracker.
As per coding guidelines, keep the tracker's "status, implementation record, validation, gaps … sections aligned". As per path instructions, flag "conflicts between architecture docs".
- Accepted Align secondary Account docs and later tracker paragraphs with actual c69 physical98cases/1fixture failure; preserve historical7a limitations and current repair proof distinction.
- Replace the nested decoder ladder with one ordered decoder list and a wrapping error.Trivial
The four-level
try/catchnesting repeats the sameAccountSourcemapping four times. It also throws the last decoder's exception (AccountSecurityStateAuthorityEventV1Codec) as the primary error for every account-source failure. As a result, a malformed password-reset carrier reports the generic security-state message "object must contain exactly the declared fields", and the useful diagnostic stays hidden in the suppressed exceptions. Throw oneaccount sourceerror that carries every decoder failure as a suppressed exception.♻️ Proposed refactor
- AccountSource event; - try { - var verified = AccountAuthoritySourceEventV1Codec.verify(supplied.canonicalEventJson()); - ... - } + List<java.util.function.Function<String, AccountSource>> decoders = + List.of( + json -> { + var verified = AccountAuthoritySourceEventV1Codec.verify(json); + if (!(verified instanceof AccountAuthoritySourceEventV1Codec.AccountEvent a)) { + throw invalid("account source", "must be an Account event"); + } + return new AccountSource(a.eventId(), a.eventDigest(), a.canonicalJson(), + a.outboxStreamKey(), a.outboxSequence(), a.accountId(), + a.accountAuthorityGeneration(), + a.accountSecurityCutoff().accountAuthorityGeneration(), + a.accountSecurityCutoff().outboxStreamKey(), + a.accountSecurityCutoff().outboxSequence()); + }, + json -> { var r = PasswordResetAuthorityEventV1Codec.verify(json); return new AccountSource(/* same mapping */); }, + json -> { var l = AccountLogoutAllAuthorityEventV1Codec.verify(json); return new AccountSource(/* same mapping */); }, + json -> { var s = AccountSecurityStateAuthorityEventV1Codec.verify(json); return new AccountSource(/* same mapping */); }); + AccountSource event = null; + IllegalArgumentException failure = + invalid("account source", "matches no supported Account source schema"); + for (var decoder : decoders) { + try { + event = decoder.apply(supplied.canonicalEventJson()); + break; + } catch (IllegalArgumentException schemaMismatch) { + failure.addSuppressed(schemaMismatch); + } + } + if (event == null) { + throw failure; + }- Accepted Replace nested codec ladder with ordered supported decoders and one account-source error retaining all decoder failures; preserve strict event mappings and validation.
- Hosted Review 3 CompletedRuntime 7m 13sFound: 4 Accepted: 0/3/1 Routed: 0
- Stop the read-only inspection paths from taking fence row locks before source locks.Minor
readOperationalways runsSELECT ... FOR UPDATE. The following methods reach it, orFOR UPDATE OF f, without callinglockSourcesfirst:readreadSettlementreadOriginalBindingreadOwnerResultreadUnresolvedOperations
The mutating paths lock source rows first and fence rows second:
reserveclaimCommitOrderrequestSourceChangerecordOwnerReadback- the V76
account_draft_authorization_owner_readback_guard
The class Javadoc also requires sources before operations. The following sequence is feasible:
- A recovery transaction calls
readUnresolvedOperations, which locks fence A. - The same transaction calls
recordOwnerReadbackfor A, which waits on source S. - A concurrent
requestSourceChangeholds S and waits on fence A.
PostgreSQL then aborts one transaction with
40P01. ThereadUnresolvedOperationsJavadoc already says that consumers re-read settlement before they act. Discovery therefore needs no row lock.Use an unlocked read for these inspection paths. Keep
FOR UPDATEonly for paths that have already locked their sorted sources.Proposed fix
public FenceSnapshot read(DraftAuthorizationFenceBinding binding) { requireTransaction(); - return snapshot(requireExact(readOperation(binding.operationId()), binding)); + return snapshot(requireExact(readOperationUnlocked(binding.operationId()), binding)); } ... - Record row = requireExact(readOperation(binding.operationId()), binding); + Record row = requireExact(readOperationUnlocked(binding.operationId()), binding); ... - sql += " ORDER BY f.reserved_at, f.operation_id LIMIT ? FOR UPDATE OF f"; + sql += " ORDER BY f.reserved_at, f.operation_id LIMIT ?"; ... + private Record readOperationUnlocked(UUID operation) { + return dsl.fetchOne("SELECT * FROM " + FENCES + " WHERE operation_id = ?", operation); + }Apply
readOperationUnlockedinreadOriginalBindingandreadOwnerResultas well.Also applies to: 606-631, 641-669
- Accepted Accepted: inspection/discovery must not acquire fence before source locks; use unlocked exact reads there only, retaining source-first locked mutations and deterministic independent-transaction proof.
- Add statement-level
TRUNCATEguards to the remaining immutable evidence tables.MinorThese migrations protect immutable evidence only with row-level
UPDATE/DELETEtriggers. ATRUNCATEbypasses those triggers. After a truncate, the insert guards accept a new "initial" state: a newINITIALcatalog, a second creator bootstrap for the same tenant, or a replayed presented token. V84, V90, V91 and V98 already guardTRUNCATEfor equivalent tables.services/account-service/src/main/resources/db/migration/V85__account_hosted_terms_acceptance_workflow.sql#L124-L129: addBEFORE TRUNCATE ... FOR EACH STATEMENT EXECUTE FUNCTION account_hosted_terms_immutable_guard()triggers onaccount_hosted_terms_catalog_versions,account_individual_hosted_terms_acceptances,account_hosted_terms_scopesandaccount_hosted_terms_publication_operations.services/account-service/src/main/resources/db/migration/V83__account_tenant_creation_bootstrap.sql#L186-L188: add aBEFORE TRUNCATEstatement trigger onaccount_tenant_creation_bootstrap_operationsthat usesaccount_tenant_creation_bootstrap_no_delete().services/account-service/src/main/resources/db/migration/V78__account_logout_all_operation_receipts.sql#L87-L89: add aBEFORE TRUNCATEstatement trigger onaccount_logout_all_operation_receiptsthat usesaccount_logout_all_operation_immutable_guard().
📍 Affects 3 files
services/account-service/src/main/resources/db/migration/V85__account_hosted_terms_acceptance_workflow.sql#L124-L129(this comment)services/account-service/src/main/resources/db/migration/V83__account_tenant_creation_bootstrap.sql#L186-L188services/account-service/src/main/resources/db/migration/V78__account_logout_all_operation_receipts.sql#L87-L89
- Accepted Accepted; overlaps CLI5#6, with additional hosted-terms scope TRUNCATE guard. Existing immutable deny functions and physical preservation regression; no production activation.
- Use the shared
AccountPostgresIntegrationFixtureinstead of a direct Docker Hub image.TrivialThis test creates its own
PostgreSQLContainer<>("postgres:16-alpine").HostedTermsEnvironmentBindingFencePostgresIntegrationTestin this PR uses the sharedAccountPostgresIntegrationFixture. According to the PR description, Account integration jobs already failed during Testcontainers image pulls (Docker Hub HTTP 429 and 504), and#3137is fixing trusted registry access separately. A hard-coded image reference bypasses any registry or image pinning that the shared fixture applies. This test then stays exposed to the same pull failures after#3137merges.Start the container through the shared fixture, and build each schema's
DataSourcewithPOSTGRES.dataSource(schema).- Accepted Accepted: reuse canonical AccountPostgresIntegrationFixture and per-schema DataSource; keep exact source/receipt proofs and Docker-unavailable behavior, remove bypass of trusted image selection.
- Update the proof-status prose after the
c69fa36run and thefb6ca4ddpublication.MinorRoot cause: Some proof statements were written before the
c69fa36physical run and were not updated afterward. That run executed 98 cases, and fresh V98 coverage and the V84 disclosure guards passed. The fixture correction is now published on headfb6ca4ddbut has not been physically rerun. The documents now contradict each other about V98 and about which head is current.design/project-management/implementation-tracking/player-access-and-session.md#L11-L11: Change the "current headc69fa36…" wording to namec69fa36as the historical run. State that the corrected canonical-order fixture is published onfb6ca4ddand is not yet physically rerun. Do not say that the correction is only "prepared locally".design/project-management/implementation-tracking/player-access-and-session.md#L37-L39: Replace "V98 disclosure persistence proof is unrun" and "V98 remains unexecuted". State that fresh V98 coverage passed atc69fa36, and that the Game Logic canonical-order fixture failed there and has no rerun yet.design/architecture/microservices/account-service/runtime-and-data.md#L11-L13: Replace "V98 and its disclosure persistence proof remain unrun" with the samec69fa36result. Keep the link to the tracker for the exact counts.
As per path instructions: "Review docs for canonical-current-state consistency." As per coding guidelines: "Keep its status, implementation record, validation, gaps, decisions, and service-map sections aligned".
📍 Affects 2 files
design/project-management/implementation-tracking/player-access-and-session.md#L11-L11(this comment)design/project-management/implementation-tracking/player-access-and-session.md#L37-L39design/architecture/microservices/account-service/runtime-and-data.md#L11-L13
- Accepted Accepted; same current-PR documentation obligation as CLI5#3. Align historical c69 versus published fixture and actual physical fb6 Account job success, retain whole-gate and activation limits.
- CLI Review 6 CompletedRuntime 3m 29sFound: 4 Accepted: 1/1/1 Routed: 0
- A missing
sourcesarray passes the reservation completeness check.MinorIf
source_payloadhas nosourceskey,vectoris SQLNULL. Bothjsonb_array_length(vector) < 1and<> (SELECT count(*) ...)then evaluate toNULL, so theIFdoes not raise. The followingFORloop overjsonb_array_elements_text(NULL)runs zero times. The reservation commits with zero participating sources.A reservation with no rows in
account_game_logic_intake_source_read_sourcesfences no source key. The preliminary source read then has no serialization effect.V91 and V95 guard the same input with
IS DISTINCT FROM, andpublicationCompletenessRejectsMissingJsonValues...covers V91. Make the V97 check fail closed in the same way.🛡️ Proposed fix
vector := convert_from(NEW.source_payload, 'UTF8')::JSONB->'sources'; - IF jsonb_array_length(vector) < 1 OR jsonb_array_length(vector) <> - (SELECT count(*) FROM account_game_logic_intake_source_read_sources WHERE operation_id = NEW.operation_id) THEN + IF jsonb_typeof(vector) IS DISTINCT FROM 'array' OR jsonb_array_length(vector) < 1 + OR jsonb_array_length(vector) IS DISTINCT FROM + (SELECT count(*)::INTEGER FROM account_game_logic_intake_source_read_sources WHERE operation_id = NEW.operation_id) THEN- Accepted Fail closed in V97 on missing/null/non-array source vectors and mismatched or zero participation; add negative and existing positive PostgreSQL regression.
- Verify that the transaction actually starts, so the ordering assertion cannot pass vacuously.Trivial
The ordering check runs only inside the
getTransactionstub. SupposecompletePasswordResetrejects the invalid token without callingtransactionManager.getTransaction(...). Two examples are a pre-transaction token lookup or a declarative transaction boundary. In that case the stub never runs. The test then passes oncandidateVerifierPreparedalone. Hashing before the transaction is never checked.Add an explicit
verifyofgetTransactionafter theassertThrows. A regression that moves hashing inside the transaction or removes the transaction then fails this test.♻️ Proposed change
} assertTrue(candidateVerifierPrepared.get()); + org.mockito.Mockito.verify(transactionManager, org.mockito.Mockito.atLeastOnce()) + .getTransaction(org.mockito.ArgumentMatchers.any(TransactionDefinition.class)); }- Accepted Implement explicit transaction-start verification so verifier-before-transaction regression cannot pass vacuously.
- Zero-row region or spawn inventories always fail settlement.Major
jsonb_aggreturns SQLNULLfor an empty input set. IfregionGeneratorInputsorspawnBindingInputsis[], the expression becomesNULL IS DISTINCT FROM '[]'::JSONB. That expression evaluates toTRUE, so the guard raises'Inventory differs from exact original selected Account, APPLIED graph or freeze'.The function explicitly accepts a zero count for these families:
- Line 126 accepts
spawnBindingCountmatching^(0|[1-9][0-9]*)$. - Line 139 requires only
counts[3] >= 1(ROOM).
As a result, a valid publication with no spawn bindings (or no region generator inputs) cannot insert its settlement. V93's
account_selected_publication_is_settledthen stays false.account_control_ui_hold_required_sourceskeeps raising55P03for every source writer on those keys. Wrap both aggregates inCOALESCE(..., '[]'::JSONB).🐛 Proposed fix
- OR (SELECT jsonb_agg(entry ORDER BY entry->>'regionTemplateId') FROM - jsonb_array_elements(model->'regionGeneratorInputs') entry) - IS DISTINCT FROM model->'regionGeneratorInputs' + OR (SELECT COALESCE(jsonb_agg(entry ORDER BY entry->>'regionTemplateId'), '[]'::JSONB) FROM + jsonb_array_elements(model->'regionGeneratorInputs') entry) + IS DISTINCT FROM model->'regionGeneratorInputs' @@ - OR (SELECT jsonb_agg(entry ORDER BY entry->>'bindingTemplateId') FROM - jsonb_array_elements(model->'spawnBindingInputs') entry) - IS DISTINCT FROM model->'spawnBindingInputs' + OR (SELECT COALESCE(jsonb_agg(entry ORDER BY entry->>'bindingTemplateId'), '[]'::JSONB) FROM + jsonb_array_elements(model->'spawnBindingInputs') entry) + IS DISTINCT FROM model->'spawnBindingInputs'Also applies to: 287-289
- Accepted Fix V94 empty optional region/spawn aggregate NULL versus [] mismatch; prove valid empty inventories settle while malformed/count-mismatched cases remain denied.
- Line 126 accepts
- Full-history verification now runs on every Account source read.Trivial
verifyEventHistoryreads and verifies every event from sequence 1 on eachreadCurrentSourcecall for an Account scope. For each closed event it also queries receipts. For each security-state event,findCommittedByRequestIdSharedruns nested readbacks, andAccountAuthoritySourceEventReadback.requireRetainedEventloads that operation twice (Line 212-227 and again inrequireSecurityStateReceipt).readCurrentIssuerAccountSourcesscans the history twice, once here and once inrequireCurrentLatest.recordAccountUpdateandadvanceClosedAccountHeadalso run several reads. Cost and lock hold time grow with every reset, logout-all and security change on the Account.Consider one of these options:
- Store a verified-history watermark (sequence plus digest) in
account_authority_source_records, and verify only events after it. - Verify the history once per transaction and pass the result to later reads.
Add an oldest-history or source-read-latency metric before a LOGIN path depends on this read.
- Rejected Repeated unmeasured history-cache/watermark proposal; immutable retained provenance is deliberately reverified. Per-invocation object reuse already fixed; transaction memoization risks hiding in-transaction source changes. No measured LOGIN latency defect.
- Store a verified-history watermark (sequence plus digest) in
Routed Findings
No routes recorded
Unlinked items
no items unlinked