diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 9f2863b989..39995f8fe7 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -336,14 +336,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. -Read-only evaluation inspection uses a bounded oldest window and requires the exact environment schedule, current hold snapshot and safe watermark before reporting candidates. The [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records the receiving owner, proof and remaining lifecycle work. +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/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 new file mode 100644 index 0000000000..b3cb49bc02 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionInspectionOwner.java @@ -0,0 +1,539 @@ +package net.firedevops.firemud.accountservice.service; + +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; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered read-only Account-local retention inspection, with no scheduler or endpoint. + * + *

Evaluation expiry ends admission freshness, not retention. Every retained reservation scope + * remains protected, including terminal reservations and earlier rearmed evaluations whose only + * historical reference is inside immutable attempt payloads. Expired evaluations outside those + * scopes still require the approved environment schedule, replay/restore compatibility and current + * governance/hold authority. None of those authorities is implemented by this component. There is + * no cleanup operation or policy-approval API here. Existing database UPDATE/DELETE/TRUNCATE guards + * remain unchanged and reject physical cleanup. + */ +@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, + RETAINED_RESERVATION_SCOPE, + POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE, + HELD, + ABOVE_SAFE_WATERMARK, + RETENTION_WINDOW_OPEN + } + + /** + * Sample counts/bytes are lower bounds, never whole-table cardinality or deletion eligibility. + */ + public record SampleWindow(int rows, long evidenceBytes, Optional oldestEvaluatedAt) { + public SampleWindow { + Objects.requireNonNull(oldestEvaluatedAt); + } + + private SampleWindow include(Instant evaluated, long bytes) { + return new SampleWindow( + rows + 1, + Math.addExact(evidenceBytes, bytes), + oldestEvaluatedAt.or(() -> Optional.of(evaluated))); + } + } + + /** + * Physical relation bytes include indexes and TOAST; the catalog row estimate may be unavailable + * 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, + long totalRelationBytes, + OptionalLong estimatedTableRows, + int sampledRows, + boolean sampleTruncated, + @Nullable Blocker governanceBlocker, + Map blockers, + Optional scheduleVersion, + SampleWindow candidates) { + public Observation { + Objects.requireNonNull(observedAt); + Objects.requireNonNull(estimatedTableRows); + blockers = Map.copyOf(blockers); + Objects.requireNonNull(scheduleVersion); + Objects.requireNonNull(candidates); + } + } + + 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); + reads = new TransactionTemplate(Objects.requireNonNull(transactions)); + reads.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + reads.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + reads.setReadOnly(true); + reads.setTimeout(5); + } + + /** One bounded consistent observation, not a sweep or a claim that the sample is erasable. */ + public Observation observe(int sampleRows) { + return observe(sampleRows, null, null); + } + + Observation observe( + int sampleRows, + AccountCapacityEvaluationRetentionPolicy.@Nullable Schedule schedule, + AccountCapacityEvaluationRetentionPolicy.@Nullable Safety safety) { + requireBound(sampleRows); + return Objects.requireNonNull( + reads.execute(status -> readObservation(sampleRows, schedule, safety))); + } + + private Observation readObservation( + int sampleRows, + AccountCapacityEvaluationRetentionPolicy.@Nullable Schedule schedule, + AccountCapacityEvaluationRetentionPolicy.@Nullable Safety safety) { + Record table = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT transaction_timestamp() AS observed_at, " + + "pg_total_relation_size(relation.oid) AS relation_bytes, " + + "relation.reltuples::bigint AS estimated_rows " + + "FROM pg_class relation WHERE relation.oid = " + + "'account_tenant_capacity_evaluations'::regclass")); + Instant observedAt = + 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)); + 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 (" + + "SELECT evaluation_identity, tenant_uuid, owner_service, evaluated_at, expires_at, " + + "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.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, " + + (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; + for (int index = 0; index < count; index++) { + 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.evaluationIdentity(), + row.evaluatedAt(), + row.expiresAt(), + referenced); + if (classification == AccountCapacityEvaluationRetentionPolicy.Classification.CANDIDATE) { + candidates = candidates.include(row.evaluatedAt(), row.evidenceBytes()); + } else { + Blocker blocker = Blocker.valueOf(classification.name()); + windows.put( + blocker, + Objects.requireNonNull(windows.get(blocker)) + .include(row.evaluatedAt(), row.evidenceBytes())); + } + } + Optional version = + schedule != null + && AccountCapacityEvaluationRetentionPolicy.current(schedule, safety, observedAt) + ? Optional.of(schedule.version()) + : Optional.empty(); + return new Observation( + observedAt, + relationBytes, + estimate < 0 ? OptionalLong.empty() : OptionalLong.of(estimate), + count, + rows.size() > sampleRows, + version.isPresent() ? null : Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE, + windows, + version, + 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( + "Capacity retention sample must be between 1 and 1000 rows"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionPolicy.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionPolicy.java new file mode 100644 index 0000000000..809cb2e8f5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionPolicy.java @@ -0,0 +1,128 @@ +package net.firedevops.firemud.accountservice.service; + +import java.time.Duration; +import java.time.Instant; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import org.jspecify.annotations.Nullable; + +/** Classifies an observed evaluation using explicit policy inputs. Grants no cleanup authority. */ +final class AccountCapacityEvaluationRetentionPolicy { + private AccountCapacityEvaluationRetentionPolicy() {} + + enum Classification { + CANDIDATE, + LIVE_EVALUATION, + RETAINED_RESERVATION_SCOPE, + POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE, + HELD, + ABOVE_SAFE_WATERMARK, + RETENTION_WINDOW_OPEN + } + + enum Hold { + CLEAR, + HELD + } + + /** The declared durations are relative to evaluation time. Maximum caps the dependencies. */ + record Schedule( + String version, + Duration maximum, + Duration evidence, + Duration retry, + Duration replay, + Duration restore, + Duration investigation) { + Schedule { + requireVersion(version); + requirePositive(maximum); + for (Duration horizon : List.of(evidence, retry, replay, restore, investigation)) { + requirePositive(horizon); + if (horizon.compareTo(maximum) > 0) + throw new IllegalArgumentException("Retention horizon exceeds the schedule maximum"); + } + } + + private Duration requiredHorizon() { + return Collections.max(List.of(evidence, retry, replay, restore, investigation)); + } + } + + /** One bounded hold observation. Its safe watermark is inclusive in evaluation-time order. */ + record Safety( + String scheduleVersion, + Instant observedAt, + Instant validUntil, + Instant safeWatermark, + Map holds) { + Safety { + requireVersion(scheduleVersion); + Objects.requireNonNull(observedAt); + Objects.requireNonNull(validUntil); + Objects.requireNonNull(safeWatermark); + if (!observedAt.isBefore(validUntil) || safeWatermark.isAfter(observedAt)) + throw new IllegalArgumentException("Invalid capacity retention observation window"); + if (Objects.requireNonNull(holds).size() + > AccountCapacityEvaluationRetentionInspectionOwner.MAX_SAMPLE_ROWS) + throw new IllegalArgumentException( + "Capacity retention hold observations exceed the sample bound"); + holds = Map.copyOf(holds); + } + } + + static boolean current( + @Nullable Schedule schedule, @Nullable Safety safety, @Nullable Instant observedAt) { + return schedule != null + && safety != null + && observedAt != null + && schedule.version().equals(safety.scheduleVersion()) + && !observedAt.isBefore(safety.observedAt()) + && observedAt.isBefore(safety.validUntil()); + } + + static Classification classify( + @Nullable Schedule schedule, + @Nullable Safety safety, + @Nullable Instant observedAt, + @Nullable String evaluationIdentity, + @Nullable Instant evaluatedAt, + @Nullable Instant expiresAt, + @Nullable Boolean scopeReferenced) { + if (Boolean.TRUE.equals(scopeReferenced)) return Classification.RETAINED_RESERVATION_SCOPE; + if (scopeReferenced == null + || observedAt == null + || evaluationIdentity == null + || evaluationIdentity.isBlank() + || evaluatedAt == null + || expiresAt == null + || !evaluatedAt.isBefore(expiresAt) + || evaluatedAt.isAfter(observedAt)) + return Classification.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE; + if (observedAt.isBefore(expiresAt)) return Classification.LIVE_EVALUATION; + if (schedule == null + || safety == null + || !current(schedule, safety, observedAt) + || Duration.between(evaluatedAt, expiresAt).compareTo(schedule.maximum()) > 0) + return Classification.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE; + Hold hold = safety.holds().get(evaluationIdentity); + if (hold == null) return Classification.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE; + if (hold == Hold.HELD) return Classification.HELD; + if (evaluatedAt.isAfter(safety.safeWatermark())) return Classification.ABOVE_SAFE_WATERMARK; + if (Duration.between(evaluatedAt, observedAt).compareTo(schedule.requiredHorizon()) < 0) + return Classification.RETENTION_WINDOW_OPEN; + return Classification.CANDIDATE; + } + + private static void requireVersion(String version) { + if (Objects.requireNonNull(version).isBlank()) + throw new IllegalArgumentException("Capacity retention schedule version is required"); + } + + private static void requirePositive(Duration duration) { + if (Objects.requireNonNull(duration).isZero() || duration.isNegative()) + throw new IllegalArgumentException("Capacity retention horizons must be positive"); + } +} 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 new file mode 100644 index 0000000000..3ecd7bf5e4 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java @@ -0,0 +1,849 @@ +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.time.temporal.ChronoUnit; +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.AccountCapacityOriginDecisionRepository; +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.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; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Disposable PostgreSQL proof of bounded read-only inspection and unchanged immutable guards. This + * suite establishes no policy approval or deletion authority. + */ +class AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + + @BeforeAll + static void start() { + POSTGRES.start(); + } + + @AfterAll + static void stop() { + POSTGRES.stop(); + } + + @Test + void freshAndPopulatedForwardMigrationPreserveRowsAndGuardsWhileBoundingObservations() { + verifyForwardMigration(false); + 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().truncatedTo(ChronoUnit.MICROS); + 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()); + 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, " + + "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().truncatedTo(ChronoUnit.MICROS); + 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"); + } + } + + @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); + 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); + if (populated) populate(dsl, write); + var beforeRows = rowImages(dsl); + if (populated) { + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isOne(); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_attempt_history"))).isOne(); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_recovery_evidence"))).isOne(); + } + var beforeGuards = guardImages(dsl); + var beforeFlyway = + dsl.fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); + String originalMigration = + dsl.fetchSingle("SELECT checksum::text FROM flyway_schema_history WHERE version = '1040'") + .get(0, String.class); + + configure(data, schema).load().migrate(); + + assertThat(rowImages(dsl)).isEqualTo(beforeRows); + assertThat(guardImages(dsl)).isEqualTo(beforeGuards); + assertThat( + dsl.fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank") + .intoMaps() + .subList(0, beforeFlyway.size())) + .isEqualTo(beforeFlyway); + 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(); + assertThat(conservation).hasSize(populated ? 2 : 0); + assertThat( + dsl.fetchSingle( + "SELECT checksum::text FROM flyway_schema_history WHERE version = '1040'") + .get(0, String.class)) + .isEqualTo(originalMigration); + assertThat(configure(data, schema).load().validateWithResult().validationSuccessful).isTrue(); + assertThat( + dsl.fetchSingle( + "SELECT pg_get_indexdef('account_capacity_evaluation_oldest_retention_idx'::regclass)") + .get(0, String.class)) + .contains("evaluated_at, evaluation_identity"); + assertThat( + dsl.fetchSingle( + "SELECT pg_get_indexdef('account_capacity_reservation_retention_scope_idx'::regclass)") + .get(0, String.class)) + .contains("tenant_uuid, owner_service"); + var owner = new AccountCapacityEvaluationRetentionInspectionOwner(dsl, transactions); + var observed = owner.observe(2); + assertThat(observed.totalRelationBytes()).isPositive(); + assertThat(observed.sampledRows()).isEqualTo(populated ? 2 : 0); + assertThat(observed.sampleTruncated()).isEqualTo(populated); + assertThat(observed.governanceBlocker()) + .isEqualTo(Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE); + if (populated) { + // The oldest evaluation has no current FK, but its reservation scope/history is retained. + assertThat(observed.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows()).isEqualTo(1); + assertThat(observed.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).evidenceBytes()) + .isEqualTo(262144); + assertThat(observed.blockers().get(Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE).rows()) + .isEqualTo(1); + assertThat(observed.blockers().get(Blocker.LIVE_EVALUATION).rows()).isZero(); + var all = owner.observe(1000); + assertThat(all.sampledRows()).isEqualTo(3); + assertThat(all.sampleTruncated()).isFalse(); + assertThat(all.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).rows()).isEqualTo(2); + for (String sql : + List.of( + "UPDATE account_tenant_capacity_evaluations SET canonical_evidence = decode('01', 'hex')", + "DELETE FROM account_tenant_capacity_evaluations WHERE evaluation_identity = '" + + digest('c') + + "'", + "TRUNCATE account_tenant_capacity_evaluations CASCADE", + "DELETE FROM account_tenant_capacity_reservations", + "UPDATE account_tenant_capacity_attempt_history SET canonical_payload = decode('01', 'hex')", + "DELETE FROM account_tenant_capacity_attempt_history", + "TRUNCATE account_tenant_capacity_attempt_history", + "UPDATE account_tenant_capacity_recovery_evidence SET outcome = 'INDETERMINATE'", + "DELETE FROM account_tenant_capacity_recovery_evidence", + "TRUNCATE account_tenant_capacity_recovery_evidence")) { + assertThatThrownBy(() -> write.executeWithoutResult(status -> dsl.execute(sql))) + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")); + } + } + assertThat(rowImages(dsl)).isEqualTo(beforeRows); + assertThat(guardImages(dsl)).isEqualTo(beforeGuards); + 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); + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private static org.flywaydb.core.api.configuration.FluentConfiguration configure( + javax.sql.DataSource data, String schema) { + return Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + } + + private static List rowImages(DSLContext dsl) { + return dsl.fetch( + "SELECT family || ':' || image AS image FROM (" + + "SELECT 'evaluation' AS family, (to_jsonb(e) || jsonb_build_object('xmin', e.xmin::text))::text AS image " + + "FROM account_tenant_capacity_evaluations e UNION ALL " + + "SELECT 'history', (to_jsonb(h) || jsonb_build_object('xmin', h.xmin::text))::text " + + "FROM account_tenant_capacity_attempt_history h UNION ALL " + + "SELECT 'recovery', (to_jsonb(r) || jsonb_build_object('xmin', r.xmin::text))::text " + + "FROM account_tenant_capacity_recovery_evidence r UNION ALL " + + "SELECT 'reservation', (to_jsonb(r) || jsonb_build_object('xmin', r.xmin::text))::text " + + "FROM account_tenant_capacity_reservations r UNION ALL " + + "SELECT 'usage', (to_jsonb(u) || jsonb_build_object('xmin', u.xmin::text))::text " + + "FROM account_tenant_capacity_usage u) retained ORDER BY family, image") + .getValues("image", String.class); + } + + private static List guardImages(DSLContext dsl) { + return dsl.fetch( + "SELECT pg_get_triggerdef(oid) AS definition FROM pg_trigger WHERE NOT tgisinternal " + + "AND tgrelid IN ('account_tenant_capacity_evaluations'::regclass, " + + "'account_tenant_capacity_attempt_history'::regclass, " + + "'account_tenant_capacity_recovery_evidence'::regclass) ORDER BY tgrelid, tgname") + .getValues("definition", String.class); + } + + private static void populate(DSLContext dsl, TransactionTemplate write) { + var tenant = source(); + UUID bootstrap = UUID.randomUUID(); + UUID request = UUID.randomUUID(); + UUID admission = UUID.randomUUID(); + write.executeWithoutResult( + status -> { + UUID account = + dsl.fetchSingle( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, 'test-password') RETURNING account_uuid", + "retention-" + UUID.randomUUID(), + "retention-" + 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 = ?, caller_bound_authority_invalidated = FALSE, " + + "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(), + "retention-bootstrap-" + bootstrap, + digest('1'), + new byte[] {4}, + UUID.randomUUID(), + digest('2'), + new byte[] {5}, + new byte[] {6}, + digest('3'), + bootstrap); + for (var evaluation : + List.of( + new Object[] {digest('a'), "game-session-service", 3, -2, new byte[262144]}, + new Object[] {digest('c'), "world-management-service", 2, -1, new byte[] {1}}, + new Object[] {digest('b'), "game-session-service", 1, 1, new byte[] {2}})) { + 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', ?, ?, CURRENT_TIMESTAMP - ? * INTERVAL '1 day', " + + "CURRENT_TIMESTAMP + ? * INTERVAL '1 day')", + evaluation[0], + digest('d'), + tenant.canonicalTenantId(), + evaluation[1], + evaluation[4], + evaluation[2], + evaluation[3]); + } + UUID attempt = UUID.randomUUID(); + String mutationDigest = "e".repeat(64); + 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, + mutationDigest, + 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, " + + "canonical_payload, evaluation_identity, capacity_delta, expires_at, state, execution_status, reconcile_deadline) " + + "VALUES (?, ?, ?, ?, 'game-session-service', 'test-workload', ?, 1, 1, ?, ?, ?, 0, " + + "CURRENT_TIMESTAMP + INTERVAL '1 day', 'RESERVED', 'OWNER_EXECUTION_PENDING', CURRENT_TIMESTAMP + INTERVAL '2 days')", + tenant.canonicalTenantId(), + request, + admission, + UUID.randomUUID(), + attempt, + mutationDigest, + capacityPayload, + digest('b')); + dsl.execute( + "INSERT INTO account_tenant_capacity_attempt_history (tenant_uuid, request_id, admission_id, admission_attempt_id, " + + "capacity_rearm_fence, mutation_digest, canonical_payload, owner_readback) VALUES (?, ?, ?, ?, 1, ?, convert_to(?, 'UTF8'), ?)", + tenant.canonicalTenantId(), + request, + admission, + UUID.randomUUID(), + "f".repeat(64), + digest('a'), + new byte[] {8}); + // Controlled SQL lineage for inspection, not a genuine execution-source observation. + // Establish the ordinary fenced claim before retaining its unavailable-source evidence. + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET recovery_owner = ?, " + + "recovery_claim_fence = 1, recovery_claim_expires_at = CURRENT_TIMESTAMP + INTERVAL '1 day' " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + UUID.randomUUID(), + tenant.canonicalTenantId(), + request, + admission); + dsl.execute( + "INSERT INTO account_tenant_capacity_recovery_evidence " + + "(tenant_uuid, request_id, admission_id, admission_attempt_id, recovery_claim_fence, " + + "recovery_policy_version, recovery_attempt_number, observed_at, outcome) " + + "SELECT tenant_uuid, request_id, admission_id, admission_attempt_id, recovery_claim_fence, " + + "recovery_policy_version, 1, CURRENT_TIMESTAMP, 'SOURCE_UNAVAILABLE' " + + "FROM account_tenant_capacity_reservations " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + tenant.canonicalTenantId(), + request, + admission); + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET recovery_attempt_count = 1 " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + tenant.canonicalTenantId(), + request, + admission); + }); + } + + 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); + String digest = + GameTenantCreationDigest.requestDigest("prod", request, slug, "Retention", null); + long row = Math.abs((long) tenant.hashCode()) + 1; + return new FreshTenantCreationEvidence( + 1, + "prod", + request, + operation, + digest, + tenant, + row, + slug, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "prod", request, operation, digest, tenant, row, slug, "NEW_GAME_ROW")); + } + + private static String digest(char digit) { + return "sha256:" + String.valueOf(digit).repeat(64); + } + + private static String sqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sql) return sql.getSQLState(); + } + return null; + } +} 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 new file mode 100644 index 0000000000..385aa1b127 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionInspectionOwnerTest.java @@ -0,0 +1,512 @@ +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; + +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +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; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; + +/** Controlled read-only inspection proof, not approval, live hold authority or deletion proof. */ +class AccountCapacityEvaluationRetentionInspectionOwnerTest { + private static final Instant NOW = Instant.parse("2026-11-11T12:00:00Z"); + + @Test + void inspectionBoundsApplyBeforeAnyDatabaseWork() { + DSLContext dsl = mock(DSLContext.class); + PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + var owner = new AccountCapacityEvaluationRetentionInspectionOwner(dsl, transactions); + for (int invalid : new int[] {-1, 0, 1001, Integer.MAX_VALUE}) { + assertThatThrownBy(() -> owner.observe(invalid)).isInstanceOf(IllegalArgumentException.class); + } + verifyNoInteractions(dsl, transactions); + } + + @Test + void observationUsesOneBoundedOldestWindowAndFixedBlockerCategoriesWithoutReadingPayloads() { + DSLContext dsl = mock(DSLContext.class); + 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(-1L); + when(dsl.fetchOne(anyString())).thenReturn(metadata); + Result rows = result(); + when(rows.size()).thenReturn(4); + Record referenced = row(NOW.minusSeconds(30), NOW.minusSeconds(20), true, 262144); + Record expired = row(NOW.minusSeconds(20), NOW.minusSeconds(1), false, 3); + Record live = row(NOW.minusSeconds(10), NOW.plusSeconds(1), false, 5); + when(rows.get(0)).thenReturn(referenced); + when(rows.get(1)).thenReturn(expired); + when(rows.get(2)).thenReturn(live); + when(dsl.fetch(anyString(), any(Object[].class))).thenReturn(rows); + var owner = new AccountCapacityEvaluationRetentionInspectionOwner(dsl, new ReadTransactions()); + + var observation = owner.observe(3); + + assertThat(observation.totalRelationBytes()).isEqualTo(4096); + assertThat(observation.estimatedTableRows()).isEmpty(); + assertThat(observation.sampledRows()).isEqualTo(3); + assertThat(observation.sampleTruncated()).isTrue(); + assertThat(observation.governanceBlocker()) + .isEqualTo(Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE); + assertThat(observation.scheduleVersion()).isEmpty(); + assertThat(observation.candidates().rows()).isZero(); + assertThat(observation.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).evidenceBytes()) + .isEqualTo(262144); + assertThat(observation.blockers().get(Blocker.RETAINED_RESERVATION_SCOPE).oldestEvaluatedAt()) + .contains(NOW.minusSeconds(30)); + assertThat(observation.blockers().get(Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE).rows()) + .isEqualTo(1); + assertThat(observation.blockers().get(Blocker.LIVE_EVALUATION).rows()).isEqualTo(1); + ArgumentCaptor query = ArgumentCaptor.forClass(String.class); + verify(dsl).fetch(query.capture(), eq(4)); + assertThat(query.getValue()) + .contains("LIMIT ?", "octet_length(canonical_evidence)") + .contains("reservation.tenant_uuid = sample.tenant_uuid") + .contains("reservation.owner_service = sample.owner_service") + .doesNotContain("reservation.evaluation_identity", "DELETE", "UPDATE", "SUM(", "COUNT("); + assertThatThrownBy(() -> observation.blockers().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void emptyTableHasNoInventedOldestBlockerAndCatalogEstimateStaysExplicit() { + DSLContext dsl = mock(DSLContext.class); + Record metadata = mock(Record.class); + when(metadata.get("observed_at", OffsetDateTime.class)).thenReturn(at(NOW)); + when(metadata.get("relation_bytes", Long.class)).thenReturn(8192L); + when(metadata.get("estimated_rows", Long.class)).thenReturn(0L); + when(dsl.fetchOne(anyString())).thenReturn(metadata); + Result rows = result(); + when(rows.size()).thenReturn(0); + when(dsl.fetch(anyString(), any(Object[].class))).thenReturn(rows); + var observation = + new AccountCapacityEvaluationRetentionInspectionOwner(dsl, new ReadTransactions()) + .observe(1000); + assertThat(observation.sampledRows()).isZero(); + assertThat(observation.sampleTruncated()).isFalse(); + assertThat(observation.estimatedTableRows()).hasValue(0); + assertThat(observation.governanceBlocker()) + .isEqualTo(Blocker.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE); + assertThat(observation.blockers().values()) + .allSatisfy( + window -> { + assertThat(window.rows()).isZero(); + assertThat(window.evidenceBytes()).isZero(); + assertThat(window.oldestEvaluatedAt()).isEmpty(); + }); + 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); + } + + 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); + when(row.get("evidence_bytes", Long.class)).thenReturn(bytes); + 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); + } + + private static final class ReadTransactions implements PlatformTransactionManager { + @Override + public TransactionStatus getTransaction( + @org.jspecify.annotations.Nullable TransactionDefinition definition) { + assertThat(definition).isNotNull(); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); + assertThat(definition.isReadOnly()).isTrue(); + assertThat(definition.getTimeout()).isEqualTo(5); + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + } +} 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 new file mode 100644 index 0000000000..053515bc2c --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCapacityEvaluationRetentionPolicyTest.java @@ -0,0 +1,207 @@ +package net.firedevops.firemud.accountservice.service; + +import static net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionPolicy.classify; +import static net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionPolicy.current; +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.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Duration; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionPolicy.Classification; +import net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionPolicy.Hold; +import net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionPolicy.Safety; +import net.firedevops.firemud.accountservice.service.AccountCapacityEvaluationRetentionPolicy.Schedule; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.SimpleTransactionStatus; + +class AccountCapacityEvaluationRetentionPolicyTest { + private static final String VERSION = "test-capacity-retention/v1"; + private static final String EVALUATION = "sha256:" + "a".repeat(64); + private static final Instant EVALUATED = Instant.parse("2026-01-01T00:00:00Z"); + private static final Instant EXPIRES = EVALUATED.plus(Duration.ofDays(1)); + private static final Instant OBSERVED = EVALUATED.plus(Duration.ofDays(5)); + + @Test + void candidateRequiresAllWindowsToCloseAndIncludesTheWatermarkBoundary() { + var schedule = schedule(Duration.ofDays(6), Duration.ofDays(2)); + var safety = safety(VERSION, EVALUATED, Map.of(EVALUATION, Hold.CLEAR)); + + assertThat(classify(schedule, safety, OBSERVED, EVALUATION, EVALUATED, EXPIRES, false)) + .isEqualTo(Classification.CANDIDATE); + assertThat( + classify( + schedule, safety, OBSERVED.minusNanos(1), EVALUATION, EVALUATED, EXPIRES, false)) + .isEqualTo(Classification.RETENTION_WINDOW_OPEN); + assertThat( + classify( + schedule, + safety(VERSION, EVALUATED.minusNanos(1), Map.of(EVALUATION, Hold.CLEAR)), + OBSERVED, + EVALUATION, + EVALUATED, + EXPIRES, + false)) + .isEqualTo(Classification.ABOVE_SAFE_WATERMARK); + assertThat( + classify( + schedule, safety, OBSERVED, EVALUATION, EVALUATED, OBSERVED.plusNanos(1), false)) + .isEqualTo(Classification.LIVE_EVALUATION); + assertThat(classify(schedule, safety, OBSERVED, EVALUATION, EVALUATED, EXPIRES, true)) + .isEqualTo(Classification.RETAINED_RESERVATION_SCOPE); + } + + @Test + void heldMissingStaleAndMismatchedObservationsRefuse() { + var schedule = schedule(Duration.ofDays(6), Duration.ofDays(2)); + var holds = new HashMap<>(Map.of(EVALUATION, Hold.HELD)); + var held = safety(VERSION, EVALUATED, holds); + holds.put(EVALUATION, Hold.CLEAR); + assertThat(classify(schedule, held, OBSERVED, EVALUATION, EVALUATED, EXPIRES, false)) + .isEqualTo(Classification.HELD); + assertThat(current(schedule, held, held.observedAt())).isTrue(); + assertThat(current(schedule, held, held.observedAt().minusNanos(1))).isFalse(); + assertThat(current(schedule, held, held.validUntil())).isFalse(); + assertThat(current(null, held, OBSERVED)).isFalse(); + assertThat(current(schedule, null, OBSERVED)).isFalse(); + assertThat(classify(schedule, held, OBSERVED, EVALUATION, EVALUATED, EXPIRES, null)) + .isEqualTo(Classification.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE); + assertThat(classify(schedule, held, held.validUntil(), EVALUATION, EVALUATED, EXPIRES, false)) + .isEqualTo(Classification.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE); + assertThat(classify(schedule, null, OBSERVED, EVALUATION, EVALUATED, EXPIRES, false)) + .isEqualTo(Classification.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE); + for (var unavailable : + new Safety[] { + safety("other-version", EVALUATED, Map.of(EVALUATION, Hold.CLEAR)), + safety(VERSION, EVALUATED, Map.of()) + }) { + assertThat(classify(schedule, unavailable, OBSERVED, EVALUATION, EVALUATED, EXPIRES, false)) + .isEqualTo(Classification.POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE); + } + } + + @Test + void malformedScheduleAndUnboundedOrContradictorySafetyRefuse() { + assertThatThrownBy(() -> schedule(Duration.ofDays(6), Duration.ZERO)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> schedule(Duration.ofDays(6), Duration.ofDays(7))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Safety(VERSION, OBSERVED, OBSERVED, EVALUATED, Map.of())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> safety(VERSION, OBSERVED.plusSeconds(1), Map.of())) + .isInstanceOf(IllegalArgumentException.class); + Map oversized = + IntStream.rangeClosed(0, AccountCapacityEvaluationRetentionInspectionOwner.MAX_SAMPLE_ROWS) + .boxed() + .collect(Collectors.toMap(index -> "test-evaluation-" + index, index -> Hold.CLEAR)); + assertThatThrownBy(() -> safety(VERSION, EVALUATED, oversized)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + @SuppressWarnings("unchecked") + void qualifiedObservationCountsOnlyUnheldUnreferencedCandidatesWithoutWrites() { + DSLContext database = mock(DSLContext.class); + Record relation = mock(Record.class); + when(relation.get("observed_at", OffsetDateTime.class)) + .thenReturn(OBSERVED.atOffset(ZoneOffset.UTC)); + when(relation.get("relation_bytes", Long.class)).thenReturn(4096L); + when(relation.get("estimated_rows", Long.class)).thenReturn(4L); + when(database.fetchOne(anyString())).thenReturn(relation); + Result rows = mock(Result.class); + when(rows.size()).thenReturn(4); + String held = "sha256:" + "b".repeat(64); + String unknown = "sha256:" + "c".repeat(64); + String referenced = "sha256:" + "d".repeat(64); + var candidateRow = evaluation(EVALUATION, false); + var heldRow = evaluation(held, false); + var unknownRow = evaluation(unknown, false); + var referencedRow = evaluation(referenced, true); + when(rows.get(0)).thenReturn(candidateRow); + when(rows.get(1)).thenReturn(heldRow); + when(rows.get(2)).thenReturn(unknownRow); + when(rows.get(3)).thenReturn(referencedRow); + when(database.fetch(anyString(), any(Object[].class))).thenReturn(rows); + PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + when(transactions.getTransaction(any())).thenAnswer(call -> new SimpleTransactionStatus()); + var owner = new AccountCapacityEvaluationRetentionInspectionOwner(database, transactions); + var schedule = schedule(Duration.ofDays(6), Duration.ofDays(2)); + var safety = + safety( + VERSION, + EVALUATED, + Map.of(EVALUATION, Hold.CLEAR, held, Hold.HELD, referenced, Hold.CLEAR)); + + var report = owner.observe(4, schedule, safety); + + assertThat(report.scheduleVersion()).contains(VERSION); + assertThat(report.governanceBlocker()).isNull(); + assertThat(report.candidates().rows()).isEqualTo(1); + assertThat(report.candidates().evidenceBytes()).isEqualTo(12); + assertThat( + report + .blockers() + .get(AccountCapacityEvaluationRetentionInspectionOwner.Blocker.HELD) + .rows()) + .isEqualTo(1); + assertThat( + report + .blockers() + .get( + AccountCapacityEvaluationRetentionInspectionOwner.Blocker + .POLICY_AND_HOLD_AUTHORITY_UNAVAILABLE) + .rows()) + .isEqualTo(1); + assertThat( + report + .blockers() + .get( + AccountCapacityEvaluationRetentionInspectionOwner.Blocker + .RETAINED_RESERVATION_SCOPE) + .rows()) + .isEqualTo(1); + verify(database, never()).execute(anyString(), any(Object[].class)); + } + + private static Record evaluation(String identity, boolean referenced) { + Record row = mock(Record.class); + when(row.get("evaluation_identity", String.class)).thenReturn(identity); + when(row.get("evaluated_at", OffsetDateTime.class)) + .thenReturn(EVALUATED.atOffset(ZoneOffset.UTC)); + 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; + } + + private static Schedule schedule(Duration maximum, Duration evidence) { + return new Schedule( + VERSION, + maximum, + evidence, + Duration.ofDays(1), + Duration.ofDays(3), + Duration.ofDays(5), + Duration.ofDays(4)); + } + + private static Safety safety(String version, Instant watermark, Map holds) { + return new Safety(version, OBSERVED.minusSeconds(1), OBSERVED.plusSeconds(1), watermark, holds); + } +}