PR #3216 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
- Subagent Review 1 CompletedModel: gpt-6-luna · XhighFound: 0 Accepted: 0 Routed: 0
- No findings recorded for this run
- Hosted Review 1 CompletedRuntime 11m 48sFound: 5 Accepted: 0/1/3 Routed: 1
- Move the bounded-retry loop into one shared helper.Trivial
authenticateandretireInitialGameplayLoginrepeat the same retry rules line for line:- one overall deadline, reduced to the parent
Contextdeadline; - checks for expiry and cancellation;
- a null-stub guard;
- at most one retry, only on
UNAVAILABLEorDEADLINE_EXCEEDED; reloadChannel()between attempts.
This retry bound is part of the documented security contract ("at most one transport reload/retry within the unchanged deadline"). Two copies can drift apart, and a later fix can reach one RPC but not the other.
♻️ Proposed helper extraction
- public CanonicalGameplayLoginResult authenticate(AuthenticateRequest originalRequest) { - CanonicalGameplayLoginResult.requireOriginalRequest(originalRequest); - Deadline overall = Deadline.after(invocationBudgetNanos, TimeUnit.NANOSECONDS); - ... - throw failure(Status.Code.UNAVAILABLE); - } + public CanonicalGameplayLoginResult authenticate(AuthenticateRequest originalRequest) { + CanonicalGameplayLoginResult.requireOriginalRequest(originalRequest); + return invokeOnceWithSingleRetry( + stub -> + CanonicalGameplayLoginResult.fromAuthenticatedResponse( + stub.authenticate(originalRequest), originalRequest, verifier, clock)); + } + + private <T> T invokeOnceWithSingleRetry( + java.util.function.Function<AccountServiceGrpc.AccountServiceBlockingStub, T> call) { + Deadline overall = Deadline.after(invocationBudgetNanos, TimeUnit.NANOSECONDS); + if (Context.current().getDeadline() != null) + overall = overall.minimum(Context.current().getDeadline()); + for (int attempt = 0; attempt < 2; attempt++) { + if (overall.isExpired()) throw failure(Status.Code.DEADLINE_EXCEEDED); + if (Context.current().isCancelled()) throw failure(Status.Code.CANCELLED); + var currentStub = stub(); + if (currentStub == null) throw failure(Status.Code.UNAVAILABLE); + try { + return call.apply(currentStub.withDeadline(overall)); + } catch (StatusRuntimeException transport) { + Status.Code code = transport.getStatus().getCode(); + if (attempt != 0 + || (code != Status.Code.UNAVAILABLE && code != Status.Code.DEADLINE_EXCEEDED)) + throw boundedTransportFailure(transport); + if (overall.isExpired()) throw failure(Status.Code.DEADLINE_EXCEEDED); + if (Context.current().isCancelled()) throw failure(Status.Code.CANCELLED); + try { + reloadChannel(); + } catch (SSLException reloadFailure) { + throw failure(Status.Code.UNAVAILABLE); + } + } + } + throw failure(Status.Code.UNAVAILABLE); + }Apply the same change to
retireInitialGameplayLogin, usingInitialGameplayLoginDisposalResult.fromAuthenticatedResponse.- Accepted Verified duplicate identical bounded transport retry loops. Extract one private helper preserving unchanged overall/parent deadline, cancellation, at-most-one allowed transport retry, reload, bounded errors and validation.
- one overall deadline, reduced to the parent
- Name the expected exception type in every disposal rejection check.Minor
Many of the new
assertThatThrownBy(...)calls do not state which exception they expect. Each of them passes on anyThrowable. For example:- Line 947:
disposeInitialLogin. - Lines 962-968: the post-tombstone
registerPending. - Lines 975-977: replay and signing after disposal.
- Lines 1061, 1088-1108, 1197 and 1253: conflict checks.
- Lines 2248-2256 and 2293-2296: resurrection checks.
This is a problem for the SQL checks. The
ExecuteListenerinnewPostgresContextturns every SQL exception into anAssertionError. Lines 1110-1120 are meant to show that a constraint rejects a fabricated terminal proof. That check also passes if theUPDATEhas a column typo, or if the schema drifts so the statement fails for another reason.The same gap affects the anti-resurrection checks. At lines 962-968,
registerPendingcould fail for an unrelated reason, such as ACL, script loading or an argument error, and the test would still pass. The test also never re-readstokenKeyafter that call ininitialLoginDisposalFencesEveryInterruptedIssuanceStage. So nothing shows that the tombstone survived.For each check, assert the owner exception the production path actually throws. Examples:
AccountCoordinationRedisExceptionfor Redis rejection.IdempotencyConflictExceptionorDisposalConflictExceptionfor conflicts.- For SQL constraint rejections, a message or SQL-state match such as
hasMessageContaining("sqlState=23").
After every rejected registration, re-assert the tombstone bytes.
♻️ Example tightening
- assertThatThrownBy(() -> unavailableRedis.disposeInitialLogin(intent)); + assertThatThrownBy(() -> unavailableRedis.disposeInitialLogin(intent)) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); @@ assertThatThrownBy( () -> redis.registerPending( candidate.tokenHash(), candidate.canonicalRecordBytes(), Math.addExact( - Math.multiplyExact(candidate.expiresAtEpochSecond(), 1000L), 30_000L))); + Math.multiplyExact(candidate.expiresAtEpochSecond(), 1000L), 30_000L))) + .isInstanceOf( + AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); + assertThat(admin.get(ascii(tokenKey))).containsExactly(intent.tombstoneBytes());This follows the retrieved learning: tests of identity-sensitive operations must assert the field or outcome that decides the result.
Also applies to: 962-968, 1110-1120, 2293-2296
- Accepted Verified disposal tests accept any Throwable and omit post-rejection tombstone readback. Assert exact owner exceptions and SQLSTATE23514 for constraint probes; reread unchanged tombstone after rejected registration.
- Line 947:
- Use one shared validator for checkpoints and source events.Trivial
validateCheckpointshere repeatsCanonicalGameplayLoginResult.validateCheckpoints(lines 186-236 of that file). The two copies already differ:- This copy compares
event.outboxStreamKeywithstreams.get(index). The DTO copy compares it withcheckpoint.get("outboxStreamKey"). - This copy reads the sequence through
text(). The DTO copy usesinstanceofpattern checks.
The two copies are equivalent today. A future change to the stream list or the event shape can update one copy and not the other. Then the Redis codec would accept or reject evidence differently from the Account-response validator.
Move the shared logic into one package-visible helper that takes
(accountId, tuple, checkpoints, events), and call it from both classes.- Accepted Verified repeated checkpoint/source-event invariant in response DTO and Redis context codec. Share the existing invariant without widening accepted evidence, authority, data or wire schema; preserve closed types/bounds and negative tests.
- This copy compares
- Plan capacity and cleanup for permanent disposal tombstones.Trivial
SET key tombstoneclears the TTL on purpose. The Java readback also requirespttl == -1. Each disposed token-bound initial LOGIN therefore leaves one permanentsession:auth:token:<hash>key in Coordination Redis. Nothing in this change removes these keys. The count grows without bound with disposal volume.Document the retention owner and the cleanup trigger. One option is to remove the tombstone only after the SQL retention hold is released and the original token's
expplus margin has passed. Add a metric or alert for the tombstone key count. A Redis reset or restore loses these keys. The SQL guards still deny issuance and recovery in that case. Confirm that the reset runbook re-asserts tombstones for in-window tokens.Route · PR #3216 → Unassigned target OpenAccount retention/capacity and reset/restore cleanup remain a held owner obligation. Current contract requires no-TTL denied markers and forbids guessed cleanup release; source stays unregistered. Route owner follow-up, not expiry or deletion implementation. View routed finding - Record a bounded reason before
mutatereturnsOptional.empty().Trivialmutateturns everyRuntimeExceptionintoOptional.empty()with no log line and no metric. The same applies toinstall(Line 57) andacquireQualification(Line 77). Many different causes give the same empty result:- lost qualification;
- wrong ACL principal;
- descriptor or SHA mismatch;
- a
WRONGTYPEreply; - an EVALSHA result other than
1; - an insufficient WAITAOF count;
- a readback mismatch.
The cleanup owner then reports
HELDwith no cause. Operators cannot tell a misconfigured binding from a transient replica lag.Keep the fail-closed result. Add a bounded, non-sensitive reason code (an enum or a fixed string) to a log line at WARN, or to a counter. Do not log payload bytes, keys with evidence, or exception messages.
Based on learnings: "wrap calls in try/catch to handle timeouts, connection errors, and script errors explicitly. Log the failure with context (operation, key)".
- Accepted Verified silent RuntimeException catches hide fail-closed Redis failures. Add fixed operation/reason WARN codes only; no exception, keys, payloads or identity data. Preserve return behavior and all guards.
- Hosted Review 2 CompletedRuntime 10m 44sFound: 1 Accepted: 0/0/1 Routed: 0
- Record a fixed, non-sensitive reason before you return
HELD.TrivialThe catch block maps every
RuntimeExceptionto the sameHELDobservation. It writes no log line. The block covers different kinds of failure:- A
JournalConflictExceptionis a permanent conflict, for example a changed Account receipt or changed coordinates. An operator must act on it, because each later redrive also returnsHELD. - A
JournalUnavailableException, a Redis closure failure or an Account transport failure can be transient. A later redrive can succeed.
An operator cannot tell these cases apart from the returned
CleanupObservation.InitialGameplayLoginContextRedisClient.warnalready uses a fixed operation/reason format. Use the same pattern here: log only the exception class category. Do not log messages, causes or identifiers.♻️ Proposed bounded reason log
--- "a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwner.java" +++ "b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwner.java" @@ -89,10 +89,15 @@ coordinates, acknowledged -> retireWithinQualifiedClosure(coordinates, acknowledged, previous)) .orElseGet(() -> held(coordinates, previous)); } catch (RuntimeException unavailableOrConflicting) { // No potentially sensitive transport/SQL/parser diagnostics become retained evidence. + LOG.warn( + "Initial LOGIN cleanup operation=ABANDON_AND_RETIRE reason={}", + unavailableOrConflicting instanceof JournalConflictException + ? "CONFLICT" + : "UNAVAILABLE"); return held(coordinates, retainedReceipt); } } private CleanupObservation retireWithinQualifiedClosure(Add a
private static final Logger LOG = LoggerFactory.getLogger(InitialGameplayLoginCleanupOwner.class);field.- Accepted Trivial: abandonAndRetire returnsHELD for runtime failures without bounded diagnostic. Add fixed WARN categoryCONFLICT forJournalConflict, UNAVAILABLEotherwise; preserve behavior and redact exceptions/identities.
- A
- Hosted Review 3 CompletedRuntime 9m 09sFound: 3 Accepted: 3 Routed: 0
- Move the new initial-LOGIN policy sections out of "Related Documentation".Trivial
Both new normative h3 sections are appended under the
## Related Documentationlink list. Readers therefore see contract text as part of a list of links. Anchors do not change if the heading text stays the same.design/architecture/system-architecture-redis-usage-and-profiles.md#L356-L360: move### Initial LOGIN context acknowledgement policyinto the profile or service-usage section, above## Related Documentation.design/architecture/infrastructure/environment-and-secrets-catalog.md#L324-L326: move### Initial LOGIN context Coordination policyinto the "Redis Coordination & Cache" section, above## Related Documentation.
📍 Affects 2 files
design/architecture/system-architecture-redis-usage-and-profiles.md#L356-L360(this comment)design/architecture/infrastructure/environment-and-secrets-catalog.md#L324-L326
- Accepted Trivial: both initial LOGIN policy sections sit under Related Documentation. Move unchanged headings/text into their profile/Coordination sections; preserve canonical ownership and anchors.
- CodeRabbit summary-only outside-diff finding 1 of 1 (aggregate; no individual detail)
summary-only aggregate; provider supplied no individual detail
- Accepted Minor outside-diff: tenantBillingCutoff uses billing event coordinates but shared validator requires tenant authority event coordinates. Retain billing sequence, take tenant outbox stream/sequence and add focused distinction regression. Full summary read; only one outside-diff item.
- Build the ACTIVE bytes with
activeRecordBytes(record), not with text replacement.TrivialdisposeInitialLoginbuilds the ACTIVE record withString.replace, which replaces every occurrence. The activation path usesactiveRecordBytes, which re-encodes the decoded fields with RFC 8785. These are two separate derivations of the same value.The Lua script requires exactly one replacement of each pattern and requires the result to equal ARGV[2]. If the two derivations diverge, disposal of an ACTIVE key fails as
-1, or the script rejects the arguments.recordhas already been decoded and checked aspending. Reuse the existing helper so that one derivation defines the ACTIVE bytes.♻️ Proposed refactor
--- "a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java" +++ "b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClient.java" @@ -71,11 +71,8 @@ if (!"pending".equals(record.state()) || !intent.requestId().toString().equals(record.requestId()) || !intent.tokenHash().equals(record.tokenHash())) throw unavailable(); - String activeText = - new String(pending, StandardCharsets.UTF_8) - .replace("\"registryVersion\":1", "\"registryVersion\":2") - .replace("\"state\":\"pending\"", "\"state\":\"active\""); - byte[] active = activeText.getBytes(StandardCharsets.UTF_8); + if (record.registryVersion() != 1L) throw unavailable(); + byte[] active = activeRecordBytes(record); RedisScriptDescriptor descriptor = scriptCatalog.require(INITIAL_LOGIN_DISPOSAL_SCRIPT_ID); if (!INITIAL_LOGIN_DISPOSAL_SCRIPT_ID.equals(descriptor.scriptId()) || !"account-service".equals(descriptor.owner())- Accepted Trivial: disposal duplicates ACTIVE encoding with text replacement. Reuse existing canonical activeRecordBytes, whose pending/v1 guard is already enforced; preserve all Redis custody/descriptor/postimage checks.
- CLI Review 1 CompletedRuntime 3m 11sFound: 5 Accepted: 1/2/0 Routed: 0
- Mark
RetireInitialGameplayLoginas not currently routable.MajorThe Markdown matrix says this receiver is unregistered. This YAML entry records that fact under
known_driftbut omits theroute_statusused by nearby target-only routes. Addroute_status: target_not_currently_routableso a route-status reader cannot treat this disposal RPC as current. As per path instructions, review design documents for “canonical-current-state consistency.”- Accepted YAML target-only disposal receiver lacks route_status while Markdown and registration state explicitly deny current routing. Add existing target_not_currently_routable field only.
- Reject a mismatched Account UUID source-row ID.Minor
If
account.getAccountUuidSourceNumericId()differs fromaccount.getId(), this check accepts contradictory UUID provenance and can return a membership snapshot. The first-JOIN producer rejects that mismatch. Compare the two IDs here. Verify whether the Account table orAccountRepository.findByAccountUuidalready excludes this state; the supplied code does not establish that invariant. As per path instructions, “Flag changes that violate documented FireMUD invariants, especially gRPC application-error handling, ownership boundaries, and failure-mode expectations.”- Accepted Current snapshot check permits positive UUID source numeric ID different from Account ID; canonical first-JOIN producer requires equality. Add Objects.equals guard and regression without wider provenance changes.
- Report a contradictory disposal owner result as
INTERNAL, notUNAVAILABLE.MinorA wrong
requestIdorcallerContextIdfromdisposalOwner.retireis an owner contract violation, not a transient outage. The code at Line 131 throws a bareIllegalStateException. TheRuntimeExceptioncatch at Line 174 then maps that exception toStatus.UNAVAILABLE.Game Session treats
UNAVAILABLEas retryable, so it retries an outcome that a retry cannot fix. Theauthenticatepath handles the same kind of contradiction (Line 248-251) asStatus.INTERNAL. Fail the disposal path the same way, and add braces to theif.Proposed fix
- if (result == null - || !canonical.requestId().equals(result.requestId()) - || !canonical.callerContextId().equals(result.callerContextId())) - throw new IllegalStateException(); + if (result == null + || !canonical.requestId().equals(result.requestId()) + || !canonical.callerContextId().equals(result.callerContextId())) { + fail(observer, Status.INTERNAL, "INTERNAL", "Initial LOGIN disposal failed"); + return; + }- Accepted Null or contradictory disposal owner coordinates throw into retryable UNAVAILABLE. Match existing authenticate INTERNAL contract and add focused null/wrong-request/wrong-context regression.
- Plan retention and cleanup for permanent disposal tombstones.Trivial
The disposal script writes the tombstone with
SETand no TTL. The client requiresPTTL == -1on readback. Each retired original LOGIN therefore leaves one permanentsession:auth:token:*key in Coordination Redis. These keys accumulate for the life of the cluster.Make one of these explicit:
- A retention bound tied to the SQL
retention_hold. - An operator cleanup procedure.
- A memory alert for the Coordination Redis role.
- Rejected Duplicate of existing open retention route 527e3903b7e674a6c7c011e13950bb80486a6d16649f04ff24354151f004c6fe, already assigned for Root coordination. No new retention/TTL/cleanup authority or distinct in-PR fix.
- A retention bound tied to the SQL
- Confirm that the disposal insert takes the same advisory lock as the writer guard.Major
account_initial_gameplay_login_writer_guardtakespg_advisory_xact_lock(hashtextextended('account-gameplay-delegation-request/' || request_id, 0)). It then checksEXISTSonaccount_initial_gameplay_login_disposals. Nothing in this migration makes a disposalINSERTtake that lock.Under READ COMMITTED, the following sequence is possible:
- An issuance
INSERTorUPDATEpasses theEXISTScheck. - A concurrent
AccountInitialGameplayLoginDisposalRepository.begininserts the PENDING disposal row. - Both transactions commit.
The result is a bind or COMMITTED transition that commits after a durable disposal intent exists. The
beginread of the issuance state can also miss the binding that the other transaction is writing, so the intent carries no token hash. That outcome breaks the "denies every later original-request writer" contract.The fix belongs in the
beginpath, which is not in this review. Choose one:- Have
begin(andrequireOriginalRequestNotDisposed) take the identical advisory lock before it reads or inserts. - Add a
BEFORE INSERTtrigger onaccount_initial_gameplay_login_disposalsthat takes that lock.
Verify that
AccountInitialGameplayLoginDisposalRepository.begincallspg_advisory_xact_lockwith the same key before it reads the issuance row and inserts the disposal row.Proposed trigger-side fix (if the repository does not lock)
CREATE FUNCTION account_initial_gameplay_login_disposal_request_lock() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_advisory_xact_lock(hashtextextended('account-gameplay-delegation-request/' || NEW.request_id::text, 0)); RETURN NEW; END $$; CREATE TRIGGER aa_account_initial_gameplay_login_disposal_request_lock BEFORE INSERT ON account_initial_gameplay_login_disposals FOR EACH ROW EXECUTE FUNCTION account_initial_gameplay_login_disposal_request_lock();A trigger lock alone does not cover a
beginread of issuance state that happens before the insert. A repository-side lock taken before that read is the stronger fix.- Rejected Repository begin already takes identical request advisory lock before authoritative reread and disposal insert. Its earlier account lookup only selects Account-first lock order; initially-absent race throws/retries. Issuance lockRequestId also locks before disposal check.
- An issuance
- CLI Review 2 CompletedRuntime 3m 33sFound: 5 Accepted: 0/0/0 Routed: 0
- Handle a null tombstone before hashing it.Minor
finishcallshash(current.tombstoneBytes()). For a no-key intent,tombstoneBytes()returns null, andMessageDigest.digest(null)throws aNullPointerException. Reject a null tombstone first and throwunavailable().Proposed fix
- || !hash(current.tombstoneBytes()).equals(receipt.tombstoneSha256()) + || current.tombstoneBytes() == null + || !hash(current.tombstoneBytes()).equals(receipt.tombstoneSha256())- Rejected No-key owner branches to readUnqualifiedNoBinding, not finish. Receipt private constructor is reachable only after client nonnull tokenHash/tombstone checks. V1005 requires hash/tombstone nullness together; hash mismatch short-circuits before digest on a no-key row.
- Align the witness and response integer types.Major
InitialGameplayLoginTokenWitnessdeclarestoken_generationandissuance_fenceasint64.AuthenticateResponsedeclares the same values asstring(fields 12 and 13). A caller that copies the values from the authenticate response into the witness must parse them. A parse that differs from Account's canonical decimal form causes a disposal conflict. Use one representation, or document the required canonical conversion.- Rejected Intentional JWT decimal strings versus typed int64 witness. Context validates canonical positive decimal/int64 range, preserving the same numeric value. No lossy or ambiguous accepted conversion shown; response type changes would break the existing contract.
- Plan retention for the persistent disposal tombstones.Trivial
disposeInitialLoginwrites each tombstone with no TTL, and the method requiresPTTL == -1. The SQL row is retained permanently becauseretention_holdis constrained toTRUE. Nothing in this change ever deletes a tombstone. Each retired initial LOGIN therefore adds one permanentsession:auth:token:*key to Coordination Redis.- Add a metric for the tombstone key count.
- Define a retention or compaction policy. One option is to delete the key after the original token's registry deadline plus a margin, provided the SQL guard is the authority for denial.
- Document the expected growth rate in the Redis usage profile.
[operational_advice]
- Rejected Duplicate open retention/capacity route527e3903b7e674a6c7c011e13950bb80486a6d16649f04ff24354151f004c6fe, coordinated with Overseer. No distinct source fix or new TTL/deletion/compaction authority.
- Compare boxed identifiers with
Objects.equals.MajorThe code compares
snapshot.accountId() != account.getId()andsnapshot.membershipId() != membership.getId().Account.getId()returnsLong, as Line 303 shows. If either side is aLong, the!=operator can compare references or unbox a null value. A reference comparison of identical values above the Long cache range (above 127) returnstrue. The snapshot is then rejected as unavailable even when the identifiers match. UseObjects.equalshere, as Line 356 already does.Proposed fix
- if (snapshot.accountId() != account.getId() + if (!Objects.equals(snapshot.accountId(), account.getId()) ... - || snapshot.membershipId() != membership.getId() + || !Objects.equals(snapshot.membershipId(), membership.getId())- Rejected RoleSnapshot IDs are primitive long: comparison unboxes Long numerically, never reference/cache comparison. Account ID is checked nonnull; physical membership PK is nonnull and the preceding role query already takes primitive long.
- Guard the unboxing of nullable issuance columns.Minor
token.tokenGeneration() != original.get("token_generation", Long.class)unboxes the column value. Ifissuance_fenceortoken_generationis null on a PENDING row, the comparison throws aNullPointerException. The caller then gets an uncategorized error instead ofDisposalConflictException. UseObjects.equalswith boxed values.Proposed fix
- || token.tokenGeneration() != original.get("token_generation", Long.class) - || token.issuanceFence() != original.get("issuance_fence", Long.class)) throw conflict(); + || !Objects.equals(token.tokenGeneration(), original.get("token_generation", Long.class)) + || !Objects.equals(token.issuanceFence(), original.get("issuance_fence", Long.class))) + throw conflict();- Rejected V147 defines token_generation and issuance_fence BIGINT NOT NULL even for PENDING; no later migration drops either constraint. Original is a physical SELECT of that row, so nullable-unboxing scenario cannot occur.
- CLI Review 3 CompletedRuntime 3m 27sFound: 4 Accepted: 0/1/0 Routed: 0
- Pin the duplicated billing constants to the Account owner values with a test.Trivial
The codec now hard-codes
BILLING_STREAM_PREFIXandBILLING_EVENT_SCHEMA_VERSION. Before, it took these values fromAccountTenantEntitlementOutboxRepositoryandDemoTenantEntitlementEventV1Codec.sealandverifynow accept receipts only when their values match these local copies.If the Account stream prefix or billing schema version changes, every new tenant authority event fails at
seal. Add an account-service unit test that checks both pairs of values:tenantBillingStreamKey(id)equals the Account outbox repository stream key.tenantBillingEventId(requestId)equalsDemoTenantEntitlementEventV1Codec's event ID.
Example account-service test
@Test void commonBillingReferenceMatchesAccountOwner() { UUID tenant = UUID.randomUUID(); UUID request = UUID.randomUUID(); assertThat(TenantAuthorityEventV1Codec.tenantBillingStreamKey(tenant)) .isEqualTo(AccountTenantEntitlementOutboxRepository.streamKey(tenant)); assertThat(TenantAuthorityEventV1Codec.tenantBillingEventId(request)) .isEqualTo(DemoTenantEntitlementEventV1Codec.eventId(request)); }- Rejected Existing TenantAuthorityEventV1CodecTest builds actual Account billingEvent with DemoTenantEntitlementEventV1Codec.seal, which uses AccountTenantEntitlementOutboxRepository.streamKey, then Common.seal validates receipt and full golden bytes/event IDs. Owner drift already fails this regression.
- Bound the lifetime of the disposal tombstone.Trivial
SET key tombstonewrites the tombstone without a TTL.disposeInitialLoginthen requiresPTTL == -1. The SQLretention_holdcheck is alwaysTRUE, so nothing ever releases the key. Each disposed bound original LOGIN therefore leaves a permanent key of up to 4096 bytes in Coordination Redis. Memory use grows with every disposal and never shrinks.The tombstone only has to block re-registration and activation while the original token could still be used. After the original registry absolute expiry,
registerPendingand activation already reject the token. The SQL original-request guards also block any new issuance or recovery.Consider one of these options:
- Set the tombstone expiry to the original registry absolute expiry from
pendingBytes(for example,SET ... PXAT <deadline>). Change the Java readback to check that exactpexpiretime. - Keep the permanent tombstone, but add a documented cleanup path and memory budget for Coordination Redis.
Confirm how often disposal happens and what memory budget Coordination Redis has before you choose an option.
- Rejected Duplicate open retention/capacity route527e3903b7e674a6c7c011e13950bb80486a6d16649f04ff24354151f004c6fe. Permanent denial markers follow current owner contract; no authority for TTL, deletion or compaction. Existing owner route preserved.
- Set the tombstone expiry to the original registry absolute expiry from
- Preserve exact revocation-intent replay after disposal.Minor
If an original login is disposed after
beginRevocationIntentstores a pending intent, an exact retry now throwsTokenRevokedExceptioninrequireExact. The retry never reaches the existing request-and-digest replay check inbeginRevocationIntent. Keep disposal denial for active-token use, but allow the stored revocation intent to be read and matched on an exact retry.- Accepted Disposal check now precedes stored revocation-intent request/digest replay, violating this purpose-only idempotent read contract. Restore exact pending-intent replay, retaining disposal denial for every active/new token use. No credential or activation return.
- Verify that the tenant source version always equals the tenant authority generation.Major
verifyTenantSourcecomparescurrentGenerationwithevent.tenantAuthorityGeneration(). It also comparescurrentGenerationwithevent.tenantAuthoritySourceVersion(). The codec stores these as two independentlongvalues. The membership projection in this PR treats version advancement and generation as independent (seeAccountSelectedGameplayAuthorityProjectionTestline 59).Assume a non-revoking tenant mutation advances
tenantAuthoritySourceVersionbut keepstenantAuthorityGeneration. In that case, the validator rejects every current snapshot for the tenant. Runtime membership validation for that tenant then fails closed until the generation changes.Confirm the Account producer contract. Find where the tenant authority producer calls
TenantAuthorityEventV1Codec.sealand check whether itstenantAuthorityGenerationandtenantAuthoritySourceVersionarguments can differ. If they can differ, remove the source-version equality check or compare the source version with its own checkpointed value.Possible correction if the values are independent
requireEquals( currentGeneration, Long.toString(event.tenantAuthorityGeneration()), "current tenant authority generation"); - requireEquals( - currentGeneration, - Long.toString(event.tenantAuthoritySourceVersion()), - "current tenant authority source version"); return event;- Rejected Actual tenant producer enrolls generation/sourceVersion1/1 and append advances both exactly one. V73 baseline/update SQL guards enforce both1+outboxSequence and event equality. No independent tenant-source-only mutation is supported; membership projections are a distinct contract.
- CLI Review 4 CompletedRuntime 3m 20sFound: 2 Accepted: 0/0/0 Routed: 0
- Verify that the disposal intent insert takes the same per-request advisory lock as the writer guard.Major
The
account_initial_gameplay_login_writer_guardtrigger serializes issuance writers onpg_advisory_xact_lock(hashtextextended('account-gameplay-delegation-request/' || request_id, 0)). The guard then checks whether a disposal row exists. Under READ COMMITTED, an uncommitted disposal row is invisible to that check. The opposite direction is also unsafe: an uncommitted bindingUPDATEis invisible to the disposal reader.Consider this interleaving, assuming
AccountInitialGameplayLoginDisposalRepository.begindoes not take the same lock:- The signer transaction runs the binding
UPDATE(token_hash,pending_registry_candidate_bytes). The trigger takes the advisory lock and finds no disposal row. - The disposal transaction reads the issuance row and sees
token_hash IS NULL. It inserts the disposal row withoriginal_token_hash,pending_record_bytesandtombstone_bytesall NULL. - Both transactions commit.
After step 3, the bound token has no recorded hash in the disposal row.
AccountInitialGameplayLoginDisposalOwner.retiretakes thereadUnqualifiedNoBindingpath and returnsPENDINGon every call. The immutability trigger blocks any later update oforiginal_token_hash. The physical Redis tombstone for the bound token is therefore never written. Any already-registered pending or active registry record stays in Redis.Confirm that
beginacquirespg_advisory_xact_lock(hashtextextended('account-gameplay-delegation-request/' || request_id, 0))before it reads the issuance row. If it does not, add the lock there, or add aBEFORE INSERTtrigger onaccount_initial_gameplay_login_disposalsthat takes the same lock.🔒️ Possible schema-level fix
CREATE FUNCTION account_initial_gameplay_login_disposal_serialize() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_advisory_xact_lock(hashtextextended('account-gameplay-delegation-request/' || NEW.request_id::text, 0)); RETURN NEW; END $$; CREATE TRIGGER aa_account_initial_gameplay_login_disposal_serialize BEFORE INSERT ON account_initial_gameplay_login_disposals FOR EACH ROW EXECUTE FUNCTION account_initial_gameplay_login_disposal_serialize();The lock alone is not sufficient if the disposal reader captured the issuance row before it took the lock. The repository must read the issuance row after acquiring the lock.
- Rejected Already implemented: DisposalRepository.begin locks Account first, then the same account-gameplay-delegation-request/ advisory key and rereads issuance afterward, using FOR UPDATE. Initially absent races retry before insert. The suggested missing-lock interleaving is excluded.
- The signer transaction runs the binding
- Plan a lifecycle for permanent disposal tombstones.Trivial
The script writes the tombstone with
SETand no expiry. The Java client requiresPTTL == -1on readback. The SQL row forcesretention_hold = TRUEthrough aCHECKconstraint, so no code path can release the hold. As a result, each disposal adds a permanent key to Coordination Redis, and no cleanup path exists.Define a bounded retention policy, for example an expiry after the maximum token lifetime plus the cleanup margin, once the token can no longer verify. As a minimum, add a metric and alert on the count of
session:auth:token:*keys without a TTL.- Rejected Duplicate of OPEN retention/capacity route527e3903; bounded expiry or hold release is not authorized. Existing SQL/Redis retention deliberately preserves denied state; do not drop the original obligation or add a duplicate route.
- CLI Review 5 CompletedRuntime 3m 16sFound: 5 Accepted: 0/0/2 Routed: 0
- Plan capacity and cleanup for the permanent disposal tombstones.Trivial
The script always writes
SET key tombstonewith no expiry. This also happens when the key is absent or expired. The Java caller requiresPTTL == -1.retention_holdin V1005 is alwaysTRUE, and no code in this change removes a tombstone. Each disposal therefore leaves a key of up to 4 KiB in Coordination Redis without a time limit. The descriptor still declaresSESSION_LEASE_CACHE_OR_WAKE_UPloss class.- Define a retention bound in the Redis usage/profile docs, such as a TTL tied to the original token expiry plus a margin, or a reconciler.
- Alternatively, document the permanent key class and add a key-count metric for the
session:auth:token:tombstones.
- Rejected Duplicate of OPEN retention/capacity route527e3903. Permanent denied-marker retention and cleanup authority remain coordinated there; do not invent expiry/hold release or duplicate the obligation.
- Move proof narrative out of the tracker's status section.Trivial
These paragraphs list commit hashes, case counts, and run timings. They also restate technical contracts such as disposal semantics (
RETIREDwithPHYSICAL_TOKEN_DENIAL,NO_TOKENwithNO_ISSUANCE_BINDING), Redis tombstone andWAITAOFbehavior, and journal retention rules. The canonical owners are the JWT/token contracts and the Redis architecture documents. Keep only status, anchors, gaps, and links in the tracker. Link to the canonical definitions instead of restating them.Based on learnings: "do not duplicate canonical technical contracts that are already defined by the owning ADRs or architecture contracts". As per coding guidelines: "Keep its status, implementation record, validation, gaps, decisions, and service-map sections aligned... technical contracts in the canonical architecture documents."
- Accepted Keep this subsection as concise status, production/test anchors, gaps and canonical-owner links. Move its historical revision/case/timing record intact into existing Validation and Proof; preserve every proof limit and old section anchor.
- Remove the misleading
@Transactionalannotation or call the method through the proxy.TrivialThe method is
publicwith@Transactional(propagation = MANDATORY). Internal calls fromselectByRequestIdandlockRequestIdbypass the Spring proxy, so the annotation does not apply. The manualisActualTransactionActivecheck covers the same condition for those calls. External callers do get the proxy check. The result is correct but inconsistent. Add a comment that states the manual check is deliberate.- Accepted Clarify the deliberate manual transaction-active check for internal self-calls bypassing the Spring proxy. Keep MANDATORY annotation and all behavior unchanged; no proxy redesign.
- Unboxing risk in the witness comparison.Minor
token.tokenGeneration() != original.get("token_generation", Long.class)compares alongprimitive to aLong. Java unboxes theLong. A null column value throwsNullPointerException. The same applies toissuance_fence. The source row exists, so the columns should be non-null. UseObjects.equals(Long.valueOf(...), ...)so a null column producesconflict()instead of an NPE.Proposed fix
- || token.tokenGeneration() != original.get("token_generation", Long.class) - || token.issuanceFence() != original.get("issuance_fence", Long.class)) throw conflict(); + || !Objects.equals(token.tokenGeneration(), original.get("token_generation", Long.class)) + || !Objects.equals(token.issuanceFence(), original.get("issuance_fence", Long.class))) + throw conflict();- Rejected V147 defines token_generation and issuance_fence NOT NULL for every issuance status, including PENDING. The actual PostgreSQL row cannot contain the proposed nulls; avoid redundant guards for an impossible stored shape.
- Confirm that
tenantAuthoritySourceVersionalways equalstenantAuthorityGeneration.MajorverifyTenantSourcenow compares one tuple value with two separate event fields.currentGenerationmust equalevent.tenantAuthorityGeneration(). It must also equalevent.tenantAuthoritySourceVersion().TenantAuthorityEventV1Codecstores these as independent fields, andsealaccepts any two positive values for them.The membership projection keeps version and generation separate.
AccountSelectedGameplayAuthorityProjectionTeststates that "Non-revoking version advancement is independent." The Account tenant producer may also advance the source version without changing the generation. If so, every current tenant snapshot fails with "current tenant authority source version". That denies runtime membership validation for every member of the affected tenant. The new validator tests only use events sealed with2L, 2L, so they cannot detect a mismatch.Check the Account-side tenant authority event producer. Confirm whether
tenantAuthoritySourceVersionequalstenantAuthorityGenerationby contract. If the values can differ, remove the secondrequireEquals. Bind the source version through the checkpoint or cutoff evidence instead. If the values cannot differ, document that invariant in the codec. Then makeTenantAuthorityEventV1Codec.sealreject unequal values so the producer cannot emit an event that this validator rejects.♻️ Option if the two values are independent
requireEquals( currentGeneration, Long.toString(event.tenantAuthorityGeneration()), "current tenant authority generation"); - requireEquals( - currentGeneration, - Long.toString(event.tenantAuthoritySourceVersion()), - "current tenant authority source version"); return event;- Rejected Actual tenant producer is bounded by V73: baseline generation/sourceVersion both1; both current values equal1+outboxSequence, and repository increments both from the locked prior head. Member-version independence is separate; unequal tenant events fail closed.
- CLI Review 6 CompletedRuntime 3m 11sFound: 5 Accepted: 0/0/2 Routed: 0
- Make one module own the billing stream key and billing event ID derivation.Trivial
This change replaces the lookups through the Account outbox repository and the billing codec with hardcoded copies of
account:tenant-entitlement:v1:tenant/andaccount-tenant-entitlement-event/v1. The account-service billing producer (AccountTenantEntitlementOutboxRepositoryandDemoTenantEntitlementEventV1Codec) also derives these values. If the two copies differ,sealrejects every real billing receipt, andverifyrejects every stored tenant event.Confirm that the account-service producer now delegates to
TenantAuthorityEventV1Codec.tenantBillingStreamKeyandtenantBillingEventId. If it does not, change the producer to use these helpers so that one module owns the constants.Also applies to: 77-91
- Accepted Outbox streamKey already delegates shared helper, but DemoTenantEntitlementEventV1Codec.eventId still repeats nameUUID schema derivation. Delegate that derivation only, preserving null checks and event bytes.
- Verify that membership events are re-emitted when tenant authority advances.Major
The historical tenant generation check is now
requireEqualsinstead ofrequireAtMost.validateHistoricalTenantCutoffalso requires the same cutoff presence and the exact same cutoff value. After a tenant authority event, every membership event sealed with an earlier tenant generation or cutoff fails validation. The previous rule accepted those events.If
AccountMembershipAuthorityEventProducerdoes not emit a new membership event for each membership of the tenant when tenant authority advances, runtime membership validation fails closed for all existing members until each membership is re-emitted. Confirm that the producer gives this guarantee. Confirm also that the canonical join path always seals the current tenant generation and cutoff.- Rejected Canonical auth requires exact current tuple/checkpoint and rejects stale tenant generation/cutoff. Unregistered first-JOIN seals current tenant source; tenantwide refresh/public admission is not claimed. Relaxing equality accepts stale authority; broader producer gap remains open.
- Confirm that disposal
begintakes the same per-request advisory lock as this writer guard.MajorThe writer guard serializes only through
pg_advisory_xact_lock(hashtextextended('account-gameplay-delegation-request/' || request_id, 0)). Under READ COMMITTED, theEXISTScheck cannot see an uncommitted disposal row. AssumeAccountInitialGameplayLoginDisposalRepository.begindoes not take this lock before it reads the issuance binding. Then the following sequence is possible:- Disposal
beginreads the issuance row whiletoken_hashis still NULL. - Disposal
begininserts a PENDING row withoriginal_token_hash IS NULL. - A concurrent signer transaction binds
token_hash. Its guard does not see the uncommitted disposal row. - Both transactions commit.
The immutability trigger blocks any later update to
original_token_hashon the disposal row. Every retry ofretiretherefore takes thereadUnqualifiedNoBindingpath and returns PENDING. The owner never calls Redis, so the tombstone is never written. A token that was issued during the race can then pass the Redis registry check. Only the SQL guards on later owner paths still deny it.Verify that
beginacquires this exact advisory key before it readsaccount_gameplay_delegation_issuance_operations. If it does not, add the samePERFORM pg_advisory_xact_lock(...)inbegin, or in a BEFORE INSERT trigger onaccount_initial_gameplay_login_disposals.🔒️ Possible DB-side fix if the repository does not lock
CREATE FUNCTION account_initial_gameplay_login_disposal_lock() RETURNS TRIGGER LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_advisory_xact_lock(hashtextextended('account-gameplay-delegation-request/' || NEW.request_id::text, 0)); RETURN NEW; END $$; CREATE TRIGGER aa_account_initial_gameplay_login_disposal_lock BEFORE INSERT ON account_initial_gameplay_login_disposals FOR EACH ROW EXECUTE FUNCTION account_initial_gameplay_login_disposal_lock();A trigger alone does not help if the repository reads the binding before the INSERT. In that case the lock must come before the read.
- Rejected Already implemented: begin takes Account lock then exact request advisory key, rereads issuance after lock and FOR UPDATE, retries absent-to-present race. Preliminary read is never used for sealing; duplicate prior CLI lock finding.
- Disposal
- Assert the expected exception type for the rolled-back intent readback.Trivial
assertThatThrownBy(...)has no type or message assertion. Any exception passes, including aNullPointerExceptionor a fixture failure. The test then cannot show that the repository rejected the non-durable intent for the intended reason. Assert the specific exception type, for exampleDisposalUnavailableException, or the listenerAssertionErrorwith its SQLSTATE.✅ Proposed tightening
- assertThatThrownBy( - () -> inTransaction(database, () -> disposals.readUnqualifiedNoBinding(rolledBackIntent))); + assertThatThrownBy( + () -> inTransaction(database, () -> disposals.readUnqualifiedNoBinding(rolledBackIntent))) + .isInstanceOf( + net.firedevops.firemud.accountservice.repository + .AccountInitialGameplayLoginDisposalRepository.DisposalUnavailableException.class);- Accepted Rolled-back intent assertion accepts any exception. Assert exact DisposalUnavailableException thrown by absent durable disposal readback; preserve transaction/repository call.
- Verify that the tenant source version always equals the tenant authority generation.Major
verifyTenantSourcecompares bothevent.tenantAuthorityGeneration()andevent.tenantAuthoritySourceVersion()with the samecurrentGenerationvalue. The class documentation describes tenant generations as opaque values that must match exactly. The documentation does not state that the source version is bound to the generation. The membership projection treats the two values as independent:AccountSelectedGameplayAuthorityProjectionTestadvancessourceVersionwithoutgeneration. Theseal(..., 2L, 2L, ...)fixtures in this PR cannot detect a divergence because the two values are equal.If the Account tenant producer advances
tenantAuthoritySourceVersionwithout a new generation, every snapshot with an advanced tenant checkpoint fails with "current tenant authority source version". Gameplay admission then fails closed for that tenant.Confirm in the Account tenant authority producer (
AccountTenantAuthorityEventRepositoryand its callers) that the source version always equals the generation. If the values can differ, remove the secondrequireEquals. As an alternative, compare the source version with a separately carried current source version.- Rejected Duplicate verified producer invariant: V73 baseline/current generation and sourceVersion start1; actual tenant producer locks source head and increments both once, sealing actual values. Membership-version independence is a different stream.
Routed Findings
Route 1 · PR #3216 → Unassigned target OpenTrivialPlan capacity and cleanup for permanent disposal tombstones.
SET key tombstoneclears the TTL on purpose. The Java readback also requirespttl == -1. Each disposed token-bound initial LOGIN therefore leaves one permanentsession:auth:token:<hash>key in Coordination Redis. Nothing in this change removes these keys. The count grows without bound with disposal volume.Document the retention owner and the cleanup trigger. One option is to remove the tombstone only after the SQL retention hold is released and the original token's
expplus margin has passed. Add a metric or alert for the tombstone key count. A Redis reset or restore loses these keys. The SQL guards still deny issuance and recovery in that case. Confirm that the reset runbook re-asserts tombstones for in-window tokens.Outcome: Account retention/capacity and reset/restore cleanup remain a held owner obligation. Current contract requires no-TTL denied markers and forbids guessed cleanup release; source stays unregistered. Route owner follow-up, not expiry or deletion implementation.
Unlinked items
no items unlinked