From 811390a086623caadf072bf1652951d2ef1b933a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:47:42 +1300 Subject: [PATCH 1/7] Qualify Account retention references through exact rearmed attempts --- .../account-service/runtime-and-data.md | 4 +- .../player-access-and-session.md | 4 +- ...ityEvaluationRetentionInspectionOwner.java | 384 +++++++++++++++++- ...tionInspectionPostgresIntegrationTest.java | 349 +++++++++++++++- ...valuationRetentionInspectionOwnerTest.java | 358 +++++++++++++++- ...CapacityEvaluationRetentionPolicyTest.java | 1 + .../capacity/CapacityAdmissionDigest.java | 220 ++++++++++ .../capacity/CapacityAdmissionDigestTest.java | 33 ++ ...GameplayRegionOwnerTransferRepository.java | 118 +----- 9 files changed, 1328 insertions(+), 143 deletions(-) diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 58d9cdf274..5e1aa2c45c 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -326,14 +326,14 @@ The numeric runtime entitlement endpoint follows the [Account API refusal bounda Account owns capacity evaluations, reservations, attempt history, recovery evidence, usage and their protected conservation aggregate under [ADR 0050](../../decisions/adr-0050-versioned-export-retention-and-erasure-policy.md) and [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md). Evaluation expiry ends admission freshness; it is not an erasure grant. No universal duration, caller-supplied approval flag or tenant setting can replace the finite environment schedule and its privacy/finance approval. -- Evaluations are purpose-bound authorization evidence. An expired evaluation can become a cleanup candidate only after its declared evidence horizon and every supported retry, replay, restore and investigation horizon end, with no hold or retained reference. References include prior evaluations retained inside immutable rearmed-attempt payloads, not only the current reservation foreign key. Until exact historical reference qualification exists, any retained reservation for the same tenant and owner conservatively blocks that scope's evaluations. Unreferenced non-admitting baselines still require the same policy and hold qualification. +- Evaluations are purpose-bound authorization evidence. An expired evaluation can become a cleanup candidate only after its declared evidence horizon and every supported retry, replay, restore and investigation horizon end, with no hold or retained reference. References include prior evaluations retained inside immutable rearmed-attempt payloads, not only the current reservation foreign key. A retained reservation conservatively blocks evaluations in the same tenant and owner scope whenever historical reference qualification is incomplete. Unreferenced non-admitting baselines still require the same policy and hold qualification. - Reservations retain live or recoverable work and the stable outer retry identity. Pending, ambiguous and quarantined work is never age-expired. Finalized or released state alone does not end the supported replay/restore window, prove teardown, or authorize removal of a reservation or its evidence. - Attempt history and recovery evidence are recovery/reconciliation lineage. All related attempts and owner observations must be terminal, reconciliation complete, and supported restore/replay unable to resurrect a dependency before bounded compaction or erasure is eligible. Compact identities, digests and outcomes must survive every applicable retry/deduplication window; an archive does not replace an online guard. - Usage and conservation are live resource-accounting state, not expiring event history. Retiring used capacity requires the once-only authoritative teardown transition; absence of an evaluation or an old timestamp cannot decrease either counter. The conservation aggregate adds no deletion or terminal-retirement authority. Every category's environment entry must name its exact finite maximum duration, purpose, authorized Account roles, subject/tenant export treatment, terminal erasure or minimization action, backup/replica handling and legal holds. Cleanup is owner-local, uses a bounded batch and safe watermark, and fails closed when a required policy, hold, reference or restore input is absent or contradictory. No cross-schema reads, unqualified partition drops or arbitrary age-only deletion are permitted. Restore must retain the applicable evidence and erasure reconciliation before traffic opens. -The prepared read-only evaluation inspection reports an oldest bounded window, blocker counts and evidence-byte totals within that window, physical relation size and an explicitly approximate catalog row count. An internal assessment accepts an exact versioned evaluation schedule, current hold snapshot and safe watermark. Its candidate counts cover only unheld and unreferenced sample rows beyond expiry and every applicable horizon. Without those inputs the default observation holds candidates. Cleanup, scheduling and receiving registration remain disabled. The [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records executed proof and remaining family-wide lifecycle obligations. +The prepared read-only evaluation inspection reports an oldest bounded window, blocker counts and evidence-byte totals within that window, physical relation size and an explicitly approximate catalog row count. An internal assessment accepts an exact versioned evaluation schedule, current hold snapshot and safe watermark. Its candidate counts cover only unheld and unreferenced sample rows beyond expiry and every applicable horizon. Reference qualification uses the current reservation foreign key and a bounded, complete chain of exact retained rearm attempts. It verifies canonical attempt bytes against their owner, identity, attempt, fence and digest. Missing, malformed or over-budget history retains the scope-wide blocker. Without those inputs the default observation holds candidates. Cleanup, scheduling and receiving registration remain disabled. The [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records executed proof and remaining family-wide lifecycle obligations. Retained player-admission version-1 evidence remains immutable and held for owner-governed retention. Player-admission version 2 is required for new capacity requests and their replay. Before activation or reuse of predecessor-populated storage, establish the retained Account and Game Session SQL and Redis inventory and resolve its outstanding confirmation, replay, recovery and restore obligations under the [objective compatibility gates](../../decisions/adr-0081-objective-compatibility-gates-for-database-evolution.md). diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 1867d379b2..605630aa0f 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -38,9 +38,9 @@ The Account owner can retry a rolled-back PostgreSQL serialization failure up to The additive [V1044 conservation correction](../../../services/account-service/src/main/resources/db/migration/V1044__account_tenant_capacity_incremental_conservation.sql) follows unchanged V1041–V1043, audits retained complete sums under a writer lock, seeds a protected tenant/owner aggregate and maintains exact reservation-transition deltas. Deferred checks use indexed/point reads rather than lifetime-history sums. The conservation route from #3407 was already fixed on published `70ddd8b4a2ee8fc197bfaf94dcd5d425430c25ec`; current-source proof at #3408 `eacc8d5bc56f359d81c857058b4bb070b05d2dc8` is [Validation run 43018214593](https://github.com/benhook1013/FireMUD/actions/runs/43018214593), attempt 1, [Account partition 4 job 130514704488](https://github.com/benhook1013/FireMUD/actions/runs/43018214593/job/130514704488), artifact `13855961789`. All six PostgreSQL 18.6 cases pass with zero failures, errors or skips, covering empty/populated V1043 upgrade, preserved rows/history and prior migration artifacts, fresh SQL-trigger composition, inconsistent inventory and forged-write refusal, atomic rollback, two-worker serialization and bounded reservation reads with 4,096 finalized rows. The read-count case proves at most eight reservation rows read for each selected hold, finalization and metadata operation, not a latency or production-load benchmark. Candidate and tested synthetic merge `bfde19362676759f34f4a618ff96f9f9ae7bd9b1` share tree `521124b63ee37fd73a80831387eab62fb0e93bc9`; V1044 and test blobs match. These fixtures drive real SQL transactions/triggers rather than the Java owner API, and their populated preservation cohort has no attempt-history or recovery-evidence rows. This already-recorded conservation fix is separate from unresolved family-wide retention, cleanup, restore/replay, teardown and activation qualification. -The Account-owned family comprises evaluation, attempt-history and recovery evidence, guarded reservations and usage, and the protected conservation aggregate. Its [canonical lifecycle classes and safety predicates](../../architecture/microservices/account-service/runtime-and-data.md#capacity-evidence-lifecycle) preserve replay, restore and hold dependencies. The unregistered evaluation inspection and [V1045 supporting indexes](../../../services/account-service/src/main/resources/db/migration/V1045__account_capacity_evaluation_retention.sql) prepare bounded oldest-window blocker/size observations without a deletion API or relaxed immutable guards. Three focused inspection unit cases pass with zero failures, errors or skips. At exact #3408 candidate [`eacc8d5`](https://github.com/benhook1013/FireMUD/commit/eacc8d5bc56f359d81c857058b4bb070b05d2dc8), [Validation run 43018214593](https://github.com/benhook1013/FireMUD/actions/runs/43018214593), attempt 1, [Account partition 2 job 130514704529](https://github.com/benhook1013/FireMUD/actions/runs/43018214593/job/130514704529) passed one JUnit case invoking both fresh and populated PostgreSQL forward-migration branches, including their preservation and refusal assertions, with zero failures, errors or skips. This exact-source CI proof is not execution at the later local head; the populated fixture has no recovery-evidence rows, reservation-byte equality is not asserted, and supported restore/replay qualification remains unproved. The approved finite environment schedule, current governance/hold source, exact historical reference qualification, actual bounded cleanup and complete family-wide lifecycle proof remain missing. `PLAYER_ADMISSION` registration and activation remain held; the retention obligation sourced in #3407 is routed to #3408 and accepted there by Dot, not closed by this preparation. +The Account-owned family comprises evaluation, attempt-history and recovery evidence, guarded reservations and usage, and the protected conservation aggregate. Its [canonical lifecycle classes and safety predicates](../../architecture/microservices/account-service/runtime-and-data.md#capacity-evidence-lifecycle) preserve replay, restore and hold dependencies. The unregistered evaluation inspection and [V1045 supporting indexes](../../../services/account-service/src/main/resources/db/migration/V1045__account_capacity_evaluation_retention.sql) prepare bounded oldest-window blocker/size observations without a deletion API or relaxed immutable guards. Three focused inspection unit cases pass with zero failures, errors or skips. At exact #3408 candidate [`eacc8d5`](https://github.com/benhook1013/FireMUD/commit/eacc8d5bc56f359d81c857058b4bb070b05d2dc8), [Validation run 43018214593](https://github.com/benhook1013/FireMUD/actions/runs/43018214593), attempt 1, [Account partition 2 job 130514704529](https://github.com/benhook1013/FireMUD/actions/runs/43018214593/job/130514704529) passed one JUnit case invoking both fresh and populated PostgreSQL forward-migration branches, including their preservation and refusal assertions, with zero failures, errors or skips. This exact-source CI proof is not execution at the later local head; the populated fixture has no recovery-evidence rows, reservation-byte equality is not asserted, and supported restore/replay qualification remains unproved. The approved finite environment schedule, current governance and hold source, actual bounded cleanup and complete family-wide lifecycle proof remain open in the dedicated Account capacity retention receiving slice. `PLAYER_ADMISSION` registration and activation remain held; the retention obligation sourced in #3407 is routed to #3408 and accepted there by Dot, not closed by this preparation. -The prepared Account evaluation observer classifies candidates under an explicit fixture schedule, current per-evaluation hold observation and safe watermark. Seven focused inspection and policy tests passed, including the default hold, expired unreferenced candidates, current and unknown holds, retained reservation scope, and horizon boundaries. The default owner still lacks approved environment schedule and hold authority. The open retention route requires bounded cleanup and replay, restore and erasure proof for the retained family. +The prepared Account evaluation observer classifies candidates under an explicit fixture schedule, current per-evaluation hold observation and safe watermark. Seven focused inspection and policy tests passed, including the default hold, expired unreferenced candidates, current and unknown holds, retained reservation scope, and horizon boundaries. The default owner still lacks approved environment schedule and hold authority. The dedicated Account capacity retention receiving slice qualifies exact historical references by checking the current evaluation foreign key and a bounded complete chain of rearmed attempts with the shared canonical capacity decoder. Unqualified scopes remain held. The focused PostgreSQL proof executes Account rearm against controlled membership, issuance and scope inputs, retains the old evaluation through immutable history, classifies the current foreign-key evaluation as referenced, and leaves the unrelated expired evaluation eligible in the synthetic policy sample. Inspection preserves the measured row images. Eleven shared digest cases and twelve Account inspection and policy unit cases passed. Its remaining work is the approved finite environment schedule and authoritative hold source, bounded reference-safe cleanup, and replay, restore and erasure proof for the retained family. The local [V1046 freshness correction](../../../services/account-service/src/main/resources/db/migration/V1046__account_capacity_attempt_write_freshness.sql) keeps earlier migrations and retained rows immutable. New creation qualifies current sources after the usage lock and rechecks fresh database time before mutation; a deferred new-attempt guard rejects expiry before commit without releasing historical holds. Added PostgreSQL proof sources cover the actual usage-lock wait across expiry with a frozen application clock, additive upgrade preservation, and original/rearm rollback. The Game Session resource boundary also exposes safely retained release-failure slots through its existing Micrometer path, with once-per-operation counting and test-thread cancellation-order assertions. Focused Account owner and Game Session resource-budget proof passes 21 tests with zero failures, errors or skips. Owning source generation, production/test/integration compilation, Java formatting, parent-pinned Flyway validation and enabled affected Checkstyle/SpotBugs tasks pass. The first attempts exposed a meter-registry fixture compilation issue, reused-exception cleanup suppression and a missed direct fixture caller; those were corrected before the passing results. Physical PostgreSQL proof remains unrun because the VM cannot access its Docker socket; compiled assertions are not execution proof. No activation or family-wide lifecycle qualification is claimed. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionInspectionOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionInspectionOwner.java index 1bd25f73ae..b3cb49bc02 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionInspectionOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionInspectionOwner.java @@ -3,11 +3,18 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; import java.time.OffsetDateTime; +import java.util.ArrayList; import java.util.EnumMap; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.OptionalLong; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; import org.jooq.DSLContext; import org.jooq.Record; import org.jspecify.annotations.Nullable; @@ -29,6 +36,13 @@ @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Private Account owner collaborator.") public final class AccountCapacityEvaluationRetentionInspectionOwner { public static final int MAX_SAMPLE_ROWS = 1000; + // At most 8 scopes × 16 reservations × 9 indexed history-key rows are inspected. At most 32 + // payloads are fetched (16 MiB under the V1040 row-size constraint); sentinels fail closed. + private static final int MAX_REFERENCE_SCOPES = 8; + private static final int MAX_RESERVATIONS_PER_SCOPE = 16; + private static final int MAX_HISTORY_ROWS_PER_SCOPE = 8; + private static final int MAX_HISTORY_ROWS_PER_OBSERVATION = 32; + private static final int MAX_RETAINED_PAYLOAD_BYTES = 524288; public enum Blocker { LIVE_EVALUATION, @@ -57,9 +71,9 @@ private SampleWindow include(Instant evaluated, long bytes) { /** * Physical relation bytes include indexes and TOAST; the catalog row estimate may be unavailable - * or stale. Only the oldest bounded sample is inspected, without reading evidence payload bytes - * or exposing tenant, caller or evaluation identities. Candidate counts describe this sample - * under the supplied policy inputs. They authorize no mutation. + * or stale. Only the oldest bounded sample is inspected. The default observation does not read + * evidence payload bytes; a current policy-qualified assessment decodes only bounded attempt + * envelopes. Neither identities nor payloads are exposed. Candidate counts authorize no mutation. */ public record Observation( Instant observedAt, @@ -83,6 +97,29 @@ public record Observation( private final DSLContext dsl; private final TransactionTemplate reads; + private record Scope(UUID tenantId, String ownerService) {} + + private record ReservationKey( + Scope scope, + UUID requestId, + UUID admissionId, + long currentRearmFence, + String callerWorkload) {} + + private record HistoryKey( + ReservationKey reservation, UUID attemptId, long rearmFence, String mutationDigest) {} + + private record SampledEvaluation( + String evaluationIdentity, + Scope scope, + Instant evaluatedAt, + Instant expiresAt, + long evidenceBytes, + boolean directlyReferenced, + boolean scopeReferenced) {} + + private record HistoryQualification(Set references, Set unqualifiedScopes) {} + public AccountCapacityEvaluationRetentionInspectionOwner( DSLContext dsl, PlatformTransactionManager transactions) { this.dsl = Objects.requireNonNull(dsl); @@ -123,8 +160,9 @@ private Observation readObservation( Objects.requireNonNull(table.get("observed_at", OffsetDateTime.class)).toInstant(); long relationBytes = Objects.requireNonNull(table.get("relation_bytes", Long.class)); long estimate = Objects.requireNonNull(table.get("estimated_rows", Long.class)); - // Scope-wide preservation is intentional: rearm replaces the current evaluation FK, while - // historical canonical_payload and owner_readback can still name the previous evaluation. + boolean policyCurrent = + AccountCapacityEvaluationRetentionPolicy.current(schedule, safety, observedAt); + // The initial sample is one bounded query; identity fields remain private to this inspection. var rows = dsl.fetch( "WITH sample AS MATERIALIZED (" @@ -132,41 +170,75 @@ private Observation readObservation( + "octet_length(canonical_evidence)::bigint AS evidence_bytes " + "FROM account_tenant_capacity_evaluations " + "ORDER BY evaluated_at, evaluation_identity LIMIT ?) " - + "SELECT sample.evaluation_identity, sample.evaluated_at, sample.expires_at, sample.evidence_bytes, " + + "SELECT sample.evaluation_identity, sample.tenant_uuid, sample.owner_service, " + + "sample.evaluated_at, sample.expires_at, sample.evidence_bytes, " + "EXISTS (SELECT 1 FROM account_tenant_capacity_reservations reservation " + "WHERE reservation.tenant_uuid = sample.tenant_uuid " - + "AND reservation.owner_service = sample.owner_service) AS scope_referenced " + + "AND reservation.owner_service = sample.owner_service) AS scope_referenced, " + + (policyCurrent + ? "EXISTS (SELECT 1 FROM account_tenant_capacity_reservations reservation " + + "WHERE reservation.tenant_uuid = sample.tenant_uuid " + + "AND reservation.owner_service = sample.owner_service " + + "AND reservation.evaluation_identity = sample.evaluation_identity) AS directly_referenced " + : "FALSE AS directly_referenced ") + "FROM sample ORDER BY sample.evaluated_at, sample.evaluation_identity", sampleRows + 1); + + int count = Math.min(rows.size(), sampleRows); + List sampled = new ArrayList<>(count); + for (int index = 0; index < count; index++) { + Record row = rows.get(index); + sampled.add( + new SampledEvaluation( + row.get("evaluation_identity", String.class), + new Scope(row.get("tenant_uuid", UUID.class), row.get("owner_service", String.class)), + Objects.requireNonNull(row.get("evaluated_at", OffsetDateTime.class)).toInstant(), + Objects.requireNonNull(row.get("expires_at", OffsetDateTime.class)).toInstant(), + Objects.requireNonNull(row.get("evidence_bytes", Long.class)), + Boolean.TRUE.equals(row.get("directly_referenced", Boolean.class)), + Boolean.TRUE.equals(row.get("scope_referenced", Boolean.class)))); + } + HistoryQualification history = + policyCurrent ? qualifyHistory(sampled) : new HistoryQualification(Set.of(), Set.of()); + var empty = new SampleWindow(0, 0, Optional.empty()); Map windows = new EnumMap<>(Blocker.class); for (Blocker blocker : Blocker.values()) { windows.put(blocker, empty); } SampleWindow candidates = empty; - int count = Math.min(rows.size(), sampleRows); for (int index = 0; index < count; index++) { - Record row = rows.get(index); - Instant evaluated = - Objects.requireNonNull(row.get("evaluated_at", OffsetDateTime.class)).toInstant(); - Instant expires = - Objects.requireNonNull(row.get("expires_at", OffsetDateTime.class)).toInstant(); - long bytes = Objects.requireNonNull(row.get("evidence_bytes", Long.class)); + SampledEvaluation row = sampled.get(index); + Boolean referenced; + if (!policyCurrent) { + // Without current policy and hold inputs, retain the original cheap scope-wide block. + referenced = row.scopeReferenced(); + } else if (row.directlyReferenced() + || history.references().contains(row.evaluationIdentity())) { + referenced = true; + } else if (history.unqualifiedScopes().contains(row.scope())) { + // An incomplete or over-limit history scan cannot prove the scope is unreferenced. + referenced = true; + } else { + referenced = false; + } var classification = AccountCapacityEvaluationRetentionPolicy.classify( schedule, safety, observedAt, - row.get("evaluation_identity", String.class), - evaluated, - expires, - row.get("scope_referenced", Boolean.class)); + row.evaluationIdentity(), + row.evaluatedAt(), + row.expiresAt(), + referenced); if (classification == AccountCapacityEvaluationRetentionPolicy.Classification.CANDIDATE) { - candidates = candidates.include(evaluated, bytes); + candidates = candidates.include(row.evaluatedAt(), row.evidenceBytes()); } else { Blocker blocker = Blocker.valueOf(classification.name()); windows.put( - blocker, Objects.requireNonNull(windows.get(blocker)).include(evaluated, bytes)); + blocker, + Objects.requireNonNull(windows.get(blocker)) + .include(row.evaluatedAt(), row.evidenceBytes())); } } Optional version = @@ -186,6 +258,278 @@ private Observation readObservation( candidates); } + private HistoryQualification qualifyHistory(List sampled) { + Set requiredScopes = new HashSet<>(); + for (SampledEvaluation row : sampled) { + if (row.scopeReferenced() && !row.directlyReferenced()) requiredScopes.add(row.scope()); + } + if (requiredScopes.isEmpty()) return new HistoryQualification(Set.of(), Set.of()); + + List orderedScopes = + requiredScopes.stream() + .sorted( + (left, right) -> { + int tenantOrder = left.tenantId().compareTo(right.tenantId()); + return tenantOrder != 0 + ? tenantOrder + : left.ownerService().compareTo(right.ownerService()); + }) + .toList(); + Set unqualified = new HashSet<>(); + if (orderedScopes.size() > MAX_REFERENCE_SCOPES) { + unqualified.addAll(orderedScopes.subList(MAX_REFERENCE_SCOPES, orderedScopes.size())); + orderedScopes = orderedScopes.subList(0, MAX_REFERENCE_SCOPES); + } + + // Cap scope enumeration before looking at attempt payloads. The extra row detects overflow. + List scopeBindings = new ArrayList<>(); + for (Scope scope : orderedScopes) { + scopeBindings.add(scope.tenantId()); + scopeBindings.add(scope.ownerService()); + } + String scopeValues = valuesClause(orderedScopes.size(), 2, "uuid", "text"); + var reservationRows = + dsl.fetch( + "WITH scopes(tenant_uuid, owner_service) AS (VALUES " + + scopeValues + + ") SELECT scopes.tenant_uuid, scopes.owner_service, reservation.request_id, " + + "reservation.admission_id, reservation.capacity_rearm_fence, reservation.caller_workload " + + "FROM scopes CROSS JOIN LATERAL (" + + "SELECT request_id, admission_id, capacity_rearm_fence, caller_workload " + + "FROM account_tenant_capacity_reservations " + + "WHERE tenant_uuid = scopes.tenant_uuid AND owner_service = scopes.owner_service " + + "LIMIT " + + (MAX_RESERVATIONS_PER_SCOPE + 1) + + ") reservation", + scopeBindings.toArray()); + Map> reservations = new HashMap<>(); + for (Record row : reservationRows) { + Scope scope = + new Scope(row.get("tenant_uuid", UUID.class), row.get("owner_service", String.class)); + reservations + .computeIfAbsent(scope, ignored -> new ArrayList<>()) + .add( + new ReservationKey( + scope, + row.get("request_id", UUID.class), + row.get("admission_id", UUID.class), + Objects.requireNonNull(row.get("capacity_rearm_fence", Long.class)), + row.get("caller_workload", String.class))); + } + for (Scope scope : orderedScopes) { + List scopeReservations = reservations.getOrDefault(scope, List.of()); + if (scopeReservations.size() > MAX_RESERVATIONS_PER_SCOPE) { + unqualified.add(scope); + reservations.remove(scope); + } + } + List qualifiedReservations = + reservations.values().stream().flatMap(List::stream).toList(); + if (qualifiedReservations.isEmpty()) + return new HistoryQualification(Set.of(), Set.copyOf(unqualified)); + + List reservationBindings = new ArrayList<>(); + for (ReservationKey reservation : qualifiedReservations) { + reservationBindings.add(reservation.scope().tenantId()); + reservationBindings.add(reservation.scope().ownerService()); + reservationBindings.add(reservation.requestId()); + reservationBindings.add(reservation.admissionId()); + reservationBindings.add(reservation.callerWorkload()); + } + String reservationValues = + valuesClause(qualifiedReservations.size(), 5, "uuid", "text", "uuid", "uuid", "text"); + var historyKeys = + dsl.fetch( + "WITH reservations(tenant_uuid, owner_service, request_id, admission_id, caller_workload) AS (VALUES " + + reservationValues + + "), scopes AS (SELECT DISTINCT tenant_uuid, owner_service FROM reservations) " + + "SELECT histories.tenant_uuid, histories.owner_service, histories.request_id, " + + "histories.admission_id, histories.caller_workload, histories.admission_attempt_id, histories.capacity_rearm_fence, " + + "histories.mutation_digest, histories.payload_bytes FROM scopes CROSS JOIN LATERAL (" + + "SELECT bounded_history.tenant_uuid, bounded_history.owner_service, bounded_history.request_id, " + + "bounded_history.admission_id, bounded_history.caller_workload, bounded_history.admission_attempt_id, " + + "bounded_history.capacity_rearm_fence, bounded_history.mutation_digest, " + + "bounded_history.payload_bytes FROM (SELECT * FROM reservations " + + "WHERE tenant_uuid = scopes.tenant_uuid AND owner_service = scopes.owner_service) reservations " + + "CROSS JOIN LATERAL (" + + "SELECT history.tenant_uuid, reservations.owner_service, history.request_id, " + + "history.admission_id, reservations.caller_workload, history.admission_attempt_id, history.capacity_rearm_fence, " + + "history.mutation_digest, octet_length(history.canonical_payload)::bigint AS payload_bytes " + + "FROM account_tenant_capacity_attempt_history history " + + "WHERE history.tenant_uuid = reservations.tenant_uuid " + + "AND history.request_id = reservations.request_id " + + "AND history.admission_id = reservations.admission_id " + + "ORDER BY history.admission_attempt_id LIMIT " + + (MAX_HISTORY_ROWS_PER_SCOPE + 1) + + ") bounded_history " + + "ORDER BY bounded_history.request_id, bounded_history.admission_id, " + + "bounded_history.admission_attempt_id LIMIT " + + (MAX_HISTORY_ROWS_PER_SCOPE + 1) + + ") histories ORDER BY histories.tenant_uuid, histories.owner_service, histories.request_id, " + + "histories.admission_id, histories.admission_attempt_id LIMIT " + + (MAX_HISTORY_ROWS_PER_OBSERVATION + 1), + reservationBindings.toArray()); + if (historyKeys.size() > MAX_HISTORY_ROWS_PER_OBSERVATION) { + // The observation-wide byte/row budget was exceeded; none of the unscanned history is + // inferred. + unqualified.addAll(reservations.keySet()); + return new HistoryQualification(Set.of(), Set.copyOf(unqualified)); + } + + Map> keysByScope = new HashMap<>(); + for (Record row : historyKeys) { + Scope scope = + new Scope(row.get("tenant_uuid", UUID.class), row.get("owner_service", String.class)); + if (Objects.requireNonNull(row.get("payload_bytes", Long.class)) + > MAX_RETAINED_PAYLOAD_BYTES) { + unqualified.add(scope); + continue; + } + UUID requestId = row.get("request_id", UUID.class); + UUID admissionId = row.get("admission_id", UUID.class); + String callerWorkload = row.get("caller_workload", String.class); + ReservationKey reservation = + qualifiedReservations.stream() + .filter( + candidate -> + candidate.scope().equals(scope) + && candidate.requestId().equals(requestId) + && candidate.admissionId().equals(admissionId) + && candidate.callerWorkload().equals(callerWorkload)) + .findFirst() + .orElse(null); + if (reservation == null) { + unqualified.add(scope); + continue; + } + keysByScope + .computeIfAbsent(scope, ignored -> new ArrayList<>()) + .add( + new HistoryKey( + reservation, + row.get("admission_attempt_id", UUID.class), + Objects.requireNonNull(row.get("capacity_rearm_fence", Long.class)), + Objects.requireNonNull(row.get("mutation_digest", String.class)).trim())); + } + for (Map.Entry> entry : keysByScope.entrySet()) { + if (entry.getValue().size() > MAX_HISTORY_ROWS_PER_SCOPE) unqualified.add(entry.getKey()); + } + for (ReservationKey reservation : qualifiedReservations) { + if (unqualified.contains(reservation.scope())) continue; + List attemptKeys = + keysByScope.getOrDefault(reservation.scope(), List.of()).stream() + .filter(key -> key.reservation().equals(reservation)) + .toList(); + long expectedHistoryRows = reservation.currentRearmFence() - 1; + if (expectedHistoryRows < 0 + || expectedHistoryRows != attemptKeys.size() + || expectedHistoryRows > MAX_HISTORY_ROWS_PER_SCOPE) { + unqualified.add(reservation.scope()); + continue; + } + Set fences = new HashSet<>(); + for (HistoryKey key : attemptKeys) fences.add(key.rearmFence()); + for (long expectedFence = 1; expectedFence <= expectedHistoryRows; expectedFence++) { + if (!fences.contains(expectedFence)) { + unqualified.add(reservation.scope()); + break; + } + } + } + + List keysToRead = + keysByScope.entrySet().stream() + .filter(entry -> !unqualified.contains(entry.getKey())) + .flatMap(entry -> entry.getValue().stream()) + .toList(); + if (keysToRead.isEmpty()) return new HistoryQualification(Set.of(), Set.copyOf(unqualified)); + List historyBindings = new ArrayList<>(); + for (HistoryKey key : keysToRead) { + historyBindings.add(key.reservation().scope().tenantId()); + historyBindings.add(key.reservation().requestId()); + historyBindings.add(key.reservation().admissionId()); + historyBindings.add(key.attemptId()); + } + String historyValues = valuesClause(keysToRead.size(), 4, "uuid", "uuid", "uuid", "uuid"); + var payloadRows = + dsl.fetch( + "WITH selected(tenant_uuid, request_id, admission_id, admission_attempt_id) AS (VALUES " + + historyValues + + ") SELECT history.tenant_uuid, history.request_id, history.admission_id, " + + "history.admission_attempt_id, history.capacity_rearm_fence, history.mutation_digest, " + + "history.canonical_payload FROM selected JOIN account_tenant_capacity_attempt_history history " + + "USING (tenant_uuid, request_id, admission_id, admission_attempt_id)", + historyBindings.toArray()); + if (payloadRows.size() != keysToRead.size()) { + unqualified.addAll(keysByScope.keySet()); + return new HistoryQualification(Set.of(), Set.copyOf(unqualified)); + } + + Map> referencesByScope = new HashMap<>(); + Set malformed = new HashSet<>(); + for (Record row : payloadRows) { + UUID tenantId = row.get("tenant_uuid", UUID.class); + UUID requestId = row.get("request_id", UUID.class); + UUID admissionId = row.get("admission_id", UUID.class); + UUID attemptId = row.get("admission_attempt_id", UUID.class); + HistoryKey expected = + keysToRead.stream() + .filter( + key -> + key.reservation().scope().tenantId().equals(tenantId) + && key.reservation().requestId().equals(requestId) + && key.reservation().admissionId().equals(admissionId) + && key.attemptId().equals(attemptId)) + .findFirst() + .orElse(null); + Scope scope = expected == null ? null : expected.reservation().scope(); + if (scope == null || requestId == null || admissionId == null || attemptId == null) { + if (scope != null) malformed.add(scope); + else unqualified.addAll(keysByScope.keySet()); + continue; + } + ReservationKey reservation = expected.reservation(); + try { + long fence = Objects.requireNonNull(row.get("capacity_rearm_fence", Long.class)); + String digest = Objects.requireNonNull(row.get("mutation_digest", String.class)).trim(); + byte[] payload = Objects.requireNonNull(row.get("canonical_payload", byte[].class)); + if (fence != expected.rearmFence() + || !digest.equals(expected.mutationDigest()) + || payload.length > MAX_RETAINED_PAYLOAD_BYTES) throw new IllegalArgumentException(); + var request = CapacityAdmissionDigest.decodeCommittable(payload, digest); + if (!request.identity().tenantId().equals(scope.tenantId()) + || !request.identity().requestId().equals(requestId) + || !request.identity().admissionId().equals(admissionId) + || !request.admissionAttemptId().equals(attemptId) + || request.capacityRearmFence() != fence + || !request.context().owner().service().equals(reservation.scope().ownerService()) + || !request.evidence().callerWorkload().equals(reservation.callerWorkload())) + throw new IllegalArgumentException(); + referencesByScope + .computeIfAbsent(scope, ignored -> new HashSet<>()) + .add(request.evidence().evaluationIdentity()); + } catch (RuntimeException invalid) { + malformed.add(scope); + } + } + unqualified.addAll(malformed); + Set references = new HashSet<>(); + for (Map.Entry> entry : referencesByScope.entrySet()) { + if (!unqualified.contains(entry.getKey())) references.addAll(entry.getValue()); + } + return new HistoryQualification(Set.copyOf(references), Set.copyOf(unqualified)); + } + + private static String valuesClause(int rows, int columns, String... casts) { + if (rows < 1 || columns != casts.length) + throw new IllegalArgumentException("Invalid SQL values shape"); + String row = + "(" + + String.join(", ", java.util.Arrays.stream(casts).map(cast -> "?::" + cast).toList()) + + ")"; + return String.join(", ", java.util.Collections.nCopies(rows, row)); + } + private static void requireBound(int rows) { if (rows < 1 || rows > MAX_SAMPLE_ROWS) { throw new IllegalArgumentException( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java index 514890dfe6..872aec65e1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java @@ -1,15 +1,33 @@ -package integration.net.firedevops.firemud.accountservice.repository; +package net.firedevops.firemud.accountservice.service; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; import java.sql.SQLException; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; -import net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionInspectionOwner; import net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionInspectionOwner.Blocker; +import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.flywaydb.core.Flyway; @@ -48,6 +66,154 @@ void freshAndPopulatedForwardMigrationPreserveRowsAndGuardsWhileBoundingObservat verifyForwardMigration(true); } + @Test + void policyQualifiedInspectionFindsRearmedOldEvaluationAndLeavesUnrelatedRowCandidate() + throws InterruptedException { + String schema = "capacity_retention_history_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + configure(data, schema).load().migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var transactions = new DataSourceTransactionManager(data); + var write = new TransactionTemplate(transactions); + FreshTenantCreationEvidence tenant = bootstrapFreshTenant(dsl, write); + + Instant priorAt = Instant.now(); + var prior = + playerRequest( + tenant.canonicalTenantId(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + priorAt, + priorAt.plusSeconds(10)); + var unrelated = + playerRequest( + tenant.canonicalTenantId(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + priorAt.minus(Duration.ofDays(10)), + priorAt.minus(Duration.ofDays(10)).plusSeconds(90)); + UUID reservationId = UUID.randomUUID(); + UUID recoveryOwner = UUID.randomUUID(); + String readbackDigest = "b".repeat(64); + write.executeWithoutResult( + status -> { + insertEvaluation(dsl, prior, priorAt, priorAt.plusSeconds(10)); + insertEvaluation( + dsl, + unrelated, + unrelated.evidence().evaluatedAt(), + unrelated.evidence().expiresAt()); + dsl.execute( + "INSERT INTO account_tenant_capacity_reservations " + + "(tenant_uuid, request_id, admission_id, reservation_id, owner_service, caller_workload, " + + "admission_attempt_id, capacity_rearm_fence, reservation_fence, mutation_digest, " + + "canonical_payload, evaluation_identity, capacity_delta, expires_at, state, execution_status, " + + "reconcile_deadline) VALUES (?, ?, ?, ?, 'game-session-service', ?, ?, 1, 1, ?, ?, ?, 1, " + + "?::timestamptz, 'RESERVED', 'OWNER_EXECUTION_PENDING', ?::timestamptz)", + prior.identity().tenantId(), + prior.identity().requestId(), + prior.identity().admissionId(), + reservationId, + prior.evidence().callerWorkload(), + prior.admissionAttemptId(), + prior.mutationDigest(), + CapacityAdmissionDigest.preimage(prior), + prior.evidence().evaluationIdentity(), + prior.evidence().expiresAt().toString(), + prior.evidence().expiresAt().plusSeconds(60).toString()); + dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = 1, usage_revision = 2 " + + "WHERE tenant_uuid = ? AND owner_service = 'game-session-service'", + tenant.canonicalTenantId()); + }); + + waitUntil(prior.evidence().expiresAt().plusMillis(100)); + Instant nextAt = Instant.now(); + var nextSeed = + playerRequest( + tenant.canonicalTenantId(), + prior.identity().requestId(), + prior.identity().admissionId(), + UUID.randomUUID(), + nextAt, + nextAt.plusSeconds(60)); + var next = + new TenantCapacityAdmission.Request( + prior.identity(), + nextSeed.admissionAttemptId(), + 2, + prior.targetNamespace(), + prior.context(), + prior.operation(), + prior.priorShape(), + prior.requestedShape(), + nextSeed.evidence(), + prior.capacityDelta(), + null) + .withDigest(); + byte[] ownerReadback = + "controlled-terminal-no-commit".getBytes(java.nio.charset.StandardCharsets.US_ASCII); + write.executeWithoutResult( + status -> { + insertEvaluation(dsl, next, next.evidence().evaluatedAt(), next.evidence().expiresAt()); + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET recovery_owner = ?, " + + "recovery_claim_fence = 1, recovery_claim_expires_at = clock_timestamp() + INTERVAL '1 day', " + + "execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION', owner_readback = ?, " + + "owner_readback_digest = ? WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + recoveryOwner, + ownerReadback, + readbackDigest, + prior.identity().tenantId(), + prior.identity().requestId(), + prior.identity().admissionId()); + }); + var capacityOwner = capacityOwner(dsl, transactions, next); + var rearmed = capacityOwner.rearm(prior, next, recoveryOwner, 1L); + assertThat(rearmed.evaluationIdentity()).isEqualTo(next.evidence().evaluationIdentity()); + + List beforeObservation = rowImages(dsl); + var owner = new AccountCapacityEvaluationRetentionInspectionOwner(dsl, transactions); + Instant policyObservedAt = Instant.now().minusSeconds(1); + var schedule = + new AccountCapacityEvaluationRetentionPolicy.Schedule( + "physical-fixture/v1", + Duration.ofDays(30), + Duration.ofDays(2), + Duration.ofDays(3), + Duration.ofDays(4), + Duration.ofDays(5), + Duration.ofDays(6)); + var safety = + new AccountCapacityEvaluationRetentionPolicy.Safety( + "physical-fixture/v1", + policyObservedAt, + policyObservedAt.plus(Duration.ofHours(1)), + policyObservedAt.minus(Duration.ofDays(1)), + Map.of( + prior.evidence().evaluationIdentity(), + AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR, + next.evidence().evaluationIdentity(), + AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR, + unrelated.evidence().evaluationIdentity(), + AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR)); + + var observation = owner.observe(10, schedule, safety); + + assertThat(observation.sampledRows()).isEqualTo(3); + assertThat(observation.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows()) + .isEqualTo(2); + assertThat(observation.candidates().rows()).isEqualTo(1); + assertThat(rowImages(dsl)).isEqualTo(beforeObservation); + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + private static void verifyForwardMigration(boolean populated) { String schema = "capacity_retention_" + UUID.randomUUID().toString().replace("-", ""); new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); @@ -313,6 +479,185 @@ private static void populate(DSLContext dsl, TransactionTemplate write) { }); } + private static FreshTenantCreationEvidence bootstrapFreshTenant( + DSLContext dsl, TransactionTemplate write) { + FreshTenantCreationEvidence tenant = source(); + UUID bootstrap = UUID.randomUUID(); + write.executeWithoutResult( + status -> { + UUID account = + dsl.fetchSingle( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, 'test-password') RETURNING account_uuid", + "lineage-" + UUID.randomUUID(), + "lineage-" + UUID.randomUUID() + "@example.test") + .get(0, UUID.class); + new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(tenant); + dsl.execute( + "INSERT INTO account_tenant_creation_bootstrap_operations " + + "(request_id, schema_version, initiating_account_uuid, tenant_uuid, creation_request_id, " + + "creation_operation_id, account_authorization_operation_id, account_authorization_digest, " + + "creator_evidence_digest, creator_evidence_payload, source_snapshot_payload, source_snapshot_digest, " + + "request_payload, request_digest, baseline_membership_version, baseline_membership_authority_generation, " + + "baseline_event_sequence, status) " + + "VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, 0, 'IN_PROGRESS')", + bootstrap, + account, + tenant.canonicalTenantId(), + tenant.creationRequestId(), + tenant.operationId(), + bootstrap, + digest('d'), + tenant.evidenceDigest(), + new byte[] {1}, + new byte[] {2}, + digest('e'), + new byte[] {3}, + digest('f')); + dsl.execute( + "UPDATE account_tenant_creation_bootstrap_operations SET membership_id = 1, membership_version = 2, " + + "membership_authority_generation = 1, membership_lifecycle_state = 'ACTIVE', gameplay_admission_allowed = FALSE, " + + "membership_roles_payload = convert_to('[\"tenantAdmin\"]', 'UTF8'), event_stream_key = ?, " + + "event_request_id = ?, event_sequence = 1, event_id = ?, event_digest = ?, event_payload = ?, " + + "audit_event_id = ?, audit_event_type = 'ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED', " + + "audit_occurred_at = CURRENT_TIMESTAMP, audit_payload_digest = ?, audit_payload = ?, result_payload = ?, " + + "result_digest = ?, status = 'COMMITTED' WHERE request_id = ?", + "account:auth-authority:v1:membership/" + account + "/" + tenant.canonicalTenantId(), + bootstrap.toString(), + "lineage-bootstrap-" + bootstrap, + digest('1'), + new byte[] {4}, + UUID.randomUUID(), + digest('2'), + new byte[] {5}, + new byte[] {6}, + digest('3'), + bootstrap); + }); + return tenant; + } + + @SuppressWarnings("unchecked") + private static AccountTenantCapacityOwner capacityOwner( + DSLContext dsl, + DataSourceTransactionManager transactions, + TenantCapacityAdmission.Request request) { + var player = (TenantCapacityAdmission.PlayerContext) request.context(); + var parsed = + RuntimePlayerAdmissionEntitlementEvidence.parseCanonical( + request.evidence().canonicalBytes()); + AccountRepository accounts = mock(AccountRepository.class); + when(accounts.findByAccountUuidForUpdate(player.accountId())) + .thenReturn(Optional.of(new Account())); + AccountCanonicalRuntimeMembershipSnapshotRepository memberships = + mock(AccountCanonicalRuntimeMembershipSnapshotRepository.class); + when(memberships.readCurrent(player.accountId(), player.tenantId())) + .thenReturn(parsed.membershipSource()); + + Map evidenceFields = request.evidence().fields(); + Map sourceReferences = + (Map) evidenceFields.get("sourceReferences"); + Map target = (Map) evidenceFields.get("target"); + UUID tokenJti = UUID.fromString((String) sourceReferences.get("callerTokenJti")); + UUID callerContextId = UUID.fromString((String) sourceReferences.get("callerContextId")); + UUID operationId = UUID.fromString((String) sourceReferences.get("callerOperationId")); + long now = Instant.now().getEpochSecond(); + var issuanceIdentity = + new AccountGameplayDelegationPendingIdentity( + operationId, + request.identity().requestId(), + player.accountId(), + request.evidence().callerWorkload(), + callerContextId, + new AccountGameplayCredentialRequestBinding(1, "fixture", "f".repeat(64)), + "e".repeat(64), + tokenJti, + now - 10, + now - 10, + now + 3600); + var issuance = + mock(AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData.class); + when(issuance.identity()).thenReturn(issuanceIdentity); + when(issuance.tokenSha256()).thenReturn((String) sourceReferences.get("callerTokenSha256")); + when(issuance.canonicalRegistryRecordSha256()) + .thenReturn((String) sourceReferences.get("callerRegistryRecordSha256")); + when(issuance.commitProofSha256()) + .thenReturn((String) sourceReferences.get("callerCommitProofSha256")); + AccountGameplayDelegationIssuanceRepository issuances = + mock(AccountGameplayDelegationIssuanceRepository.class); + when(issuances.readCurrentCommittedCandidateByJti(tokenJti)).thenReturn(Optional.of(issuance)); + + var scope = mock(AccountConnectScopeRepository.CanonicalConnectScopeEvidence.class); + when(scope.accountUuid()).thenReturn(player.accountId()); + when(scope.tenantUuid()).thenReturn(player.tenantId()); + when(scope.scopeDigest()).thenReturn((String) sourceReferences.get("scopeDigest")); + when(scope.gameInstanceUuid()).thenReturn(player.gameInstanceId()); + when(scope.playableStateNamespaceUuid()).thenReturn(player.playableStateNamespaceId()); + when(scope.realmId()).thenReturn(player.realmId()); + when(scope.playableStateScope()).thenReturn(player.playableStateScope()); + when(scope.connectScopeExpiresAt()).thenReturn((String) target.get("connectScopeExpiresAt")); + AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); + when(scopes.findCanonicalEvidenceByTokenHash(parsed.verifiedConnectScopeTokenHash())) + .thenReturn(Optional.of(scope)); + + return new AccountTenantCapacityOwner( + dsl, accounts, memberships, issuances, scopes, transactions, Clock.systemUTC(), "prod"); + } + + @SuppressWarnings("unchecked") + private static TenantCapacityAdmission.Request playerRequest( + UUID tenantId, + UUID requestId, + UUID admissionId, + UUID attemptId, + Instant at, + Instant scopeExpiry) { + var template = CapacityAdmissionTestFixture.playerRequest(); + var original = (TenantCapacityAdmission.PlayerContext) template.context(); + var player = + new TenantCapacityAdmission.PlayerContext( + original.accountId(), + tenantId, + original.playableStateNamespaceId(), + original.gameInstanceId(), + original.characterId(), + original.sessionId(), + original.realmId(), + requestId, + original.playableStateScope()); + var target = + new LinkedHashMap( + (Map) template.evidence().fields().get("target")); + target.put("tenantId", tenantId.toString()); + target.put("evaluatedAt", at.toString()); + target.put("connectScopeExpiresAt", scopeExpiry.toString()); + return CapacityAdmissionTestFixture.playerRequestFor( + player, admissionId, attemptId, "prod", target, at); + } + + private static void insertEvaluation( + DSLContext dsl, + TenantCapacityAdmission.Request request, + Instant evaluatedAt, + Instant expiresAt) { + dsl.execute( + "INSERT INTO account_tenant_capacity_evaluations " + + "(evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, owner_service, " + + "canonical_evidence, evaluated_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz)", + request.evidence().evaluationIdentity(), + request.evidence().snapshotIdentity(), + request.identity().tenantId(), + request.evidence().callerWorkload(), + request.context().owner().service(), + request.evidence().canonicalBytes(), + evaluatedAt.toString(), + expiresAt.toString()); + } + + private static void waitUntil(Instant deadline) throws InterruptedException { + long remainingMillis = Duration.between(Instant.now(), deadline).toMillis(); + if (remainingMillis > 0) Thread.sleep(remainingMillis); + } + private static FreshTenantCreationEvidence source() { UUID request = UUID.randomUUID(), operation = UUID.randomUUID(), tenant = UUID.randomUUID(); String slug = "retention-" + UUID.randomUUID().toString().substring(0, 8); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionInspectionOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionInspectionOwnerTest.java index 3b3c35ec8f..385aa1b127 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionInspectionOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionInspectionOwnerTest.java @@ -1,11 +1,13 @@ -package unit.net.firedevops.firemud.accountservice.service; +package net.firedevops.firemud.accountservice.service; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -13,8 +15,13 @@ import java.time.Instant; import java.time.OffsetDateTime; import java.time.ZoneOffset; -import net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionInspectionOwner; +import java.util.List; +import java.util.Map; +import java.util.UUID; import net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionInspectionOwner.Blocker; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.Result; @@ -116,6 +123,224 @@ void emptyTableHasNoInventedOldestBlockerAndCatalogEstimateStaysExplicit() { verify(dsl).fetch(anyString(), eq(1001)); } + @Test + void currentPolicyUsesExactHistoryLineageAndLeavesAnUnrelatedEvaluationUnblocked() { + DSLContext dsl = mock(DSLContext.class); + metadata(dsl); + TenantCapacityAdmission.Request request = CapacityAdmissionTestFixture.playerRequest(); + String referencedIdentity = request.evidence().evaluationIdentity(); + String unrelatedIdentity = "sha256:" + "c".repeat(64); + Result samples = result(); + when(samples.size()).thenReturn(2); + Instant evaluated = NOW.minusSeconds(10 * 86400L); + doReturn(sample(referencedIdentity, true, false, evaluated)).when(samples).get(0); + doReturn(sample(unrelatedIdentity, true, false, evaluated)).when(samples).get(1); + Result reservations = result(); + when(reservations.size()).thenReturn(1); + when(reservations.iterator()).thenAnswer(ignored -> List.of(reservations.get(0)).iterator()); + doReturn(reservation(request)).when(reservations).get(0); + Result historyKeys = result(); + when(historyKeys.size()).thenReturn(1); + when(historyKeys.iterator()).thenAnswer(ignored -> List.of(historyKeys.get(0)).iterator()); + doReturn(historyKey(request)).when(historyKeys).get(0); + Result payloads = result(); + when(payloads.size()).thenReturn(1); + when(payloads.iterator()).thenAnswer(ignored -> List.of(payloads.get(0)).iterator()); + doReturn(historyPayload(request)).when(payloads).get(0); + when(dsl.fetch(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String query = invocation.getArgument(0); + if (query.contains("WITH sample AS MATERIALIZED")) return samples; + if (query.contains("WITH scopes(tenant_uuid")) return reservations; + if (query.contains("WITH reservations(tenant_uuid")) return historyKeys; + if (query.contains("WITH selected(tenant_uuid")) return payloads; + throw new AssertionError("Unexpected inspection query: " + query); + }); + + var observation = + owner(dsl).observe(2, schedule(), safety(referencedIdentity, unrelatedIdentity)); + + assertThat(observation.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows()).isEqualTo(1); + assertThat(observation.candidates().rows()).isEqualTo(1); + assertThat(observation.governanceBlocker()).isNull(); + verify(dsl, times(4)).fetch(anyString(), any(Object[].class)); + } + + @Test + void historyAbovePerScopeBoundFailsClosedWithoutReadingPayloads() { + DSLContext dsl = mock(DSLContext.class); + metadata(dsl); + TenantCapacityAdmission.Request request = CapacityAdmissionTestFixture.playerRequest(); + Result samples = result(); + when(samples.size()).thenReturn(1); + doReturn(sample("sha256:" + "c".repeat(64), true, false, NOW.minusSeconds(10 * 86400L))) + .when(samples) + .get(0); + Result reservations = result(); + when(reservations.size()).thenReturn(1); + when(reservations.iterator()).thenAnswer(ignored -> List.of(reservations.get(0)).iterator()); + doReturn(reservation(request)).when(reservations).get(0); + Result historyKeys = result(); + when(historyKeys.size()).thenReturn(9); + when(historyKeys.iterator()) + .thenAnswer( + ignored -> + java.util.stream.IntStream.range(0, 9).mapToObj(historyKeys::get).iterator()); + for (int index = 0; index < 9; index++) { + doReturn(historyKey(request, UUID.randomUUID())).when(historyKeys).get(index); + } + when(dsl.fetch(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String query = invocation.getArgument(0); + if (query.contains("WITH sample AS MATERIALIZED")) return samples; + if (query.contains("WITH scopes(tenant_uuid")) return reservations; + if (query.contains("WITH reservations(tenant_uuid")) return historyKeys; + throw new AssertionError("Over-limit lineage must not fetch payload bytes"); + }); + + var observation = owner(dsl).observe(1, schedule(), safety("sha256:" + "c".repeat(64))); + + assertThat(observation.candidates().rows()).isZero(); + assertThat(observation.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows()).isOne(); + } + + @Test + void malformedHistoryPayloadFailsClosedForItsScope() { + DSLContext dsl = mock(DSLContext.class); + metadata(dsl); + TenantCapacityAdmission.Request request = CapacityAdmissionTestFixture.playerRequest(); + Result samples = result(); + when(samples.size()).thenReturn(1); + doReturn(sample("sha256:" + "c".repeat(64), true, false, NOW.minusSeconds(10 * 86400L))) + .when(samples) + .get(0); + Result reservations = result(); + when(reservations.size()).thenReturn(1); + when(reservations.iterator()).thenAnswer(ignored -> List.of(reservations.get(0)).iterator()); + doReturn(reservation(request)).when(reservations).get(0); + Result historyKeys = result(); + when(historyKeys.size()).thenReturn(1); + when(historyKeys.iterator()).thenAnswer(ignored -> List.of(historyKeys.get(0)).iterator()); + doReturn(historyKey(request)).when(historyKeys).get(0); + Result payloads = result(); + when(payloads.size()).thenReturn(1); + when(payloads.iterator()).thenAnswer(ignored -> List.of(payloads.get(0)).iterator()); + Record malformed = historyPayload(request); + when(malformed.get("canonical_payload", byte[].class)).thenReturn(new byte[] {1}); + doReturn(malformed).when(payloads).get(0); + when(dsl.fetch(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String query = invocation.getArgument(0); + if (query.contains("WITH sample AS MATERIALIZED")) return samples; + if (query.contains("WITH scopes(tenant_uuid")) return reservations; + if (query.contains("WITH reservations(tenant_uuid")) return historyKeys; + if (query.contains("WITH selected(tenant_uuid")) return payloads; + throw new AssertionError("Unexpected inspection query: " + query); + }); + + var observation = owner(dsl).observe(1, schedule(), safety("sha256:" + "c".repeat(64))); + + assertThat(observation.candidates().rows()).isZero(); + assertThat(observation.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows()).isOne(); + } + + @Test + void missingFenceInRetainedHistoryChainFailsClosed() { + DSLContext dsl = mock(DSLContext.class); + metadata(dsl); + TenantCapacityAdmission.Request request = CapacityAdmissionTestFixture.playerRequest(); + Result samples = result(); + when(samples.size()).thenReturn(1); + doReturn(sample("sha256:" + "c".repeat(64), true, false, NOW.minusSeconds(10 * 86400L))) + .when(samples) + .get(0); + Result reservations = result(); + when(reservations.size()).thenReturn(1); + when(reservations.iterator()).thenAnswer(ignored -> List.of(reservations.get(0)).iterator()); + doReturn(reservation(request, 3L)).when(reservations).get(0); + Result historyKeys = result(); + when(historyKeys.size()).thenReturn(1); + when(historyKeys.iterator()).thenAnswer(ignored -> List.of(historyKeys.get(0)).iterator()); + doReturn(historyKey(request)).when(historyKeys).get(0); + when(dsl.fetch(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String query = invocation.getArgument(0); + if (query.contains("WITH sample AS MATERIALIZED")) return samples; + if (query.contains("WITH scopes(tenant_uuid")) return reservations; + if (query.contains("WITH reservations(tenant_uuid")) return historyKeys; + throw new AssertionError( + "A gap in the fence chain must be found before payload reads"); + }); + + var observation = owner(dsl).observe(1, schedule(), safety("sha256:" + "c".repeat(64))); + + assertThat(observation.candidates().rows()).isZero(); + assertThat(observation.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows()).isOne(); + } + + @Test + void aggregateHistoryBoundFailsClosedForAllQueriedScopesWithoutPayloadReads() { + DSLContext dsl = mock(DSLContext.class); + metadata(dsl); + Result samples = result(); + Result reservations = result(); + Result historyKeys = result(); + int scopeCount = 4; + when(samples.size()).thenReturn(scopeCount); + when(reservations.size()).thenReturn(scopeCount); + when(reservations.iterator()) + .thenAnswer( + ignored -> + java.util.stream.IntStream.range(0, scopeCount) + .mapToObj(reservations::get) + .iterator()); + when(historyKeys.size()).thenReturn(33); + Instant evaluated = NOW.minusSeconds(10 * 86400L); + List identities = new java.util.ArrayList<>(); + for (int scopeIndex = 0; scopeIndex < scopeCount; scopeIndex++) { + UUID tenantId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID admissionId = UUID.randomUUID(); + UUID evaluationId = UUID.randomUUID(); + String identity = "sha256:" + evaluationId.toString().replace("-", ""); + identities.add(identity); + doReturn(sample(identity, tenantId, true, false, evaluated)).when(samples).get(scopeIndex); + doReturn(reservation(tenantId, requestId, admissionId)).when(reservations).get(scopeIndex); + } + for (int index = 0; index < 33; index++) { + int scopeIndex = index % scopeCount; + Record reservation = reservations.get(scopeIndex); + doReturn( + historyKey( + reservation.get("tenant_uuid", UUID.class), + reservation.get("request_id", UUID.class), + reservation.get("admission_id", UUID.class), + UUID.randomUUID())) + .when(historyKeys) + .get(index); + } + when(dsl.fetch(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String query = invocation.getArgument(0); + if (query.contains("WITH sample AS MATERIALIZED")) return samples; + if (query.contains("WITH scopes(tenant_uuid")) return reservations; + if (query.contains("WITH reservations(tenant_uuid")) return historyKeys; + throw new AssertionError("Aggregate over-limit lineage must not fetch payload bytes"); + }); + + var observation = owner(dsl).observe(4, schedule(), safety(identities.toArray(String[]::new))); + + assertThat(observation.candidates().rows()).isZero(); + assertThat(observation.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows()) + .isEqualTo(scopeCount); + verify(dsl, times(3)).fetch(anyString(), any(Object[].class)); + } + @SuppressWarnings("unchecked") private static Result result() { return mock(Result.class); @@ -124,6 +349,8 @@ private static Result result() { private static Record row(Instant evaluated, Instant expires, boolean referenced, long bytes) { Record row = mock(Record.class); when(row.get("evaluation_identity", String.class)).thenReturn("sha256:" + "a".repeat(64)); + when(row.get("tenant_uuid", UUID.class)).thenReturn(CapacityAdmissionTestFixture.TENANT); + when(row.get("owner_service", String.class)).thenReturn("game-session-service"); when(row.get("evaluated_at", OffsetDateTime.class)).thenReturn(at(evaluated)); when(row.get("expires_at", OffsetDateTime.class)).thenReturn(at(expires)); when(row.get("scope_referenced", Boolean.class)).thenReturn(referenced); @@ -131,6 +358,133 @@ private static Record row(Instant evaluated, Instant expires, boolean referenced return row; } + private static Record metadata(DSLContext dsl) { + Record metadata = mock(Record.class); + when(metadata.get("observed_at", OffsetDateTime.class)).thenReturn(at(NOW)); + when(metadata.get("relation_bytes", Long.class)).thenReturn(4096L); + when(metadata.get("estimated_rows", Long.class)).thenReturn(2L); + when(dsl.fetchOne(anyString())).thenReturn(metadata); + return metadata; + } + + private static AccountCapacityEvaluationRetentionInspectionOwner owner(DSLContext dsl) { + return new AccountCapacityEvaluationRetentionInspectionOwner(dsl, new ReadTransactions()); + } + + private static AccountCapacityEvaluationRetentionPolicy.Schedule schedule() { + return new AccountCapacityEvaluationRetentionPolicy.Schedule( + "fixture/v1", + java.time.Duration.ofDays(30), + java.time.Duration.ofDays(2), + java.time.Duration.ofDays(3), + java.time.Duration.ofDays(4), + java.time.Duration.ofDays(5), + java.time.Duration.ofDays(6)); + } + + private static AccountCapacityEvaluationRetentionPolicy.Safety safety(String... identities) { + Map holds = new java.util.HashMap<>(); + for (String identity : identities) + holds.put(identity, AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR); + return new AccountCapacityEvaluationRetentionPolicy.Safety( + "fixture/v1", NOW.minusSeconds(1), NOW.plusSeconds(60), NOW.minusSeconds(1), holds); + } + + private static Record sample( + String identity, boolean scopeReferenced, boolean direct, Instant evaluated) { + return sample( + identity, CapacityAdmissionTestFixture.TENANT, scopeReferenced, direct, evaluated); + } + + private static Record sample( + String identity, UUID tenantId, boolean scopeReferenced, boolean direct, Instant evaluated) { + Record row = mock(Record.class); + when(row.get("evaluation_identity", String.class)).thenReturn(identity); + when(row.get("tenant_uuid", UUID.class)).thenReturn(tenantId); + when(row.get("owner_service", String.class)).thenReturn("game-session-service"); + when(row.get("evaluated_at", OffsetDateTime.class)).thenReturn(at(evaluated)); + when(row.get("expires_at", OffsetDateTime.class)).thenReturn(at(evaluated.plusSeconds(1))); + when(row.get("evidence_bytes", Long.class)).thenReturn(10L); + when(row.get("scope_referenced", Boolean.class)).thenReturn(scopeReferenced); + when(row.get("directly_referenced", Boolean.class)).thenReturn(direct); + return row; + } + + private static Record reservation(TenantCapacityAdmission.Request request) { + return reservation(request, 2L); + } + + private static Record reservation(TenantCapacityAdmission.Request request, long rearmFence) { + Record row = + reservation( + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId()); + when(row.get("owner_service", String.class)).thenReturn(request.context().owner().service()); + when(row.get("caller_workload", String.class)).thenReturn(request.evidence().callerWorkload()); + when(row.get("capacity_rearm_fence", Long.class)).thenReturn(rearmFence); + return row; + } + + private static Record reservation(UUID tenantId, UUID requestId, UUID admissionId) { + Record row = mock(Record.class); + when(row.get("tenant_uuid", UUID.class)).thenReturn(tenantId); + when(row.get("owner_service", String.class)).thenReturn("game-session-service"); + when(row.get("request_id", UUID.class)).thenReturn(requestId); + when(row.get("admission_id", UUID.class)).thenReturn(admissionId); + when(row.get("capacity_rearm_fence", Long.class)).thenReturn(2L); + when(row.get("caller_workload", String.class)).thenReturn("test-workload"); + return row; + } + + private static Record historyKey(TenantCapacityAdmission.Request request) { + return historyKey(request, request.admissionAttemptId()); + } + + private static Record historyKey(TenantCapacityAdmission.Request request, UUID attemptId) { + Record row = + historyKey( + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + attemptId); + when(row.get("owner_service", String.class)).thenReturn(request.context().owner().service()); + when(row.get("capacity_rearm_fence", Long.class)).thenReturn(request.capacityRearmFence()); + when(row.get("mutation_digest", String.class)).thenReturn(request.mutationDigest()); + when(row.get("caller_workload", String.class)).thenReturn(request.evidence().callerWorkload()); + when(row.get("payload_bytes", Long.class)) + .thenReturn((long) CapacityAdmissionDigest.preimage(request).length); + return row; + } + + private static Record historyKey( + UUID tenantId, UUID requestId, UUID admissionId, UUID attemptId) { + Record row = mock(Record.class); + when(row.get("tenant_uuid", UUID.class)).thenReturn(tenantId); + when(row.get("owner_service", String.class)).thenReturn("game-session-service"); + when(row.get("request_id", UUID.class)).thenReturn(requestId); + when(row.get("admission_id", UUID.class)).thenReturn(admissionId); + when(row.get("admission_attempt_id", UUID.class)).thenReturn(attemptId); + when(row.get("caller_workload", String.class)).thenReturn("test-workload"); + when(row.get("capacity_rearm_fence", Long.class)).thenReturn(1L); + when(row.get("mutation_digest", String.class)).thenReturn("f".repeat(64)); + when(row.get("payload_bytes", Long.class)).thenReturn(1L); + return row; + } + + private static Record historyPayload(TenantCapacityAdmission.Request request) { + Record row = mock(Record.class); + when(row.get("tenant_uuid", UUID.class)).thenReturn(request.identity().tenantId()); + when(row.get("request_id", UUID.class)).thenReturn(request.identity().requestId()); + when(row.get("admission_id", UUID.class)).thenReturn(request.identity().admissionId()); + when(row.get("admission_attempt_id", UUID.class)).thenReturn(request.admissionAttemptId()); + when(row.get("capacity_rearm_fence", Long.class)).thenReturn(request.capacityRearmFence()); + when(row.get("mutation_digest", String.class)).thenReturn(request.mutationDigest()); + when(row.get("canonical_payload", byte[].class)) + .thenReturn(CapacityAdmissionDigest.preimage(request)); + return row; + } + private static OffsetDateTime at(Instant value) { return value.atOffset(ZoneOffset.UTC); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionPolicyTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionPolicyTest.java index ed452c2397..053515bc2c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionPolicyTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionPolicyTest.java @@ -186,6 +186,7 @@ private static Record evaluation(String identity, boolean referenced) { when(row.get("expires_at", OffsetDateTime.class)).thenReturn(EXPIRES.atOffset(ZoneOffset.UTC)); when(row.get("evidence_bytes", Long.class)).thenReturn(12L); when(row.get("scope_referenced", Boolean.class)).thenReturn(referenced); + when(row.get("directly_referenced", Boolean.class)).thenReturn(referenced); return row; } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigest.java index 5536f68777..a2024da01d 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigest.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigest.java @@ -1,12 +1,18 @@ package net.firedevops.firemud.common.account.capacity; import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.Normalizer; +import java.util.Arrays; import java.util.Base64; import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.PlayerContext; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Shape; @@ -117,6 +123,122 @@ public static String digest(Request request) { } } + /** + * Decodes the one canonical capacity-admission/1 preimage accepted for a new committable + * admission. The digest and Account evidence remain content bindings, not proof of authority. + */ + public static Request decodeCommittable(byte[] canonicalPreimage, String mutationDigest) { + try { + if (canonicalPreimage == null + || canonicalPreimage.length == 0 + || canonicalPreimage.length > MAX_PREIMAGE_BYTES + || mutationDigest == null + || mutationDigest.length() != 64 + || !mutationDigest.matches("[0-9a-f]{64}")) throw invalid(); + + byte[] preimageBytes = canonicalPreimage.clone(); + var parser = new Frame(preimageBytes); + if (!"mutationDigest/v1".equals(parser.segment())) throw invalid(); + Map fields = parser.fields(7, 0); + if (!parser.done() + || !TenantCapacityAdmission.SCHEMA_ID.equals(text(fields, "actionFamilySchemaId")) + || !TenantCapacityAdmission.SCHEMA_VERSION.equals( + text(fields, "actionFamilySchemaVersion"))) throw invalid(); + + var scope = object(fields, "scope"); + var target = object(fields, "target"); + var expected = object(fields, "expectedVersion"); + var mutation = object(fields, "mutation"); + var identity = + new TenantCapacityAdmission.Identity( + uuid(scope, "tenantId"), uuid(scope, "requestId"), uuid(scope, "admissionId")); + + String ownerService = text(target, "ownerService"); + var contextFields = object(target, "ownerContext"); + TenantCapacityAdmission.OwnerContext context; + TenantCapacityAdmission.Owner owner; + if (TenantCapacityAdmission.Owner.GAME_SESSION.service().equals(ownerService)) { + owner = TenantCapacityAdmission.Owner.GAME_SESSION; + context = + new PlayerContext( + uuid(contextFields, "accountId"), + uuid(contextFields, "tenantId"), + uuid(contextFields, "playableStateNamespaceId"), + uuid(contextFields, "gameInstanceId"), + uuid(contextFields, "characterId"), + uuid(contextFields, "sessionId"), + uuid(contextFields, "realmId"), + uuid(contextFields, "requestId"), + text(contextFields, "playableStateScope")); + } else if (TenantCapacityAdmission.Owner.WORLD_MANAGEMENT.service().equals(ownerService)) { + owner = TenantCapacityAdmission.Owner.WORLD_MANAGEMENT; + context = + new WorldContext( + uuid(contextFields, "tenantId"), + uuid(contextFields, "operationId"), + uuid(contextFields, "lifecycleId"), + uuid(contextFields, "gameInstanceId"), + uuid(contextFields, "ownerId"), + number(contextFields, "ownerFence")); + } else { + throw invalid(); + } + + Object rawCapacityDelta = mutation.get("capacityDelta"); + Long capacityDelta; + if (rawCapacityDelta == null) capacityDelta = null; + else if (rawCapacityDelta instanceof Long value) capacityDelta = value; + else throw invalid(); + Request request = + new Request( + identity, + uuid(expected, "admissionAttemptId"), + number(expected, "capacityRearmFence"), + text(target, "targetNamespace"), + context, + TenantCapacityAdmission.Operation.valueOf(text(mutation, "operation")), + shape(object(mutation, "priorShape")), + shape(object(mutation, "requestedShape")), + TenantCapacityAdmission.Evidence.parse( + Base64.getDecoder().decode(text(mutation, "accountEvidence")), owner), + capacityDelta, + mutationDigest); + if (!Arrays.equals(preimageBytes, preimage(request))) throw invalid(); + request.requireCommittable(); + return request; + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + private static Map object(Map fields, String key) { + if (!(fields.get(key) instanceof Map value)) throw invalid(); + @SuppressWarnings("unchecked") + Map result = (Map) value; + return result; + } + + private static String text(Map fields, String key) { + if (!(fields.get(key) instanceof String value)) throw invalid(); + return value; + } + + private static long number(Map fields, String key) { + if (!(fields.get(key) instanceof Long value)) throw invalid(); + return value; + } + + private static java.util.UUID uuid(Map fields, String key) { + return java.util.UUID.fromString(text(fields, key)); + } + + private static Shape shape(Map fields) { + return new Shape( + number(fields, "activeSessions"), + number(fields, "concurrentGameInstances"), + number(fields, "storageBytes")); + } + private static byte[] shape(Shape shape) { return object( "activeSessions", @@ -185,4 +307,102 @@ private static byte[] ascii(String value) { private static IllegalArgumentException invalid() { return new IllegalArgumentException("Invalid capacity-admission/1 canonical value"); } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException malformed) { + throw invalid(); + } + } + + /** Bounded parser for the shared ADR 0047 frame grammar. */ + private static final class Frame { + private final byte[] data; + private int offset; + + private Frame(byte[] data) { + if (data == null || data.length > MAX_PREIMAGE_BYTES) throw invalid(); + this.data = data; + } + + private String segment() { + return decodeUtf8(segmentBytes()); + } + + private byte[] segmentBytes() { + int start = offset; + while (offset < data.length && data[offset] >= '0' && data[offset] <= '9') offset++; + int digits = offset - start; + if (digits == 0 + || digits > 7 + || offset >= data.length + || data[offset++] != ':' + || (digits > 1 && data[start] == '0')) throw invalid(); + int size; + try { + size = Integer.parseInt(new String(data, start, digits, StandardCharsets.US_ASCII)); + } catch (NumberFormatException malformed) { + throw invalid(); + } + if (size < 0 || size > MAX_SEGMENT_BYTES || size > data.length - offset) throw invalid(); + byte[] result = Arrays.copyOfRange(data, offset, offset + size); + offset += size; + return result; + } + + private Map fields(int count, int depth) { + if (count < 0 || count > 16 || depth > 8) throw invalid(); + Map result = new LinkedHashMap<>(); + for (int index = 0; index < count; index++) { + String name = segment(); + String type = segment(); + if (offset >= data.length) throw invalid(); + byte presence = data[offset++]; + byte[] payload = segmentBytes(); + Object value; + if ("object".equals(type) && presence == '1') { + Frame nested = new Frame(payload); + Map object = nested.fields(parseCount(nested.segment()), depth + 1); + if (!nested.done()) throw invalid(); + value = object; + } else if ("string".equals(type) && presence == '1') { + value = decodeUtf8(payload); + } else if ("number".equals(type) && presence == '1') { + String number = decodeUtf8(payload); + if (!number.matches("0|[1-9][0-9]{0,18}")) throw invalid(); + try { + value = Long.parseLong(number); + } catch (NumberFormatException overflow) { + throw invalid(); + } + } else if ("absent".equals(type) && presence == '0' && payload.length == 0) { + value = null; + } else { + throw invalid(); + } + if (result.containsKey(name)) throw invalid(); + result.put(name, value); + } + return result; + } + + private static int parseCount(String value) { + if (value == null || !value.matches("0|[1-9][0-9]{0,1}")) throw invalid(); + try { + return Integer.parseInt(value); + } catch (NumberFormatException malformed) { + throw invalid(); + } + } + + private boolean done() { + return offset == data.length; + } + } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java index a8f6b0e863..53bb3b9041 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.Base64; import java.util.HexFormat; import java.util.List; @@ -20,6 +21,38 @@ /** Shared vectors prove content encoding only, never a current Account or runtime grant. */ class CapacityAdmissionDigestTest { + @Test + void decodesCommittablePreimagesForPlayerAndWorldOwners() { + for (Request request : + List.of( + CapacityAdmissionTestFixture.playerRequest(), + CapacityAdmissionTestFixture.worldRequest(17L))) { + assertThat( + CapacityAdmissionDigest.decodeCommittable( + CapacityAdmissionDigest.preimage(request), request.mutationDigest())) + .isEqualTo(request); + } + } + + @Test + void rejectsMalformedPreimagesAndInvalidOrIncorrectDigests() { + Request request = CapacityAdmissionTestFixture.playerRequest(); + byte[] preimage = CapacityAdmissionDigest.preimage(request); + byte[] trailing = Arrays.copyOf(preimage, preimage.length + 1); + trailing[trailing.length - 1] = 'x'; + String incorrectDigest = + (request.mutationDigest().charAt(0) == '0' ? "1" : "0") + + request.mutationDigest().substring(1); + + assertThatThrownBy( + () -> CapacityAdmissionDigest.decodeCommittable(trailing, request.mutationDigest())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> CapacityAdmissionDigest.decodeCommittable(preimage, "bad-digest")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> CapacityAdmissionDigest.decodeCommittable(preimage, incorrectDigest)) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void sharedCorpusFixesCompleteEvidenceAndAbsentZeroPositiveBoundaryPreimages() throws Exception { var resource = getClass().getResourceAsStream("/capacity/capacity-admission-v1-vectors.json"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java index 275ee9f1b5..ac89742286 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerTransferRepository.java @@ -6,9 +6,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.function.Function; @@ -916,43 +914,10 @@ static OriginalNewCapacityExecution decode(byte[] canonical) { throw unavailable(); JsonNode node = JSON.readTree(canonical); byte[] payload = Base64.getDecoder().decode(node.get("canonicalAttemptPayload").textValue()); - var parser = new Frame(payload); - if (!"mutationDigest/v1".equals(parser.segment())) throw unavailable(); - Map fields = parser.fields(7, 0); - var scope = object(fields, "scope"); - var target = object(fields, "target"); - var player = object(target, "ownerContext"); - var expected = object(fields, "expectedVersion"); - var mutation = object(fields, "mutation"); - var identity = - new TenantCapacityAdmission.Identity( - uuid(scope, "tenantId"), uuid(scope, "requestId"), uuid(scope, "admissionId")); var request = - new TenantCapacityAdmission.Request( - identity, - uuid(expected, "admissionAttemptId"), - number(expected, "capacityRearmFence"), - text(target, "targetNamespace"), - new TenantCapacityAdmission.PlayerContext( - uuid(player, "accountId"), - uuid(player, "tenantId"), - uuid(player, "playableStateNamespaceId"), - uuid(player, "gameInstanceId"), - uuid(player, "characterId"), - uuid(player, "sessionId"), - uuid(player, "realmId"), - uuid(player, "requestId"), - text(player, "playableStateScope")), - TenantCapacityAdmission.Operation.valueOf(text(mutation, "operation")), - shape(object(mutation, "priorShape")), - shape(object(mutation, "requestedShape")), - TenantCapacityAdmission.Evidence.parse( - Base64.getDecoder().decode(text(mutation, "accountEvidence")), - TenantCapacityAdmission.Owner.GAME_SESSION), - number(mutation, "capacityDelta"), - node.get("mutationDigest").textValue()); - if (!parser.done() || !Arrays.equals(payload, CapacityAdmissionDigest.preimage(request))) - throw unavailable(); + CapacityAdmissionDigest.decodeCommittable( + payload, node.get("mutationDigest").textValue()); + var identity = request.identity(); var reservation = new TenantCapacityAdmission.Result( identity, @@ -980,33 +945,6 @@ static OriginalNewCapacityExecution decode(byte[] canonical) { } } - private static TenantCapacityAdmission.Shape shape(Map value) { - return new TenantCapacityAdmission.Shape( - number(value, "activeSessions"), - number(value, "concurrentGameInstances"), - number(value, "storageBytes")); - } - - @SuppressWarnings("unchecked") - private static Map object(Map value, String key) { - if (!(value.get(key) instanceof Map)) throw unavailable(); - return (Map) value.get(key); - } - - private static String text(Map value, String key) { - if (!(value.get(key) instanceof String text)) throw unavailable(); - return text; - } - - private static long number(Map value, String key) { - if (!(value.get(key) instanceof Long number)) throw unavailable(); - return number; - } - - private static UUID uuid(Map value, String key) { - return UUID.fromString(text(value, key)); - } - private static byte[] bytes(String text) { return text.getBytes(StandardCharsets.UTF_8); } @@ -1029,56 +967,6 @@ private static IllegalStateException unavailable() { return new IllegalStateException("Normal region owner transfer is held"); } - private static final class Frame { - private final byte[] data; - private int offset; - - private Frame(byte[] data) { - if (data.length > CapacityAdmissionDigest.MAX_PREIMAGE_BYTES) throw unavailable(); - this.data = data; - } - - private String segment() { - int start = offset; - while (offset < data.length && data[offset] >= '0' && data[offset] <= '9') offset++; - if (offset == start || offset >= data.length || data[offset++] != ':' || offset - start > 8) - throw unavailable(); - int size = - Integer.parseInt(new String(data, start, offset - start - 1, StandardCharsets.US_ASCII)); - if (size < 0 - || size > CapacityAdmissionDigest.MAX_SEGMENT_BYTES - || size > data.length - offset) throw unavailable(); - String result = new String(data, offset, size, StandardCharsets.UTF_8); - offset += size; - return result; - } - - private Map fields(int count, int depth) { - if (count < 0 || count > 16 || depth > 8) throw unavailable(); - Map result = new LinkedHashMap<>(); - for (int index = 0; index < count; index++) { - String name = segment(), type = segment(); - if (offset >= data.length || data[offset++] != '1') throw unavailable(); - String payload = segment(); - Object value; - if (type.equals("object")) { - Frame nested = new Frame(bytes(payload)); - value = nested.fields(Integer.parseInt(nested.segment()), depth + 1); - if (!nested.done()) throw unavailable(); - } else if (type.equals("string")) value = payload; - else if (type.equals("number") && payload.matches("0|[1-9][0-9]{0,18}")) - value = Long.parseLong(payload); - else throw unavailable(); - if (result.put(name, value) != null) throw unavailable(); - } - return result; - } - - private boolean done() { - return offset == data.length; - } - } - record FrozenOriginal( UUID transferId, String executionDigest, CanonicalGameplayOriginalNewCandidate candidate) {} From ec1c951c60825b53dcce8173650a23ddb81bba21 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:08:42 +1300 Subject: [PATCH 2/7] Match retained capacity fixture evidence to PostgreSQL precision --- ...EvaluationRetentionInspectionPostgresIntegrationTest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java index 872aec65e1..0fd15860f6 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java @@ -10,6 +10,7 @@ import java.time.Clock; import java.time.Duration; import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -79,7 +80,7 @@ void policyQualifiedInspectionFindsRearmedOldEvaluationAndLeavesUnrelatedRowCand var write = new TransactionTemplate(transactions); FreshTenantCreationEvidence tenant = bootstrapFreshTenant(dsl, write); - Instant priorAt = Instant.now(); + Instant priorAt = Instant.now().truncatedTo(ChronoUnit.MICROS); var prior = playerRequest( tenant.canonicalTenantId(), @@ -132,7 +133,7 @@ void policyQualifiedInspectionFindsRearmedOldEvaluationAndLeavesUnrelatedRowCand }); waitUntil(prior.evidence().expiresAt().plusMillis(100)); - Instant nextAt = Instant.now(); + Instant nextAt = Instant.now().truncatedTo(ChronoUnit.MICROS); var nextSeed = playerRequest( tenant.canonicalTenantId(), From 152bfbc6d27c3aca958f4731a05bbd595a5a5148 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 02:04:44 +1300 Subject: [PATCH 3/7] Use the shared capacity decoder in origin transfers --- .../CanonicalGameplayCapacityOriginTransferRepository.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginTransferRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginTransferRepository.java index 3b978d0559..3a67833418 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginTransferRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginTransferRepository.java @@ -6,6 +6,7 @@ import java.util.List; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; import net.firedevops.firemud.common.account.capacity.OriginalNewCapacityExecution; import org.jooq.DSLContext; import org.jooq.Record; @@ -550,7 +551,7 @@ private static byte[] encodeReadback(Item item, String state) { static CanonicalGameplayCapacityOrigin decodeOrigin(Record row) { var request = - net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest.decodeCommittable( + CapacityAdmissionDigest.decodeCommittable( row.get("canonical_request", byte[].class), row.get("mutation_digest", String.class)); var candidate = CanonicalGameplayOriginalNewCandidate.parseCanonical( From 6ce78aa70bab85927dec19b75b8685d490d3ecf4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 02:16:15 +1300 Subject: [PATCH 4/7] Seed exact capacity origin evidence in retention proof --- ...tionInspectionPostgresIntegrationTest.java | 20 +++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java index 0fd15860f6..17c68f100a 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java @@ -18,6 +18,7 @@ import java.util.UUID; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountCapacityOriginDecisionRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; @@ -108,6 +109,7 @@ void policyQualifiedInspectionFindsRearmedOldEvaluationAndLeavesUnrelatedRowCand unrelated, unrelated.evidence().evaluatedAt(), unrelated.evidence().expiresAt()); + new AccountCapacityOriginDecisionRepository(dsl).accept(prior); dsl.execute( "INSERT INTO account_tenant_capacity_reservations " + "(tenant_uuid, request_id, admission_id, reservation_id, owner_service, caller_workload, " @@ -426,6 +428,20 @@ private static void populate(DSLContext dsl, TransactionTemplate write) { evaluation[2], evaluation[3]); } + UUID attempt = UUID.randomUUID(); + byte[] capacityPayload = {7}; + dsl.execute( + "INSERT INTO account_capacity_origin_decisions " + + "(tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, " + + "mutation_digest, canonical_payload, decision, decision_id) " + + "VALUES (?, ?, ?, 1, ?, ?, ?, 'ACCEPTED', ?)", + tenant.canonicalTenantId(), + request, + admission, + attempt, + "e".repeat(64), + capacityPayload, + UUID.randomUUID()); dsl.execute( "INSERT INTO account_tenant_capacity_reservations (tenant_uuid, request_id, admission_id, reservation_id, " + "owner_service, caller_workload, admission_attempt_id, capacity_rearm_fence, reservation_fence, mutation_digest, " @@ -436,9 +452,9 @@ private static void populate(DSLContext dsl, TransactionTemplate write) { request, admission, UUID.randomUUID(), - UUID.randomUUID(), + attempt, "e".repeat(64), - new byte[] {7}, + capacityPayload, digest('b')); dsl.execute( "INSERT INTO account_tenant_capacity_attempt_history (tenant_uuid, request_id, admission_id, admission_attempt_id, " From 5642fce53ddd766fe00386d41de44bb2939838b8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 02:50:43 +1300 Subject: [PATCH 5/7] Test origin transfer with the shared capacity decoder --- ...meplayCapacityOriginTransferRepositoryTest.java | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginTransferRepositoryTest.java b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginTransferRepositoryTest.java index c5bdaee886..7368b0813e 100644 --- a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginTransferRepositoryTest.java +++ b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayCapacityOriginTransferRepositoryTest.java @@ -8,6 +8,7 @@ import java.nio.charset.StandardCharsets; import java.util.List; import java.util.UUID; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; import org.junit.jupiter.api.Test; /** Pure source contracts only. Controlled objects do not prove SQL/Redis custody or a handoff. */ @@ -197,16 +198,11 @@ void requestDecoderRefusesMissingAndNoncanonicalFrames() { new byte[0], "mutationDigest/v1".getBytes(StandardCharsets.US_ASCII), "0:trailing".getBytes(StandardCharsets.US_ASCII))) { - assertThatThrownBy( - () -> - CanonicalGameplayRegionOwnerTransferRepository.decodeRequest( - bytes, "a".repeat(64))) - .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> CapacityAdmissionDigest.decodeCommittable(bytes, "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - CanonicalGameplayRegionOwnerTransferRepository.decodeRequest(null, "a".repeat(64))) - .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> CapacityAdmissionDigest.decodeCommittable(null, "a".repeat(64))) + .isInstanceOf(IllegalArgumentException.class); } private static CanonicalGameplayCapacityOriginTransferRepository.Item item( From 71e1c27554b311c1efdd0467844664d90ed3bd6f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 06:17:39 +1300 Subject: [PATCH 6/7] Carry transfer-history fixture formatting --- ...untimeStatusRepositoryIntegrationTest.java | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index c51f441f05..81df295fc3 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -2583,8 +2583,14 @@ private TransferSqlProof( int maximumRetainedRecords, boolean withOtherCandidate) throws Exception { - this(listener, maximumRecords, maximumBindingBytes, maximumRetainedRecords, - 256, 1024, withOtherCandidate); + this( + listener, + maximumRecords, + maximumBindingBytes, + maximumRetainedRecords, + 256, + 1024, + withOtherCandidate); } private TransferSqlProof( @@ -2595,8 +2601,14 @@ private TransferSqlProof( int maximumTransfers, int maximumItems) throws Exception { - this(listener, maximumRecords, maximumBindingBytes, maximumRetainedRecords, - maximumTransfers, maximumItems, false); + this( + listener, + maximumRecords, + maximumBindingBytes, + maximumRetainedRecords, + maximumTransfers, + maximumItems, + false); } private TransferSqlProof( From c4c487e3957900b5aaaa90bc252155d0b3318fd1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 14 Nov 2026 10:10:53 +1300 Subject: [PATCH 7/7] Prove bounded mixed capacity retention inspection preserves the ledger --- ...tionInspectionPostgresIntegrationTest.java | 140 ++++++++++++++++++ 1 file changed, 140 insertions(+) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java index cbdeb61008..3ecd7bf5e4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java @@ -217,6 +217,146 @@ void policyQualifiedInspectionFindsRearmedOldEvaluationAndLeavesUnrelatedRowCand } } + @Test + void populatedMixedCohortKeepsExactImagesAcrossBoundedPolicyAndUnqualifiedReads() { + String schema = "capacity_retention_mixed_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + configure(data, schema).target("1043").load().migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var transactions = new DataSourceTransactionManager(data); + var write = new TransactionTemplate(transactions); + populate(dsl, write); + UUID tenant = + dsl.fetchSingle("SELECT tenant_uuid FROM account_tenant_capacity_reservations") + .get(0, UUID.class); + Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); + // Controlled historical storage, not production hold authority or cleanup eligibility. + // The existing game-session history/direct references share this tenant but not the + // world-management owner scope of these unrelated evaluations. + write.executeWithoutResult( + status -> { + for (var row : + List.of( + new Object[] { + digest('4'), now.minus(Duration.ofDays(10)), now.minus(Duration.ofDays(9)), 4 + }, + new Object[] { + digest('5'), now.minus(Duration.ofDays(9)), now.minus(Duration.ofDays(8)), 5 + }, + new Object[] { + digest('6'), now.minus(Duration.ofDays(8)), now.minus(Duration.ofDays(7)), 6 + }, + new Object[] { + digest('7'), + now.minus(Duration.ofHours(12)), + now.minus(Duration.ofHours(6)), + 7 + }, + new Object[] { + digest('8'), now.minus(Duration.ofHours(1)), now.plus(Duration.ofHours(1)), 8 + })) { + dsl.execute( + "INSERT INTO account_tenant_capacity_evaluations " + + "(evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, owner_service, " + + "canonical_evidence, evaluated_at, expires_at) " + + "VALUES (?, ?, ?, 'test-workload', 'world-management-service', ?, ?::timestamptz, ?::timestamptz)", + row[0], + digest('d'), + tenant, + new byte[(int) row[3]], + row[1].toString(), + row[2].toString()); + } + }); + var beforeMigration = rowImages(dsl); + var guards = guardImages(dsl); + configure(data, schema).load().migrate(); + assertThat(rowImages(dsl)).isEqualTo(beforeMigration); + assertThat(guardImages(dsl)).isEqualTo(guards); + var conservation = + dsl.fetch( + "SELECT to_jsonb(c)::text AS row, xmin::text AS xmin " + + "FROM account_tenant_capacity_conservation c ORDER BY tenant_uuid, owner_service") + .intoMaps(); + var flyway = + dsl.fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); + var owner = new AccountCapacityEvaluationRetentionInspectionOwner(dsl, transactions); + // Same controlled schedule as the existing physical qualification, not a new policy choice. + var schedule = + new AccountCapacityEvaluationRetentionPolicy.Schedule( + "physical-fixture/v1", + Duration.ofDays(30), + Duration.ofDays(2), + Duration.ofDays(3), + Duration.ofDays(4), + Duration.ofDays(5), + Duration.ofDays(6)); + var safety = + new AccountCapacityEvaluationRetentionPolicy.Safety( + "physical-fixture/v1", + now.minusSeconds(1), + now.plus(Duration.ofHours(1)), + now.minus(Duration.ofDays(1)), + Map.of( + digest('a'), AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR, + digest('b'), AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR, + digest('c'), AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR, + digest('4'), AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR, + digest('5'), AccountCapacityEvaluationRetentionPolicy.Hold.HELD, + digest('7'), AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR, + digest('8'), AccountCapacityEvaluationRetentionPolicy.Hold.CLEAR)); + for (int repeat = 0; repeat < 2; repeat++) { + var bounded = owner.observe(3, schedule, safety); + assertThat(bounded.sampledRows()).isEqualTo(3); + assertThat(bounded.sampleTruncated()).isTrue(); + assertThat(bounded.candidates().rows()).isOne(); + assertThat(bounded.candidates().evidenceBytes()).isEqualTo(4); + assertThat(bounded.blockers().get(Blocker.HELD).rows()).isOne(); + assertThat(bounded.blockers().get(Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE).rows()) + .isOne(); + var all = owner.observe(10, schedule, safety); + assertThat(all.sampledRows()).isEqualTo(8); + assertThat(all.sampleTruncated()).isFalse(); + assertThat(all.governanceBlocker()).isNull(); + assertThat(all.candidates().rows()).isOne(); + assertThat(all.candidates().evidenceBytes()).isEqualTo(4); + assertThat(all.candidates().oldestEvaluatedAt()).contains(now.minus(Duration.ofDays(10))); + assertThat(all.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows()).isEqualTo(2); + assertThat(all.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).evidenceBytes()) + .isEqualTo(262145); + assertThat(all.blockers().get(Blocker.HELD).rows()).isOne(); + assertThat(all.blockers().get(Blocker.HELD).evidenceBytes()).isEqualTo(5); + assertThat(all.blockers().get(Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE).rows()) + .isOne(); + assertThat(all.blockers().get(Blocker.ABOVE_SAFE_WATERMARK).rows()).isOne(); + assertThat(all.blockers().get(Blocker.RETENTION_WINDOW_OPEN).rows()).isOne(); + assertThat(all.blockers().get(Blocker.LIVE_EVALUATION).rows()).isOne(); + var unqualified = owner.observe(10); + assertThat(unqualified.candidates().rows()).isZero(); + assertThat(unqualified.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows()) + .isEqualTo(2); + assertThat(unqualified.blockers().get(Blocker.LIVE_EVALUATION).rows()).isOne(); + assertThat(unqualified.blockers().get(Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE).rows()) + .isEqualTo(5); + assertThat(rowImages(dsl)).isEqualTo(beforeMigration); + assertThat(guardImages(dsl)).isEqualTo(guards); + assertThat( + dsl.fetch( + "SELECT to_jsonb(c)::text AS row, xmin::text AS xmin " + + "FROM account_tenant_capacity_conservation c ORDER BY tenant_uuid, owner_service") + .intoMaps()) + .isEqualTo(conservation); + assertThat( + dsl.fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps()) + .isEqualTo(flyway); + } + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + private static void verifyForwardMigration(boolean populated) { String schema = "capacity_retention_" + UUID.randomUUID().toString().replace("-", ""); new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema);