FireMUD Delivery Status

PR data refreshed

PR #3216 review history

Review rounds

Three-number pills mean: found (raw) / accepted here (useful) / routed

Hosted CodeRabbit3 completed
5/4/11/1/03/3/0
CLI CodeRabbit6 completed
5/0/04/1/02/0/05/2/05/2/0
Subagent Review1 completed
0/0/0

Recorded review history

Reviews and findings

  1. Subagent Review 1 CompletedModel: gpt-6-luna · Xhigh
    Found: 0 Accepted: 0 Routed: 0
    1. No findings recorded for this run
  2. Hosted Review 1 CompletedRuntime 11m 48s
    Found: 5 Accepted: 0/1/3 Routed: 1
    1. Move the bounded-retry loop into one shared helper.Trivial

      authenticate and retireInitialGameplayLogin repeat the same retry rules line for line:

      • one overall deadline, reduced to the parent Context deadline;
      • checks for expiry and cancellation;
      • a null-stub guard;
      • at most one retry, only on UNAVAILABLE or DEADLINE_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, using InitialGameplayLoginDisposalResult.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.
    2. 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 any Throwable. 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 ExecuteListener in newPostgresContext turns every SQL exception into an AssertionError. Lines 1110-1120 are meant to show that a constraint rejects a fabricated terminal proof. That check also passes if the UPDATE has 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, registerPending could 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-reads tokenKey after that call in initialLoginDisposalFencesEveryInterruptedIssuanceStage. So nothing shows that the tombstone survived.

      For each check, assert the owner exception the production path actually throws. Examples:

      • AccountCoordinationRedisException for Redis rejection.
      • IdempotencyConflictException or DisposalConflictException for 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.
    3. Use one shared validator for checkpoints and source events.Trivial

      validateCheckpoints here repeats CanonicalGameplayLoginResult.validateCheckpoints (lines 186-236 of that file). The two copies already differ:

      • This copy compares event.outboxStreamKey with streams.get(index). The DTO copy compares it with checkpoint.get("outboxStreamKey").
      • This copy reads the sequence through text(). The DTO copy uses instanceof pattern 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.
    4. Plan capacity and cleanup for permanent disposal tombstones.Trivial

      SET key tombstone clears the TTL on purpose. The Java readback also requires pttl == -1. Each disposed token-bound initial LOGIN therefore leaves one permanent session: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 exp plus 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
    5. Record a bounded reason before mutate returns Optional.empty().Trivial

      mutate turns every RuntimeException into Optional.empty() with no log line and no metric. The same applies to install (Line 57) and acquireQualification (Line 77). Many different causes give the same empty result:

      • lost qualification;
      • wrong ACL principal;
      • descriptor or SHA mismatch;
      • a WRONGTYPE reply;
      • an EVALSHA result other than 1;
      • an insufficient WAITAOF count;
      • a readback mismatch.

      The cleanup owner then reports HELD with 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.
  3. Hosted Review 2 CompletedRuntime 10m 44s
    Found: 1 Accepted: 0/0/1 Routed: 0
    1. Record a fixed, non-sensitive reason before you return HELD.Trivial

      The catch block maps every RuntimeException to the same HELD observation. It writes no log line. The block covers different kinds of failure:

      • A JournalConflictException is a permanent conflict, for example a changed Account receipt or changed coordinates. An operator must act on it, because each later redrive also returns HELD.
      • 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.warn already 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.
  4. Hosted Review 3 CompletedRuntime 9m 09s
    Found: 3 Accepted: 3 Routed: 0
    1. Move the new initial-LOGIN policy sections out of "Related Documentation".Trivial

      Both new normative h3 sections are appended under the ## Related Documentation link 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 policy into the profile or service-usage section, above ## Related Documentation.
      • design/architecture/infrastructure/environment-and-secrets-catalog.md#L324-L326: move ### Initial LOGIN context Coordination policy into 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.
    2. 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.
    3. Build the ACTIVE bytes with activeRecordBytes(record), not with text replacement.Trivial

      disposeInitialLogin builds the ACTIVE record with String.replace, which replaces every occurrence. The activation path uses activeRecordBytes, 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. record has already been decoded and checked as pending. 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.
  5. CLI Review 1 CompletedRuntime 3m 11s
    Found: 5 Accepted: 1/2/0 Routed: 0
    1. Mark RetireInitialGameplayLogin as not currently routable.Major

      The Markdown matrix says this receiver is unregistered. This YAML entry records that fact under known_drift but omits the route_status used by nearby target-only routes. Add route_status: target_not_currently_routable so 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.
    2. Reject a mismatched Account UUID source-row ID.Minor

      If account.getAccountUuidSourceNumericId() differs from account.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 or AccountRepository.findByAccountUuid already 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.
    3. Report a contradictory disposal owner result as INTERNAL, not UNAVAILABLE.Minor

      A wrong requestId or callerContextId from disposalOwner.retire is an owner contract violation, not a transient outage. The code at Line 131 throws a bare IllegalStateException. The RuntimeException catch at Line 174 then maps that exception to Status.UNAVAILABLE.

      Game Session treats UNAVAILABLE as retryable, so it retries an outcome that a retry cannot fix. The authenticate path handles the same kind of contradiction (Line 248-251) as Status.INTERNAL. Fail the disposal path the same way, and add braces to the if.

      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.
    4. Plan retention and cleanup for permanent disposal tombstones.Trivial

      The disposal script writes the tombstone with SET and no TTL. The client requires PTTL == -1 on readback. Each retired original LOGIN therefore leaves one permanent session: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.
    5. Confirm that the disposal insert takes the same advisory lock as the writer guard.Major

      account_initial_gameplay_login_writer_guard takes pg_advisory_xact_lock(hashtextextended('account-gameplay-delegation-request/' || request_id, 0)). It then checks EXISTS on account_initial_gameplay_login_disposals. Nothing in this migration makes a disposal INSERT take that lock.

      Under READ COMMITTED, the following sequence is possible:

      1. An issuance INSERT or UPDATE passes the EXISTS check.
      2. A concurrent AccountInitialGameplayLoginDisposalRepository.begin inserts the PENDING disposal row.
      3. Both transactions commit.

      The result is a bind or COMMITTED transition that commits after a durable disposal intent exists. The begin read 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 begin path, which is not in this review. Choose one:

      • Have begin (and requireOriginalRequestNotDisposed) take the identical advisory lock before it reads or inserts.
      • Add a BEFORE INSERT trigger on account_initial_gameplay_login_disposals that takes that lock.

      Verify that AccountInitialGameplayLoginDisposalRepository.begin calls pg_advisory_xact_lock with 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 begin read 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.
  6. CLI Review 2 CompletedRuntime 3m 33s
    Found: 5 Accepted: 0/0/0 Routed: 0
    1. Handle a null tombstone before hashing it.Minor

      finish calls hash(current.tombstoneBytes()). For a no-key intent, tombstoneBytes() returns null, and MessageDigest.digest(null) throws a NullPointerException. Reject a null tombstone first and throw unavailable().

      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.
    2. Align the witness and response integer types.Major

      InitialGameplayLoginTokenWitness declares token_generation and issuance_fence as int64. AuthenticateResponse declares the same values as string (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.
    3. Plan retention for the persistent disposal tombstones.Trivial

      disposeInitialLogin writes each tombstone with no TTL, and the method requires PTTL == -1. The SQL row is retained permanently because retention_hold is constrained to TRUE. Nothing in this change ever deletes a tombstone. Each retired initial LOGIN therefore adds one permanent session: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.
    4. Compare boxed identifiers with Objects.equals.Major

      The code compares snapshot.accountId() != account.getId() and snapshot.membershipId() != membership.getId(). Account.getId() returns Long, as Line 303 shows. If either side is a Long, the != operator can compare references or unbox a null value. A reference comparison of identical values above the Long cache range (above 127) returns true. The snapshot is then rejected as unavailable even when the identifiers match. Use Objects.equals here, 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.
    5. Guard the unboxing of nullable issuance columns.Minor

      token.tokenGeneration() != original.get("token_generation", Long.class) unboxes the column value. If issuance_fence or token_generation is null on a PENDING row, the comparison throws a NullPointerException. The caller then gets an uncategorized error instead of DisposalConflictException. Use Objects.equals with 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.
  7. CLI Review 3 CompletedRuntime 3m 27s
    Found: 4 Accepted: 0/1/0 Routed: 0
    1. Pin the duplicated billing constants to the Account owner values with a test.Trivial

      The codec now hard-codes BILLING_STREAM_PREFIX and BILLING_EVENT_SCHEMA_VERSION. Before, it took these values from AccountTenantEntitlementOutboxRepository and DemoTenantEntitlementEventV1Codec. seal and verify now 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) equals DemoTenantEntitlementEventV1Codec'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.
    2. Bound the lifetime of the disposal tombstone.Trivial

      SET key tombstone writes the tombstone without a TTL. disposeInitialLogin then requires PTTL == -1. The SQL retention_hold check is always TRUE, 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, registerPending and 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 exact pexpiretime.
      • 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.
    3. Preserve exact revocation-intent replay after disposal.Minor

      If an original login is disposed after beginRevocationIntent stores a pending intent, an exact retry now throws TokenRevokedException in requireExact. The retry never reaches the existing request-and-digest replay check in beginRevocationIntent. 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.
    4. Verify that the tenant source version always equals the tenant authority generation.Major

      verifyTenantSource compares currentGeneration with event.tenantAuthorityGeneration(). It also compares currentGeneration with event.tenantAuthoritySourceVersion(). The codec stores these as two independent long values. The membership projection in this PR treats version advancement and generation as independent (see AccountSelectedGameplayAuthorityProjectionTest line 59).

      Assume a non-revoking tenant mutation advances tenantAuthoritySourceVersion but keeps tenantAuthorityGeneration. 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.seal and check whether its tenantAuthorityGeneration and tenantAuthoritySourceVersion arguments 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.
  8. CLI Review 4 CompletedRuntime 3m 20s
    Found: 2 Accepted: 0/0/0 Routed: 0
    1. Verify that the disposal intent insert takes the same per-request advisory lock as the writer guard.Major

      The account_initial_gameplay_login_writer_guard trigger serializes issuance writers on pg_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 binding UPDATE is invisible to the disposal reader.

      Consider this interleaving, assuming AccountInitialGameplayLoginDisposalRepository.begin does not take the same lock:

      1. The signer transaction runs the binding UPDATE (token_hash, pending_registry_candidate_bytes). The trigger takes the advisory lock and finds no disposal row.
      2. The disposal transaction reads the issuance row and sees token_hash IS NULL. It inserts the disposal row with original_token_hash, pending_record_bytes and tombstone_bytes all NULL.
      3. Both transactions commit.

      After step 3, the bound token has no recorded hash in the disposal row. AccountInitialGameplayLoginDisposalOwner.retire takes the readUnqualifiedNoBinding path and returns PENDING on every call. The immutability trigger blocks any later update of original_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 begin acquires pg_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 a BEFORE INSERT trigger on account_initial_gameplay_login_disposals that 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.
    2. Plan a lifecycle for permanent disposal tombstones.Trivial

      The script writes the tombstone with SET and no expiry. The Java client requires PTTL == -1 on readback. The SQL row forces retention_hold = TRUE through a CHECK constraint, 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.
  9. CLI Review 5 CompletedRuntime 3m 16s
    Found: 5 Accepted: 0/0/2 Routed: 0
    1. Plan capacity and cleanup for the permanent disposal tombstones.Trivial

      The script always writes SET key tombstone with no expiry. This also happens when the key is absent or expired. The Java caller requires PTTL == -1. retention_hold in V1005 is always TRUE, 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 declares SESSION_LEASE_CACHE_OR_WAKE_UP loss 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.
    2. 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 (RETIRED with PHYSICAL_TOKEN_DENIAL, NO_TOKEN with NO_ISSUANCE_BINDING), Redis tombstone and WAITAOF behavior, 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.
    3. Remove the misleading @Transactional annotation or call the method through the proxy.Trivial

      The method is public with @Transactional(propagation = MANDATORY). Internal calls from selectByRequestId and lockRequestId bypass the Spring proxy, so the annotation does not apply. The manual isActualTransactionActive check 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.
    4. Unboxing risk in the witness comparison.Minor

      token.tokenGeneration() != original.get("token_generation", Long.class) compares a long primitive to a Long. Java unboxes the Long. A null column value throws NullPointerException. The same applies to issuance_fence. The source row exists, so the columns should be non-null. Use Objects.equals(Long.valueOf(...), ...) so a null column produces conflict() 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.
    5. Confirm that tenantAuthoritySourceVersion always equals tenantAuthorityGeneration.Major

      verifyTenantSource now compares one tuple value with two separate event fields. currentGeneration must equal event.tenantAuthorityGeneration(). It must also equal event.tenantAuthoritySourceVersion(). TenantAuthorityEventV1Codec stores these as independent fields, and seal accepts any two positive values for them.

      The membership projection keeps version and generation separate. AccountSelectedGameplayAuthorityProjectionTest states 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 with 2L, 2L, so they cannot detect a mismatch.

      Check the Account-side tenant authority event producer. Confirm whether tenantAuthoritySourceVersion equals tenantAuthorityGeneration by contract. If the values can differ, remove the second requireEquals. Bind the source version through the checkpoint or cutoff evidence instead. If the values cannot differ, document that invariant in the codec. Then make TenantAuthorityEventV1Codec.seal reject 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.
  10. CLI Review 6 CompletedRuntime 3m 11s
    Found: 5 Accepted: 0/0/2 Routed: 0
    1. 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/ and account-tenant-entitlement-event/v1. The account-service billing producer (AccountTenantEntitlementOutboxRepository and DemoTenantEntitlementEventV1Codec) also derives these values. If the two copies differ, seal rejects every real billing receipt, and verify rejects every stored tenant event.

      Confirm that the account-service producer now delegates to TenantAuthorityEventV1Codec.tenantBillingStreamKey and tenantBillingEventId. 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.
    2. Verify that membership events are re-emitted when tenant authority advances.Major

      The historical tenant generation check is now requireEquals instead of requireAtMost. validateHistoricalTenantCutoff also 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 AccountMembershipAuthorityEventProducer does 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.
    3. Confirm that disposal begin takes the same per-request advisory lock as this writer guard.Major

      The writer guard serializes only through pg_advisory_xact_lock(hashtextextended('account-gameplay-delegation-request/' || request_id, 0)). Under READ COMMITTED, the EXISTS check cannot see an uncommitted disposal row. Assume AccountInitialGameplayLoginDisposalRepository.begin does not take this lock before it reads the issuance binding. Then the following sequence is possible:

      1. Disposal begin reads the issuance row while token_hash is still NULL.
      2. Disposal begin inserts a PENDING row with original_token_hash IS NULL.
      3. A concurrent signer transaction binds token_hash. Its guard does not see the uncommitted disposal row.
      4. Both transactions commit.

      The immutability trigger blocks any later update to original_token_hash on the disposal row. Every retry of retire therefore takes the readUnqualifiedNoBinding path 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 begin acquires this exact advisory key before it reads account_gameplay_delegation_issuance_operations. If it does not, add the same PERFORM pg_advisory_xact_lock(...) in begin, or in a BEFORE INSERT trigger on account_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.
    4. Assert the expected exception type for the rolled-back intent readback.Trivial

      assertThatThrownBy(...) has no type or message assertion. Any exception passes, including a NullPointerException or 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 example DisposalUnavailableException, or the listener AssertionError with 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.
    5. Verify that the tenant source version always equals the tenant authority generation.Major

      verifyTenantSource compares both event.tenantAuthorityGeneration() and event.tenantAuthoritySourceVersion() with the same currentGeneration value. 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: AccountSelectedGameplayAuthorityProjectionTest advances sourceVersion without generation. The seal(..., 2L, 2L, ...) fixtures in this PR cannot detect a divergence because the two values are equal.

      If the Account tenant producer advances tenantAuthoritySourceVersion without 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 (AccountTenantAuthorityEventRepository and its callers) that the source version always equals the generation. If the values can differ, remove the second requireEquals. 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

1 Open0 Accepted/Fixed0 Rejected
  1. Route 1 · PR #3216 → Unassigned target OpenTrivialPlan capacity and cleanup for permanent disposal tombstones.

    SET key tombstone clears the TTL on purpose. The Java readback also requires pttl == -1. Each disposed token-bound initial LOGIN therefore leaves one permanent session: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 exp plus 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