From 08791e315bef3c0f53d5ba2c8b5be32c90b95a60 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:53:17 +1300 Subject: [PATCH 01/96] Extract Account capacity origin prerequisite with coherent physical fixtures --- .../account-service/api-contracts.md | 4 +- .../account-service/runtime-and-data.md | 8 +- .../v1/tenant_capacity_admission.proto | 20 + ...countCapacityOriginDecisionRepository.java | 105 ++++ ...ccountCapacityRefusalBudgetRepository.java | 81 +++ .../AccountTenantCapacityRepository.java | 25 +- .../service/AccountTenantCapacityOwner.java | 50 +- .../AccountTenantCapacityGrpcService.java | 11 +- ...0.1__account_capacity_origin_decisions.sql | 92 +++ ...1040.2__bound_capacity_origin_refusals.sql | 75 +++ ...acityMigrationPostgresIntegrationTest.java | 48 ++ ...tionCompletionPostgresIntegrationTest.java | 10 +- .../AccountTenantCapacityOwnerTest.java | 49 +- .../AccountTenantCapacityGrpcServiceTest.java | 47 ++ .../OriginalNewCapacityExecution.java | 22 +- .../AbstractReloadingBlockingGrpcClient.java | 108 +++- ...stractReloadingBlockingGrpcClientTest.java | 122 +++- .../TenantCapacityAdmissionGrpcCodec.java | 89 ++- .../TenantCapacityAdmissionGrpcCodecTest.java | 115 +++- .../client/AccountTenantCapacityClient.java | 157 +++++ .../AccountTenantCapacityClientMtlsTest.java | 553 ++++++++++++++++++ 21 files changed, 1714 insertions(+), 77 deletions(-) create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityRefusalBudgetRepository.java create mode 100644 services/account-service/src/main/resources/db/migration/V1040.1__account_capacity_origin_decisions.sql create mode 100644 services/account-service/src/main/resources/db/migration/V1040.2__bound_capacity_origin_refusals.sql create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index f5e79e14bf..826097d019 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -161,7 +161,7 @@ Explicit playtest grants remain partial: registered Account persistence and inte Account has unregistered individual Creator Party, hosted-terms catalog, and individual acceptance storage in V84/V85 through `IndividualCreatorPartyRepository` and `HostedTermsRepository`, with focused repository test sources. These are storage foundations only: authenticated party provisioning and signer verification, operative legal publication, a registered acceptance API/UI, organization acceptance, party transfer, and a commit-bound currentness gate for Game Design writes remain unavailable or unproved. The canonical authority and capability limits are recorded in [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and the [authoring implementation tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status); Game Design must not maintain a copied catalog or authorize a creator mutation from a tenant-local flag. -`CommitTenantCapacityAdmission` has a prepared proto RPC, a shared exact contract and codec, and the Account-owned durable evaluation, usage, reservation and recovery components. Account's default runtime composition leaves the capacity receiver and recovery worker unregistered. The [strict tenant-capacity tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) owns the receiving work and proof status. +`CommitTenantCapacityAdmission` has a prepared proto RPC, shared strict contract/codec, durable Account evaluation/usage/reservation storage and owner/finalization/recovery code, and a Game Session caller adapter. These components remain unregistered and unqualified for live admission; the [strict tenant-capacity owner tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records the supported source boundary, focused proof and remaining producer, physical and runtime gates. The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. JOIN receiver availability and its blocked Gateway route are recorded under [Current Receiver Composition](#current-receiver-composition). Target JOIN operation, digest, retry, and commit semantics remain owned by [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md) and the linked [Authentication contract](../../system-architecture-authentication.md). The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Connect-token receiver availability is recorded under [Current Receiver Composition](#current-receiver-composition). Current text `PLAY` validates the emitted `membershipLifecycleState` and independent `membershipAuthorityGeneration` and requires coherent `ACTIVE` admitting membership. Missing or `INACTIVE` public-production membership yields `JOIN_REQUIRED` only when fresh enrollment policy permits repair; an existing active but non-admitting response is not a join fallback. The implemented consumer limits remain in [Account runtime status](./runtime-and-data.md#implementation-status); these checks do not establish the complete caller-target and atomic-freshness contract. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers. Tenant representations follow the [Account tenant identifier boundary](#account-tenant-identifier-boundary). Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. @@ -233,7 +233,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 canonical Account UUIDs. Account resolves known subjects through one local UUID batch query with the same persisted provenance and source-row checks as scalar identity reads, then returns policies keyed by UUID. Unknown or unproven entries are intentionally omitted so Social applies complete `PRIVATE` redaction. - `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current gRPC adapter returns `FAILED_PRECONDITION` before selector parsing or owner reads; this does not implement the target export operation. -- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns `TENANT_BILLING_BLOCKED` with `RESOURCE_EXHAUSTED`. Fresh creation-eligible evidence with checked insufficient capacity returns `CAPACITY_QUOTA_EXCEEDED` with the same gRPC status. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a changed exact retry. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns the typed `TENANT_BILLING_BLOCKED` response. Fresh creation-eligible evidence with checked insufficient capacity returns the typed `CAPACITY_QUOTA_EXCEEDED` response. Each refusal is bound to the exact original attempt, mutation digest, snapshot and evaluation. A quota refusal includes the immutable Account decision UUID only after an exact durable `NO_ACCEPT` commits. A matching exact retry returns the retained receipt. A quota refusal without that receipt grants no evidence settlement authority. The response contains exactly one commitment or one typed refusal. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a changed exact retry. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact attempt-and-fence retries replay; a changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. The shared [capacity-admission/v1 schema](../../../../services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json) declares the exact ADR 0047 seven-field mapping and bounds. Its `accountEvidence` member is canonical padded base64 of the complete existing Account bundle bytes, validated by the closed variant codec with canonical re-encoding equality before hashing. This binds every evidence field and cutoff/checkpoint byte, not a digest or reconstructed subset. `capacity_delta` is `optional int64`; missing presence is invalid and a present zero remains distinct. The Game Session and World alternatives retain distinct typed contexts. The ordinary registered Account receiver does not expose this private composition, and no route is enabled by adding the proto. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index fe4f92d77d..0ae3953af8 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -6,6 +6,10 @@ This document defines the Account Service runtime model, persistent data ownersh Account owns platform identity, hosted Creator Party/operator and terms currentness authority, durable membership, entitlement authority, Account-local authentication persistence, global `account_security_lock`/`platform_access_ban` enforcement, Stripe v1 hosting-billing state, and future marketplace financial reconciliation. The hosted terms and creator-party authority are target-only under [ADR 0180](../../decisions/adr-0180-account-owned-hosted-terms-acceptance-gate.md) and [ADR 0181](../../decisions/adr-0181-changed-hosted-terms-decline-and-existing-content-continuity.md); future creator commerce remains separately gated by [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md). This document records only local runtime and data consequences; fixed-category moderation and appeal ownership is defined by [Moderation Policies](../logging-admin-service/moderation-policies.md), gameplay/chat enforcement remains in Game Session and Social & Groups, gameplay admission and JOIN identity binding are defined by [Authentication](../../system-architecture-authentication.md), and token refresh, replacement, generation, revocation, fencing, and logout are defined by [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). +### Finalized capacity usage retirement + +After [Game Session supplies authenticated terminal proof](../game-session-service/runtime-and-data.md#finalized-capacity-usage-retirement) for the exact finalized binding and reservation, Account retains a unique retirement receipt and decrements used units in the same owner transaction. Exact retirement retries replay that receipt. Account preserves the original `FINALIZED` result and its replay evidence. + ## Implementation Status Both existing `bootstrap-connect-scope` producer paths mint the exact persisted Account UUID. Scope validation compares canonical UUID subject/Account claims before owner readback; malformed identity remains `CONNECT_SCOPE_INVALID`, while unavailable owner evidence is `AUTH_UNAVAILABLE`. Retained scope/JOIN rows and digests continue to use private Account row keys without a schema rewrite. This scope-artifact transition itself adds no Game Session text dispatch; the separately qualified ordinary receiving cohort now carries UUID Account identity through the direct-text caller context and Account-to-Entity references. Proof and retained-scope rediscovery limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#bootstrap-connect-scope-uuid-artifact) and [ordinary UUID receiving](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). @@ -84,7 +88,9 @@ Current public bootstrap, direct-scope, JOIN, connect-token and numeric entitlem Strict capacity follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). The prepared V1040 storage records immutable exact Account evaluation bytes, one stable outer request/reservation identity, the current attempt/digest and monotonic rearm/reservation fences, prior-attempt evidence, recovery claims, and durable held/used units. Deferred PostgreSQL constraints compare the complete reservation inventory with usage; eligibility reads and issuer-local counters cannot initialize or replace it. Zero usage is established only when the existing creator bootstrap commits against a genuinely new fresh-tenant association born in that same Account transaction, with the exact creation tuple and nonadmitting sequence-zero baseline. Earlier tenants are not backfilled. The actual player evaluator retains its complete bundle inside its final source transaction, so failed source commit exposes neither a capacity evaluation nor an entitlement result. Reservations use conservative microsecond expiry bounds without extending the evidence lifetime. The same prepared recovery schema retains its immutable read history and `capacity-recovery/1` retry budget. Deadline or budget exhaustion quarantines the original complete hold; it does not expire, release or replace it. No live recovery source/scheduler or quarantine-resolution authority is registered. -The unregistered capacity owner requires exact retained evidence and current Account membership/issuance/scope source equality before creating a new positive player-binding reservation. Exact attempt retries replay before fresh-source or usage work; changed complete payloads conflict. The Account recovery component alone can finalize, release or rearm under its current durable claim and exact selected-owner readback; an ambiguous observation records only the bounded retry/deadline and retains the hold. Account's default runtime leaves the capacity receiver, selected-owner readback and recovery worker unregistered. Controlled observations prove Account ledger transitions. Actual Game Session execution, closure and admitted-session teardown require their own retained owner receipts. World lifecycle, authoritative prior-shape/zero-delta recovery, current selected-owner activation and complete end-to-end qualification remain held as detailed in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). +V1040.1 serializes the exact Account `ACCEPTED` and `NO_ACCEPT` origin decisions against reservation creation and rearm. A pre-V1040.1 writer cannot create a reservation after the guard applies. Upgrading a retained Account database requires independently verified [writer quiescence](../../system-architecture-database-migrations.md#version-aware-migration-checklist), including closed writer endpoints and exclusion of old writers. V1040.2 retains an exact quota denial under an explicitly installed finite tenant refusal limit. The same serializable owner transaction checks quota and chooses between a reservation and a denial. The denial carries no reservation and permanently excludes acceptance for the exact original. Exact replay returns the same decision even after capacity becomes available. An unavailable refusal budget or uncertain outcome leaves Game Session's reserve active. Account neither frees nor rearms an accepted reservation through this path. Before enabling any admission producer, the Account operator must provision every supported canonical tenant through `AccountCapacityRefusalBudgetRepository.provision` in a committed owner transaction, then call `requireReady` with the same explicit lifetime limit and the bounded admission cohort headroom while producers remain quiescent. Sizing is explicit: the finite lifetime limit must cover retained denials plus the planned denial cohort; it is not the gameplay capacity quota or an automatically replenished rate limit. Exact provisioning retries preserve the row and its historical evidence; a different limit conflicts. Missing, mismatched or insufficient budgets fail readiness. Readiness is a local observation, not a reservation or authority to admit, and the SQL trigger remains the runtime concurrency authority. Exhaustion requires stopping new admission and an independently designed retention-safe lifecycle, never deleting denials or resetting/increasing this immutable budget. These private methods do not register an endpoint, seed tenants automatically or activate the default-off capacity component. + +The unregistered capacity owner requires exact retained evidence and current Account membership/issuance/scope source equality before creating a new positive player-binding reservation. Exact attempt retries replay before fresh-source or usage work; changed complete payloads conflict. The Account recovery component alone can finalize, release or rearm under its current durable claim and exact selected-owner readback; an ambiguous observation records only the bounded retry/deadline and retains the hold. No runtime readback producer or recovery client is registered. World lifecycle, authoritative prior-shape/zero-delta recovery, current selected-owner activation and complete end-to-end qualification remain held as detailed in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). The canonical gameplay LOGIN primary-credential adapter reuses Account’s password and email-OTP authority without creating a legacy token or session. Its owner transaction retains the verified challenge identity and consumes it only after new PENDING issuance; denial accounting and expiry cleanup commit under the existing owner denial path. Exact pending retry does not reverify or reconsume. Canonical-only verification pads to two KDF comparisons with non-authorizing process-local random decoy evidence using the existing Argon2 profile. The adapter participates only in the explicitly enabled protected LOGIN composition; default deployment behavior remains unchanged. Focused unit and real PostgreSQL proof and its controlled upstream/external-owner limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). Deployed authenticated issuance and timing parity remain unproved. diff --git a/protos/account/v1/tenant_capacity_admission.proto b/protos/account/v1/tenant_capacity_admission.proto index 973bb17cc1..ceb65654d8 100644 --- a/protos/account/v1/tenant_capacity_admission.proto +++ b/protos/account/v1/tenant_capacity_admission.proto @@ -65,6 +65,26 @@ message TenantCapacityAdmissionCommitment { repeated string snapshot_identity = 11; repeated string evaluation_identity = 12; } +message TenantCapacityAdmissionRefusal { + enum Code { + CODE_UNSPECIFIED = 0; + TENANT_BILLING_BLOCKED = 1; + CAPACITY_QUOTA_EXCEEDED = 2; + } + repeated string tenant_id = 1; + repeated string request_id = 2; + repeated string admission_id = 3; + repeated string admission_attempt_id = 4; + repeated int64 capacity_rearm_fence = 5; + repeated string mutation_digest = 6; + repeated string snapshot_identity = 7; + repeated string evaluation_identity = 8; + repeated Code code = 9; + // Zero or one canonical UUID. Only an irrevocable Account quota denial can carry this receipt. + repeated string durable_denial_id = 10; +} +// Exactly one commitment or one produced domain refusal. Transport/pre-domain failure is non-OK. message CommitTenantCapacityAdmissionResponse { repeated TenantCapacityAdmissionCommitment commitment = 1; + repeated TenantCapacityAdmissionRefusal refusal = 2; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java new file mode 100644 index 0000000000..aa2a8e2018 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java @@ -0,0 +1,105 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.conflict; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.transaction; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.unavailable; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import org.jooq.DSLContext; +import org.jooq.Record; + +/** Immutable Account decision; unique-key arbitration also excludes caller/account aliases. */ +@SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Private transaction collaborator.") +public final class AccountCapacityOriginDecisionRepository { + private static final String QUOTA_REFUSAL = Failure.CAPACITY_QUOTA_EXCEEDED.name(); + + private final DSLContext dsl; + + public AccountCapacityOriginDecisionRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Read only. Missing row is not a refusal. */ + public Record find(Request request) { + transaction(); + Record row = + dsl.fetchOne( + "SELECT * FROM account_capacity_origin_decisions WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND capacity_rearm_fence = ?", + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.capacityRearmFence()); + if (row != null) requireExact(request, row); + return row; + } + + /** + * Must commit atomically with reservation creation/rearm, otherwise the transaction rolls back. + */ + public void accept(Request request) { + retain(request, "ACCEPTED", null); + } + + /** Caller has locked Account and verified no exact or conflicting reservation exists. */ + public UUID refuse(Request request) { + return retain(request, "NO_ACCEPT", null).get("decision_id", UUID.class); + } + + /** Replays an exact durable quota refusal before any mutable eligibility check. */ + public UUID retainedQuotaDenial(Request request) { + Record row = find(request); + if (row == null) return null; + return requireOutcome(row, "NO_ACCEPT", QUOTA_REFUSAL).get("decision_id", UUID.class); + } + + /** Caller holds the Account and usage locks and found insufficient capacity before any write. */ + public UUID refuseQuota(Request request) { + return retain(request, "NO_ACCEPT", QUOTA_REFUSAL).get("decision_id", UUID.class); + } + + private Record retain(Request request, String decision, String refusalCode) { + Record existing = find(request); + if (existing != null) return requireOutcome(existing, decision, refusalCode); + int inserted = + 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, refusal_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (tenant_uuid, request_id, admission_id, capacity_rearm_fence) DO NOTHING", + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.capacityRearmFence(), + request.admissionAttemptId(), + request.mutationDigest(), + CapacityAdmissionDigest.preimage(request), + decision, + UUID.randomUUID(), + refusalCode); + if (inserted != 0 && inserted != 1) throw unavailable(); + Record row = find(request); + if (row == null) throw unavailable(); + return requireOutcome(row, decision, refusalCode); + } + + private static Record requireOutcome(Record row, String decision, String refusalCode) { + if (!decision.equals(row.get("decision", String.class)) + || !Objects.equals(refusalCode, row.get("refusal_code", String.class))) { + throw conflict(); + } + return row; + } + + private static void requireExact(Request request, Record row) { + if (!request.admissionAttemptId().equals(row.get("admission_attempt_id", UUID.class)) + || !request.mutationDigest().equals(row.get("mutation_digest", String.class)) + || !Arrays.equals( + CapacityAdmissionDigest.preimage(request), row.get("canonical_payload", byte[].class)) + || row.get("decision_id", UUID.class) == null + || !("ACCEPTED".equals(row.get("decision", String.class)) + || "NO_ACCEPT".equals(row.get("decision", String.class)))) throw conflict(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityRefusalBudgetRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityRefusalBudgetRepository.java new file mode 100644 index 0000000000..64b3262ca0 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityRefusalBudgetRepository.java @@ -0,0 +1,81 @@ +package net.firedevops.firemud.accountservice.repository; + +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.conflict; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.transaction; +import static net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.unavailable; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import org.jooq.DSLContext; + +/** Explicit Account-local provisioning only. No bean, RPC, automatic seed or budget reset. */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Private owner transaction collaborator.") +public final class AccountCapacityRefusalBudgetRepository { + private final DSLContext dsl; + + public AccountCapacityRefusalBudgetRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** + * Install an explicitly sized lifetime limit for a known canonical tenant. Exact retries preserve + * the row; a different limit is a conflict, never an increase, reset or replacement. The caller + * owns the writable transaction and must commit before enabling any admission producer. + */ + public void provision(UUID tenantId, int maximumRefusals) { + validate(tenantId, maximumRefusals); + transaction(); + int inserted = + dsl.execute( + "INSERT INTO account_capacity_origin_refusal_budget (tenant_uuid,maximum_refusals) VALUES (?,?) ON CONFLICT (tenant_uuid) DO NOTHING", + tenantId, + maximumRefusals); + if (inserted != 0 && inserted != 1) throw unavailable(); + var row = + dsl.fetchOne( + "SELECT maximum_refusals FROM account_capacity_origin_refusal_budget WHERE tenant_uuid=? FOR SHARE", + tenantId); + if (row == null) throw unavailable(); + if (!Integer.valueOf(maximumRefusals).equals(row.get(0, Integer.class))) throw conflict(); + } + + /** + * Fail closed unless the exact installed policy has room for the stated bounded admission cohort. + * This is a transaction-local readiness observation, not a reservation or admission + * authorization. Callers must exclude admission writers while checking startup readiness. The + * existing SQL trigger remains authoritative for every refusal and serializes competing runtime + * writers. + */ + public long requireReady(UUID tenantId, int maximumRefusals, int requiredHeadroom) { + validate(tenantId, maximumRefusals); + if (requiredHeadroom < 1 || requiredHeadroom > maximumRefusals) + throw new IllegalArgumentException("Positive headroom within the explicit limit required"); + transaction(); + var row = + dsl.fetchOne( + "SELECT maximum_refusals FROM account_capacity_origin_refusal_budget WHERE tenant_uuid=? FOR SHARE", + tenantId); + if (row == null) throw unavailable(); + if (!Integer.valueOf(maximumRefusals).equals(row.get(0, Integer.class))) throw conflict(); + var count = + dsl.fetchOne( + "SELECT count(*) FROM (SELECT 1 FROM account_capacity_origin_decisions WHERE tenant_uuid=? AND decision='NO_ACCEPT' LIMIT ?) retained", + tenantId, + (long) maximumRefusals + 1); + Long retained = count == null ? null : count.get(0, Long.class); + if (retained == null || retained < 0 || retained > maximumRefusals) throw unavailable(); + long remaining = maximumRefusals - retained; + if (remaining < requiredHeadroom) throw unavailable(); + return remaining; + } + + private static void validate(UUID tenantId, int maximumRefusals) { + TenantCapacityAdmission.uuid(tenantId); + if (maximumRefusals < 1) + throw new IllegalArgumentException("Explicit finite refusal limit required"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java index 9fdb6c982d..012af3be5b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java @@ -8,9 +8,11 @@ import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Evidence; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Identity; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; @@ -139,13 +141,14 @@ public void requirePriorHistory(Request prior, Request next) { || history.get("owner_readback", byte[].class) == null) throw conflict(); } - public Result create(Request request, Instant expiresAt, Clock clock) { + /** Retains acceptance only after the locked quota check, in the same reservation transaction. */ + public Optional createIfQuotaAvailable(Request request, Instant expiresAt, Clock clock) { Record usage = usage(request); requireCurrentLifetime(request.evidence(), clock.instant()); long delta = Objects.requireNonNull(request.capacityDelta()); long occupied = Math.addExact(number(usage, "held_units"), number(usage, "used_units")); - if (delta > request.evidence().quota() - occupied) - throw new CapacityException(Failure.CAPACITY_QUOTA_EXCEEDED); + if (delta > request.evidence().quota() - occupied) return Optional.empty(); + new AccountCapacityOriginDecisionRepository(dsl).accept(request); long held = Math.addExact(number(usage, "held_units"), delta); updateUsage(request, usage, held, number(usage, "used_units")); int created = @@ -168,7 +171,7 @@ public Result create(Request request, Instant expiresAt, Clock clock) { at(expiresAt), at(expiresAt.plusSeconds(60))); if (created != 1) throw unavailable(); - return exact(request, Objects.requireNonNull(find(request.identity()))); + return Optional.of(exact(request, Objects.requireNonNull(find(request.identity())))); } public static void requireCurrentLifetime(Evidence evidence, Instant now) { @@ -249,14 +252,28 @@ public static CapacityException unavailable() { public static final class CapacityException extends IllegalStateException { private final Failure code; + private final UUID durableDenialId; public CapacityException(Failure code) { super(code.name()); this.code = code; + this.durableDenialId = null; + } + + public CapacityException(Failure code, UUID durableDenialId) { + super(code.name()); + if (code != Failure.CAPACITY_QUOTA_EXCEEDED) + throw new IllegalArgumentException("Only a quota refusal can carry a durable denial"); + this.code = code; + this.durableDenialId = TenantCapacityAdmission.uuid(durableDenialId); } public Failure code() { return code; } + + public UUID durableDenialId() { + return durableDenialId; + } } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index 2a00b3420c..bd6d915759 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -20,6 +20,7 @@ import java.util.concurrent.TimeUnit; import java.util.function.Supplier; 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.AccountGameplayDelegationIssuanceRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; @@ -62,6 +63,7 @@ public final class AccountTenantCapacityOwner { private final AccountGameplayDelegationIssuanceRepository issuances; private final AccountConnectScopeRepository scopes; private final AccountTenantCapacityRepository capacity; + private final AccountCapacityOriginDecisionRepository originDecisions; private final TransactionTemplate transaction; private final Clock clock; private final String namespace; @@ -81,6 +83,7 @@ public AccountTenantCapacityOwner( this.issuances = Objects.requireNonNull(issuances); this.scopes = Objects.requireNonNull(scopes); this.capacity = new AccountTenantCapacityRepository(dsl); + this.originDecisions = new AccountCapacityOriginDecisionRepository(dsl); this.clock = Objects.requireNonNull(clock); if (!GrpcPeerIdentity.isValidNamespace(namespace)) throw new IllegalArgumentException("Namespace required"); @@ -95,22 +98,38 @@ public Result commit(Request request, String authenticatedCaller) { requireCaller(request, authenticatedCaller); request.requireStructurallyValid(); if (!(request.context() instanceof PlayerContext)) throw unavailable(); - return commitWithFreshSnapshot( - () -> { - // Exact replay/conflict can linearize at the snapshot read without taking a mutation - // lock. - Record existing = capacity.findForReplay(request.identity()); - if (existing != null) return capacity.exact(request, existing); - lockPlayerAccount(request); - if (request.capacityRearmFence() != 1) throw conflict(); - current(request); - requireSupportedShape(request); - if (!request.evidence().permitsCreation()) - throw new CapacityException(Failure.TENANT_BILLING_BLOCKED); - return capacity.create(request, request.evidence().expiresAt(), clock); - }); + CommitDecision decision = + commitWithFreshSnapshot( + () -> { + // Replay precedes current sources and quota. A lost refusal response retains its + // original decision even if capacity becomes available before the caller retries. + Record existing = capacity.findForReplay(request.identity()); + if (existing != null) { + return new CommitDecision(capacity.exact(request, existing), null); + } + if (request.capacityRearmFence() != 1) throw conflict(); + UUID retainedDenial = originDecisions.retainedQuotaDenial(request); + if (retainedDenial != null) return new CommitDecision(null, retainedDenial); + lockPlayerAccount(request); + current(request); + requireSupportedShape(request); + if (!request.evidence().permitsCreation()) + throw new CapacityException(Failure.TENANT_BILLING_BLOCKED); + var reservation = + capacity.createIfQuotaAvailable(request, request.evidence().expiresAt(), clock); + if (reservation.isPresent()) { + return new CommitDecision(reservation.orElseThrow(), null); + } + return new CommitDecision(null, originDecisions.refuseQuota(request)); + }); + // Throw only after the transaction has committed the exact denial. + if (decision.denialId() != null) + throw new CapacityException(Failure.CAPACITY_QUOTA_EXCEEDED, decision.denialId()); + return decision.reservation(); } + private record CommitDecision(Result reservation, UUID denialId) {} + /** Only the Account-owned recovery worker calls this after storing terminal no-commit proof. */ Result rearm(Request prior, Request next, UUID recoveryOwner, long claimFence) { prior.requireCommittable(); @@ -143,6 +162,7 @@ Result rearm(Request prior, Request next, UUID recoveryOwner, long claimFence) { || row.get("owner_readback", byte[].class) == null) throw conflict(); current(next); requireSupportedShape(next); + originDecisions.accept(next); requireCurrentLifetime(next.evidence(), clock.instant()); int history = dsl.execute( @@ -283,7 +303,7 @@ static void requireClaim(Record row, UUID owner, long fence, Instant now) { throw conflict(); } - private Result commitWithFreshSnapshot(Supplier action) { + private T commitWithFreshSnapshot(Supplier action) { Context caller = Context.current(); Deadline localDeadline = Deadline.after(TRANSACTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); Deadline incoming = caller.getDeadline(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java index 22a326f5f3..02b92e229b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java @@ -77,12 +77,17 @@ public void commitTenantCapacityAdmission( observer.onError(Failure.PERMISSION_DENIED.toStatusException()); return; } - final CommitTenantCapacityAdmissionResponse result; + CommitTenantCapacityAdmissionResponse result; try { result = TenantCapacityAdmissionGrpcCodec.toResponse(request, owner.commit(request, peer)); } catch (CapacityException denied) { - observer.onError(denied.code().toStatusException()); - return; + if (!denied.code().isDomainRefusal()) { + observer.onError(denied.code().toStatusException()); + return; + } + result = + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, denied.code(), denied.durableDenialId()); } catch (org.jooq.exception.DataAccessException | org.springframework.dao.DataAccessException | org.springframework.transaction.TransactionException unavailable) { diff --git a/services/account-service/src/main/resources/db/migration/V1040.1__account_capacity_origin_decisions.sql b/services/account-service/src/main/resources/db/migration/V1040.1__account_capacity_origin_decisions.sql new file mode 100644 index 0000000000..41f80940ef --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1040.1__account_capacity_origin_decisions.sql @@ -0,0 +1,92 @@ +-- Retain the exact Account decision before a new reservation or rearm can commit. +-- Existing reservation identities and terminal evidence are left intact. +CREATE TABLE account_capacity_origin_decisions ( + tenant_uuid uuid NOT NULL, + request_id uuid NOT NULL, + admission_id uuid NOT NULL, + capacity_rearm_fence bigint NOT NULL CHECK (capacity_rearm_fence > 0), + admission_attempt_id uuid NOT NULL, + mutation_digest text NOT NULL CHECK (mutation_digest ~ '^[0-9a-f]{64}$'), + canonical_payload bytea NOT NULL CHECK (octet_length(canonical_payload) BETWEEN 1 AND 524288), + decision text NOT NULL CHECK (decision IN ('ACCEPTED', 'NO_ACCEPT')), + decision_id uuid NOT NULL UNIQUE CHECK (decision_id <> '00000000-0000-0000-0000-000000000000'), + PRIMARY KEY (tenant_uuid, request_id, admission_id, capacity_rearm_fence), + CHECK (decision <> 'NO_ACCEPT' OR capacity_rearm_fence = 1) +); + +-- [jooq ignore start] +CREATE FUNCTION account_capacity_origin_decision_immutable() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Account capacity origin decisions are immutable'; +END +$$; +CREATE TRIGGER account_capacity_origin_decision_immutable +BEFORE UPDATE OR DELETE ON account_capacity_origin_decisions +FOR EACH ROW EXECUTE FUNCTION account_capacity_origin_decision_immutable(); +CREATE TRIGGER account_capacity_origin_decision_no_truncate +BEFORE TRUNCATE ON account_capacity_origin_decisions +FOR EACH STATEMENT EXECUTE FUNCTION account_capacity_origin_decision_immutable(); + +CREATE FUNCTION account_capacity_origin_reservation_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + -- Existing reservation recovery does not need invented historical origin evidence. + IF TG_OP = 'UPDATE' AND NEW.tenant_uuid = OLD.tenant_uuid + AND NEW.request_id = OLD.request_id AND NEW.admission_id = OLD.admission_id + AND NEW.mutation_digest = OLD.mutation_digest + AND NEW.admission_attempt_id = OLD.admission_attempt_id + AND NEW.capacity_rearm_fence = OLD.capacity_rearm_fence + AND NEW.canonical_payload = OLD.canonical_payload THEN + RETURN NEW; + END IF; + IF EXISTS ( + SELECT 1 FROM account_capacity_origin_decisions d + WHERE d.tenant_uuid = NEW.tenant_uuid AND d.request_id = NEW.request_id + AND d.admission_id = NEW.admission_id AND d.decision = 'NO_ACCEPT') THEN + RAISE EXCEPTION 'Retained Account refusal excludes reservation creation or rearm'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM account_capacity_origin_decisions d + WHERE d.tenant_uuid = NEW.tenant_uuid AND d.request_id = NEW.request_id + AND d.admission_id = NEW.admission_id + AND d.capacity_rearm_fence = NEW.capacity_rearm_fence + AND d.admission_attempt_id = NEW.admission_attempt_id + AND d.mutation_digest = NEW.mutation_digest + AND d.canonical_payload = NEW.canonical_payload AND d.decision = 'ACCEPTED') THEN + RAISE EXCEPTION 'Exact Account ACCEPTED origin decision required'; + END IF; + RETURN NEW; +END +$$; +CREATE TRIGGER account_capacity_origin_reservation_guard +BEFORE INSERT OR UPDATE ON account_tenant_capacity_reservations +FOR EACH ROW EXECUTE FUNCTION account_capacity_origin_reservation_guard(); + +CREATE FUNCTION account_capacity_origin_decision_completion_guard() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.decision = 'ACCEPTED' AND NOT EXISTS ( + SELECT 1 FROM account_tenant_capacity_reservations r + WHERE r.tenant_uuid = NEW.tenant_uuid AND r.request_id = NEW.request_id + AND r.admission_id = NEW.admission_id + AND r.capacity_rearm_fence = NEW.capacity_rearm_fence + AND r.admission_attempt_id = NEW.admission_attempt_id + AND r.mutation_digest = NEW.mutation_digest + AND r.canonical_payload = NEW.canonical_payload) THEN + RAISE EXCEPTION 'ACCEPTED origin decision must commit with exact reservation'; + END IF; + IF NEW.decision = 'NO_ACCEPT' AND EXISTS ( + SELECT 1 FROM account_tenant_capacity_reservations r + WHERE r.tenant_uuid = NEW.tenant_uuid AND r.request_id = NEW.request_id + AND r.admission_id = NEW.admission_id) THEN + RAISE EXCEPTION 'NO_ACCEPT cannot contradict retained reservation'; + END IF; + RETURN NULL; +END +$$; +CREATE CONSTRAINT TRIGGER account_capacity_origin_decision_completion_guard +AFTER INSERT ON account_capacity_origin_decisions +DEFERRABLE INITIALLY DEFERRED +FOR EACH ROW EXECUTE FUNCTION account_capacity_origin_decision_completion_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V1040.2__bound_capacity_origin_refusals.sql b/services/account-service/src/main/resources/db/migration/V1040.2__bound_capacity_origin_refusals.sql new file mode 100644 index 0000000000..fc7455013d --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1040.2__bound_capacity_origin_refusals.sql @@ -0,0 +1,75 @@ +-- Refusal capacity is provisioned explicitly per tenant. Existing decisions remain immutable. +CREATE TABLE account_capacity_origin_refusal_budget ( + tenant_uuid UUID PRIMARY KEY + REFERENCES account_canonical_tenant_identity_claims(canonical_tenant_id), + maximum_refusals INTEGER NOT NULL CHECK (maximum_refusals > 0) +); + +ALTER TABLE account_capacity_origin_decisions + ADD COLUMN refusal_code TEXT, + ADD CONSTRAINT account_capacity_origin_refusal_code_check CHECK ( + refusal_code IS NULL OR ( + decision = 'NO_ACCEPT' AND refusal_code = 'CAPACITY_QUOTA_EXCEEDED')); + +CREATE INDEX account_capacity_origin_refusals_by_tenant + ON account_capacity_origin_decisions (tenant_uuid, request_id) + WHERE decision = 'NO_ACCEPT'; + +-- [jooq ignore start] +CREATE FUNCTION guard_account_capacity_origin_refusal_budget() RETURNS TRIGGER +LANGUAGE plpgsql AS $$ +DECLARE retained_count BIGINT; +BEGIN + IF TG_OP = 'INSERT' THEN + SELECT count(*) INTO retained_count FROM ( + SELECT 1 FROM account_capacity_origin_decisions + WHERE tenant_uuid = NEW.tenant_uuid AND decision = 'NO_ACCEPT' + LIMIT NEW.maximum_refusals::BIGINT + 1 + ) retained; + IF retained_count > NEW.maximum_refusals THEN + RAISE EXCEPTION 'Capacity refusal budget cannot exclude retained evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF TG_OP = 'UPDATE' THEN + -- A same-value update serializes competing refusal writers under SERIALIZABLE. + IF NEW IS NOT DISTINCT FROM OLD THEN RETURN NEW; END IF; + END IF; + RAISE EXCEPTION 'Capacity refusal budget is immutable' USING ERRCODE = '23514'; +END; +$$; +CREATE TRIGGER account_capacity_origin_refusal_budget_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_capacity_origin_refusal_budget + FOR EACH ROW EXECUTE FUNCTION guard_account_capacity_origin_refusal_budget(); +CREATE TRIGGER account_capacity_origin_refusal_budget_no_truncate + BEFORE TRUNCATE ON account_capacity_origin_refusal_budget + FOR EACH STATEMENT EXECUTE FUNCTION account_capacity_origin_decision_immutable(); + +CREATE FUNCTION require_account_capacity_origin_refusal_budget() RETURNS TRIGGER +LANGUAGE plpgsql AS $$ +DECLARE refusal_limit INTEGER; retained_count BIGINT; +BEGIN + IF NEW.decision <> 'NO_ACCEPT' THEN RETURN NEW; END IF; + UPDATE account_capacity_origin_refusal_budget + SET maximum_refusals = maximum_refusals + WHERE tenant_uuid = NEW.tenant_uuid + RETURNING maximum_refusals INTO refusal_limit; + IF NOT FOUND THEN + RAISE EXCEPTION 'Capacity refusal budget is unavailable' USING ERRCODE = '23514'; + END IF; + SELECT count(*) INTO retained_count FROM ( + SELECT 1 FROM account_capacity_origin_decisions + WHERE tenant_uuid = NEW.tenant_uuid AND decision = 'NO_ACCEPT' + LIMIT refusal_limit + ) retained; + IF retained_count >= refusal_limit THEN + RAISE EXCEPTION 'Capacity refusal budget is exhausted' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER account_capacity_origin_refusal_budget_required + BEFORE INSERT ON account_capacity_origin_decisions + FOR EACH ROW EXECUTE FUNCTION require_account_capacity_origin_refusal_budget(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index 7f67a85b2e..688570cc3d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -1,6 +1,7 @@ package integration.net.firedevops.firemud.accountservice.repository; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.charset.StandardCharsets; import java.time.Instant; @@ -8,7 +9,9 @@ import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountCapacityRefusalBudgetRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest; import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Completion; @@ -115,6 +118,51 @@ void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { .isNotNull(); assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isZero(); assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_refusal_budget"))).isZero(); + var budgets = new AccountCapacityRefusalBudgetRepository(dsl); + assertThatThrownBy( + () -> + transaction.execute( + status -> budgets.requireReady(existing.canonicalTenantId(), 4, 2))) + .isInstanceOf(AccountTenantCapacityRepository.CapacityException.class); + transaction.executeWithoutResult( + status -> budgets.provision(existing.canonicalTenantId(), 4)); + var beforeBudget = + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget WHERE tenant_uuid=?", + existing.canonicalTenantId()) + .intoMap(); + transaction.executeWithoutResult( + status -> budgets.provision(existing.canonicalTenantId(), 4)); + assertThat( + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget WHERE tenant_uuid=?", + existing.canonicalTenantId()) + .intoMap()) + .isEqualTo(beforeBudget); + Long readyHeadroom = + transaction.execute(status -> budgets.requireReady(existing.canonicalTenantId(), 4, 2)); + assertThat(readyHeadroom).isEqualTo(4L); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> budgets.provision(existing.canonicalTenantId(), 5))) + .isInstanceOf(AccountTenantCapacityRepository.CapacityException.class); + assertThatThrownBy( + () -> + transaction.execute( + status -> budgets.requireReady(later.canonicalTenantId(), 4, 1))) + .isInstanceOf(AccountTenantCapacityRepository.CapacityException.class); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> budgets.provision(existing.canonicalTenantId(), 0))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_reservations"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))).isZero(); + } finally { new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java index 0def873ad4..70c88486ea 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java @@ -865,10 +865,12 @@ private static CapacityPersistenceFixture capacityPersistenceFixture(boolean exp .at(evidence.evaluatedAt()), net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository .at(evidence.expiresAt())); - return repository.create( - request, - evidence.expiresAt(), - Clock.fixed(evidence.evaluatedAt(), ZoneOffset.UTC)); + return repository + .createIfQuotaAvailable( + request, + evidence.expiresAt(), + Clock.fixed(evidence.evaluatedAt(), ZoneOffset.UTC)) + .orElseThrow(() -> new AssertionError("Controlled fixture must have capacity")); }); var owner = new net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index 0b811bf47e..42babce94f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -80,15 +80,14 @@ void sharedRejectedUsageVectorsReachAccountReservationGuardWithoutWrites() throw request.requireCommittable(); TransactionSynchronizationManager.setActualTransactionActive(true); try { - assertThatThrownBy( - () -> - new AccountTenantCapacityRepository(dsl) - .create( - request, - request.evidence().expiresAt(), - Clock.fixed(request.evidence().evaluatedAt(), ZoneOffset.UTC))) + assertThat( + new AccountTenantCapacityRepository(dsl) + .createIfQuotaAvailable( + request, + request.evidence().expiresAt(), + Clock.fixed(request.evidence().evaluatedAt(), ZoneOffset.UTC))) .as(vector.path("name").asText()) - .hasMessage(vector.path("expected").asText()); + .isEmpty(); verify(dsl, never()).execute(anyString(), any(Object[].class)); } finally { TransactionSynchronizationManager.setActualTransactionActive(false); @@ -114,7 +113,7 @@ void expiryWhileWaitingForUsageDoesNotReserveCapacity() { assertThatThrownBy( () -> new AccountTenantCapacityRepository(dsl) - .create(request, request.evidence().expiresAt(), clock)) + .createIfQuotaAvailable(request, request.evidence().expiresAt(), clock)) .isInstanceOfSatisfying( AccountTenantCapacityRepository.CapacityException.class, failure -> assertThat(failure.code()).isEqualTo(Failure.CAPACITY_ADMISSION_STALE)); @@ -132,6 +131,35 @@ void exactReplayPrecedesFreshnessCurrentSourcesAndUsageEvenAfterOriginalExpiry() verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } + @Test + void genericNoAcceptCannotReplayAsQuotaDenial() throws Exception { + var f = new Fixture(false); + f.existing = false; + Record genericRefusal = mock(Record.class); + UUID decisionId = UUID.randomUUID(); + when(genericRefusal.get("tenant_uuid", UUID.class)).thenReturn(f.request.identity().tenantId()); + when(genericRefusal.get("request_id", UUID.class)).thenReturn(f.request.identity().requestId()); + when(genericRefusal.get("admission_id", UUID.class)) + .thenReturn(f.request.identity().admissionId()); + when(genericRefusal.get("admission_attempt_id", UUID.class)) + .thenReturn(f.request.admissionAttemptId()); + when(genericRefusal.get("mutation_digest", String.class)) + .thenReturn(f.request.mutationDigest()); + when(genericRefusal.get("canonical_payload", byte[].class)) + .thenReturn(CapacityAdmissionDigest.preimage(f.request)); + when(genericRefusal.get("decision", String.class)).thenReturn("NO_ACCEPT"); + when(genericRefusal.get("decision_id", UUID.class)).thenReturn(decisionId); + when(genericRefusal.get("refusal_code", String.class)).thenReturn(null); + f.originDecision = genericRefusal; + + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.IDEMPOTENCY_CONFLICT)); + verifyNoInteractions(f.accounts, f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + @Test void repeatedSerializationFailuresRetryAndReplayInAFreshTransaction() throws Exception { var f = new Fixture(true); @@ -450,6 +478,7 @@ private static final class Fixture { private final AccountTenantCapacityOwner owner; private boolean existing = true; private boolean retained; + private Record originDecision; private Fixture(boolean expired) throws Exception { this(expired, CapacityAdmissionTestFixture.playerRequest()); @@ -509,6 +538,8 @@ private Fixture(boolean expired, Request request, String namespace) throws Excep String sql = invocation.getArgument(0, String.class); if (sql.startsWith("SELECT * FROM account_tenant_capacity_reservations ")) return existing ? row : null; + if (sql.startsWith("SELECT * FROM account_capacity_origin_decisions ")) + return originDecision; if (sql.startsWith( "SELECT snapshot_identity FROM account_tenant_capacity_evaluations ")) return evaluation; diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java index 0bda32761b..59d525917c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -12,6 +12,7 @@ import io.grpc.Status; import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; +import java.util.UUID; import java.util.stream.Stream; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; @@ -21,8 +22,10 @@ import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Refusal; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import org.mockito.MockedConstruction; @@ -93,6 +96,50 @@ void typedOwnerEvidenceUnavailableKeepsItsPublicFailure() { } } + @ParameterizedTest + @EnumSource( + value = Failure.class, + names = {"TENANT_BILLING_BLOCKED", "CAPACITY_QUOTA_EXCEEDED"}) + void producedBillingAndQuotaDenialsReturnAnExactTypedResponse(Failure code) { + var request = CapacityAdmissionTestFixture.playerRequest(); + try (var guards = authenticatedCaller()) { + AccountTenantCapacityOwner owner = mock(); + when(owner.commit(request, CapacityAdmissionTestFixture.PEER)) + .thenThrow(new CapacityException(code)); + StreamObserver observer = mock(); + new AccountTenantCapacityGrpcService(owner, "prod") + .commitTenantCapacityAdmission( + TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); + var response = ArgumentCaptor.forClass(CommitTenantCapacityAdmissionResponse.class); + verify(observer).onNext(response.capture()); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response.getValue())) + .contains(new Refusal(code, null)); + verify(observer).onCompleted(); + verify(observer, never()).onError(any()); + } + } + + @Test + void retainedQuotaDenialCarriesTheExactAccountDecision() { + var request = CapacityAdmissionTestFixture.playerRequest(); + var decisionId = UUID.randomUUID(); + try (var guards = authenticatedCaller()) { + AccountTenantCapacityOwner owner = mock(); + when(owner.commit(request, CapacityAdmissionTestFixture.PEER)) + .thenThrow(new CapacityException(Failure.CAPACITY_QUOTA_EXCEEDED, decisionId)); + StreamObserver observer = mock(); + new AccountTenantCapacityGrpcService(owner, "prod") + .commitTenantCapacityAdmission( + TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); + var response = ArgumentCaptor.forClass(CommitTenantCapacityAdmissionResponse.class); + verify(observer).onNext(response.capture()); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response.getValue())) + .contains(new Refusal(Failure.CAPACITY_QUOTA_EXCEEDED, decisionId)); + verify(observer).onCompleted(); + verify(observer, never()).onError(any()); + } + } + private static Stream ownerEvidenceFailures() { return Stream.of( new NumberFormatException("Controlled retained billing parse failure"), diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java index 2632939b7d..23cbe5db8a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java @@ -20,18 +20,12 @@ public record OriginalNewCapacityExecution( String selectedOwnerId, long selectedOwnerFence) { public OriginalNewCapacityExecution { - Objects.requireNonNull(request).requireCommittable(); + requireOriginalNewRequest(request); Objects.requireNonNull(reservation).requireBinding(request); TenantCapacityAdmission.uuid(transitionId); if (selectedOwnerId == null || !selectedOwnerId.matches("[A-Za-z0-9._:-]{1,120}")) throw new IllegalArgumentException("Exact selected owner instance required"); - if (!(request.context() instanceof TenantCapacityAdmission.PlayerContext player) - || !"SHARED".equals(player.playableStateScope()) - || request.operation() != TenantCapacityAdmission.Operation.CAPACITY_CREATING - || !Long.valueOf(1).equals(request.capacityDelta()) - || !request.priorShape().equals(new TenantCapacityAdmission.Shape(0, 0, 0)) - || !request.requestedShape().equals(new TenantCapacityAdmission.Shape(1, 0, 0)) - || (reservation.state() != TenantCapacityAdmission.State.RESERVED + if ((reservation.state() != TenantCapacityAdmission.State.RESERVED && reservation.state() != TenantCapacityAdmission.State.FINALIZED) || !request.identity().admissionId().equals(transitionId) || selectedOwnerFence <= 0 @@ -40,6 +34,18 @@ public record OriginalNewCapacityExecution( throw new IllegalArgumentException("Exact original NEW capacity execution required"); } + public static void requireOriginalNewRequest(TenantCapacityAdmission.Request request) { + Objects.requireNonNull(request).requireCommittable(); + if (!(request.context() instanceof TenantCapacityAdmission.PlayerContext player) + || !"SHARED".equals(player.playableStateScope()) + || request.operation() != TenantCapacityAdmission.Operation.CAPACITY_CREATING + || !Long.valueOf(1).equals(request.capacityDelta()) + || !request.priorShape().equals(new TenantCapacityAdmission.Shape(0, 0, 0)) + || !request.requestedShape().equals(new TenantCapacityAdmission.Shape(1, 0, 0))) { + throw new IllegalArgumentException("Exact original NEW capacity request required"); + } + } + /** All strings have closed grammars; the complete canonical attempt includes Account evidence. */ public byte[] canonicalBytes() { Map fields = new LinkedHashMap<>(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java index 8840f13cee..5e12a2428c 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java @@ -6,6 +6,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.List; +import java.util.function.Function; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; @@ -20,11 +21,13 @@ public abstract class AbstractReloadingBlockingGrpcClient R withPublishedInitializedStub( + String unavailableMessage, Function call) { + ChannelGeneration selected; + TStub selectedStub; + synchronized (generationLock) { + selectedStub = requirePublishedInitializedStub(unavailableMessage); + selected = generation; + if (selected == null) { + throw new IllegalStateException(unavailableMessage); + } + selected.activeCalls++; + } + try { + return call.apply(selectedStub); + } finally { + boolean shutdown; + synchronized (generationLock) { + selected.activeCalls--; + shutdown = selected.retired && selected.activeCalls == 0; + } + if (shutdown) { + selected.channel.shutdown(); + } + } } protected final synchronized void reloadChannel() throws SSLException { @@ -155,11 +191,17 @@ protected final synchronized void reloadChannel() throws SSLException { newChannel.shutdown(); throw e; } - if (channel != null) { - channel.shutdown(); + retire(publishGeneration(new ChannelGeneration(newChannel), newStub)); + } + + private ChannelGeneration publishGeneration( + ChannelGeneration replacement, TStub replacementStub) { + synchronized (generationLock) { + ChannelGeneration previous = generation; + generation = replacement; + stub = replacementStub; + return previous; } - channel = newChannel; - stub = newStub; } protected final TStub stub() { @@ -191,25 +233,20 @@ protected final TStub applyStubCustomizer(TStub stub) { @Override public void close() throws IOException { TlsCertificateWatcher watcherToClose; + ChannelGeneration generationToRetire; synchronized (this) { closed = true; explicitlyInitialized = false; watcherToClose = watcher; watcher = null; + generationToRetire = publishGeneration(null, stub); } try { if (watcherToClose != null) { watcherToClose.close(); } } finally { - ManagedChannel channelToShutdown; - synchronized (this) { - channelToShutdown = channel; - channel = null; - } - if (channelToShutdown != null) { - channelToShutdown.shutdown(); - } + retire(generationToRetire); } } @@ -233,19 +270,38 @@ private void cleanupAfterInitialisationFailure(Throwable failure) { } } - ManagedChannel initialChannel; + ChannelGeneration initialGeneration; synchronized (this) { closed = true; - initialChannel = channel; - channel = null; - stub = null; + initialGeneration = publishGeneration(null, null); } - if (initialChannel != null) { - try { - initialChannel.shutdown(); - } catch (RuntimeException cleanupFailure) { - failure.addSuppressed(cleanupFailure); + try { + retire(initialGeneration); + } catch (RuntimeException cleanupFailure) { + failure.addSuppressed(cleanupFailure); + } + } + + private void retire(ChannelGeneration previous) { + synchronized (generationLock) { + if (previous == null || previous.retired) { + return; + } + previous.retired = true; + if (previous.activeCalls != 0) { + return; } } + previous.channel.shutdown(); + } + + private static final class ChannelGeneration { + private final ManagedChannel channel; + private int activeCalls; + private boolean retired; + + private ChannelGeneration(ManagedChannel channel) { + this.channel = channel; + } } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java index 1fc70b1206..02db783768 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java @@ -2,22 +2,36 @@ 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.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import io.grpc.ManagedChannel; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.stub.StreamObserver; import java.io.IOException; +import java.net.InetSocketAddress; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.BooleanSupplier; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; +import net.firedevops.firemud.gamedesign.v1.PingRequest; +import net.firedevops.firemud.gamedesign.v1.PingResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.health.contributor.Health; @@ -52,6 +66,8 @@ void explicitLifecycleInitializesOnceAndRejectsUseAfterClose() throws Exception assertThatThrownBy(client::requireExplicitStub) .isInstanceOf(IllegalStateException.class) .hasMessage("test client is not initialized and available"); + assertThatThrownBy(client::requirePublishedExplicitStub) + .isInstanceOf(IllegalStateException.class); client.initExplicit(); GameDesignServiceGrpc.GameDesignServiceBlockingStub initializedStub = @@ -60,17 +76,117 @@ void explicitLifecycleInitializesOnceAndRejectsUseAfterClose() throws Exception assertThat(factory.buildAttempts.get()).isEqualTo(1); assertThat(client.requireExplicitStub()).isSameAs(initializedStub); + assertThat(client.requirePublishedExplicitStub()).isSameAs(initializedStub); client.close(); assertThatThrownBy(client::requireExplicitStub) .isInstanceOf(IllegalStateException.class) .hasMessage("test client is not initialized and available"); + assertThatThrownBy(client::requirePublishedExplicitStub) + .isInstanceOf(IllegalStateException.class); assertThatThrownBy(client::initExplicit) .isInstanceOf(IllegalStateException.class) .hasMessage("test client is closed"); } + @Test + void replacementStubIsPublishedWhenPreviousChannelStartsShutdown() throws Exception { + var grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + var previous = mock(ManagedChannel.class); + var replacement = mock(ManagedChannel.class); + var factory = mock(GrpcChannelFactory.class); + when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(previous, replacement); + var stubAtShutdown = new AtomicReference(); + try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory)) { + client.initExplicit(); + var original = client.requirePublishedExplicitStub(); + when(previous.shutdown()) + .thenAnswer( + invocation -> { + stubAtShutdown.set(client.requirePublishedExplicitStub()); + return previous; + }); + + client.reloadChannel(); + + var published = client.requirePublishedExplicitStub(); + assertThat(published).isNotSameAs(original); + assertThat(stubAtShutdown.get()).isSameAs(published); + verify(previous).shutdown(); + } + verify(replacement).shutdown(); + } + + @Test + void selectedChannelSurvivesReplacementUntilTheBlockingCallReturns() throws Exception { + var calls = new AtomicInteger(); + var expectedResponse = PingResponse.getDefaultInstance(); + var server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .addService( + new GameDesignServiceGrpc.GameDesignServiceImplBase() { + @Override + public void ping(PingRequest request, StreamObserver observer) { + calls.incrementAndGet(); + observer.onNext(expectedResponse); + observer.onCompleted(); + } + }) + .build() + .start(); + var previous = + NettyChannelBuilder.forAddress("127.0.0.1", server.getPort()).usePlaintext().build(); + var replacement = + NettyChannelBuilder.forAddress("127.0.0.1", server.getPort()).usePlaintext().build(); + var grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + var factory = mock(GrpcChannelFactory.class); + when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(previous, replacement); + var selected = new CountDownLatch(1); + var startCall = new CountDownLatch(1); + try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory); + var executor = Executors.newSingleThreadExecutor()) { + client.initExplicit(); + var result = + executor.submit( + () -> + client.withPublishedInitializedStub( + "test client has no stub", + stub -> { + assertThat(stub.getChannel()).isSameAs(previous); + selected.countDown(); + try { + assertThat(startCall.await(5, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError(interrupted); + } + return stub.withDeadlineAfter(5, TimeUnit.SECONDS) + .ping(PingRequest.getDefaultInstance()); + })); + try { + assertThat(selected.await(5, TimeUnit.SECONDS)).isTrue(); + client.reloadChannel(); + assertThat(client.requirePublishedExplicitStub().getChannel()).isSameAs(replacement); + assertThat(previous.isShutdown()).isFalse(); + assertThat(calls).hasValue(0); + } finally { + startCall.countDown(); + } + assertThat(result.get(5, TimeUnit.SECONDS)).isEqualTo(expectedResponse); + assertThat(calls).hasValue(1); + assertThat(previous.isShutdown()).isTrue(); + } finally { + previous.shutdownNow(); + replacement.shutdownNow(); + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + @Test void initialisationFailurePreventsLateReloadFromCreatingAnotherChannel(@TempDir Path directory) throws Exception { @@ -246,6 +362,10 @@ private GameDesignServiceGrpc.GameDesignServiceBlockingStub requireExplicitStub( return requireInitializedStub("test client is not initialized and available"); } + private GameDesignServiceGrpc.GameDesignServiceBlockingStub requirePublishedExplicitStub() { + return requirePublishedInitializedStub("test client is not initialized and available"); + } + private GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub() { return stub(); } @@ -263,7 +383,7 @@ protected String defaultTarget() { @Override protected GameDesignServiceGrpc.GameDesignServiceBlockingStub buildStub( ManagedChannel channel) { - return mock(GameDesignServiceGrpc.GameDesignServiceBlockingStub.class); + return GameDesignServiceGrpc.newBlockingStub(channel); } } } diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java index 537c57c303..85d1b21e3c 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java @@ -9,11 +9,13 @@ import io.grpc.protobuf.StatusProto; import java.time.Instant; import java.util.List; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; import net.firedevops.firemud.account.v1.TenantCapacityAdmissionAttempt; import net.firedevops.firemud.account.v1.TenantCapacityAdmissionCommitment; +import net.firedevops.firemud.account.v1.TenantCapacityAdmissionRefusal; import net.firedevops.firemud.account.v1.TenantCapacityPlayerContext; import net.firedevops.firemud.account.v1.TenantCapacityShape; import net.firedevops.firemud.account.v1.TenantCapacityWorldContext; @@ -55,6 +57,10 @@ public enum Failure { this.code = code; } + public boolean isDomainRefusal() { + return this == TENANT_BILLING_BLOCKED || this == CAPACITY_QUOTA_EXCEEDED; + } + public StatusRuntimeException toStatusException() { return toStatusException(code); } @@ -74,8 +80,20 @@ private ErrorDetail detail() { } private boolean matches(Status.Code status) { - return status == code - || (this == ENTITLEMENT_UNAVAILABLE && status == Status.Code.FAILED_PRECONDITION); + return !isDomainRefusal() + && (status == code + || (this == ENTITLEMENT_UNAVAILABLE && status == Status.Code.FAILED_PRECONDITION)); + } + } + + /** Request-bound refusal content. A missing durable decision supplies no settlement proof. */ + public record Refusal(Failure code, UUID durableDenialId) { + public Refusal { + if (code == null || !code.isDomainRefusal()) throw invalid(); + if (durableDenialId != null) { + if (code != Failure.CAPACITY_QUOTA_EXCEEDED) throw invalid(); + TenantCapacityAdmission.uuid(durableDenialId); + } } } @@ -180,6 +198,7 @@ public static CommitTenantCapacityAdmissionResponse toResponse(Request request, public static Result requireResponse( Request request, CommitTenantCapacityAdmissionResponse wire) { clean(wire, MAX_RESPONSE_WIRE_BYTES); + if (wire.getRefusalCount() != 0) throw invalid(); var result = one(wire.getCommitmentList()); clean(result, MAX_RESPONSE_WIRE_BYTES); String expires = one(result.getExpiresAtList()); @@ -209,6 +228,72 @@ public static Result requireResponse( return parsed; } + public static CommitTenantCapacityAdmissionResponse toRefusal(Request request, Failure failure) { + return toRefusal(request, failure, null); + } + + public static CommitTenantCapacityAdmissionResponse toRefusal( + Request request, Failure failure, UUID durableDenialId) { + request.requireStructurallyValid(); + var refusal = new Refusal(failure, durableDenialId); + var exact = + TenantCapacityAdmissionRefusal.newBuilder() + .addTenantId(request.identity().tenantId().toString()) + .addRequestId(request.identity().requestId().toString()) + .addAdmissionId(request.identity().admissionId().toString()) + .addAdmissionAttemptId(request.admissionAttemptId().toString()) + .addCapacityRearmFence(request.capacityRearmFence()) + .addMutationDigest(request.mutationDigest()) + .addSnapshotIdentity(request.evidence().snapshotIdentity()) + .addEvaluationIdentity(request.evidence().evaluationIdentity()) + .addCode(TenantCapacityAdmissionRefusal.Code.valueOf(refusal.code().name())); + if (refusal.durableDenialId() != null) + exact.addDurableDenialId(refusal.durableDenialId().toString()); + var wire = CommitTenantCapacityAdmissionResponse.newBuilder().addRefusal(exact).build(); + clean(wire, MAX_RESPONSE_WIRE_BYTES); + return wire; + } + + /** Returns empty for the commitment envelope, which callers then verify with requireResponse. */ + public static Optional readRefusal( + Request request, CommitTenantCapacityAdmissionResponse wire) { + return readRefusalDetails(request, wire).map(Refusal::code); + } + + /** Decodes the exact refusal, including the optional durable Account decision. */ + public static Optional readRefusalDetails( + Request request, CommitTenantCapacityAdmissionResponse wire) { + clean(wire, MAX_RESPONSE_WIRE_BYTES); + if (wire.getRefusalCount() == 0) { + clean(one(wire.getCommitmentList()), MAX_RESPONSE_WIRE_BYTES); + return Optional.empty(); + } + if (wire.getCommitmentCount() != 0) throw invalid(); + var refusal = one(wire.getRefusalList()); + clean(refusal, MAX_RESPONSE_WIRE_BYTES); + request.requireStructurallyValid(); + if (!request.identity().tenantId().toString().equals(one(refusal.getTenantIdList())) + || !request.identity().requestId().toString().equals(one(refusal.getRequestIdList())) + || !request.identity().admissionId().toString().equals(one(refusal.getAdmissionIdList())) + || !request.admissionAttemptId().toString().equals(one(refusal.getAdmissionAttemptIdList())) + || request.capacityRearmFence() != one(refusal.getCapacityRearmFenceList()) + || !request.mutationDigest().equals(one(refusal.getMutationDigestList())) + || !request.evidence().snapshotIdentity().equals(one(refusal.getSnapshotIdentityList())) + || !request + .evidence() + .evaluationIdentity() + .equals(one(refusal.getEvaluationIdentityList()))) throw invalid(); + Failure code = + switch (one(refusal.getCodeList())) { + case TENANT_BILLING_BLOCKED -> Failure.TENANT_BILLING_BLOCKED; + case CAPACITY_QUOTA_EXCEEDED -> Failure.CAPACITY_QUOTA_EXCEEDED; + default -> throw invalid(); + }; + UUID durableDenialId = + refusal.getDurableDenialIdCount() == 0 ? null : uuid(one(refusal.getDurableDenialIdList())); + return Optional.of(new Refusal(code, durableDenialId)); + } + private static TenantCapacityShape shape(Shape value) { return TenantCapacityShape.newBuilder() .addActiveSessions(value.activeSessions()) diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java index bea9dda822..4d2d6ec316 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java @@ -8,11 +8,13 @@ import io.grpc.Status; import io.grpc.protobuf.StatusProto; import java.util.List; +import java.util.Locale; import java.util.UUID; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.State; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Refusal; import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.Test; @@ -20,8 +22,27 @@ class TenantCapacityAdmissionGrpcCodecTest { @Test void onlyCanonicalFailureDetailsSurviveWithoutChangingTransportStatus() { for (var failure : Failure.values()) { - var canonical = failure.toStatusException(); - assertThat(TenantCapacityAdmissionGrpcCodec.validateFailure(canonical)).isSameAs(canonical); + if (failure.isDomainRefusal()) { + assertThatThrownBy(failure::toStatusException).isInstanceOf(IllegalArgumentException.class); + var oldTransport = + StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(Status.Code.RESOURCE_EXHAUSTED.value()) + .setMessage("Tenant capacity commitment did not complete") + .addDetails( + Any.pack( + ErrorDetail.newBuilder() + .setCode(failure.name()) + .setMessage("Tenant capacity commitment did not complete") + .build())) + .build()); + var verified = TenantCapacityAdmissionGrpcCodec.validateFailure(oldTransport); + assertThat(verified.getStatus().getCode()).isEqualTo(Status.Code.RESOURCE_EXHAUSTED); + assertThat(StatusProto.fromThrowable(verified).getDetailsList()).isEmpty(); + } else { + var canonical = failure.toStatusException(); + assertThat(TenantCapacityAdmissionGrpcCodec.validateFailure(canonical)).isSameAs(canonical); + } } var deadline = Status.DEADLINE_EXCEEDED.asRuntimeException(); assertThat(TenantCapacityAdmissionGrpcCodec.validateFailure(deadline)).isSameAs(deadline); @@ -36,6 +57,96 @@ void onlyCanonicalFailureDetailsSurviveWithoutChangingTransportStatus() { assertThat(StatusProto.fromThrowable(verified).getDetailsList()).isEmpty(); } + @Test + void domainRefusalsRequireTheExactOriginalAndExclusiveResponseAlternative() { + Request request = CapacityAdmissionTestFixture.playerRequest(false); + var commitment = TenantCapacityAdmissionGrpcCodec.toResponse(request, result(request)); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusal(request, commitment)).isEmpty(); + for (var code : List.of(Failure.TENANT_BILLING_BLOCKED, Failure.CAPACITY_QUOTA_EXCEEDED)) { + var response = TenantCapacityAdmissionGrpcCodec.toRefusal(request, code); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusal(request, response)).contains(code); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response)) + .contains(new Refusal(code, null)); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.requireResponse(request, response)) + .isInstanceOf(IllegalArgumentException.class); + for (var malformed : + List.of( + response.toBuilder().clearRefusal().build(), + response.toBuilder().addRefusal(response.getRefusal(0)).build(), + response.toBuilder().addCommitment(commitment.getCommitment(0)).build(), + response.toBuilder() + .setRefusal(0, response.getRefusal(0).toBuilder().setCapacityRearmFence(0, 2)) + .build(), + response.toBuilder() + .setRefusal( + 0, + response.getRefusal(0).toBuilder() + .setTenantId(0, "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")) + .build(), + response.toBuilder() + .setRefusal( + 0, + response.getRefusal(0).toBuilder() + .setAdmissionAttemptId(0, "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")) + .build(), + response.toBuilder() + .setRefusal( + 0, response.getRefusal(0).toBuilder().setMutationDigest(0, "b".repeat(64))) + .build(), + response.toBuilder() + .setRefusal(0, response.getRefusal(0).toBuilder().setCodeValue(0, 999)) + .build())) { + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusal(request, malformed)) + .isInstanceOf(IllegalArgumentException.class); + } + } + } + + @Test + void onlyExactQuotaRefusalMayCarryOneCanonicalNonnilAccountDecisionId() { + var request = CapacityAdmissionTestFixture.playerRequest(); + var decisionId = UUID.fromString("aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"); + var response = + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, Failure.CAPACITY_QUOTA_EXCEEDED, decisionId); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response)) + .contains(new Refusal(Failure.CAPACITY_QUOTA_EXCEEDED, decisionId)); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusal(request, response)) + .contains(Failure.CAPACITY_QUOTA_EXCEEDED); + + var receipt = response.getRefusal(0); + for (var malformed : + List.of( + receipt.toBuilder().addDurableDenialId(decisionId.toString()).build(), + receipt.toBuilder().setDurableDenialId(0, "").build(), + receipt.toBuilder().setDurableDenialId(0, new UUID(0, 0).toString()).build(), + receipt.toBuilder() + .setDurableDenialId(0, decisionId.toString().toUpperCase(Locale.ROOT)) + .build(), + receipt.toBuilder().setCapacityRearmFence(0, 2).build(), + TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.TENANT_BILLING_BLOCKED) + .getRefusal(0) + .toBuilder() + .addDurableDenialId(decisionId.toString()) + .build())) { + assertThatThrownBy( + () -> + TenantCapacityAdmissionGrpcCodec.readRefusalDetails( + request, response.toBuilder().setRefusal(0, malformed).build())) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, Failure.TENANT_BILLING_BLOCKED, decisionId)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, Failure.CAPACITY_QUOTA_EXCEEDED, new UUID(0, 0))) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void exactBothAlternativesRoundTripWithCompleteBundleAndReservationBinding() { for (Request request : diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java new file mode 100644 index 0000000000..8144c9cbc0 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java @@ -0,0 +1,157 @@ +package net.firedevops.firemud.gamesession.client; + +import io.grpc.Context; +import io.grpc.Deadline; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.time.Clock; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** + * Unregistered exact Account capacity adapter. It performs no admission or owner activation CAS. + */ +public final class AccountTenantCapacityClient + extends AbstractReloadingBlockingGrpcClient { + private final String namespace; + private final Clock clock; + private final String expectedPeer; + + public AccountTenantCapacityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace, + Clock clock) { + super( + endpoints, + requireFileBackedMtls(tls, "Tenant capacity commitment"), + channels, + AccountTenantCapacityClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Namespace required"); + this.namespace = namespace; + this.expectedPeer = "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + this.clock = Objects.requireNonNull(clock); + } + + public void init() throws IOException { + requireNoAmbientSql("Capacity client initialization requires no SQL transaction"); + initOnce("Capacity client is closed", "Account capacity unavailable"); + } + + /** + * The caller must obtain its typed context from current owned player state, not text/metadata. + * Retries retain this exact request. The Account call consumes the remaining absolute admission + * budget, capped at five seconds and the incoming deadline. A timeout or an inexact response + * leaves the commitment indeterminate. Retry with the original identity. + */ + public Result commit(Request request, long absoluteDeadlineMillis) { + long maximumMillis = + TimeUnit.SECONDS.toMillis(TenantCapacityAdmissionGrpcCodec.CALL_DEADLINE_SECONDS); + Deadline maximum = Deadline.after(maximumMillis, TimeUnit.MILLISECONDS); + requireNoAmbientSql("Capacity commitment requires no ambient SQL"); + long startedMillis = clock.millis(); + request.requireStructurallyValid(); + if (request.context().owner() != TenantCapacityAdmission.Owner.GAME_SESSION + || !namespace.equals(request.targetNamespace())) + throw new IllegalArgumentException("Exact Game Session context required"); + long remainingMillis = Math.subtractExact(absoluteDeadlineMillis, startedMillis); + Deadline absoluteDeadline = + maximum.offset( + Math.max(0L, Math.min(maximumMillis, remainingMillis)) - maximumMillis, + TimeUnit.MILLISECONDS); + Deadline incoming = Context.current().getDeadline(); + Deadline deadline = incoming == null ? absoluteDeadline : absoluteDeadline.minimum(incoming); + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); + CommitTenantCapacityAdmissionResponse response; + try { + response = + withPublishedInitializedStub( + "Account capacity unavailable", + stub -> { + if (deadline.isExpired()) throw Status.DEADLINE_EXCEEDED.asRuntimeException(); + return stub.withDeadline(deadline) + .withMaxOutboundMessageSize( + TenantCapacityAdmissionGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .withMaxInboundMessageSize( + TenantCapacityAdmissionGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .commitTenantCapacityAdmission(wire); + }); + } catch (StatusRuntimeException failure) { + throw TenantCapacityAdmissionGrpcCodec.validateFailure(failure); + } + try { + var refusal = TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response); + if (refusal.isPresent()) throw new CapacityRefusedException(refusal.orElseThrow()); + // Exact retry may replay an expired/terminal reservation. The final owner still checks it. + return TenantCapacityAdmissionGrpcCodec.requireResponse(request, response); + } catch (IllegalArgumentException inexactResponse) { + throw Status.UNKNOWN + .withDescription("Account capacity commitment response was inexact") + .asRuntimeException(); + } + } + + /** Exact Account domain refusal without a capacity commitment. */ + public static final class CapacityRefusedException extends IllegalStateException { + private final TenantCapacityAdmissionGrpcCodec.Failure code; + private final UUID durableDenialId; + + private CapacityRefusedException(TenantCapacityAdmissionGrpcCodec.Refusal refusal) { + super(refusal.code().name()); + this.code = refusal.code(); + this.durableDenialId = refusal.durableDenialId(); + } + + /** Replays a durable quota denial after the local owner verifies its exact retained binding. */ + public static CapacityRefusedException retainedQuotaDenial(UUID denialId) { + return new CapacityRefusedException( + new TenantCapacityAdmissionGrpcCodec.Refusal( + TenantCapacityAdmissionGrpcCodec.Failure.CAPACITY_QUOTA_EXCEEDED, + TenantCapacityAdmission.uuid(denialId))); + } + + public TenantCapacityAdmissionGrpcCodec.Failure code() { + return code; + } + + /** The exact Account denial receipt, if the authenticated response carried one. */ + public UUID durableDenialId() { + return durableDenialId; + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountServiceGrpc.AccountServiceBlockingStub buildStub(ManagedChannel channel) { + return AccountServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeer)); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java new file mode 100644 index 0000000000..59bf151d2e --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -0,0 +1,553 @@ +package net.firedevops.firemud.gamesession.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.time.Clock; +import java.time.ZoneOffset; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.api.parallel.Resources; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +/** Real loopback mTLS with a controlled Account result; not Account sources or final admission. */ +@Timeout(90) +class AccountTenantCapacityClientMtlsTest { + private static final String TLS_RELOAD_PROPERTY = "firemud.grpc.tls-reload.enabled"; + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void certificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "Capacity client test CA", + new LoopbackMtlsTestPki.IdentitySpec( + "client", "spiffe://firemud/ns/prod/sa/game-session-service", false), + new LoopbackMtlsTestPki.IdentitySpec( + "account", "spiffe://firemud/ns/prod/sa/account-service", true), + new LoopbackMtlsTestPki.IdentitySpec( + "wrong", "spiffe://firemud/ns/prod/sa/world-management-service", true)); + } + + @Test + void exactAccountPeerReceivesCompleteRequestAndExactRetryKeepsReservation() throws Exception { + AtomicInteger calls = new AtomicInteger(); + Server server = server("account", calls, false); + try (var client = client(server)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(); + var first = client.commit(request, deadline()); + assertThat(client.commit(request, deadline())).isEqualTo(first); + assertThat(first.identity()).isEqualTo(request.identity()); + assertThat(calls).hasValue(2); + } finally { + stop(server); + } + } + + @Test + void nonCreatingEvidenceReachesControlledAccountAndReturnsStructuredPolicyDenial() + throws Exception { + AtomicInteger calls = new AtomicInteger(); + Server server = server("account", calls, false); + try (var client = client(server)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(false); + assertThatThrownBy(() -> client.commit(request, deadline())) + .isInstanceOfSatisfying( + AccountTenantCapacityClient.CapacityRefusedException.class, + refusal -> { + assertThat(refusal.code()) + .isEqualTo(TenantCapacityAdmissionGrpcCodec.Failure.TENANT_BILLING_BLOCKED); + assertThat(refusal.durableDenialId()).isNull(); + }); + assertThat(calls).hasValue(1); + } finally { + stop(server); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void quotaRefusalExposesAReceiptOnlyWhenTheAuthenticatedAccountSuppliesOne(boolean retained) + throws Exception { + var request = CapacityAdmissionTestFixture.playerRequest(); + UUID decisionId = retained ? UUID.randomUUID() : null; + var response = + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, TenantCapacityAdmissionGrpcCodec.Failure.CAPACITY_QUOTA_EXCEEDED, decisionId); + Server server = + startServer( + "account", + new AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest wire, + StreamObserver observer) { + assertThat(TenantCapacityAdmissionGrpcCodec.parseRequest(wire)).isEqualTo(request); + observer.onNext(response); + observer.onCompleted(); + } + }); + try (var client = client(server)) { + client.init(); + assertThatThrownBy(() -> client.commit(request, deadline())) + .isInstanceOfSatisfying( + AccountTenantCapacityClient.CapacityRefusedException.class, + refusal -> { + assertThat(refusal.code()) + .isEqualTo(TenantCapacityAdmissionGrpcCodec.Failure.CAPACITY_QUOTA_EXCEEDED); + assertThat(refusal.durableDenialId()).isEqualTo(decisionId); + }); + } finally { + stop(server); + } + } + + @Test + void localDenialReplayRequiresADurableDecisionId() { + var denialId = UUID.randomUUID(); + var replay = AccountTenantCapacityClient.CapacityRefusedException.retainedQuotaDenial(denialId); + assertThat(replay.code()) + .isEqualTo(TenantCapacityAdmissionGrpcCodec.Failure.CAPACITY_QUOTA_EXCEEDED); + assertThat(replay.durableDenialId()).isEqualTo(denialId); + assertThatThrownBy( + () -> + assertThat( + AccountTenantCapacityClient.CapacityRefusedException.retainedQuotaDenial( + null)) + .isNotNull()) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void mismatchedTypedRefusalDoesNotBecomeAnAccountDecision() throws Exception { + AtomicInteger calls = new AtomicInteger(); + AtomicReference serverFailure = new AtomicReference<>(); + Server server = server("account", calls, true, serverFailure); + try (var client = client(server)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(false); + assertThatThrownBy(() -> client.commit(request, deadline())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNKNOWN)); + assertThat(calls).hasValue(1); + assertThat(serverFailure.get()).isNull(); + } finally { + stop(server); + } + } + + @Test + void wrongAccountPeerIsRejectedBeforeRequestBodyRelease() throws Exception { + AtomicInteger calls = new AtomicInteger(); + Server server = server("wrong", calls, false); + try (var client = client(server)) { + client.init(); + assertThatThrownBy( + () -> client.commit(CapacityAdmissionTestFixture.playerRequest(), deadline())) + .isInstanceOf(StatusRuntimeException.class); + assertThat(calls).hasValue(0); + } finally { + stop(server); + } + } + + @Test + void changedResponseFenceLeavesTheOriginalCommitmentIndeterminate() throws Exception { + AtomicInteger calls = new AtomicInteger(); + AtomicReference serverFailure = new AtomicReference<>(); + Server server = server("account", calls, true, serverFailure); + try (var client = client(server)) { + client.init(); + assertThatThrownBy( + () -> client.commit(CapacityAdmissionTestFixture.playerRequest(), deadline())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNKNOWN)); + assertThat(calls).hasValue(1); + assertThat(serverFailure.get()).isNull(); + } finally { + stop(server); + } + } + + @ParameterizedTest + @CsvSource({"3000, 60000, 3000", "60000, 3000, 3000", "60000, 60000, 5000"}) + void successfulRpcPropagatesMinimumOfExplicitIncomingAndMaximumDeadline( + long explicitMillis, long incomingMillis, long expectedMaximumMillis) throws Exception { + AtomicInteger calls = new AtomicInteger(); + AtomicLong observedNanos = new AtomicLong(); + // Each case owns one server and one successful RPC, so no other call can supply its sample. + Server server = server("account", calls, false, observedNanos, new AtomicBoolean(true)); + var scheduler = Executors.newSingleThreadScheduledExecutor(); + try (var client = client(server)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(); + try (var context = + Context.current().withDeadlineAfter(incomingMillis, TimeUnit.MILLISECONDS, scheduler)) { + var result = + context.call( + () -> + client.commit( + request, CapacityAdmissionTestFixture.NOW.toEpochMilli() + explicitMillis)); + assertThat(result.identity()).isEqualTo(request.identity()); + } + assertThat(calls).hasValue(1); + assertThat(observedNanos.get()) + .isPositive() + .isLessThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(expectedMaximumMillis)); + } finally { + scheduler.shutdownNow(); + stop(server); + } + } + + @Test + void explicitRemainingBudgetBoundsAStalledAccountCallAndExactRetryStillReplays() + throws Exception { + AtomicInteger calls = new AtomicInteger(); + AtomicBoolean respond = new AtomicBoolean(true); + Server server = server("account", calls, false, new AtomicLong(), respond); + try (var client = client(server)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(); + var first = client.commit(request, deadline()); + respond.set(false); + long started = System.nanoTime(); + assertThatThrownBy( + () -> client.commit(request, CapacityAdmissionTestFixture.NOW.toEpochMilli() + 200L)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(2_000L); + respond.set(true); + assertThat(client.commit(request, deadline())).isEqualTo(first); + } finally { + stop(server); + } + } + + @Test + @ResourceLock(Resources.SYSTEM_PROPERTIES) + void commitReachesItsTransportDeadlineWhileTlsReloadIsBlocked() throws Exception { + String previousReloadPolicy = System.getProperty(TLS_RELOAD_PROPERTY); + System.setProperty(TLS_RELOAD_PROPERTY, "true"); + Server server = null; + try { + var calls = new AtomicInteger(); + var respond = new AtomicBoolean(true); + var tls = pki.clientProperties(directory, pki.identity("client")); + var factory = new BlockingReloadChannelFactory(); + server = server("account", calls, false, new AtomicLong(), respond); + try (var client = client(server, tls, factory); + var executor = Executors.newSingleThreadExecutor()) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(); + client.commit(request, deadline()); + respond.set(false); + try { + Files.writeString(Path.of(tls.getCertChain()), "\n", StandardOpenOption.APPEND); + assertThat(factory.reloadStarted.await(5, TimeUnit.SECONDS)).isTrue(); + long explicitDeadline = CapacityAdmissionTestFixture.NOW.toEpochMilli() + 1_000L; + var timedOut = + executor.submit( + () -> + assertThatThrownBy(() -> client.commit(request, explicitDeadline)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED))); + timedOut.get(3, TimeUnit.SECONDS); + assertThat(calls).hasValue(2); + } finally { + factory.releaseReload.countDown(); + } + } + } finally { + try { + if (server != null) stop(server); + } finally { + if (previousReloadPolicy == null) { + System.clearProperty(TLS_RELOAD_PROPERTY); + } else { + System.setProperty(TLS_RELOAD_PROPERTY, previousReloadPolicy); + } + } + } + } + + @Test + void incomingDeadlineBoundsAStalledAccountCall() throws Exception { + AtomicInteger calls = new AtomicInteger(); + AtomicBoolean respond = new AtomicBoolean(true); + Server server = server("account", calls, false, new AtomicLong(), respond); + var scheduler = Executors.newSingleThreadScheduledExecutor(); + try (var client = client(server)) { + client.init(); + var request = CapacityAdmissionTestFixture.playerRequest(); + client.commit(request, CapacityAdmissionTestFixture.NOW.toEpochMilli() + 60_000L); + respond.set(false); + long started = System.nanoTime(); + assertThatThrownBy( + () -> + Context.current() + .withDeadlineAfter(200, TimeUnit.MILLISECONDS, scheduler) + .call(() -> client.commit(request, deadline()))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(2_000L); + } finally { + scheduler.shutdownNow(); + stop(server); + } + } + + @Test + void expiredExplicitBudgetSendsNoAccountRequest() throws Exception { + AtomicInteger calls = new AtomicInteger(); + Server server = server("account", calls, false); + try (var client = client(server)) { + client.init(); + assertThatThrownBy( + () -> + client.commit( + CapacityAdmissionTestFixture.playerRequest(), + CapacityAdmissionTestFixture.NOW.toEpochMilli() - 1L)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(calls).hasValue(0); + } finally { + stop(server); + } + } + + private static long deadline() { + return CapacityAdmissionTestFixture.NOW.toEpochMilli() + 5_000L; + } + + private static AccountTenantCapacityClient client(Server server) throws Exception { + return client( + server, pki.clientProperties(directory, pki.identity("client")), new GrpcChannelFactory()); + } + + private static AccountTenantCapacityClient client( + Server server, CommonGrpcClientProperties tls, GrpcChannelFactory factory) { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + return new AccountTenantCapacityClient( + endpoints, + tls, + factory, + "prod", + Clock.fixed(CapacityAdmissionTestFixture.NOW, ZoneOffset.UTC)); + } + + private static Server server(String identity, AtomicInteger calls, boolean wrongFence) + throws Exception { + return server(identity, calls, wrongFence, new AtomicLong(), new AtomicBoolean(true)); + } + + private static Server server( + String identity, + AtomicInteger calls, + boolean wrongFence, + AtomicReference serverFailure) + throws Exception { + return server( + identity, calls, wrongFence, new AtomicLong(), new AtomicBoolean(true), serverFailure); + } + + private static Server server( + String identity, + AtomicInteger calls, + boolean wrongFence, + AtomicLong observedNanos, + AtomicBoolean respond) + throws Exception { + return server(identity, calls, wrongFence, observedNanos, respond, null); + } + + private static Server server( + String identity, + AtomicInteger calls, + boolean wrongFence, + AtomicLong observedNanos, + AtomicBoolean respond, + AtomicReference serverFailure) + throws Exception { + UUID reservationId = UUID.randomUUID(); + var service = + new AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest wire, + StreamObserver observer) { + calls.incrementAndGet(); + observedNanos.set( + Objects.requireNonNull(Context.current().getDeadline()) + .timeRemaining(TimeUnit.NANOSECONDS)); + if (!respond.get()) return; + assertServerSide( + serverFailure, + () -> + assertThat(GrpcPeerIdentity.current().uri()) + .isEqualTo("spiffe://firemud/ns/prod/sa/game-session-service")); + var request = TenantCapacityAdmissionGrpcCodec.parseRequest(wire); + assertServerSide( + serverFailure, + () -> + assertThat(request) + .isEqualTo( + CapacityAdmissionTestFixture.playerRequest( + request.evidence().permitsCreation()))); + if (!request.evidence().permitsCreation()) { + var response = + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, TenantCapacityAdmissionGrpcCodec.Failure.TENANT_BILLING_BLOCKED); + if (wrongFence) + response = + response.toBuilder() + .setRefusal( + 0, response.getRefusal(0).toBuilder().setCapacityRearmFence(0, 2)) + .build(); + observer.onNext(response); + observer.onCompleted(); + return; + } + var result = + new TenantCapacityAdmission.Result( + request.identity(), + request.admissionAttemptId(), + request.capacityRearmFence(), + request.mutationDigest(), + reservationId, + 1, + request.evidence().expiresAt(), + TenantCapacityAdmission.State.RESERVED, + request.evidence().snapshotIdentity(), + request.evidence().evaluationIdentity()); + var response = TenantCapacityAdmissionGrpcCodec.toResponse(request, result); + if (wrongFence) + response = + response.toBuilder() + .setCommitment( + 0, response.getCommitment(0).toBuilder().setCapacityRearmFence(0, 2)) + .build(); + observer.onNext(response); + observer.onCompleted(); + } + }; + return startServer(identity, service); + } + + private static Server startServer( + String identity, AccountServiceGrpc.AccountServiceImplBase service) throws Exception { + var peer = pki.identity(identity); + return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(peer.privateKey(), peer.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private static void assertServerSide( + AtomicReference serverFailure, Runnable assertion) { + try { + assertion.run(); + } catch (AssertionError failure) { + if (serverFailure != null) serverFailure.compareAndSet(null, failure); + throw failure; + } + } + + private static void stop(Server server) throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + + private static final class BlockingReloadChannelFactory extends GrpcChannelFactory { + private final AtomicBoolean initialBuild = new AtomicBoolean(true); + private final CountDownLatch reloadStarted = new CountDownLatch(1); + private final CountDownLatch releaseReload = new CountDownLatch(1); + + @Override + public ManagedChannel buildChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + if (!initialBuild.getAndSet(false)) { + reloadStarted.countDown(); + try { + if (!releaseReload.await(10, TimeUnit.SECONDS)) { + throw new SSLException("Test reload release timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new SSLException("Test reload wait interrupted", interrupted); + } + } + return super.buildChannel(target, defaultPort, properties, keepAlive); + } + } +} From a04d1ff6496f633a74554324a84cd3202d4c944d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 16 Nov 2026 05:00:56 +1300 Subject: [PATCH 02/96] fix(ci): recover failed event gate from verified PLAY exception --- .github/workflows/smoke.yml | 25 +++++++++ .../pr-required-gate-context-contract.sh | 56 +++++++++++++++++++ 2 files changed, 81 insertions(+) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index e17d781603..8d4b51095b 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -930,6 +930,28 @@ jobs: return true; } + // A failed original event is not replaced by arbitrary green history. Only + // a newer exact typed refresh with independently proven canonical exception + // evidence can recover this diagnostic gate; it never proves PLAY succeeded. + async function verifyFailedPullCanonicalRefresh(run, identity) { + if (repositoryName !== "benhook1013/FireMUD" || run.event !== "pull_request" || + run.status !== "completed" || run.conclusion !== "failure" || + !positiveInteger(run.id)) return false; + const title = `Build Runtime Images secure-pr-artifact pr-${prNumber} ` + + `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; + const replacement = await findMatchingRuntimeImagesRun("repository_dispatch", title, identity); + if (!replacement || !positiveInteger(replacement.id) || !positiveInteger(replacement.run_attempt) || replacement.id <= run.id || + replacement.event !== "repository_dispatch" || replacement.status !== "completed" || + replacement.conclusion !== "success") return false; + const jobs = await withTransientGitHubRetry("canonical transition refresh jobs lookup", () => + github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", { + owner, repo, run_id: replacement.id, attempt_number: replacement.run_attempt, per_page: 100, + }) + ); + const candidate = jobs.find((job) => job.name === canonicalSmokeJobName); + return Boolean(candidate) && await verifyKnownPlayFailure(replacement, candidate, identity); + } + // Commit objects are immutable; mutable PR/base reads stay fresh. const immutableCommits = new Map(); async function immutableCommit(ref, label) { @@ -1243,6 +1265,9 @@ jobs: const candidate = jobs.find((job) => job.name === canonicalSmokeJobName); knownPlayVerified = Boolean(candidate) && await verifyKnownPlayFailure(matching, candidate, currentIdentity); + if (!knownPlayVerified) { + knownPlayVerified = await verifyFailedPullCanonicalRefresh(matching, currentIdentity); + } } catch (error) { if (error instanceof TerminalGitHubRequestError) throw error; core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index aed084a800..a394112028 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3575,6 +3575,37 @@ async function verify(mutate = () => {}, event = "pull_request", knownPlay = tru if (accepted) assert.deepEqual(contentRequests, knownPlay ? [workflowPath, ...Object.keys(classifierDefinitions)] : [workflowPath]); return accepted; } +// A failed original event may recover only through a newer exact verified exception. +const refreshStart = script.indexOf("async function verifyFailedPullCanonicalRefresh("); +const refreshEnd = script.indexOf("// Commit objects", refreshStart); +const refreshFunction = script.slice(refreshStart, refreshEnd); +async function recoveredFailure(options = {}) { + const original = {id: 98, event: "pull_request", status: "completed", conclusion: "failure", ...options.original}; + const replacement = options.absent ? null : {id: 99, run_attempt: 2, event: "repository_dispatch", + status: "completed", conclusion: "success", ...options.replacement}; + let verified = 0, queries = 0; + const execute = new Function("repositoryName", "prNumber", "positiveInteger", "findMatchingRuntimeImagesRun", + "withTransientGitHubRetry", "github", "owner", "repo", "canonicalSmokeJobName", "verifyKnownPlayFailure", + `${refreshFunction}; return verifyFailedPullCanonicalRefresh;`); + const recover = execute(options.repository || repositoryName, "3390", value => Number.isSafeInteger(value) && value > 0, + async (event, title, selected) => { + queries++; + assert.equal(event, "repository_dispatch"); + assert.deepEqual(selected, identity); + assert.equal(title, source.display_title); + if (options.lookupError) throw options.lookupError; + return replacement; + }, (_label, call) => call(), {paginate: async (route, input) => { + assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); + assert.equal(input.run_id, 99); assert.equal(input.attempt_number, 2); + return options.noProducer ? [] : [candidate]; + }}, "benhook1013", "FireMUD", canonicalSmokeJobName, async (selected, job, selectedIdentity) => { + verified++; + assert.equal(selected, replacement); assert.equal(job, candidate); assert.deepEqual(selectedIdentity, identity); + return verify(options.mutateProof, "repository_dispatch"); + }); + return {accepted: await recover(original, identity), verified, queries}; +} // Proof errors in a successful exception attempt must fail closed. const failedStart = script.indexOf('// A continued probe'); const failedEnd = script.indexOf('if (fullSmokeJob?.conclusion !== "success")', failedStart); @@ -3652,6 +3683,31 @@ function markerAccepted(overrides = {}) { await assert.rejects(failedLegacyProof(stage, terminal), error => error === terminal); await assert.rejects(failedProof(terminal), error => error === terminal); } + assert.deepEqual(await recoveredFailure(), {accepted: true, verified: 1, queries: 1}); + for (const options of [ + {repository: "attacker/FireMUD"}, {original: {event: "repository_dispatch"}}, + {original: {status: "in_progress"}}, {original: {conclusion: "success"}}, + {original: {id: 0}}, {absent: true}, {replacement: {id: 98}}, {replacement: {id: 97}}, + {replacement: {run_attempt: 0}}, {replacement: {event: "pull_request"}}, + {replacement: {status: "in_progress"}}, {replacement: {conclusion: "failure"}}, + {replacement: {conclusion: "cancelled"}}, {noProducer: true}, + ]) { + const result = await recoveredFailure(options); + assert.equal(result.accepted, false, JSON.stringify(options)); + assert.equal(result.verified, 0, JSON.stringify(options)); + } + for (const mutateProof of [ + d => {d.currentPullRequest.labels = [];}, + d => {d.identity.headSha = "e".repeat(40);}, + d => {d.source.head_repository.full_name = "attacker/FireMUD";}, + d => {d.source.head_branch = "other";}, + d => {d.latest.run_attempt++;}, + d => {d.candidate.steps.find(s => s.name === "Stop smoke stack").conclusion = "failure";}, + d => {d.candidate.steps.find(s => s.name.startsWith("Known canonical transition")).conclusion = "skipped";}, + d => {d.candidate.steps.find(s => s.name === "Export fixed-tag preview image artifact").conclusion = "success";}, + d => {d.definitions[workflowPath].content = Buffer.from("untrusted workflow").toString("base64");}, + ]) assert.equal((await recoveredFailure({mutateProof})).accepted, false); + await assert.rejects(recoveredFailure({lookupError: new Error("unavailable")}), /unavailable/); assert.equal(markerAccepted(), true); const refreshMarker = {"github.event_name": "repository_dispatch", "github.event.pull_request.labels.*.name": [], "needs.image-meta.outputs.canonical_play_transition": "true"}; From 4a628b7b836275c08f0e4945b234a3bbfc834ea9 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:05:14 +1300 Subject: [PATCH 03/96] Fix pending canonical refresh polling and capacity retirement link --- .github/workflows/smoke.yml | 17 ++++++-- .../game-session-service/runtime-and-data.md | 4 ++ .../pr-required-gate-context-contract.sh | 42 ++++++++++++++++++- 3 files changed, 59 insertions(+), 4 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 8d4b51095b..fefd4b8095 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -941,8 +941,13 @@ jobs: `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; const replacement = await findMatchingRuntimeImagesRun("repository_dispatch", title, identity); if (!replacement || !positiveInteger(replacement.id) || !positiveInteger(replacement.run_attempt) || replacement.id <= run.id || - replacement.event !== "repository_dispatch" || replacement.status !== "completed" || - replacement.conclusion !== "success") return false; + replacement.event !== "repository_dispatch") return false; + // Pending exact refreshes are not proof, but must not fail the caller + // before the asynchronous producer can finish within its existing deadline. + if (["queued", "in_progress", "waiting", "pending", "requested"].includes(replacement.status)) { + return "pending"; + } + if (replacement.status !== "completed" || replacement.conclusion !== "success") return false; const jobs = await withTransientGitHubRetry("canonical transition refresh jobs lookup", () => github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", { owner, repo, run_id: replacement.id, attempt_number: replacement.run_attempt, per_page: 100, @@ -1266,7 +1271,13 @@ jobs: knownPlayVerified = Boolean(candidate) && await verifyKnownPlayFailure(matching, candidate, currentIdentity); if (!knownPlayVerified) { - knownPlayVerified = await verifyFailedPullCanonicalRefresh(matching, currentIdentity); + const refreshProof = await verifyFailedPullCanonicalRefresh(matching, currentIdentity); + if (refreshProof === "pending") { + core.info("Exact canonical refresh is pending; continuing within the existing smoke-gate deadline."); + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + knownPlayVerified = refreshProof === true; } } catch (error) { if (error instanceof TerminalGitHubRequestError) throw error; diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index cbb533f566..11465fc8ab 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -6,6 +6,10 @@ Game Session coordinates with Redis to store volatile session state and command The service runtime model assumes replaceable workers, not authoritative in-process state. +### Finalized capacity usage retirement + +The exact current Game Session owner establishes irreversible closure of serving and resume for the admitted binding and retains settlement of applicable effects and indexes. Game Session supplies an authenticated terminal receipt linked to the original admission, FINAL evidence, binding lineage and Account reservation. [Account owns retirement of the corresponding used capacity](../account-service/runtime-and-data.md#finalized-capacity-usage-retirement). + ## Implementation Status The manually composed initial region bridge preserves either PRESEEDED assignment provenance or the separate PLAYER_CREATED creation origin. It selects the matching authenticated Entity reader and exact purpose-versioned World placement; a sealed reference is constructed only after authenticated response validation. Preparation and bridge rows retain the closed origin independently from operation IDs, and created rows keep assignment columns NULL. Current acquisition, retry, ACK, definitive abort and final commit preserve each bridge’s own authenticated actor origin. The first actor matches its exact timeline preparation; later distinct actor transitions use that same installed region source and protected incarnation while retaining their own origins, without replacing the first preparation or its actor-bound read digest. The shared numeric runtime ID remains a scoped projection, never a creation/assignment UUID or a credential. This path is unregistered and supplies no production custody, first-OPEN or activation authority. diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index a394112028..4f93691735 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3649,6 +3649,39 @@ async function failedLegacyProof(stage, error, event = "pull_request") { assert.match(warnings[0], /^Canonical PLAY transition exception proof is unavailable:/); assert.deepEqual(outputs, []); } +// Execute the actual failed-run caller, including its labelled continue, with +// the actual refresh helper. Pending must neither grant proof nor fail early. +async function pendingRefreshCaller(statuses, expires = false) { + const failures = [], outputs = [], warnings = []; + let sleeps = 0, polls = 0, writes = 0; + const core = {info: () => {}, warning: value => warnings.push(value), + setFailed: value => failures.push(value), setOutput: (...value) => outputs.push(value)}; + core.summary = {addHeading() {return this;}, addRaw() {return this;}, + async write() {writes++;}}; + const original = {...source, id: 98, event: "pull_request", conclusion: "failure"}; + const execute = new Function("matching", "repositoryName", "github", "owner", "repo", + "canonicalSmokeJobName", "currentIdentity", "withTransientGitHubRetry", "verifyKnownPlayFailure", + "verifyFailedPullCanonicalRefresh", "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", + "core", "resolveCurrentIdentity", "identityKey", "setTimeout", "sleepMs", "withinDeadline", + `return (async () => { + smokeGatePolling: while (withinDeadline()) { ${legacyFailedBranch} break; } + core.setFailed("existing deadline expired"); + })();`); + await execute(original, repositoryName, {paginate: async () => [candidate]}, "benhook1013", "FireMUD", + canonicalSmokeJobName, identity, (_label, call) => call(), async () => false, + async () => { + const status = statuses[polls++]; + return (await recoveredFailure({replacement: {status, + conclusion: status === "completed" ? "success" : null}})).accepted; + }, async () => false, TerminalGitHubRequestError, core, async () => identity, + selected => JSON.stringify(selected), resolve => {sleeps++; resolve();}, 0, + () => polls < statuses.length); + assert.equal(polls, statuses.length); + assert.equal(sleeps, expires ? statuses.length : statuses.length - 1); + assert.deepEqual(failures, expires ? ["existing deadline expired"] : []); + assert.deepEqual(outputs, expires ? [] : [["known_play_exception", "true"]]); + assert.equal(writes, expires ? 0 : 1); +} const markerExpression = fs.readFileSync(process.argv[2] + ".marker", "utf8").trim().slice(3, -2); const markerValues = { "github.event_name": "pull_request", "github.repository": repositoryName, @@ -3684,12 +3717,19 @@ function markerAccepted(overrides = {}) { await assert.rejects(failedProof(terminal), error => error === terminal); } assert.deepEqual(await recoveredFailure(), {accepted: true, verified: 1, queries: 1}); + for (const status of ["queued", "in_progress", "waiting", "pending", "requested"]) { + assert.deepEqual(await recoveredFailure({replacement: {status, conclusion: null}}), + {accepted: "pending", verified: 0, queries: 1}); + } + await pendingRefreshCaller(["queued", "in_progress", "completed"]); + await pendingRefreshCaller(["queued", "in_progress"], true); + for (const options of [ {repository: "attacker/FireMUD"}, {original: {event: "repository_dispatch"}}, {original: {status: "in_progress"}}, {original: {conclusion: "success"}}, {original: {id: 0}}, {absent: true}, {replacement: {id: 98}}, {replacement: {id: 97}}, {replacement: {run_attempt: 0}}, {replacement: {event: "pull_request"}}, - {replacement: {status: "in_progress"}}, {replacement: {conclusion: "failure"}}, + {replacement: {status: "unknown"}}, {replacement: {conclusion: "failure"}}, {replacement: {conclusion: "cancelled"}}, {noProducer: true}, ]) { const result = await recoveredFailure(options); From 109908f780b48648a2277d27c847316bc9bf4a12 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:28:38 +1300 Subject: [PATCH 04/96] Fix capacity review contracts and bounded runtime proof polling --- .github/workflows/smoke.yml | 36 +++-- .../account-service/api-contracts.md | 2 +- .../game-session-service/runtime-and-data.md | 2 + .../pr-required-gate-context-contract.sh | 129 +++++++++++++----- ...validate_only_inserted_refusal_budgets.sql | 13 ++ ...acityMigrationPostgresIntegrationTest.java | 75 ++++++++++ .../AccountTenantCapacityOwnerTest.java | 76 +++++++++++ .../AbstractReloadingBlockingGrpcClient.java | 8 +- ...stractReloadingBlockingGrpcClientTest.java | 77 +++++++++++ .../TenantCapacityAdmissionGrpcCodec.java | 11 +- .../TenantCapacityAdmissionGrpcCodecTest.java | 60 +++++++- .../client/AccountTenantCapacityClient.java | 36 +++-- .../AccountTenantCapacityClientMtlsTest.java | 51 +++++++ 13 files changed, 522 insertions(+), 54 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V1040.3__validate_only_inserted_refusal_budgets.sql diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index fefd4b8095..f3f74ec327 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -940,7 +940,8 @@ jobs: const title = `Build Runtime Images secure-pr-artifact pr-${prNumber} ` + `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; const replacement = await findMatchingRuntimeImagesRun("repository_dispatch", title, identity); - if (!replacement || !positiveInteger(replacement.id) || !positiveInteger(replacement.run_attempt) || replacement.id <= run.id || + if (!replacement) return "pending"; + if (!positiveInteger(replacement.id) || !positiveInteger(replacement.run_attempt) || replacement.id <= run.id || replacement.event !== "repository_dispatch") return false; // Pending exact refreshes are not proof, but must not fail the caller // before the asynchronous producer can finish within its existing deadline. @@ -954,7 +955,8 @@ jobs: }) ); const candidate = jobs.find((job) => job.name === canonicalSmokeJobName); - return Boolean(candidate) && await verifyKnownPlayFailure(replacement, candidate, identity); + if (!candidate || candidate.status !== "completed") return "pending"; + return await verifyKnownPlayFailure(replacement, candidate, identity); } // Commit objects are immutable; mutable PR/base reads stay fresh. @@ -1061,7 +1063,7 @@ jobs: return newestPreExecutionCancellation; } - async function resolveCurrentIdentity(label) { + async function resolveCurrentIdentity(label, requireCurrent = false) { let currentPullRequest; try { ({ data: currentPullRequest } = await withTransientGitHubRetry( @@ -1094,6 +1096,7 @@ jobs: : null; const parents = mergeCommit?.parents ?? []; if ( + !requireCurrent && mergeCommit?.sha === eventMergeSha && parents.length === 2 && parents[0]?.sha === eventBaseSha && @@ -1174,12 +1177,13 @@ jobs: } let currentIdentity = null; + let requireCurrentIdentity = false; let cancelledRunId = null; let cancelledRunObservedAt = null; smokeGatePolling: while (Date.now() - started < timeoutMs) { if (pollIteration % pullRequestCheckInterval === 0 || !currentIdentity) { const resolvedIdentity = await resolveCurrentIdentity( - "Stopping obsolete smoke gate for" + "Stopping obsolete smoke gate for", requireCurrentIdentity ); if (resolvedIdentity?.obsolete) { return; @@ -1261,6 +1265,7 @@ jobs: if (matching.conclusion === "failure" && repositoryName === "benhook1013/FireMUD" && ["pull_request", "repository_dispatch"].includes(matching.event)) { let knownPlayVerified = false; + let refreshVerified = false; try { const jobs = await withTransientGitHubRetry("canonical transition PLAY failure jobs lookup", () => github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", { @@ -1270,6 +1275,11 @@ jobs: const candidate = jobs.find((job) => job.name === canonicalSmokeJobName); knownPlayVerified = Boolean(candidate) && await verifyKnownPlayFailure(matching, candidate, currentIdentity); + } catch (error) { + if (error instanceof TerminalGitHubRequestError) throw error; + core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); + } + try { if (!knownPlayVerified) { const refreshProof = await verifyFailedPullCanonicalRefresh(matching, currentIdentity); if (refreshProof === "pending") { @@ -1278,15 +1288,23 @@ jobs: continue smokeGatePolling; } knownPlayVerified = refreshProof === true; + refreshVerified = knownPlayVerified; } } catch (error) { if (error instanceof TerminalGitHubRequestError) throw error; core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); } if (knownPlayVerified) { - const freshIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception"); + requireCurrentIdentity ||= refreshVerified; + const freshIdentity = await resolveCurrentIdentity( + "Stopping stale canonical transition PLAY exception", requireCurrentIdentity); + // Original event proof keeps its immutable tuple semantics. Refreshed + // proof additionally requires the live base and test merge right now. + const comparableFreshIdentity = refreshVerified && freshIdentity + ? {...freshIdentity, sourceEvent: currentIdentity.sourceEvent} + : freshIdentity; if (freshIdentity?.obsolete) return; - if (!freshIdentity || identityKey(freshIdentity) !== identityKey(currentIdentity)) { + if (!freshIdentity || identityKey(comparableFreshIdentity) !== identityKey(currentIdentity)) { currentIdentity = freshIdentity; continue smokeGatePolling; } @@ -1305,7 +1323,7 @@ jobs: } const latestIdentity = await resolveCurrentIdentity( - "Stopping stale completed smoke gate for" + "Stopping stale completed smoke gate for", requireCurrentIdentity ); if (latestIdentity?.obsolete) { return; @@ -1431,7 +1449,7 @@ jobs: core.setFailed("Canonical PLAY transition exception could not be verified; runtime qualification remains blocked."); return; } - const freshIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception"); + const freshIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception", requireCurrentIdentity); if (freshIdentity?.obsolete) return; if (!freshIdentity || identityKey(freshIdentity) !== identityKey(currentIdentity)) { currentIdentity = freshIdentity; @@ -1472,7 +1490,7 @@ jobs: return; } const finalIdentity = await resolveCurrentIdentity( - "Stopping stale smoke gate before accepting full-stack proof" + "Stopping stale smoke gate before accepting full-stack proof", requireCurrentIdentity ); if (finalIdentity?.obsolete) { return; diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 826097d019..604453d6f1 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -233,7 +233,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 canonical Account UUIDs. Account resolves known subjects through one local UUID batch query with the same persisted provenance and source-row checks as scalar identity reads, then returns policies keyed by UUID. Unknown or unproven entries are intentionally omitted so Social applies complete `PRIVATE` redaction. - `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current gRPC adapter returns `FAILED_PRECONDITION` before selector parsing or owner reads; this does not implement the target export operation. -- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns the typed `TENANT_BILLING_BLOCKED` response. Fresh creation-eligible evidence with checked insufficient capacity returns the typed `CAPACITY_QUOTA_EXCEEDED` response. Each refusal is bound to the exact original attempt, mutation digest, snapshot and evaluation. A quota refusal includes the immutable Account decision UUID only after an exact durable `NO_ACCEPT` commits. A matching exact retry returns the retained receipt. A quota refusal without that receipt grants no evidence settlement authority. The response contains exactly one commitment or one typed refusal. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a changed exact retry. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns the typed `TENANT_BILLING_BLOCKED` response. Fresh creation-eligible evidence with checked insufficient capacity returns the typed `CAPACITY_QUOTA_EXCEEDED` response only after the exact durable `NO_ACCEPT` decision commits. If its refusal budget is missing or exhausted, Account returns non-OK `ENTITLEMENT_UNAVAILABLE` instead; no quota receipt or settlement authority is issued. Each refusal is bound to the exact original attempt, mutation digest, snapshot and evaluation. A quota refusal includes the immutable Account decision UUID only after an exact durable `NO_ACCEPT` commits. A matching exact retry returns the retained receipt. A quota refusal without that receipt grants no evidence settlement authority. The response contains exactly one commitment or one typed refusal. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a changed exact retry. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact attempt-and-fence retries replay; a changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. The shared [capacity-admission/v1 schema](../../../../services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json) declares the exact ADR 0047 seven-field mapping and bounds. Its `accountEvidence` member is canonical padded base64 of the complete existing Account bundle bytes, validated by the closed variant codec with canonical re-encoding equality before hashing. This binds every evidence field and cutoff/checkpoint byte, not a digest or reconstructed subset. `capacity_delta` is `optional int64`; missing presence is invalid and a present zero remains distinct. The Game Session and World alternatives retain distinct typed contexts. The ordinary registered Account receiver does not expose this private composition, and no route is enabled by adding the proto. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 11465fc8ab..1b5423f1ff 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -8,6 +8,8 @@ The service runtime model assumes replaceable workers, not authoritative in-proc ### Finalized capacity usage retirement +This is a target-only contract, not an enabled or runtime-qualified retirement path. + The exact current Game Session owner establishes irreversible closure of serving and resume for the admitted binding and retains settlement of applicable effects and indexes. Game Session supplies an authenticated terminal receipt linked to the original admission, FINAL evidence, binding lineage and Account reservation. [Account owns retirement of the corresponding used capacity](../account-service/runtime-and-data.md#finalized-capacity-usage-retirement). ## Implementation Status diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 4f93691735..c0fd881c3a 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3598,10 +3598,10 @@ async function recoveredFailure(options = {}) { }, (_label, call) => call(), {paginate: async (route, input) => { assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); assert.equal(input.run_id, 99); assert.equal(input.attempt_number, 2); - return options.noProducer ? [] : [candidate]; + return options.noProducer ? [] : [{...candidate, ...options.candidate}]; }}, "benhook1013", "FireMUD", canonicalSmokeJobName, async (selected, job, selectedIdentity) => { verified++; - assert.equal(selected, replacement); assert.equal(job, candidate); assert.deepEqual(selectedIdentity, identity); + assert.equal(selected, replacement); assert.deepEqual(job, {...candidate, ...options.candidate}); assert.deepEqual(selectedIdentity, identity); return verify(options.mutateProof, "repository_dispatch"); }); return {accepted: await recover(original, identity), verified, queries}; @@ -3639,48 +3639,96 @@ async function failedLegacyProof(stage, error, event = "pull_request") { setOutput: (...value) => outputs.push(value)}; const execute = new Function("matching", "repositoryName", "github", "owner", "repo", "canonicalSmokeJobName", "currentIdentity", "withTransientGitHubRetry", "verifyKnownPlayFailure", - "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", "core", + "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", "core", "verifyFailedPullCanonicalRefresh", `return (async () => { smokeGatePolling: while (true) { ${legacyFailedBranch} break; } })();`); await execute({...source, conclusion: "failure", event}, repositoryName, github, "benhook1013", "FireMUD", canonicalSmokeJobName, identity, (_label, call) => call(), async () => {throw error;}, async () => false, - TerminalGitHubRequestError, core); + TerminalGitHubRequestError, core, async () => false); assert.deepEqual(failures, ["Runtime images run 99 did not complete successfully: run=failure"]); assert.equal(warnings.length, 1); assert.match(warnings[0], /^Canonical PLAY transition exception proof is unavailable:/); assert.deepEqual(outputs, []); } -// Execute the actual failed-run caller, including its labelled continue, with -// the actual refresh helper. Pending must neither grant proof nor fail early. -async function pendingRefreshCaller(statuses, expires = false) { - const failures = [], outputs = [], warnings = []; - let sleeps = 0, polls = 0, writes = 0; - const core = {info: () => {}, warning: value => warnings.push(value), +// Run the production polling loop and timeout handler with a fake clock. +const loopStart = script.indexOf("let currentIdentity = null;"); +const actualPollingLoop = script.slice(loopStart); +async function pendingRefreshCaller(statuses, expires = false, options = {}) { + const failures = [], outputs = []; + let sleeps = 0, polls = 0, writes = 0, now = 0, currentChecks = 0; + const core = {info: () => {}, warning: () => {}, setFailed: value => failures.push(value), setOutput: (...value) => outputs.push(value)}; core.summary = {addHeading() {return this;}, addRaw() {return this;}, async write() {writes++;}}; - const original = {...source, id: 98, event: "pull_request", conclusion: "failure"}; - const execute = new Function("matching", "repositoryName", "github", "owner", "repo", - "canonicalSmokeJobName", "currentIdentity", "withTransientGitHubRetry", "verifyKnownPlayFailure", + const original = {...source, id: 98, event: "pull_request", status: "completed", conclusion: "failure"}; + const execute = new Function("repositoryName", "github", "owner", "repo", + "canonicalSmokeJobName", "withTransientGitHubRetry", "verifyKnownPlayFailure", "verifyFailedPullCanonicalRefresh", "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", - "core", "resolveCurrentIdentity", "identityKey", "setTimeout", "sleepMs", "withinDeadline", - `return (async () => { - smokeGatePolling: while (withinDeadline()) { ${legacyFailedBranch} break; } - core.setFailed("existing deadline expired"); - })();`); - await execute(original, repositoryName, {paginate: async () => [candidate]}, "benhook1013", "FireMUD", - canonicalSmokeJobName, identity, (_label, call) => call(), async () => false, + "core", "resolveCurrentIdentity", "identityKey", "setTimeout", "sleepMs", + "Date", "started", "timeoutMs", "pullRequestCheckInterval", "findMatchingRuntimeImagesRun", + "prNumber", "identityDiagnostic", "cancelledReplacementTimeoutMs", + `return (async () => { let pollIteration = 0; ${actualPollingLoop} })();`); + await execute(repositoryName, {rest: {actions: {listJobsForWorkflowRun: "jobs"}}, paginate: async () => { + if (options.originalError) throw options.originalError; + return [candidate]; + }}, "benhook1013", "FireMUD", canonicalSmokeJobName, (_label, call) => call(), async run => Boolean(options.recoverDrift && run.event === "repository_dispatch"), async () => { - const status = statuses[polls++]; - return (await recoveredFailure({replacement: {status, - conclusion: status === "completed" ? "success" : null}})).accepted; - }, async () => false, TerminalGitHubRequestError, core, async () => identity, - selected => JSON.stringify(selected), resolve => {sleeps++; resolve();}, 0, - () => polls < statuses.length); - assert.equal(polls, statuses.length); - assert.equal(sleeps, expires ? statuses.length : statuses.length - 1); - assert.deepEqual(failures, expires ? ["existing deadline expired"] : []); - assert.deepEqual(outputs, expires ? [] : [["known_play_exception", "true"]]); - assert.equal(writes, expires ? 0 : 1); + const status = statuses[Math.min(polls++, statuses.length - 1)]; + return (await recoveredFailure(status === "absent" ? {absent: true} + : status === "missing-job" ? {noProducer: true} + : status === "pending-job" ? {candidate: {status: "in_progress"}} + : {replacement: {status, conclusion: status === "completed" ? "success" : null}})).accepted; + }, async () => false, TerminalGitHubRequestError, core, async (_label, requireCurrent) => { + if (requireCurrent) { + currentChecks++; + if (options.finalIdentity && (!options.recoverDrift || currentChecks === 1)) now += 30; + return {...identity, sourceEvent: "repository_dispatch", ...options.finalIdentity}; + } + return identity; + }, selected => JSON.stringify(selected), resolve => {sleeps++; now += 30; resolve();}, 30, + {now: () => now}, 0, statuses.length * 30, 1, async (event, _title, selected) => { + if (options.recoverDrift && polls > 0) { + assert.equal(event, "repository_dispatch"); + assert.equal(selected.baseSha, options.finalIdentity.baseSha); + assert.equal(selected.mergeSha, options.finalIdentity.mergeSha); + return {...source, event: "repository_dispatch", status: "completed", conclusion: "success"}; + } + return original; + }, "3390", "test identity", 60); + if (expires) { + assert.equal(failures.length, 1); + assert.match(failures[0], /^Timed out waiting for the exact runtime-images\/full-smoke run/); + assert.deepEqual(outputs, []); + assert.equal(writes, 0); + } else { + assert.deepEqual(failures, []); + assert.deepEqual(outputs, [["known_play_exception", "true"]]); + assert.equal(writes, 1); + assert.equal(currentChecks, options.recoverDrift ? 4 : 1); + } + assert.equal(polls, options.recoverDrift ? 1 : statuses.length); + assert.equal(sleeps, options.finalIdentity ? 0 : expires ? statuses.length : statuses.length - 1); +} +// Exercise the real resolver, not merely a stub that honors requireCurrent. +async function refreshFinalIdentity() { + const start = script.indexOf("async function resolveCurrentIdentity("); + const end = script.indexOf("async function isCurrentPullRequestObsolete", start); + const resolver = script.slice(start, end); + const movedBase = "d".repeat(40), movedMerge = "e".repeat(40); + const execute = new Function("withTransientGitHubRetry", "github", "owner", "repo", "prNumber", + "isObsoletePullRequest", "logObsoletePullRequest", "TerminalGitHubRequestError", "core", + "eventBaseSha", "eventMergeSha", "headSha", "baseRef", "immutableCommit", + `let identityDiagnostic = ""; ${resolver}; return resolveCurrentIdentity;`); + const resolve = execute((_label, call) => call(), {rest: { + pulls: {get: async () => ({data: {merge_commit_sha: movedMerge}})}, + git: {getRef: async () => ({data: {object: {sha: movedBase}}})}, + }}, "benhook1013", "FireMUD", "3390", () => false, () => {}, TerminalGitHubRequestError, + {info: () => {}, warning: () => {}}, identity.baseSha, identity.mergeSha, identity.headSha, + identity.baseRef, async sha => ({sha, parents: [{sha: sha === movedMerge ? movedBase : identity.baseSha}, + {sha: identity.headSha}]})); + assert.equal((await resolve("original")).mergeSha, identity.mergeSha); + const fresh = await resolve("refresh", true); + assert.equal(fresh.baseSha, movedBase); + assert.equal(fresh.mergeSha, movedMerge); } const markerExpression = fs.readFileSync(process.argv[2] + ".marker", "utf8").trim().slice(3, -2); const markerValues = { @@ -3723,14 +3771,29 @@ function markerAccepted(overrides = {}) { } await pendingRefreshCaller(["queued", "in_progress", "completed"]); await pendingRefreshCaller(["queued", "in_progress"], true); + assert.equal((await recoveredFailure({absent: true})).accepted, "pending"); + assert.equal((await recoveredFailure({noProducer: true})).accepted, "pending"); + assert.equal((await recoveredFailure({candidate: {status: "in_progress"}})).accepted, "pending"); + await pendingRefreshCaller(["absent", "queued", "completed"]); + await pendingRefreshCaller(["missing-job", "pending-job", "completed"]); + await pendingRefreshCaller(["absent", "absent"], true); + await pendingRefreshCaller(["completed"], false, {originalError: Object.assign(new Error("missing"), {status: 404})}); + await refreshFinalIdentity(); + await pendingRefreshCaller(["completed"], true, {finalIdentity: {baseSha: "d".repeat(40)}}); + await pendingRefreshCaller(["completed"], true, {finalIdentity: {mergeSha: "e".repeat(40)}}); + await pendingRefreshCaller(["completed", "completed"], false, { + recoverDrift: true, finalIdentity: {baseSha: "d".repeat(40), mergeSha: "e".repeat(40)}, + }); + + for (const options of [ {repository: "attacker/FireMUD"}, {original: {event: "repository_dispatch"}}, {original: {status: "in_progress"}}, {original: {conclusion: "success"}}, - {original: {id: 0}}, {absent: true}, {replacement: {id: 98}}, {replacement: {id: 97}}, + {original: {id: 0}}, {replacement: {id: 98}}, {replacement: {id: 97}}, {replacement: {run_attempt: 0}}, {replacement: {event: "pull_request"}}, {replacement: {status: "unknown"}}, {replacement: {conclusion: "failure"}}, - {replacement: {conclusion: "cancelled"}}, {noProducer: true}, + {replacement: {conclusion: "cancelled"}}, ]) { const result = await recoveredFailure(options); assert.equal(result.accepted, false, JSON.stringify(options)); diff --git a/services/account-service/src/main/resources/db/migration/V1040.3__validate_only_inserted_refusal_budgets.sql b/services/account-service/src/main/resources/db/migration/V1040.3__validate_only_inserted_refusal_budgets.sql new file mode 100644 index 0000000000..46b335d3e8 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1040.3__validate_only_inserted_refusal_budgets.sql @@ -0,0 +1,13 @@ +-- Check historical retained evidence only when a budget is actually inserted. +-- BEFORE INSERT also runs for ON CONFLICT DO NOTHING and must not mask the +-- repository's immutable-limit IDEMPOTENCY_CONFLICT result. +-- [jooq ignore start] +DROP TRIGGER account_capacity_origin_refusal_budget_guard + ON account_capacity_origin_refusal_budget; +CREATE TRIGGER account_capacity_origin_refusal_budget_guard + BEFORE UPDATE OR DELETE ON account_capacity_origin_refusal_budget + FOR EACH ROW EXECUTE FUNCTION guard_account_capacity_origin_refusal_budget(); +CREATE TRIGGER account_capacity_origin_refusal_budget_insert_guard + AFTER INSERT ON account_capacity_origin_refusal_budget + FOR EACH ROW EXECUTE FUNCTION guard_account_capacity_origin_refusal_budget(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index 688570cc3d..b7216374ea 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -48,6 +48,81 @@ static void stop() { POSTGRES.stop(); } + @Test + void budgetConflictDoesNotMaskRetainedHistoryAndFirstInstallStillChecksIt() { + String schema = "capacity_budget_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("1040.1") + .load() + .migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); + var tenant = source(); + transaction.executeWithoutResult( + status -> + new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(tenant)); + for (int index = 0; index < 3; index++) { + 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, ?, ?, ?, 'NO_ACCEPT', ?)", + tenant.canonicalTenantId(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "a".repeat(64), + new byte[] {1}, + UUID.randomUUID()); + } + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + var budgets = new AccountCapacityRefusalBudgetRepository(dsl); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> budgets.provision(tenant.canonicalTenantId(), 2))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_refusal_budget"))).isZero(); + transaction.executeWithoutResult(status -> budgets.provision(tenant.canonicalTenantId(), 4)); + var original = + dsl.fetchOne( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget") + .intoMap(); + transaction.executeWithoutResult(status -> budgets.provision(tenant.canonicalTenantId(), 4)); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> budgets.provision(tenant.canonicalTenantId(), 2))) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> + assertThat(failure.code()) + .isEqualTo( + net.firedevops.firemud.common.account.capacity + .TenantCapacityAdmissionGrpcCodec.Failure.IDEMPOTENCY_CONFLICT)); + assertThat( + dsl.fetchOne( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget") + .intoMap()) + .isEqualTo(original); + assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))).isEqualTo(3); + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + @Test void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { String schema = "capacity_migration_" + UUID.randomUUID().toString().replace("-", ""); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index 42babce94f..d348d5660b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -160,6 +160,82 @@ void genericNoAcceptCannotReplayAsQuotaDenial() throws Exception { verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } + @Test + void durableQuotaDenialReplaysWithoutConsultingMutableCapacity() throws Exception { + var f = new Fixture(false); + f.existing = false; + Record genericRefusal = mock(Record.class); + UUID decisionId = UUID.randomUUID(); + when(genericRefusal.get("tenant_uuid", UUID.class)).thenReturn(f.request.identity().tenantId()); + when(genericRefusal.get("request_id", UUID.class)).thenReturn(f.request.identity().requestId()); + when(genericRefusal.get("admission_id", UUID.class)) + .thenReturn(f.request.identity().admissionId()); + when(genericRefusal.get("admission_attempt_id", UUID.class)) + .thenReturn(f.request.admissionAttemptId()); + when(genericRefusal.get("mutation_digest", String.class)) + .thenReturn(f.request.mutationDigest()); + when(genericRefusal.get("canonical_payload", byte[].class)) + .thenReturn(CapacityAdmissionDigest.preimage(f.request)); + when(genericRefusal.get("decision", String.class)).thenReturn("NO_ACCEPT"); + when(genericRefusal.get("decision_id", UUID.class)).thenReturn(decisionId); + when(genericRefusal.get("refusal_code", String.class)).thenReturn("CAPACITY_QUOTA_EXCEEDED"); + Record usage = mock(Record.class); + when(usage.get("held_units", Long.class)).thenReturn(f.request.evidence().quota()); + when(usage.get("used_units", Long.class)).thenReturn(0L); + org.mockito.Mockito.doReturn(usage) + .when(f.dsl) + .fetchOne(startsWith("SELECT * FROM account_tenant_capacity_usage "), any(Object[].class)); + when(f.dsl.execute( + startsWith("INSERT INTO account_capacity_origin_decisions "), any(Object[].class))) + .thenAnswer( + invocation -> { + Object[] arguments = (Object[]) invocation.getRawArguments()[1]; + assertThat(arguments[7]).isEqualTo("NO_ACCEPT"); + assertThat(arguments[9]).isEqualTo("CAPACITY_QUOTA_EXCEEDED"); + when(genericRefusal.get("decision_id", UUID.class)).thenReturn((UUID) arguments[8]); + f.originDecision = genericRefusal; + return 1; + }); + var transaction = + new org.springframework.transaction.support.TransactionTemplate( + new ControlledTransactions()); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + transaction.setTimeout(5); + UUID committedId = + transaction.execute( + status -> { + assertThat( + new AccountTenantCapacityRepository(f.dsl) + .createIfQuotaAvailable( + f.request, + f.request.evidence().expiresAt(), + Clock.fixed(CapacityAdmissionTestFixture.NOW, ZoneOffset.UTC))) + .isEmpty(); + return new net.firedevops.firemud.accountservice.repository + .AccountCapacityOriginDecisionRepository(f.dsl) + .refuseQuota(f.request); + }); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + when(usage.get("held_units", Long.class)).thenReturn(0L); + org.mockito.Mockito.clearInvocations(f.dsl); + + // Capacity is now available, but the owner must replay the committed denial. + for (int retry = 0; retry < 2; retry++) { + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> { + assertThat(failure.code()).isEqualTo(Failure.CAPACITY_QUOTA_EXCEEDED); + assertThat(failure.durableDenialId()).isEqualTo(committedId); + }); + } + verifyNoInteractions(f.accounts, f.memberships, f.issuances, f.scopes); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + verify(f.dsl, never()) + .fetchOne(startsWith("SELECT * FROM account_tenant_capacity_usage "), any(Object[].class)); + } + @Test void repeatedSerializationFailuresRetryAndReplayInAFreshTransaction() throws Exception { var f = new Fixture(true); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java index 5e12a2428c..25f6621a4a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java @@ -169,7 +169,13 @@ protected final R withPublishedInitializedStub( shutdown = selected.retired && selected.activeCalls == 0; } if (shutdown) { - selected.channel.shutdown(); + try { + selected.channel.shutdown(); + } catch (RuntimeException shutdownFailure) { + // Retirement must not replace a completed RPC response or its original failure. + logger.warn( + "Failed to shut down retired gRPC channel after call completion", shutdownFailure); + } } } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java index 02db783768..df119064bd 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java @@ -187,6 +187,83 @@ public void ping(PingRequest request, StreamObserver observer) { } } + @Test + void retiredChannelShutdownFailureDoesNotReplaceCallOutcome() throws Exception { + var grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + for (boolean failCall : new boolean[] {false, true}) { + var previous = mock(ManagedChannel.class); + var replacement = mock(ManagedChannel.class); + var factory = mock(GrpcChannelFactory.class); + when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(previous, replacement); + when(previous.shutdown()).thenThrow(new IllegalStateException("shutdown failure")); + var originalFailure = new IllegalArgumentException("original call failure"); + try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory)) { + client.initExplicit(); + java.util.function.Supplier invoke = + () -> + client.withPublishedInitializedStub( + "missing", + stub -> { + try { + client.reloadChannel(); + } catch (SSLException failure) { + throw new AssertionError(failure); + } + if (failCall) throw originalFailure; + return "response"; + }); + if (failCall) { + assertThatThrownBy(invoke::get).isSameAs(originalFailure); + } else { + assertThat(invoke.get()).isEqualTo("response"); + } + verify(previous).shutdown(); + } + } + } + + @Test + void callSelectionDoesNotWaitForReplacementChannelConstruction() throws Exception { + var grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + var previous = mock(ManagedChannel.class); + var replacement = mock(ManagedChannel.class); + var factory = mock(GrpcChannelFactory.class); + var building = new CountDownLatch(1); + var release = new CountDownLatch(1); + when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(previous) + .thenAnswer( + invocation -> { + building.countDown(); + assertThat(release.await(5, TimeUnit.SECONDS)).isTrue(); + return replacement; + }); + try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory); + var executor = Executors.newFixedThreadPool(2)) { + client.initExplicit(); + var reload = + executor.submit( + () -> { + client.reloadChannel(); + return null; + }); + try { + assertThat(building.await(5, TimeUnit.SECONDS)).isTrue(); + var call = + executor.submit( + () -> client.withPublishedInitializedStub("missing", stub -> stub.getChannel())); + assertThat(call.get(1, TimeUnit.SECONDS)).isSameAs(previous); + assertThat(release.getCount()).isEqualTo(1); + } finally { + release.countDown(); + } + reload.get(5, TimeUnit.SECONDS); + } + } + @Test void initialisationFailurePreventsLateReloadFromCreatingAnotherChannel(@TempDir Path directory) throws Exception { diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java index 85d1b21e3c..d0d9d9ba2a 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java @@ -236,6 +236,7 @@ public static CommitTenantCapacityAdmissionResponse toRefusal( Request request, Failure failure, UUID durableDenialId) { request.requireStructurallyValid(); var refusal = new Refusal(failure, durableDenialId); + requireRefusalAuthority(request, refusal); var exact = TenantCapacityAdmissionRefusal.newBuilder() .addTenantId(request.identity().tenantId().toString()) @@ -291,7 +292,15 @@ public static Optional readRefusalDetails( }; UUID durableDenialId = refusal.getDurableDenialIdCount() == 0 ? null : uuid(one(refusal.getDurableDenialIdList())); - return Optional.of(new Refusal(code, durableDenialId)); + var result = new Refusal(code, durableDenialId); + requireRefusalAuthority(request, result); + return Optional.of(result); + } + + private static void requireRefusalAuthority(Request request, Refusal refusal) { + if (refusal.code() == Failure.CAPACITY_QUOTA_EXCEEDED && !request.evidence().permitsCreation()) + throw invalid(); + if (refusal.durableDenialId() != null && request.capacityRearmFence() != 1) throw invalid(); } private static TenantCapacityShape shape(Shape value) { diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java index 4d2d6ec316..5bf5e14286 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java @@ -59,7 +59,7 @@ void onlyCanonicalFailureDetailsSurviveWithoutChangingTransportStatus() { @Test void domainRefusalsRequireTheExactOriginalAndExclusiveResponseAlternative() { - Request request = CapacityAdmissionTestFixture.playerRequest(false); + Request request = CapacityAdmissionTestFixture.playerRequest(); var commitment = TenantCapacityAdmissionGrpcCodec.toResponse(request, result(request)); assertThat(TenantCapacityAdmissionGrpcCodec.readRefusal(request, commitment)).isEmpty(); for (var code : List.of(Failure.TENANT_BILLING_BLOCKED, Failure.CAPACITY_QUOTA_EXCEEDED)) { @@ -102,6 +102,64 @@ void domainRefusalsRequireTheExactOriginalAndExclusiveResponseAlternative() { } } + @Test + void nonCreatingEvidenceCannotCarryQuotaRefusal() { + var request = CapacityAdmissionTestFixture.playerRequest(false); + var billing = + TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.TENANT_BILLING_BLOCKED); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusal(request, billing)) + .contains(Failure.TENANT_BILLING_BLOCKED); + assertThatThrownBy( + () -> + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, Failure.CAPACITY_QUOTA_EXCEEDED)) + .isInstanceOf(IllegalArgumentException.class); + var quota = + billing.toBuilder() + .setRefusal( + 0, + billing.getRefusal(0).toBuilder() + .setCode( + 0, + net.firedevops.firemud.account.v1.TenantCapacityAdmissionRefusal.Code + .CAPACITY_QUOTA_EXCEEDED)) + .build(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusal(request, quota)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void matchedRearmCannotCarryDurableOriginalDenial() { + var original = CapacityAdmissionTestFixture.playerRequest(); + var request = + new Request( + original.identity(), + UUID.randomUUID(), + 2, + original.targetNamespace(), + original.context(), + original.operation(), + original.priorShape(), + original.requestedShape(), + original.evidence(), + original.capacityDelta(), + null) + .withDigest(); + var id = UUID.randomUUID(); + assertThatThrownBy( + () -> + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, Failure.CAPACITY_QUOTA_EXCEEDED, id)) + .isInstanceOf(IllegalArgumentException.class); + var wire = TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.CAPACITY_QUOTA_EXCEEDED); + var forged = + wire.toBuilder() + .setRefusal(0, wire.getRefusal(0).toBuilder().addDurableDenialId(id.toString())) + .build(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, forged)) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void onlyExactQuotaRefusalMayCarryOneCanonicalNonnilAccountDecisionId() { var request = CapacityAdmissionTestFixture.playerRequest(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java index 8144c9cbc0..9f045cd491 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java @@ -67,18 +67,21 @@ public Result commit(Request request, long absoluteDeadlineMillis) { TimeUnit.SECONDS.toMillis(TenantCapacityAdmissionGrpcCodec.CALL_DEADLINE_SECONDS); Deadline maximum = Deadline.after(maximumMillis, TimeUnit.MILLISECONDS); requireNoAmbientSql("Capacity commitment requires no ambient SQL"); - long startedMillis = clock.millis(); + // Anchor conversion near the wall-clock sample, not at invocation entry. A pause + // during sampling can only shorten the bound; it must never extend the caller budget. + Deadline sampledAt = Deadline.after(0, TimeUnit.NANOSECONDS); + long sampledMillis = clock.millis(); request.requireStructurallyValid(); if (request.context().owner() != TenantCapacityAdmission.Owner.GAME_SESSION || !namespace.equals(request.targetNamespace())) throw new IllegalArgumentException("Exact Game Session context required"); - long remainingMillis = Math.subtractExact(absoluteDeadlineMillis, startedMillis); - Deadline absoluteDeadline = - maximum.offset( - Math.max(0L, Math.min(maximumMillis, remainingMillis)) - maximumMillis, - TimeUnit.MILLISECONDS); - Deadline incoming = Context.current().getDeadline(); - Deadline deadline = incoming == null ? absoluteDeadline : absoluteDeadline.minimum(incoming); + Deadline deadline = + selectDeadline( + maximum, + sampledAt, + Context.current().getDeadline(), + absoluteDeadlineMillis, + sampledMillis); var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); CommitTenantCapacityAdmissionResponse response; try { @@ -109,6 +112,23 @@ public Result commit(Request request, long absoluteDeadlineMillis) { } } + /** Converts paired clock samples without resetting the invocation or incoming cap. */ + static Deadline selectDeadline( + Deadline maximum, + Deadline sampledAt, + Deadline incoming, + long absoluteDeadlineMillis, + long sampledMillis) { + long remainingMillis = Math.subtractExact(absoluteDeadlineMillis, sampledMillis); + long maximumMillis = + TimeUnit.SECONDS.toMillis(TenantCapacityAdmissionGrpcCodec.CALL_DEADLINE_SECONDS); + Deadline absoluteDeadline = + sampledAt.offset( + Math.max(0L, Math.min(maximumMillis, remainingMillis)), TimeUnit.MILLISECONDS); + Deadline selected = maximum.minimum(absoluteDeadline); + return incoming == null ? selected : selected.minimum(incoming); + } + /** Exact Account domain refusal without a capacity commitment. */ public static final class CapacityRefusedException extends IllegalStateException { private final TenantCapacityAdmissionGrpcCodec.Failure code; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index 59bf151d2e..46ed96df3c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.grpc.Context; +import io.grpc.Deadline; import io.grpc.ManagedChannel; import io.grpc.Server; import io.grpc.ServerInterceptors; @@ -250,6 +251,54 @@ void successfulRpcPropagatesMinimumOfExplicitIncomingAndMaximumDeadline( } } + @ParameterizedTest + @CsvSource({"3000, 60000, 3000", "60000, 3000, 3000", "60000, 60000, 5000"}) + void deadlineSelectionKeepsTheWholeChosenBudget( + long explicitMillis, long incomingMillis, long expectedMillis) { + var nanos = new AtomicLong(); + var ticker = + new Deadline.Ticker() { + @Override + public long nanoTime() { + return nanos.get(); + } + }; + var maximum = Deadline.after(5, TimeUnit.SECONDS, ticker); + var incoming = Deadline.after(incomingMillis, TimeUnit.MILLISECONDS, ticker); + var sample = Deadline.after(0, TimeUnit.NANOSECONDS, ticker); + var selected = + AccountTenantCapacityClient.selectDeadline(maximum, sample, incoming, explicitMillis, 0); + assertThat(selected.timeRemaining(TimeUnit.MILLISECONDS)).isEqualTo(expectedMillis); + } + + @Test + void setupDelayIsNotDeductedTwiceAndOriginalInvocationCapStillApplies() { + var nanos = new AtomicLong(); + var ticker = + new Deadline.Ticker() { + @Override + public long nanoTime() { + return nanos.get(); + } + }; + var maximum = Deadline.after(5, TimeUnit.SECONDS, ticker); + nanos.set(TimeUnit.SECONDS.toNanos(1)); // Pause before the paired conversion samples. + var sample = Deadline.after(0, TimeUnit.NANOSECONDS, ticker); + assertThat( + AccountTenantCapacityClient.selectDeadline(maximum, sample, null, 3000, 1000) + .timeRemaining(TimeUnit.MILLISECONDS)) + .isEqualTo(2000); + assertThat( + AccountTenantCapacityClient.selectDeadline(maximum, sample, null, 60000, 1000) + .timeRemaining(TimeUnit.MILLISECONDS)) + .isEqualTo(4000); + nanos.addAndGet(TimeUnit.MILLISECONDS.toNanos(200)); // Delay after sampling consumes budget. + assertThat( + AccountTenantCapacityClient.selectDeadline(maximum, sample, null, 3000, 1000) + .timeRemaining(TimeUnit.MILLISECONDS)) + .isEqualTo(1800); + } + @Test void explicitRemainingBudgetBoundsAStalledAccountCallAndExactRetryStillReplays() throws Exception { @@ -269,6 +318,7 @@ void explicitRemainingBudgetBoundsAStalledAccountCallAndExactRetryStillReplays() failure -> assertThat(Status.fromThrowable(failure).getCode()) .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(calls).hasValue(2); // The timed-out invocation reached the nonresponding handler. assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(2_000L); respond.set(true); assertThat(client.commit(request, deadline())).isEqualTo(first); @@ -349,6 +399,7 @@ void incomingDeadlineBoundsAStalledAccountCall() throws Exception { failure -> assertThat(Status.fromThrowable(failure).getCode()) .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(calls).hasValue(2); // The incoming deadline bounded an actual in-flight call. assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(2_000L); } finally { scheduler.shutdownNow(); From 28e18d2467c2a2d2b32080913d6d5a9fbf9aa752 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:54:26 +1300 Subject: [PATCH 05/96] Make capacity migration proof row presence explicit --- ...TenantCapacityMigrationPostgresIntegrationTest.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index b7216374ea..c45b6ea356 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -97,8 +97,9 @@ void budgetConflictDoesNotMaskRetainedHistoryAndFirstInstallStillChecksIt() { assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_refusal_budget"))).isZero(); transaction.executeWithoutResult(status -> budgets.provision(tenant.canonicalTenantId(), 4)); var original = - dsl.fetchOne( - "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget") + Objects.requireNonNull( + dsl.fetchOne( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget")) .intoMap(); transaction.executeWithoutResult(status -> budgets.provision(tenant.canonicalTenantId(), 4)); assertThatThrownBy( @@ -113,8 +114,9 @@ void budgetConflictDoesNotMaskRetainedHistoryAndFirstInstallStillChecksIt() { net.firedevops.firemud.common.account.capacity .TenantCapacityAdmissionGrpcCodec.Failure.IDEMPOTENCY_CONFLICT)); assertThat( - dsl.fetchOne( - "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget") + Objects.requireNonNull( + dsl.fetchOne( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget")) .intoMap()) .isEqualTo(original); assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))).isEqualTo(3); From 0a7e8539f120d0ff47a49e0d261049e8d3946e3f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:21:30 +1300 Subject: [PATCH 06/96] Enforce exact capacity attempts and refresh proof boundaries --- .github/workflows/smoke.yml | 37 +++- .../pr-required-gate-context-contract.sh | 73 +++++-- ...countCapacityOriginDecisionRepository.java | 27 ++- .../service/AccountTenantCapacityOwner.java | 3 + ...1040.4__unique_capacity_origin_attempt.sql | 4 + ...acityMigrationPostgresIntegrationTest.java | 80 +++++++- .../AccountTenantCapacityOwnerTest.java | 184 +++++++++++++++--- ...stractReloadingBlockingGrpcClientTest.java | 12 +- .../TenantCapacityAdmissionGrpcCodec.java | 5 +- .../TenantCapacityAdmissionGrpcCodecTest.java | 46 ++++- .../AccountTenantCapacityClientMtlsTest.java | 21 +- 11 files changed, 433 insertions(+), 59 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V1040.4__unique_capacity_origin_attempt.sql diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index f3f74ec327..b3e8a97b6c 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -934,7 +934,9 @@ jobs: // a newer exact typed refresh with independently proven canonical exception // evidence can recover this diagnostic gate; it never proves PLAY succeeded. async function verifyFailedPullCanonicalRefresh(run, identity) { - if (repositoryName !== "benhook1013/FireMUD" || run.event !== "pull_request" || + if (repositoryName !== "benhook1013/FireMUD" || + context.payload.pull_request.head.repo?.full_name !== repositoryName || + run.event !== "pull_request" || run.status !== "completed" || run.conclusion !== "failure" || !positiveInteger(run.id)) return false; const title = `Build Runtime Images secure-pr-artifact pr-${prNumber} ` + @@ -1085,6 +1087,11 @@ jobs: return { obsolete: true }; } + const canonicalPlayEligible = + currentPullRequest.head?.repo?.full_name === repositoryName && + currentPullRequest.base?.repo?.full_name === repositoryName && + Array.isArray(currentPullRequest.labels) && + currentPullRequest.labels.some((label) => label?.name === "canonical-play-transition"); try { // Edited events can omit a usable test-merge SHA. Only immutable // ordered parents authorize event proof; otherwise require the @@ -1109,6 +1116,7 @@ jobs: headSha, mergeSha: eventMergeSha, sourceEvent: "pull_request", + canonicalPlayEligible, }; } @@ -1151,6 +1159,7 @@ jobs: headSha, mergeSha: currentMergeSha, sourceEvent: "repository_dispatch", + canonicalPlayEligible, }; } catch (error) { if (error instanceof TerminalGitHubRequestError) throw error; @@ -1281,6 +1290,24 @@ jobs: } try { if (!knownPlayVerified) { + // Direct event proof remains immutable. Its refresh fallback must + // follow base movement even before any old refresh becomes visible. + if (matching.event === "pull_request" && + context.payload.pull_request.head.repo?.full_name === repositoryName) { + const liveIdentity = await resolveCurrentIdentity( + "Resolving current canonical refresh identity", true); + if (liveIdentity?.obsolete) return; + if (!liveIdentity) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + if (identityKey({...liveIdentity, sourceEvent: currentIdentity.sourceEvent}) !== + identityKey(currentIdentity)) { + requireCurrentIdentity = true; + currentIdentity = liveIdentity; + continue smokeGatePolling; + } + } const refreshProof = await verifyFailedPullCanonicalRefresh(matching, currentIdentity); if (refreshProof === "pending") { core.info("Exact canonical refresh is pending; continuing within the existing smoke-gate deadline."); @@ -1308,6 +1335,10 @@ jobs: currentIdentity = freshIdentity; continue smokeGatePolling; } + if (!freshIdentity.canonicalPlayEligible) { + core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); + return; + } core.setOutput("known_play_exception", "true"); core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); await core.summary.addHeading("Canonical PLAY transition exception accepted") @@ -1455,6 +1486,10 @@ jobs: currentIdentity = freshIdentity; continue smokeGatePolling; } + if (!freshIdentity.canonicalPlayEligible) { + core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); + return; + } core.setOutput("known_play_exception", "true"); core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); await core.summary.addHeading("Canonical PLAY transition exception accepted") diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index c0fd881c3a..ea91494596 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3585,7 +3585,7 @@ async function recoveredFailure(options = {}) { status: "completed", conclusion: "success", ...options.replacement}; let verified = 0, queries = 0; const execute = new Function("repositoryName", "prNumber", "positiveInteger", "findMatchingRuntimeImagesRun", - "withTransientGitHubRetry", "github", "owner", "repo", "canonicalSmokeJobName", "verifyKnownPlayFailure", + "withTransientGitHubRetry", "github", "owner", "repo", "canonicalSmokeJobName", "verifyKnownPlayFailure", "context", `${refreshFunction}; return verifyFailedPullCanonicalRefresh;`); const recover = execute(options.repository || repositoryName, "3390", value => Number.isSafeInteger(value) && value > 0, async (event, title, selected) => { @@ -3603,7 +3603,7 @@ async function recoveredFailure(options = {}) { verified++; assert.equal(selected, replacement); assert.deepEqual(job, {...candidate, ...options.candidate}); assert.deepEqual(selectedIdentity, identity); return verify(options.mutateProof, "repository_dispatch"); - }); + }, {payload: {pull_request: {head: {repo: {full_name: options.headRepository || repositoryName}}}}}); return {accepted: await recover(original, identity), verified, queries}; } // Proof errors in a successful exception attempt must fail closed. @@ -3639,11 +3639,13 @@ async function failedLegacyProof(stage, error, event = "pull_request") { setOutput: (...value) => outputs.push(value)}; const execute = new Function("matching", "repositoryName", "github", "owner", "repo", "canonicalSmokeJobName", "currentIdentity", "withTransientGitHubRetry", "verifyKnownPlayFailure", - "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", "core", "verifyFailedPullCanonicalRefresh", + "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", "core", "verifyFailedPullCanonicalRefresh", "context", "resolveCurrentIdentity", "identityKey", `return (async () => { smokeGatePolling: while (true) { ${legacyFailedBranch} break; } })();`); await execute({...source, conclusion: "failure", event}, repositoryName, github, "benhook1013", "FireMUD", canonicalSmokeJobName, identity, (_label, call) => call(), async () => {throw error;}, async () => false, - TerminalGitHubRequestError, core, async () => false); + TerminalGitHubRequestError, core, async () => false, + {payload: {pull_request: {head: {repo: {full_name: repositoryName}}}}}, + async () => identity, selected => JSON.stringify(selected)); assert.deepEqual(failures, ["Runtime images run 99 did not complete successfully: run=failure"]); assert.equal(warnings.length, 1); assert.match(warnings[0], /^Canonical PLAY transition exception proof is unavailable:/); @@ -3665,36 +3667,47 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { "verifyFailedPullCanonicalRefresh", "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", "core", "resolveCurrentIdentity", "identityKey", "setTimeout", "sleepMs", "Date", "started", "timeoutMs", "pullRequestCheckInterval", "findMatchingRuntimeImagesRun", - "prNumber", "identityDiagnostic", "cancelledReplacementTimeoutMs", + "prNumber", "identityDiagnostic", "cancelledReplacementTimeoutMs", "context", `return (async () => { let pollIteration = 0; ${actualPollingLoop} })();`); await execute(repositoryName, {rest: {actions: {listJobsForWorkflowRun: "jobs"}}, paginate: async () => { if (options.originalError) throw options.originalError; return [candidate]; - }}, "benhook1013", "FireMUD", canonicalSmokeJobName, (_label, call) => call(), async run => Boolean(options.recoverDrift && run.event === "repository_dispatch"), + }}, "benhook1013", "FireMUD", canonicalSmokeJobName, (_label, call) => call(), async run => Boolean(options.directProof || (options.recoverDrift && run.event === "repository_dispatch")), async () => { const status = statuses[Math.min(polls++, statuses.length - 1)]; - return (await recoveredFailure(status === "absent" ? {absent: true} + return (await recoveredFailure(options.headRepository ? {headRepository: options.headRepository} + : status === "absent" ? {absent: true} : status === "missing-job" ? {noProducer: true} : status === "pending-job" ? {candidate: {status: "in_progress"}} : {replacement: {status, conclusion: status === "completed" ? "success" : null}})).accepted; }, async () => false, TerminalGitHubRequestError, core, async (_label, requireCurrent) => { if (requireCurrent) { currentChecks++; - if (options.finalIdentity && (!options.recoverDrift || currentChecks === 1)) now += 30; - return {...identity, sourceEvent: "repository_dispatch", ...options.finalIdentity}; + if (options.finalIdentity && polls > 0 && !options.recoverDrift) now += 30; + return {...identity, canonicalPlayEligible: !options.labelRemoved, + sourceEvent: "repository_dispatch", ...(polls > 0 ? options.finalIdentity : {})}; } - return identity; - }, selected => JSON.stringify(selected), resolve => {sleeps++; now += 30; resolve();}, 30, + return {...identity, canonicalPlayEligible: !options.labelRemoved}; + }, selected => { const {canonicalPlayEligible, ...tuple} = selected; return JSON.stringify(tuple); }, resolve => {sleeps++; now += 30; resolve();}, 30, {now: () => now}, 0, statuses.length * 30, 1, async (event, _title, selected) => { - if (options.recoverDrift && polls > 0) { + if (options.recoverDrift && polls > 0 && event === "repository_dispatch") { assert.equal(event, "repository_dispatch"); assert.equal(selected.baseSha, options.finalIdentity.baseSha); assert.equal(selected.mergeSha, options.finalIdentity.mergeSha); return {...source, event: "repository_dispatch", status: "completed", conclusion: "success"}; } return original; - }, "3390", "test identity", 60); - if (expires) { + }, "3390", "test identity", 60, + {payload: {pull_request: {head: {repo: {full_name: options.headRepository || repositoryName}}}}}); + if (options.headRepository) { + assert.deepEqual(failures, ["Runtime images run 98 did not complete successfully: run=failure"]); + assert.deepEqual(outputs, []); + assert.equal(writes, 0); + } else if (options.labelRemoved) { + assert.deepEqual(failures, ["Canonical PLAY transition exception label is absent or no longer eligible."]); + assert.deepEqual(outputs, []); + assert.equal(writes, 0); + } else if (expires) { assert.equal(failures.length, 1); assert.match(failures[0], /^Timed out waiting for the exact runtime-images\/full-smoke run/); assert.deepEqual(outputs, []); @@ -3703,10 +3716,11 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { assert.deepEqual(failures, []); assert.deepEqual(outputs, [["known_play_exception", "true"]]); assert.equal(writes, 1); - assert.equal(currentChecks, options.recoverDrift ? 4 : 1); + assert.ok(options.directProof || currentChecks >= 1); } - assert.equal(polls, options.recoverDrift ? 1 : statuses.length); - assert.equal(sleeps, options.finalIdentity ? 0 : expires ? statuses.length : statuses.length - 1); + assert.equal(polls, options.directProof ? 0 : options.recoverDrift ? 1 : statuses.length); + assert.equal(sleeps, options.finalIdentity ? (statuses[0] === "absent" ? 1 : 0) + : expires ? statuses.length : statuses.length - 1); } // Exercise the real resolver, not merely a stub that honors requireCurrent. async function refreshFinalIdentity() { @@ -3716,19 +3730,25 @@ async function refreshFinalIdentity() { const movedBase = "d".repeat(40), movedMerge = "e".repeat(40); const execute = new Function("withTransientGitHubRetry", "github", "owner", "repo", "prNumber", "isObsoletePullRequest", "logObsoletePullRequest", "TerminalGitHubRequestError", "core", - "eventBaseSha", "eventMergeSha", "headSha", "baseRef", "immutableCommit", + "eventBaseSha", "eventMergeSha", "headSha", "baseRef", "immutableCommit", "repositoryName", `let identityDiagnostic = ""; ${resolver}; return resolveCurrentIdentity;`); + const livePull = {merge_commit_sha: movedMerge, head: {repo: {full_name: repositoryName}}, + base: {repo: {full_name: repositoryName}}, labels: [{name: "canonical-play-transition"}]}; const resolve = execute((_label, call) => call(), {rest: { - pulls: {get: async () => ({data: {merge_commit_sha: movedMerge}})}, + pulls: {get: async () => ({data: livePull})}, git: {getRef: async () => ({data: {object: {sha: movedBase}}})}, }}, "benhook1013", "FireMUD", "3390", () => false, () => {}, TerminalGitHubRequestError, {info: () => {}, warning: () => {}}, identity.baseSha, identity.mergeSha, identity.headSha, identity.baseRef, async sha => ({sha, parents: [{sha: sha === movedMerge ? movedBase : identity.baseSha}, - {sha: identity.headSha}]})); + {sha: identity.headSha}]}), repositoryName); assert.equal((await resolve("original")).mergeSha, identity.mergeSha); const fresh = await resolve("refresh", true); assert.equal(fresh.baseSha, movedBase); assert.equal(fresh.mergeSha, movedMerge); + assert.equal(fresh.canonicalPlayEligible, true); + livePull.labels = []; + assert.equal((await resolve("withdrawn refresh", true)).canonicalPlayEligible, false); + assert.equal((await resolve("withdrawn direct event")).canonicalPlayEligible, false); } const markerExpression = fs.readFileSync(process.argv[2] + ".marker", "utf8").trim().slice(3, -2); const markerValues = { @@ -3769,6 +3789,16 @@ function markerAccepted(overrides = {}) { assert.deepEqual(await recoveredFailure({replacement: {status, conclusion: null}}), {accepted: "pending", verified: 0, queries: 1}); } + assert.deepEqual(await recoveredFailure({headRepository: "fork/FireMUD", absent: true}), + {accepted: false, verified: 0, queries: 0}); + await pendingRefreshCaller(["completed"], false, {labelRemoved: true}); + await pendingRefreshCaller(["completed"], false, {headRepository: "fork/FireMUD"}); + await pendingRefreshCaller(["completed"], false, {directProof: true}); + await pendingRefreshCaller(["completed"], false, {directProof: true, labelRemoved: true}); + await pendingRefreshCaller(["completed", "completed"], false, { + recoverDrift: true, labelRemoved: true, + finalIdentity: {baseSha: "d".repeat(40), mergeSha: "e".repeat(40)}, + }); await pendingRefreshCaller(["queued", "in_progress", "completed"]); await pendingRefreshCaller(["queued", "in_progress"], true); assert.equal((await recoveredFailure({absent: true})).accepted, "pending"); @@ -3784,6 +3814,9 @@ function markerAccepted(overrides = {}) { await pendingRefreshCaller(["completed", "completed"], false, { recoverDrift: true, finalIdentity: {baseSha: "d".repeat(40), mergeSha: "e".repeat(40)}, }); + await pendingRefreshCaller(["absent", "completed"], false, { + recoverDrift: true, finalIdentity: {baseSha: "d".repeat(40), mergeSha: "e".repeat(40)}, + }); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java index aa2a8e2018..0a00b96757 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java @@ -66,9 +66,10 @@ public UUID refuseQuota(Request request) { private Record retain(Request request, String decision, String refusalCode) { Record existing = find(request); if (existing != null) return requireOutcome(existing, decision, refusalCode); + requireFreshAttemptBinding(request); int inserted = 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, refusal_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (tenant_uuid, request_id, admission_id, capacity_rearm_fence) DO NOTHING", + "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, refusal_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", request.identity().tenantId(), request.identity().requestId(), request.identity().admissionId(), @@ -81,10 +82,32 @@ private Record retain(Request request, String decision, String refusalCode) { refusalCode); if (inserted != 0 && inserted != 1) throw unavailable(); Record row = find(request); - if (row == null) throw unavailable(); + if (row == null) { + requireFreshAttemptBinding(request); + throw unavailable(); + } return requireOutcome(row, decision, refusalCode); } + /** SERIALIZABLE caller: include pre-origin reservations and retained rearm history. */ + private void requireFreshAttemptBinding(Request request) { + Record conflict = + dsl.fetchOne( + "SELECT 1 FROM (" + + "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, canonical_payload FROM account_capacity_origin_decisions " + + "UNION ALL SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, canonical_payload FROM account_tenant_capacity_reservations " + + "UNION ALL SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, canonical_payload FROM account_tenant_capacity_attempt_history" + + ") retained_attempt WHERE admission_attempt_id = ? AND (tenant_uuid <> ? OR request_id <> ? OR admission_id <> ? OR capacity_rearm_fence <> ? OR mutation_digest <> ? OR canonical_payload <> ?) LIMIT 1", + request.admissionAttemptId(), + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.capacityRearmFence(), + request.mutationDigest(), + CapacityAdmissionDigest.preimage(request)); + if (conflict != null) throw conflict(); + } + private static Record requireOutcome(Record row, String decision, String refusalCode) { if (!decision.equals(row.get("decision", String.class)) || !Objects.equals(refusalCode, row.get("refusal_code", String.class))) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index bd6d915759..41c5947414 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -261,6 +261,9 @@ private void current(Request request) { || !scope.realmId().equals(player.realmId()) || !scope.playableStateScope().equals(player.playableStateScope()) || !now.isBefore(Instant.parse(scope.connectScopeExpiresAt()))) throw unavailable(); + // Source reads can consume the remaining evaluation lifetime. Retained replays + // return before current(), but a fresh refusal must still be current after qualification. + requireCurrentLifetime(evidence, clock.instant()); } private static T qualifiedSource(Supplier read) { diff --git a/services/account-service/src/main/resources/db/migration/V1040.4__unique_capacity_origin_attempt.sql b/services/account-service/src/main/resources/db/migration/V1040.4__unique_capacity_origin_attempt.sql new file mode 100644 index 0000000000..5e6fcaa847 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1040.4__unique_capacity_origin_attempt.sql @@ -0,0 +1,4 @@ +-- Fresh attempt identity is global, including durable refusals that never create a reservation. +-- Do not rewrite or discard retained evidence: conflicting historical rows require investigation. +CREATE UNIQUE INDEX account_capacity_origin_attempt_unique + ON account_capacity_origin_decisions (admission_attempt_id); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index c45b6ea356..21dbee2333 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -48,6 +48,69 @@ static void stop() { POSTGRES.stop(); } + @Test + void duplicateHistoricalOriginAttemptsStopUpgradeWithoutRewritingEvidence() { + String schema = "capacity_duplicate_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("1040.1") + .load() + .migrate(); + var dsl = DSL.using(data, SQLDialect.POSTGRES); + UUID attempt = UUID.randomUUID(); + for (int index = 0; index < 2; index++) { + 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, ?, ?, ?, 'NO_ACCEPT', ?)", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + attempt, + "a".repeat(64), + new byte[] {1}, + UUID.randomUUID()); + } + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("1040.3") + .load() + .migrate(); + var original = + dsl.fetch( + "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM account_capacity_origin_decisions ORDER BY decision_id") + .intoMaps(); + assertThatThrownBy( + () -> + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate()) + .isInstanceOf(org.flywaydb.core.api.FlywayException.class); + assertThat( + dsl.fetch( + "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM account_capacity_origin_decisions ORDER BY decision_id") + .intoMaps()) + .isEqualTo(original); + assertThat(original).hasSize(2); + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + @Test void budgetConflictDoesNotMaskRetainedHistoryAndFirstInstallStillChecksIt() { String schema = "capacity_budget_" + UUID.randomUUID().toString().replace("-", ""); @@ -69,13 +132,14 @@ void budgetConflictDoesNotMaskRetainedHistoryAndFirstInstallStillChecksIt() { transaction.executeWithoutResult( status -> new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(tenant)); + UUID retainedAttempt = UUID.randomUUID(); for (int index = 0; index < 3; index++) { 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, ?, ?, ?, 'NO_ACCEPT', ?)", tenant.canonicalTenantId(), UUID.randomUUID(), UUID.randomUUID(), - UUID.randomUUID(), + index == 0 ? retainedAttempt : UUID.randomUUID(), "a".repeat(64), new byte[] {1}, UUID.randomUUID()); @@ -119,6 +183,20 @@ void budgetConflictDoesNotMaskRetainedHistoryAndFirstInstallStillChecksIt() { "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget")) .intoMap()) .isEqualTo(original); + assertThatThrownBy( + () -> + 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, ?, ?, ?, 'NO_ACCEPT', ?)", + tenant.canonicalTenantId(), + UUID.randomUUID(), + UUID.randomUUID(), + retainedAttempt, + "b".repeat(64), + new byte[] {2}, + UUID.randomUUID())) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23505")); assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))).isEqualTo(3); } finally { new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index d348d5660b..e408498de2 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -162,7 +162,7 @@ void genericNoAcceptCannotReplayAsQuotaDenial() throws Exception { @Test void durableQuotaDenialReplaysWithoutConsultingMutableCapacity() throws Exception { - var f = new Fixture(false); + var f = new Fixture(false, qualifiedRequest(true)); f.existing = false; Record genericRefusal = mock(Record.class); UUID decisionId = UUID.randomUUID(); @@ -196,29 +196,20 @@ void durableQuotaDenialReplaysWithoutConsultingMutableCapacity() throws Exceptio f.originDecision = genericRefusal; return 1; }); - var transaction = - new org.springframework.transaction.support.TransactionTemplate( - new ControlledTransactions()); - transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); - transaction.setTimeout(5); - UUID committedId = - transaction.execute( - status -> { - assertThat( - new AccountTenantCapacityRepository(f.dsl) - .createIfQuotaAvailable( - f.request, - f.request.evidence().expiresAt(), - Clock.fixed(CapacityAdmissionTestFixture.NOW, ZoneOffset.UTC))) - .isEmpty(); - return new net.firedevops.firemud.accountservice.repository - .AccountCapacityOriginDecisionRepository(f.dsl) - .refuseQuota(f.request); + f.retained = true; + qualifySources(f); + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(failure.code()).isEqualTo(Failure.CAPACITY_QUOTA_EXCEEDED); + assertThat(failure.durableDenialId()) + .isEqualTo(genericRefusal.get("decision_id", UUID.class)); }); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + UUID committedId = genericRefusal.get("decision_id", UUID.class); when(usage.get("held_units", Long.class)).thenReturn(0L); - org.mockito.Mockito.clearInvocations(f.dsl); + org.mockito.Mockito.clearInvocations(f.dsl, f.accounts, f.memberships, f.issuances, f.scopes); // Capacity is now available, but the owner must replay the committed denial. for (int retry = 0; retry < 2; retry++) { @@ -541,6 +532,148 @@ void nonCreatingEvidenceCannotStartRecoveryOrRearmWork() throws Exception { verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes, source); } + @Test + void attemptAlreadyBoundToAnotherReservationCannotBecomeQuotaDenial() throws Exception { + var f = new Fixture(false, qualifiedRequest(true)); + f.existing = false; + f.retained = true; + qualifySources(f); + Record usage = mock(Record.class); + when(usage.get("held_units", Long.class)).thenReturn(f.request.evidence().quota()); + when(usage.get("used_units", Long.class)).thenReturn(0L); + org.mockito.Mockito.doReturn(usage) + .when(f.dsl) + .fetchOne(startsWith("SELECT * FROM account_tenant_capacity_usage "), any(Object[].class)); + // A retained reservation/history/origin with this attempt but a different outer identity. + org.mockito.Mockito.doReturn(mock(Record.class)) + .when(f.dsl) + .fetchOne(startsWith("SELECT 1 FROM (SELECT tenant_uuid"), any(Object[].class)); + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.IDEMPOTENCY_CONFLICT)); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void expiryDuringSourceQualificationCannotBecomeBillingRefusal() throws Exception { + var f = new Fixture(false, qualifiedRequest(false)); + f.existing = false; + f.retained = true; + qualifySources(f); + when(f.clock.instant()) + .thenReturn( + CapacityAdmissionTestFixture.NOW.plusSeconds(1), f.request.evidence().expiresAt()); + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.CAPACITY_ADMISSION_STALE)); + verify(f.scopes).findCanonicalEvidenceByTokenHash(anyString()); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + + @SuppressWarnings("unchecked") + private static Request qualifiedRequest(boolean creating) { + var original = CapacityAdmissionTestFixture.playerRequest(); + var player = (TenantCapacityAdmission.PlayerContext) original.context(); + var target = (Map) original.evidence().fields().get("target"); + var admitted = + CapacityAdmissionTestFixture.playerRequestFor( + player, + original.identity().admissionId(), + original.admissionAttemptId(), + "prod", + target, + CapacityAdmissionTestFixture.NOW); + if (creating) return admitted; + var fields = admitted.evidence().fields(); + var parsed = + net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence + .parseCanonical(admitted.evidence().canonicalBytes()); + Map facts = new java.util.LinkedHashMap<>(); + for (String key : + java.util.List.of( + "sourceKind", + "subscriptionStatus", + "provisioningStatus", + "gameplayAvailable", + "allowPublicJoin", + "allowNewGameplayBindings", + "allowNewInstanceStarts", + "quotas", + "entitlementVersion", + "tenantBillingSequence", + "tenantAuthorityGeneration")) { + facts.put(key, fields.get(key)); + } + facts.put("allowNewGameplayBindings", false); + var evidence = + net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence + .fromOwnerEvaluation( + player.requestId(), + admitted.evidence().callerWorkload(), + parsed.verifiedConnectScopeTokenHash(), + parsed.membershipSource(), + target, + facts, + (Map) fields.get("sourceReferences"), + CapacityAdmissionTestFixture.NOW); + return new Request( + admitted.identity(), + admitted.admissionAttemptId(), + 1, + admitted.targetNamespace(), + admitted.context(), + admitted.operation(), + admitted.priorShape(), + admitted.requestedShape(), + TenantCapacityAdmission.Evidence.player(evidence), + 1L, + null) + .withDigest(); + } + + private static void qualifySources(Fixture f) { + var player = (TenantCapacityAdmission.PlayerContext) f.request.context(); + var parsed = + net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence + .parseCanonical(f.request.evidence().canonicalBytes()); + when(f.memberships.readCurrent(player.accountId(), player.tenantId())) + .thenReturn(parsed.membershipSource()); + var source = (Map) f.request.evidence().fields().get("sourceReferences"); + var issuance = + mock( + AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData.class, + org.mockito.Mockito.RETURNS_DEEP_STUBS); + when(issuance.identity().accountId()).thenReturn(player.accountId()); + when(issuance.identity().callerWorkload()).thenReturn(f.request.evidence().callerWorkload()); + when(issuance.identity().callerContextId()) + .thenReturn(UUID.fromString((String) source.get("callerContextId"))); + when(issuance.identity().operationId()) + .thenReturn(UUID.fromString((String) source.get("callerOperationId"))); + when(issuance.identity().notBeforeEpochSecond()) + .thenReturn(CapacityAdmissionTestFixture.NOW.minusSeconds(60).getEpochSecond()); + when(issuance.identity().expiresAtEpochSecond()) + .thenReturn(CapacityAdmissionTestFixture.NOW.plusSeconds(3600).getEpochSecond()); + when(issuance.tokenSha256()).thenReturn((String) source.get("callerTokenSha256")); + when(issuance.canonicalRegistryRecordSha256()) + .thenReturn((String) source.get("callerRegistryRecordSha256")); + when(issuance.commitProofSha256()).thenReturn((String) source.get("callerCommitProofSha256")); + when(f.issuances.readCurrentCommittedCandidateByJti(any(UUID.class))) + .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) source.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(CapacityAdmissionTestFixture.NOW.plusSeconds(3600).toString()); + when(f.scopes.findCanonicalEvidenceByTokenHash(anyString())).thenReturn(Optional.of(scope)); + } + private static final class Fixture { private final DSLContext dsl = mock(DSLContext.class); private final AccountRepository accounts = mock(AccountRepository.class); @@ -549,6 +682,7 @@ private static final class Fixture { private final AccountGameplayDelegationIssuanceRepository issuances = mock(AccountGameplayDelegationIssuanceRepository.class); private final AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); + private final Clock clock = mock(Clock.class); private final Request request; private final UUID reservation = UUID.randomUUID(); private final AccountTenantCapacityOwner owner; @@ -566,6 +700,8 @@ private Fixture(boolean expired, Request request) throws Exception { private Fixture(boolean expired, Request request, String namespace) throws Exception { this.request = request; + when(clock.instant()) + .thenReturn(CapacityAdmissionTestFixture.NOW.plusSeconds(expired ? 60 : 1)); when(accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) .thenReturn(Optional.of(new Account())); Connection connection = mock(Connection.class); @@ -614,6 +750,7 @@ private Fixture(boolean expired, Request request, String namespace) throws Excep String sql = invocation.getArgument(0, String.class); if (sql.startsWith("SELECT * FROM account_tenant_capacity_reservations ")) return existing ? row : null; + if (sql.startsWith("SELECT 1 FROM (SELECT tenant_uuid")) return null; if (sql.startsWith("SELECT * FROM account_capacity_origin_decisions ")) return originDecision; if (sql.startsWith( @@ -631,8 +768,7 @@ private Fixture(boolean expired, Request request, String namespace) throws Excep issuances, scopes, new ControlledTransactions(), - Clock.fixed( - CapacityAdmissionTestFixture.NOW.plusSeconds(expired ? 60 : 1), ZoneOffset.UTC), + clock, namespace); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java index df119064bd..ec8ca0c50d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java @@ -241,8 +241,9 @@ void callSelectionDoesNotWaitForReplacementChannelConstruction() throws Exceptio assertThat(release.await(5, TimeUnit.SECONDS)).isTrue(); return replacement; }); - try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory); - var executor = Executors.newFixedThreadPool(2)) { + var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory); + var executor = Executors.newFixedThreadPool(2, Thread.ofPlatform().daemon().factory()); + try { client.initExplicit(); var reload = executor.submit( @@ -261,6 +262,13 @@ void callSelectionDoesNotWaitForReplacementChannelConstruction() throws Exceptio release.countDown(); } reload.get(5, TimeUnit.SECONDS); + } finally { + release.countDown(); + executor.shutdownNow(); + boolean terminated = executor.awaitTermination(5, TimeUnit.SECONDS); + // A regression may deadlock on non-interruptible monitors. Do not block cleanup on them. + if (terminated) client.close(); + assertThat(terminated).isTrue(); } } diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java index d0d9d9ba2a..4195637e15 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java @@ -298,8 +298,9 @@ public static Optional readRefusalDetails( } private static void requireRefusalAuthority(Request request, Refusal refusal) { - if (refusal.code() == Failure.CAPACITY_QUOTA_EXCEEDED && !request.evidence().permitsCreation()) - throw invalid(); + if (refusal.code() == Failure.CAPACITY_QUOTA_EXCEEDED + && (!request.evidence().permitsCreation() + || request.operation() != Operation.CAPACITY_CREATING)) throw invalid(); if (refusal.durableDenialId() != null && request.capacityRearmFence() != 1) throw invalid(); } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java index 5bf5e14286..ae41571fa8 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java @@ -21,8 +21,11 @@ class TenantCapacityAdmissionGrpcCodecTest { @Test void onlyCanonicalFailureDetailsSurviveWithoutChangingTransportStatus() { + var domainCodes = + java.util.Set.of(Failure.TENANT_BILLING_BLOCKED, Failure.CAPACITY_QUOTA_EXCEEDED); for (var failure : Failure.values()) { - if (failure.isDomainRefusal()) { + assertThat(failure.isDomainRefusal()).isEqualTo(domainCodes.contains(failure)); + if (domainCodes.contains(failure)) { assertThatThrownBy(failure::toStatusException).isInstanceOf(IllegalArgumentException.class); var oldTransport = StatusProto.toStatusRuntimeException( @@ -128,6 +131,47 @@ void nonCreatingEvidenceCannotCarryQuotaRefusal() { .isInstanceOf(IllegalArgumentException.class); } + @Test + void nonExpandingRequestCannotCarryQuotaRefusal() { + var original = CapacityAdmissionTestFixture.playerRequest(); + var request = + new Request( + original.identity(), + original.admissionAttemptId(), + 1, + original.targetNamespace(), + original.context(), + TenantCapacityAdmission.Operation.NON_EXPANDING_RECOVERY, + original.requestedShape(), + original.requestedShape(), + original.evidence(), + 0L, + null) + .withDigest(); + request.requireStructurallyValid(); + var id = UUID.randomUUID(); + assertThatThrownBy( + () -> + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, Failure.CAPACITY_QUOTA_EXCEEDED, id)) + .isInstanceOf(IllegalArgumentException.class); + var billing = + TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.TENANT_BILLING_BLOCKED); + var forged = + billing.toBuilder() + .setRefusal( + 0, + billing.getRefusal(0).toBuilder() + .setCode( + 0, + net.firedevops.firemud.account.v1.TenantCapacityAdmissionRefusal.Code + .CAPACITY_QUOTA_EXCEEDED) + .addDurableDenialId(id.toString())) + .build(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, forged)) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void matchedRearmCannotCarryDurableOriginalDenial() { var original = CapacityAdmissionTestFixture.playerRequest(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index 46ed96df3c..b9382942ea 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -176,7 +176,11 @@ void mismatchedTypedRefusalDoesNotBecomeAnAccountDecision() throws Exception { assertThatThrownBy(() -> client.commit(request, deadline())) .isInstanceOfSatisfying( StatusRuntimeException.class, - failure -> assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNKNOWN)); + failure -> assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNKNOWN)) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getDescription()) + .isEqualTo("Account capacity commitment response was inexact")); assertThat(calls).hasValue(1); assertThat(serverFailure.get()).isNull(); } finally { @@ -212,7 +216,11 @@ void changedResponseFenceLeavesTheOriginalCommitmentIndeterminate() throws Excep .satisfies( failure -> assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNKNOWN)); + .isEqualTo(Status.Code.UNKNOWN)) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getDescription()) + .isEqualTo("Account capacity commitment response was inexact")); assertThat(calls).hasValue(1); assertThat(serverFailure.get()).isNull(); } finally { @@ -312,14 +320,15 @@ void explicitRemainingBudgetBoundsAStalledAccountCallAndExactRetryStillReplays() respond.set(false); long started = System.nanoTime(); assertThatThrownBy( - () -> client.commit(request, CapacityAdmissionTestFixture.NOW.toEpochMilli() + 200L)) + () -> + client.commit(request, CapacityAdmissionTestFixture.NOW.toEpochMilli() + 1_000L)) .isInstanceOf(StatusRuntimeException.class) .satisfies( failure -> assertThat(Status.fromThrowable(failure).getCode()) .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); assertThat(calls).hasValue(2); // The timed-out invocation reached the nonresponding handler. - assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(2_000L); + assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(3_000L); respond.set(true); assertThat(client.commit(request, deadline())).isEqualTo(first); } finally { @@ -392,7 +401,7 @@ void incomingDeadlineBoundsAStalledAccountCall() throws Exception { assertThatThrownBy( () -> Context.current() - .withDeadlineAfter(200, TimeUnit.MILLISECONDS, scheduler) + .withDeadlineAfter(1_000, TimeUnit.MILLISECONDS, scheduler) .call(() -> client.commit(request, deadline()))) .isInstanceOf(StatusRuntimeException.class) .satisfies( @@ -400,7 +409,7 @@ void incomingDeadlineBoundsAStalledAccountCall() throws Exception { assertThat(Status.fromThrowable(failure).getCode()) .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); assertThat(calls).hasValue(2); // The incoming deadline bounded an actual in-flight call. - assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(2_000L); + assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(3_000L); } finally { scheduler.shutdownNow(); stop(server); From 284a7960985e7c6615ea04c37427db9b320e7661 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 01:58:42 +1300 Subject: [PATCH 07/96] fix: address capacity prerequisite CLI review findings --- .github/workflows/smoke.yml | 22 +++++++++++ .../game-session-service/runtime-and-data.md | 2 +- .../pr-required-gate-context-contract.sh | 38 ++++++++++++++++--- ...acityMigrationPostgresIntegrationTest.java | 12 +++++- .../AccountTenantCapacityOwnerTest.java | 20 ++++++++-- .../AccountTenantCapacityGrpcServiceTest.java | 11 ++++-- .../client/AccountTenantCapacityClient.java | 11 +++++- .../AccountTenantCapacityClientMtlsTest.java | 28 +++++++++++++- 8 files changed, 126 insertions(+), 18 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index b3e8a97b6c..a0a9d0129b 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -1301,6 +1301,10 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } + if (!liveIdentity.canonicalPlayEligible) { + core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); + return; + } if (identityKey({...liveIdentity, sourceEvent: currentIdentity.sourceEvent}) !== identityKey(currentIdentity)) { requireCurrentIdentity = true; @@ -1314,6 +1318,24 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } + if (refreshProof === false && matching.event === "pull_request" && + context.payload.pull_request.head.repo?.full_name === repositoryName) { + // A rejected proof may have observed base movement during its + // live reads. Follow that new tuple, never accept the old proof. + const liveIdentity = await resolveCurrentIdentity( + "Rechecking rejected canonical refresh identity", true); + if (liveIdentity?.obsolete) return; + if (!liveIdentity) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + if (identityKey({...liveIdentity, sourceEvent: currentIdentity.sourceEvent}) !== + identityKey(currentIdentity)) { + requireCurrentIdentity = true; + currentIdentity = liveIdentity; + continue smokeGatePolling; + } + } knownPlayVerified = refreshProof === true; refreshVerified = knownPlayVerified; } diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 1b5423f1ff..c002b1162b 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,7 +10,7 @@ The service runtime model assumes replaceable workers, not authoritative in-proc This is a target-only contract, not an enabled or runtime-qualified retirement path. -The exact current Game Session owner establishes irreversible closure of serving and resume for the admitted binding and retains settlement of applicable effects and indexes. Game Session supplies an authenticated terminal receipt linked to the original admission, FINAL evidence, binding lineage and Account reservation. [Account owns retirement of the corresponding used capacity](../account-service/runtime-and-data.md#finalized-capacity-usage-retirement). +The exact current Game Session owner establishes irreversible closure of serving and resume for the admitted binding and retains settlement of applicable effects and indexes. Game Session supplies an authenticated terminal receipt linked to the original admission, FINAL evidence, binding lineage and Account reservation. [Account owns retirement of the corresponding used capacity](../account-service/runtime-and-data.md#finalized-capacity-usage-retirement). The terminal receipt remains durable and exactly readable after binding closure and worker replacement. A replacement owner recovers and redelivers that same receipt until Account's exact retirement acknowledgement is known; this recovery never reopens serving or resume. ## Implementation Status diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index ea91494596..36a3167a53 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3556,7 +3556,7 @@ async function verify(mutate = () => {}, event = "pull_request", knownPlay = tru git: {getRef: async ({ref}) => {assert.equal(ref, `heads/${data.identity.baseRef}`); return {data: data.currentBase};}}, repos: {getContent: async ({owner, repo, path, ref}) => { assert.equal(`${owner}/${repo}`, repositoryName); - assert.equal(ref, path === workflowPath && event === "repository_dispatch" ? workflowSha : mergeSha, + assert.equal(ref, path === workflowPath && event === "repository_dispatch" ? workflowSha : data.identity.mergeSha, "workflow attestation must use its executed revision; classifier attestation must use the verified merge"); contentRequests.push(path); if (!data.definitions[path]) throw Object.assign(new Error("definition unavailable"), {status: 404}); @@ -3645,7 +3645,7 @@ async function failedLegacyProof(stage, error, event = "pull_request") { identity, (_label, call) => call(), async () => {throw error;}, async () => false, TerminalGitHubRequestError, core, async () => false, {payload: {pull_request: {head: {repo: {full_name: repositoryName}}}}}, - async () => identity, selected => JSON.stringify(selected)); + async () => ({...identity, canonicalPlayEligible: true}), selected => { const {canonicalPlayEligible, ...tuple} = selected; return JSON.stringify(tuple); }); assert.deepEqual(failures, ["Runtime images run 99 did not complete successfully: run=failure"]); assert.equal(warnings.length, 1); assert.match(warnings[0], /^Canonical PLAY transition exception proof is unavailable:/); @@ -3657,6 +3657,7 @@ const actualPollingLoop = script.slice(loopStart); async function pendingRefreshCaller(statuses, expires = false, options = {}) { const failures = [], outputs = []; let sleeps = 0, polls = 0, writes = 0, now = 0, currentChecks = 0; + const proofLive = {baseSha: identity.baseSha, mergeSha: identity.mergeSha}; const core = {info: () => {}, warning: () => {}, setFailed: value => failures.push(value), setOutput: (...value) => outputs.push(value)}; core.summary = {addHeading() {return this;}, addRaw() {return this;}, @@ -3672,9 +3673,29 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { await execute(repositoryName, {rest: {actions: {listJobsForWorkflowRun: "jobs"}}, paginate: async () => { if (options.originalError) throw options.originalError; return [candidate]; - }}, "benhook1013", "FireMUD", canonicalSmokeJobName, (_label, call) => call(), async run => Boolean(options.directProof || (options.recoverDrift && run.event === "repository_dispatch")), + }}, "benhook1013", "FireMUD", canonicalSmokeJobName, (_label, call) => call(), async run => { + if (options.proofDrift && run.event === "repository_dispatch") { + return verify(data => { + Object.assign(data.identity, proofLive); + data.currentBase.object.sha = proofLive.baseSha; + data.currentPullRequest.merge_commit_sha = proofLive.mergeSha; + data.source.display_title = data.latest.display_title = + `Build Runtime Images secure-pr-artifact pr-3390 base-${proofLive.baseSha} head-${headSha} merge-${proofLive.mergeSha} mode-required`; + }, "repository_dispatch"); + } + return Boolean(options.directProof || (options.recoverDrift && run.event === "repository_dispatch")); + }, async () => { const status = statuses[Math.min(polls++, statuses.length - 1)]; + if (options.proofDrift) { + const result = await recoveredFailure({mutateProof(data) { + Object.assign(proofLive, options.finalIdentity); + data.currentBase.object.sha = proofLive.baseSha; + data.currentPullRequest.merge_commit_sha = proofLive.mergeSha; + }}); + assert.equal(result.accepted, false, "the old refresh must fail its live tuple proof"); + return false; + } return (await recoveredFailure(options.headRepository ? {headRepository: options.headRepository} : status === "absent" ? {absent: true} : status === "missing-job" ? {noProducer: true} @@ -3685,7 +3706,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { currentChecks++; if (options.finalIdentity && polls > 0 && !options.recoverDrift) now += 30; return {...identity, canonicalPlayEligible: !options.labelRemoved, - sourceEvent: "repository_dispatch", ...(polls > 0 ? options.finalIdentity : {})}; + sourceEvent: "repository_dispatch", ...(options.proofDrift ? proofLive : polls > 0 ? options.finalIdentity : {})}; } return {...identity, canonicalPlayEligible: !options.labelRemoved}; }, selected => { const {canonicalPlayEligible, ...tuple} = selected; return JSON.stringify(tuple); }, resolve => {sleeps++; now += 30; resolve();}, 30, @@ -3718,8 +3739,8 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { assert.equal(writes, 1); assert.ok(options.directProof || currentChecks >= 1); } - assert.equal(polls, options.directProof ? 0 : options.recoverDrift ? 1 : statuses.length); - assert.equal(sleeps, options.finalIdentity ? (statuses[0] === "absent" ? 1 : 0) + assert.equal(polls, options.directProof || options.labelRemoved ? 0 : options.recoverDrift ? 1 : statuses.length); + assert.equal(sleeps, options.labelRemoved ? 0 : options.finalIdentity ? (statuses[0] === "absent" ? 1 : 0) : expires ? statuses.length : statuses.length - 1); } // Exercise the real resolver, not merely a stub that honors requireCurrent. @@ -3799,6 +3820,11 @@ function markerAccepted(overrides = {}) { recoverDrift: true, labelRemoved: true, finalIdentity: {baseSha: "d".repeat(40), mergeSha: "e".repeat(40)}, }); + await pendingRefreshCaller(["absent"], false, {labelRemoved: true}); + await pendingRefreshCaller(["completed", "completed"], false, { + recoverDrift: true, proofDrift: true, + finalIdentity: {baseSha: "d".repeat(40), mergeSha: "e".repeat(40)}, + }); await pendingRefreshCaller(["queued", "in_progress", "completed"]); await pendingRefreshCaller(["queued", "in_progress"], true); assert.equal((await recoveredFailure({absent: true})).accepted, "pending"); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index 21dbee2333..46fca1dd56 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -97,9 +97,19 @@ void duplicateHistoricalOriginAttemptsStopUpgradeWithoutRewritingEvidence() { .defaultSchema(schema) .placeholders(java.util.Map.of("serviceSchema", schema)) .locations("classpath:db/migration") + .target("1040.4") .load() .migrate()) - .isInstanceOf(org.flywaydb.core.api.FlywayException.class); + .isInstanceOf(org.flywaydb.core.api.FlywayException.class) + .hasStackTraceContaining("account_capacity_origin_attempt_unique") + .satisfies( + failure -> { + Throwable cause = failure; + while (cause != null && !(cause instanceof java.sql.SQLException)) + cause = cause.getCause(); + assertThat(cause).isInstanceOf(java.sql.SQLException.class); + assertThat(((java.sql.SQLException) cause).getSQLState()).isEqualTo("23505"); + }); assertThat( dsl.fetch( "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM account_capacity_origin_decisions ORDER BY decision_id") diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index e408498de2..4ac6d8d182 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -193,7 +193,7 @@ void durableQuotaDenialReplaysWithoutConsultingMutableCapacity() throws Exceptio assertThat(arguments[7]).isEqualTo("NO_ACCEPT"); assertThat(arguments[9]).isEqualTo("CAPACITY_QUOTA_EXCEEDED"); when(genericRefusal.get("decision_id", UUID.class)).thenReturn((UUID) arguments[8]); - f.originDecision = genericRefusal; + f.pendingOriginDecision = genericRefusal; return 1; }); f.retained = true; @@ -207,6 +207,8 @@ void durableQuotaDenialReplaysWithoutConsultingMutableCapacity() throws Exceptio assertThat(failure.durableDenialId()) .isEqualTo(genericRefusal.get("decision_id", UUID.class)); }); + assertThat(f.originDecision).isSameAs(genericRefusal); + assertThat(f.pendingOriginDecision).isNull(); UUID committedId = genericRefusal.get("decision_id", UUID.class); when(usage.get("held_units", Long.class)).thenReturn(0L); org.mockito.Mockito.clearInvocations(f.dsl, f.accounts, f.memberships, f.issuances, f.scopes); @@ -689,6 +691,7 @@ private static final class Fixture { private boolean existing = true; private boolean retained; private Record originDecision; + private Record pendingOriginDecision; private Fixture(boolean expired) throws Exception { this(expired, CapacityAdmissionTestFixture.playerRequest()); @@ -752,7 +755,7 @@ private Fixture(boolean expired, Request request, String namespace) throws Excep return existing ? row : null; if (sql.startsWith("SELECT 1 FROM (SELECT tenant_uuid")) return null; if (sql.startsWith("SELECT * FROM account_capacity_origin_decisions ")) - return originDecision; + return pendingOriginDecision != null ? pendingOriginDecision : originDecision; if (sql.startsWith( "SELECT snapshot_identity FROM account_tenant_capacity_evaluations ")) return evaluation; @@ -767,13 +770,19 @@ private Fixture(boolean expired, Request request, String namespace) throws Excep memberships, issuances, scopes, - new ControlledTransactions(), + new ControlledTransactions(this), clock, namespace); } } private static final class ControlledTransactions implements PlatformTransactionManager { + private final Fixture fixture; + + private ControlledTransactions(Fixture fixture) { + this.fixture = fixture; + } + @Override public TransactionStatus getTransaction( @org.jspecify.annotations.Nullable TransactionDefinition definition) { @@ -784,17 +793,22 @@ public TransactionStatus getTransaction( .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); assertThat(definition.getTimeout()).isEqualTo(5); assertThat(definition.isReadOnly()).isFalse(); + fixture.pendingOriginDecision = null; TransactionSynchronizationManager.setActualTransactionActive(true); return new SimpleTransactionStatus(); } @Override public void commit(TransactionStatus status) { + if (fixture.pendingOriginDecision != null) + fixture.originDecision = fixture.pendingOriginDecision; + fixture.pendingOriginDecision = null; TransactionSynchronizationManager.setActualTransactionActive(false); } @Override public void rollback(TransactionStatus status) { + fixture.pendingOriginDecision = null; TransactionSynchronizationManager.setActualTransactionActive(false); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java index 59d525917c..a1425d8464 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.never; @@ -111,10 +112,11 @@ void producedBillingAndQuotaDenialsReturnAnExactTypedResponse(Failure code) { .commitTenantCapacityAdmission( TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); var response = ArgumentCaptor.forClass(CommitTenantCapacityAdmissionResponse.class); - verify(observer).onNext(response.capture()); + var ordered = inOrder(observer); + ordered.verify(observer).onNext(response.capture()); assertThat(TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response.getValue())) .contains(new Refusal(code, null)); - verify(observer).onCompleted(); + ordered.verify(observer).onCompleted(); verify(observer, never()).onError(any()); } } @@ -132,10 +134,11 @@ void retainedQuotaDenialCarriesTheExactAccountDecision() { .commitTenantCapacityAdmission( TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); var response = ArgumentCaptor.forClass(CommitTenantCapacityAdmissionResponse.class); - verify(observer).onNext(response.capture()); + var ordered = inOrder(observer); + ordered.verify(observer).onNext(response.capture()); assertThat(TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response.getValue())) .contains(new Refusal(Failure.CAPACITY_QUOTA_EXCEEDED, decisionId)); - verify(observer).onCompleted(); + ordered.verify(observer).onCompleted(); verify(observer, never()).onError(any()); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java index 9f045cd491..4d5feeafe7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java @@ -60,7 +60,8 @@ public void init() throws IOException { * The caller must obtain its typed context from current owned player state, not text/metadata. * Retries retain this exact request. The Account call consumes the remaining absolute admission * budget, capped at five seconds and the incoming deadline. A timeout or an inexact response - * leaves the commitment indeterminate. Retry with the original identity. + * leaves the commitment indeterminate. Collect read-only evidence for the original attempt first; + * only replay this mutation with the exact original request when reconciliation permits it. */ public Result commit(Request request, long absoluteDeadlineMillis) { long maximumMillis = @@ -119,9 +120,15 @@ static Deadline selectDeadline( Deadline incoming, long absoluteDeadlineMillis, long sampledMillis) { - long remainingMillis = Math.subtractExact(absoluteDeadlineMillis, sampledMillis); long maximumMillis = TimeUnit.SECONDS.toMillis(TenantCapacityAdmissionGrpcCodec.CALL_DEADLINE_SECONDS); + long remainingMillis = 0; + if (absoluteDeadlineMillis > sampledMillis) { + // A positive difference can overflow only across the signed long boundary. + // Such a future deadline is beyond the invocation cap, not an expired budget. + long difference = absoluteDeadlineMillis - sampledMillis; + remainingMillis = difference < 0 ? maximumMillis : Math.min(maximumMillis, difference); + } Deadline absoluteDeadline = sampledAt.offset( Math.max(0L, Math.min(maximumMillis, remainingMillis)), TimeUnit.MILLISECONDS); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index b9382942ea..579cec4aed 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -196,7 +196,13 @@ void wrongAccountPeerIsRejectedBeforeRequestBodyRelease() throws Exception { client.init(); assertThatThrownBy( () -> client.commit(CapacityAdmissionTestFixture.playerRequest(), deadline())) - .isInstanceOf(StatusRuntimeException.class); + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> { + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(failure.getStatus().getDescription()) + .isEqualTo("Request requires the exact authenticated server workload identity"); + }); assertThat(calls).hasValue(0); } finally { stop(server); @@ -279,6 +285,26 @@ public long nanoTime() { assertThat(selected.timeRemaining(TimeUnit.MILLISECONDS)).isEqualTo(expectedMillis); } + @ParameterizedTest + @CsvSource({"-9223372036854775808, 1, 0", "9223372036854775807, -1, 5000", "0, 0, 0"}) + void extremeWallClockDeadlinesRemainExpiredOrCapped( + long absoluteMillis, long sampledMillis, long expectedMillis) { + var ticker = + new Deadline.Ticker() { + @Override + public long nanoTime() { + return 0; + } + }; + var sample = Deadline.after(0, TimeUnit.NANOSECONDS, ticker); + var maximum = Deadline.after(5, TimeUnit.SECONDS, ticker); + assertThat( + AccountTenantCapacityClient.selectDeadline( + maximum, sample, null, absoluteMillis, sampledMillis) + .timeRemaining(TimeUnit.MILLISECONDS)) + .isEqualTo(expectedMillis); + } + @Test void setupDelayIsNotDeductedTwiceAndOriginalInvocationCapStillApplies() { var nanos = new AtomicLong(); From c4def7835bcfcbb7ef331c4c38f926f02f37c529 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:57:07 +1300 Subject: [PATCH 08/96] fix: preserve capacity conflict ordering and bounded smoke recovery --- .github/workflows/smoke.yml | 36 ++++++- .../account-service/runtime-and-data.md | 2 +- .../pr-required-gate-context-contract.sh | 95 +++++++++++++++---- ...countCapacityOriginDecisionRepository.java | 2 +- .../service/AccountTenantCapacityOwner.java | 1 + ...acityMigrationPostgresIntegrationTest.java | 24 +++++ .../AccountTenantCapacityOwnerTest.java | 38 +++++++- .../AccountTenantCapacityGrpcServiceTest.java | 11 +-- .../AbstractReloadingBlockingGrpcClient.java | 2 +- ...stractReloadingBlockingGrpcClientTest.java | 3 +- .../AccountTenantCapacityClientMtlsTest.java | 23 ++--- 11 files changed, 186 insertions(+), 51 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index a0a9d0129b..9dde61ef10 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -942,7 +942,7 @@ jobs: const title = `Build Runtime Images secure-pr-artifact pr-${prNumber} ` + `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; const replacement = await findMatchingRuntimeImagesRun("repository_dispatch", title, identity); - if (!replacement) return "pending"; + if (!replacement) return "absent"; if (!positiveInteger(replacement.id) || !positiveInteger(replacement.run_attempt) || replacement.id <= run.id || replacement.event !== "repository_dispatch") return false; // Pending exact refreshes are not proof, but must not fail the caller @@ -950,7 +950,7 @@ jobs: if (["queued", "in_progress", "waiting", "pending", "requested"].includes(replacement.status)) { return "pending"; } - if (replacement.status !== "completed" || replacement.conclusion !== "success") return false; + if (replacement.status !== "completed" || !["success", "failure"].includes(replacement.conclusion)) return false; const jobs = await withTransientGitHubRetry("canonical transition refresh jobs lookup", () => github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", { owner, repo, run_id: replacement.id, attempt_number: replacement.run_attempt, per_page: 100, @@ -958,7 +958,15 @@ jobs: ); const candidate = jobs.find((job) => job.name === canonicalSmokeJobName); if (!candidate || candidate.status !== "completed") return "pending"; - return await verifyKnownPlayFailure(replacement, candidate, identity); + if (await verifyKnownPlayFailure(replacement, candidate, identity)) return true; + // A new attempt can start between list/proof reads. Invalid current proof + // is terminal; only a verified newer attempt warrants bounded reselection. + const { data: latest } = await withTransientGitHubRetry( + "superseding canonical refresh attempt lookup", + () => github.rest.actions.getWorkflowRun({owner, repo, run_id: replacement.id}) + ); + return latest.id === replacement.id && positiveInteger(latest.run_attempt) && + latest.run_attempt > replacement.run_attempt ? "pending" : false; } // Commit objects are immutable; mutable PR/base reads stay fresh. @@ -1186,6 +1194,9 @@ jobs: } let currentIdentity = null; + let absentRefreshKey = null; + let discoveredRefreshKey = null; + let absentRefreshObservedAt = null; let requireCurrentIdentity = false; let cancelledRunId = null; let cancelledRunObservedAt = null; @@ -1313,7 +1324,24 @@ jobs: } } const refreshProof = await verifyFailedPullCanonicalRefresh(matching, currentIdentity); - if (refreshProof === "pending") { + const refreshKey = `${matching.id}:${identityKey(currentIdentity)}`; + if (refreshProof === "absent" && discoveredRefreshKey !== refreshKey) { + const missingKey = refreshKey; + if (absentRefreshKey !== missingKey) { + absentRefreshKey = missingKey; + absentRefreshObservedAt = Date.now(); + } + if (Date.now() - absentRefreshObservedAt >= cancelledReplacementTimeoutMs) { + core.setFailed(`Failed runtime-images run ${matching.id} has no exact canonical refresh ` + + `after ${cancelledReplacementTimeoutMs / 60000} minutes`); + return; + } + } else { + if (refreshProof !== "absent") discoveredRefreshKey = refreshKey; + absentRefreshKey = null; + absentRefreshObservedAt = null; + } + if (refreshProof === "pending" || refreshProof === "absent") { core.info("Exact canonical refresh is pending; continuing within the existing smoke-gate deadline."); await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 0ae3953af8..f591d0ba6a 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -88,7 +88,7 @@ Current public bootstrap, direct-scope, JOIN, connect-token and numeric entitlem Strict capacity follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). The prepared V1040 storage records immutable exact Account evaluation bytes, one stable outer request/reservation identity, the current attempt/digest and monotonic rearm/reservation fences, prior-attempt evidence, recovery claims, and durable held/used units. Deferred PostgreSQL constraints compare the complete reservation inventory with usage; eligibility reads and issuer-local counters cannot initialize or replace it. Zero usage is established only when the existing creator bootstrap commits against a genuinely new fresh-tenant association born in that same Account transaction, with the exact creation tuple and nonadmitting sequence-zero baseline. Earlier tenants are not backfilled. The actual player evaluator retains its complete bundle inside its final source transaction, so failed source commit exposes neither a capacity evaluation nor an entitlement result. Reservations use conservative microsecond expiry bounds without extending the evidence lifetime. The same prepared recovery schema retains its immutable read history and `capacity-recovery/1` retry budget. Deadline or budget exhaustion quarantines the original complete hold; it does not expire, release or replace it. No live recovery source/scheduler or quarantine-resolution authority is registered. -V1040.1 serializes the exact Account `ACCEPTED` and `NO_ACCEPT` origin decisions against reservation creation and rearm. A pre-V1040.1 writer cannot create a reservation after the guard applies. Upgrading a retained Account database requires independently verified [writer quiescence](../../system-architecture-database-migrations.md#version-aware-migration-checklist), including closed writer endpoints and exclusion of old writers. V1040.2 retains an exact quota denial under an explicitly installed finite tenant refusal limit. The same serializable owner transaction checks quota and chooses between a reservation and a denial. The denial carries no reservation and permanently excludes acceptance for the exact original. Exact replay returns the same decision even after capacity becomes available. An unavailable refusal budget or uncertain outcome leaves Game Session's reserve active. Account neither frees nor rearms an accepted reservation through this path. Before enabling any admission producer, the Account operator must provision every supported canonical tenant through `AccountCapacityRefusalBudgetRepository.provision` in a committed owner transaction, then call `requireReady` with the same explicit lifetime limit and the bounded admission cohort headroom while producers remain quiescent. Sizing is explicit: the finite lifetime limit must cover retained denials plus the planned denial cohort; it is not the gameplay capacity quota or an automatically replenished rate limit. Exact provisioning retries preserve the row and its historical evidence; a different limit conflicts. Missing, mismatched or insufficient budgets fail readiness. Readiness is a local observation, not a reservation or authority to admit, and the SQL trigger remains the runtime concurrency authority. Exhaustion requires stopping new admission and an independently designed retention-safe lifecycle, never deleting denials or resetting/increasing this immutable budget. These private methods do not register an endpoint, seed tenants automatically or activate the default-off capacity component. +V1040.1 serializes the exact Account `ACCEPTED` and `NO_ACCEPT` origin decisions against reservation creation and rearm. A pre-V1040.1 writer cannot create a reservation after the guard applies. Upgrading a retained Account database requires independently verified [writer quiescence](../../system-architecture-database-migrations.md#version-aware-migration-checklist), including closed writer endpoints and exclusion of old writers. V1040.2 retains an exact quota denial under an explicitly installed finite tenant refusal limit. The same serializable owner transaction checks quota and chooses between a reservation and a denial. The denial carries no reservation and permanently excludes acceptance for the exact original. Exact replay returns the same decision even after capacity becomes available. An unavailable refusal budget or uncertain outcome leaves Game Session's reserve active. Account neither frees nor rearms an accepted reservation through this path. Before enabling any admission producer, the Account operator must provision every supported canonical tenant through `AccountCapacityRefusalBudgetRepository.provision` and call `requireReady` with the same explicit lifetime limit and the bounded admission cohort headroom in one writable owner transaction while producers remain quiescent. Commit only after both succeed; otherwise roll back the undersized installation so it does not permanently bind an unusable limit. Sizing is explicit: the finite lifetime limit must cover retained denials plus the planned denial cohort; it is not the gameplay capacity quota or an automatically replenished rate limit. Exact provisioning retries preserve the row and its historical evidence; a different limit conflicts. Missing, mismatched or insufficient budgets fail readiness. Readiness is a local observation, not a reservation or authority to admit, and the SQL trigger remains the runtime concurrency authority. Exhaustion requires stopping new admission and an independently designed retention-safe lifecycle, never deleting denials or resetting/increasing this immutable budget. These private methods do not register an endpoint, seed tenants automatically or activate the default-off capacity component. The unregistered capacity owner requires exact retained evidence and current Account membership/issuance/scope source equality before creating a new positive player-binding reservation. Exact attempt retries replay before fresh-source or usage work; changed complete payloads conflict. The Account recovery component alone can finalize, release or rearm under its current durable claim and exact selected-owner readback; an ambiguous observation records only the bounded retry/deadline and retains the hold. No runtime readback producer or recovery client is registered. World lifecycle, authoritative prior-shape/zero-delta recovery, current selected-owner activation and complete end-to-end qualification remain held as detailed in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 36a3167a53..afdd065e7f 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3579,10 +3579,14 @@ async function verify(mutate = () => {}, event = "pull_request", knownPlay = tru const refreshStart = script.indexOf("async function verifyFailedPullCanonicalRefresh("); const refreshEnd = script.indexOf("// Commit objects", refreshStart); const refreshFunction = script.slice(refreshStart, refreshEnd); -async function recoveredFailure(options = {}) { - const original = {id: 98, event: "pull_request", status: "completed", conclusion: "failure", ...options.original}; - const replacement = options.absent ? null : {id: 99, run_attempt: 2, event: "repository_dispatch", +async function recoveredFailure(options = {}, selectedRun = null, selectedIdentity = identity) { + const original = selectedRun ?? {id: 98, event: "pull_request", status: "completed", conclusion: "failure", ...options.original}; + const replacement = options.absent ? null : {id: original.id + 1, run_attempt: 2, event: "repository_dispatch", status: "completed", conclusion: "success", ...options.replacement}; + const selectedTitle = `Build Runtime Images secure-pr-artifact pr-3390 base-${selectedIdentity.baseSha} ` + + `head-${selectedIdentity.headSha} merge-${selectedIdentity.mergeSha} mode-required`; + const selectedCandidate = {...candidate, run_id: replacement?.id, run_attempt: replacement?.run_attempt, + head_sha: workflowSha, conclusion: replacement?.conclusion, ...options.candidate}; let verified = 0, queries = 0; const execute = new Function("repositoryName", "prNumber", "positiveInteger", "findMatchingRuntimeImagesRun", "withTransientGitHubRetry", "github", "owner", "repo", "canonicalSmokeJobName", "verifyKnownPlayFailure", "context", @@ -3591,20 +3595,43 @@ async function recoveredFailure(options = {}) { async (event, title, selected) => { queries++; assert.equal(event, "repository_dispatch"); - assert.deepEqual(selected, identity); - assert.equal(title, source.display_title); + assert.deepEqual(selected, selectedIdentity); + assert.equal(title, selectedTitle); if (options.lookupError) throw options.lookupError; return replacement; }, (_label, call) => call(), {paginate: async (route, input) => { assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); - assert.equal(input.run_id, 99); assert.equal(input.attempt_number, 2); - return options.noProducer ? [] : [{...candidate, ...options.candidate}]; - }}, "benhook1013", "FireMUD", canonicalSmokeJobName, async (selected, job, selectedIdentity) => { + assert.equal(input.run_id, replacement.id); assert.equal(input.attempt_number, replacement.run_attempt); + return options.noProducer ? [] : [selectedCandidate]; + }, rest: {actions: {getWorkflowRun: async ({run_id}) => { + assert.equal(run_id, replacement.id); + return {data: {...replacement, ...options.latest}}; + }}}}, "benhook1013", "FireMUD", canonicalSmokeJobName, async (selected, job, proofIdentity) => { verified++; - assert.equal(selected, replacement); assert.deepEqual(job, {...candidate, ...options.candidate}); assert.deepEqual(selectedIdentity, identity); - return verify(options.mutateProof, "repository_dispatch"); + assert.deepEqual(proofIdentity, selectedIdentity); + assert.equal(selected, replacement); assert.deepEqual(job, selectedCandidate); + return verify(data => { + data.identity = structuredClone(selectedIdentity); + Object.assign(data.run, replacement); + for (const native of [data.source, data.latest]) Object.assign(native, replacement, { + display_title: selectedTitle, head_sha: workflowSha, + }); + Object.assign(data.candidate, structuredClone(selectedCandidate)); + Object.assign(data.jobs[0], structuredClone(selectedCandidate)); + data.currentPullRequest.head.sha = selectedIdentity.headSha; + data.currentPullRequest.base.ref = selectedIdentity.baseRef; + data.currentPullRequest.merge_commit_sha = selectedIdentity.mergeSha; + data.currentBase = {ref: `refs/heads/${selectedIdentity.baseRef}`, object: {sha: selectedIdentity.baseSha}}; + if (options.legacyProof) { + data.legacyDefinition = true; + for (const job of [data.candidate, data.jobs[0]]) { + for (const step of job.steps) if (failures.includes(step.name)) step.conclusion = "failure"; + } + } + if (options.mutateProof) options.mutateProof(data); + }, "repository_dispatch"); }, {payload: {pull_request: {head: {repo: {full_name: options.headRepository || repositoryName}}}}}); - return {accepted: await recover(original, identity), verified, queries}; + return {accepted: await recover(original, selectedIdentity), verified, queries}; } // Proof errors in a successful exception attempt must fail closed. const failedStart = script.indexOf('// A continued probe'); @@ -3640,7 +3667,8 @@ async function failedLegacyProof(stage, error, event = "pull_request") { const execute = new Function("matching", "repositoryName", "github", "owner", "repo", "canonicalSmokeJobName", "currentIdentity", "withTransientGitHubRetry", "verifyKnownPlayFailure", "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", "core", "verifyFailedPullCanonicalRefresh", "context", "resolveCurrentIdentity", "identityKey", - `return (async () => { smokeGatePolling: while (true) { ${legacyFailedBranch} break; } })();`); + `return (async () => { let absentRefreshKey = null, discoveredRefreshKey = null, absentRefreshObservedAt = null; + smokeGatePolling: while (true) { ${legacyFailedBranch} break; } })();`); await execute({...source, conclusion: "failure", event}, repositoryName, github, "benhook1013", "FireMUD", canonicalSmokeJobName, identity, (_label, call) => call(), async () => {throw error;}, async () => false, TerminalGitHubRequestError, core, async () => false, @@ -3685,22 +3713,29 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { } return Boolean(options.directProof || (options.recoverDrift && run.event === "repository_dispatch")); }, - async () => { + async (selectedRun, selectedIdentity) => { + assert.equal(selectedRun.id, original.id); + assert.equal(selectedIdentity.headSha, identity.headSha); + assert.equal(selectedIdentity.baseSha, identity.baseSha); + assert.equal(selectedIdentity.mergeSha, identity.mergeSha); const status = statuses[Math.min(polls++, statuses.length - 1)]; if (options.proofDrift) { const result = await recoveredFailure({mutateProof(data) { Object.assign(proofLive, options.finalIdentity); data.currentBase.object.sha = proofLive.baseSha; data.currentPullRequest.merge_commit_sha = proofLive.mergeSha; - }}); + }}, selectedRun, selectedIdentity); assert.equal(result.accepted, false, "the old refresh must fail its live tuple proof"); return false; } return (await recoveredFailure(options.headRepository ? {headRepository: options.headRepository} : status === "absent" ? {absent: true} + : status === "superseded" ? {latest: {run_attempt: 3}, mutateProof: data => {data.latest.run_attempt = 3;}} : status === "missing-job" ? {noProducer: true} : status === "pending-job" ? {candidate: {status: "in_progress"}} - : {replacement: {status, conclusion: status === "completed" ? "success" : null}})).accepted; + : {replacement: {status, conclusion: status === "completed" ? "success" : null, + run_attempt: statuses[0] === "superseded" && polls > 1 ? 3 : 2}}, + selectedRun, selectedIdentity)).accepted; }, async () => false, TerminalGitHubRequestError, core, async (_label, requireCurrent) => { if (requireCurrent) { currentChecks++; @@ -3728,6 +3763,10 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { assert.deepEqual(failures, ["Canonical PLAY transition exception label is absent or no longer eligible."]); assert.deepEqual(outputs, []); assert.equal(writes, 0); + } else if (options.absentExpires) { + assert.deepEqual(failures, ["Failed runtime-images run 98 has no exact canonical refresh after 0.001 minutes"]); + assert.deepEqual(outputs, []); + assert.equal(writes, 0); } else if (expires) { assert.equal(failures.length, 1); assert.match(failures[0], /^Timed out waiting for the exact runtime-images\/full-smoke run/); @@ -3739,8 +3778,8 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { assert.equal(writes, 1); assert.ok(options.directProof || currentChecks >= 1); } - assert.equal(polls, options.directProof || options.labelRemoved ? 0 : options.recoverDrift ? 1 : statuses.length); - assert.equal(sleeps, options.labelRemoved ? 0 : options.finalIdentity ? (statuses[0] === "absent" ? 1 : 0) + assert.equal(polls, options.directProof || options.labelRemoved ? 0 : options.absentExpires ? 3 : options.recoverDrift ? 1 : statuses.length); + assert.equal(sleeps, options.labelRemoved ? 0 : options.absentExpires ? 2 : options.finalIdentity ? (statuses[0] === "absent" ? 1 : 0) : expires ? statuses.length : statuses.length - 1); } // Exercise the real resolver, not merely a stub that honors requireCurrent. @@ -3806,6 +3845,24 @@ function markerAccepted(overrides = {}) { await assert.rejects(failedProof(terminal), error => error === terminal); } assert.deepEqual(await recoveredFailure(), {accepted: true, verified: 1, queries: 1}); + const alternateIdentity = {...identity, baseSha: "e".repeat(40), mergeSha: "f".repeat(40)}; + assert.equal((await recoveredFailure({}, {...source, id: 199, conclusion: "failure"}, alternateIdentity)).accepted, true); + assert.equal((await recoveredFailure({replacement: {conclusion: "failure"}, legacyProof: true})).accepted, true); + assert.equal((await recoveredFailure({replacement: {conclusion: "failure"}})).accepted, false); + assert.equal((await recoveredFailure({mutateProof: data => { + data.jobs[0].steps.push(step("Start database", "failure")); + }})).accepted, false, "a latest refresh with unrelated failure never supplies exception proof"); + assert.equal((await recoveredFailure({latest: {run_attempt: 3}, mutateProof: data => { + data.latest.run_attempt = 3; + }})).accepted, "pending"); + assert.equal((await recoveredFailure({mutateProof: data => { + data.jobs[0].steps.push(step("Start database", "failure")); + }, latest: {run_attempt: 2}})).accepted, false); + await pendingRefreshCaller(["absent", "absent", "absent", "completed"], false, {absentExpires: true}); + await pendingRefreshCaller(["absent", "queued", "in_progress", "in_progress", "completed"]); + await pendingRefreshCaller(["absent", "queued", "absent", "absent", "absent", "completed"]); + await pendingRefreshCaller(["superseded", "queued", "completed"]); + for (const status of ["queued", "in_progress", "waiting", "pending", "requested"]) { assert.deepEqual(await recoveredFailure({replacement: {status, conclusion: null}}), {accepted: "pending", verified: 0, queries: 1}); @@ -3827,7 +3884,7 @@ function markerAccepted(overrides = {}) { }); await pendingRefreshCaller(["queued", "in_progress", "completed"]); await pendingRefreshCaller(["queued", "in_progress"], true); - assert.equal((await recoveredFailure({absent: true})).accepted, "pending"); + assert.equal((await recoveredFailure({absent: true})).accepted, "absent"); assert.equal((await recoveredFailure({noProducer: true})).accepted, "pending"); assert.equal((await recoveredFailure({candidate: {status: "in_progress"}})).accepted, "pending"); await pendingRefreshCaller(["absent", "queued", "completed"]); @@ -3851,7 +3908,7 @@ function markerAccepted(overrides = {}) { {original: {status: "in_progress"}}, {original: {conclusion: "success"}}, {original: {id: 0}}, {replacement: {id: 98}}, {replacement: {id: 97}}, {replacement: {run_attempt: 0}}, {replacement: {event: "pull_request"}}, - {replacement: {status: "unknown"}}, {replacement: {conclusion: "failure"}}, + {replacement: {status: "unknown"}}, {replacement: {conclusion: "cancelled"}}, ]) { const result = await recoveredFailure(options); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java index 0a00b96757..6940b02b27 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java @@ -90,7 +90,7 @@ private Record retain(Request request, String decision, String refusalCode) { } /** SERIALIZABLE caller: include pre-origin reservations and retained rearm history. */ - private void requireFreshAttemptBinding(Request request) { + public void requireFreshAttemptBinding(Request request) { Record conflict = dsl.fetchOne( "SELECT 1 FROM (" diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index 41c5947414..350e9fbd83 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -110,6 +110,7 @@ public Result commit(Request request, String authenticatedCaller) { if (request.capacityRearmFence() != 1) throw conflict(); UUID retainedDenial = originDecisions.retainedQuotaDenial(request); if (retainedDenial != null) return new CommitDecision(null, retainedDenial); + originDecisions.requireFreshAttemptBinding(request); lockPlayerAccount(request); current(request); requireSupportedShape(request); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index 46fca1dd56..d53fc98b55 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -169,7 +169,31 @@ void budgetConflictDoesNotMaskRetainedHistoryAndFirstInstallStillChecksIt() { status -> budgets.provision(tenant.canonicalTenantId(), 2))) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_refusal_budget"))).isZero(); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> { + budgets.provision(tenant.canonicalTenantId(), 4); + budgets.requireReady(tenant.canonicalTenantId(), 4, 2); + })) + .isInstanceOf(AccountTenantCapacityRepository.CapacityException.class); + assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_refusal_budget"))).isZero(); transaction.executeWithoutResult(status -> budgets.provision(tenant.canonicalTenantId(), 4)); + assertThat( + transaction.execute( + status -> budgets.requireReady(tenant.canonicalTenantId(), 4, 1))) + .isEqualTo(1); + assertThatThrownBy( + () -> + transaction.execute( + status -> budgets.requireReady(tenant.canonicalTenantId(), 4, 2))) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> + assertThat(failure.code()) + .isEqualTo( + net.firedevops.firemud.common.account.capacity + .TenantCapacityAdmissionGrpcCodec.Failure.ENTITLEMENT_UNAVAILABLE)); var original = Objects.requireNonNull( dsl.fetchOne( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index 4ac6d8d182..e8fbe80818 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -557,15 +557,47 @@ void attemptAlreadyBoundToAnotherReservationCannotBecomeQuotaDenial() throws Exc verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } + @Test + void globalAttemptConflictPrecedesFreshOrExpiredNonCreatingEvidence() throws Exception { + for (boolean expired : new boolean[] {false, true}) { + var f = new Fixture(false, qualifiedRequest(false)); + f.existing = false; + f.retained = true; + when(f.clock.instant()) + .thenReturn( + expired + ? f.request.evidence().expiresAt() + : CapacityAdmissionTestFixture.NOW.plusSeconds(1)); + org.mockito.Mockito.doReturn(mock(Record.class)) + .when(f.dsl) + .fetchOne(startsWith("SELECT 1 FROM (SELECT tenant_uuid"), any(Object[].class)); + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.IDEMPOTENCY_CONFLICT)); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + verify(f.scopes, never()).findCanonicalEvidenceByTokenHash(anyString()); + } + } + @Test void expiryDuringSourceQualificationCannotBecomeBillingRefusal() throws Exception { var f = new Fixture(false, qualifiedRequest(false)); f.existing = false; f.retained = true; qualifySources(f); - when(f.clock.instant()) - .thenReturn( - CapacityAdmissionTestFixture.NOW.plusSeconds(1), f.request.evidence().expiresAt()); + var now = + new java.util.concurrent.atomic.AtomicReference<>( + CapacityAdmissionTestFixture.NOW.plusSeconds(1)); + when(f.clock.instant()).thenAnswer(ignored -> now.get()); + var scope = f.scopes.findCanonicalEvidenceByTokenHash("fixture"); + org.mockito.Mockito.clearInvocations(f.scopes); + when(f.scopes.findCanonicalEvidenceByTokenHash(anyString())) + .thenAnswer( + ignored -> { + now.set(f.request.evidence().expiresAt()); + return scope; + }); assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) .isInstanceOfSatisfying( AccountTenantCapacityRepository.CapacityException.class, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java index a1425d8464..dd66d37954 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -26,7 +26,6 @@ import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Refusal; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import org.mockito.MockedConstruction; @@ -97,12 +96,10 @@ void typedOwnerEvidenceUnavailableKeepsItsPublicFailure() { } } - @ParameterizedTest - @EnumSource( - value = Failure.class, - names = {"TENANT_BILLING_BLOCKED", "CAPACITY_QUOTA_EXCEEDED"}) - void producedBillingAndQuotaDenialsReturnAnExactTypedResponse(Failure code) { - var request = CapacityAdmissionTestFixture.playerRequest(); + @Test + void producedBillingDenialReturnsAnExactTypedResponse() { + Failure code = Failure.TENANT_BILLING_BLOCKED; + var request = CapacityAdmissionTestFixture.playerRequest(false); try (var guards = authenticatedCaller()) { AccountTenantCapacityOwner owner = mock(); when(owner.commit(request, CapacityAdmissionTestFixture.PEER)) diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java index 25f6621a4a..8a570e4cc6 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java @@ -139,7 +139,7 @@ protected final synchronized TStub requireInitializedStub(String unavailableMess } /** Takes the last published stub without waiting for a TLS reload. */ - protected final TStub requirePublishedInitializedStub(String unavailableMessage) { + private TStub requirePublishedInitializedStub(String unavailableMessage) { TStub current = stub; if (closed || !explicitlyInitialized || current == null) { throw new IllegalStateException(unavailableMessage); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java index ec8ca0c50d..0c05bbc33d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java @@ -448,7 +448,8 @@ private GameDesignServiceGrpc.GameDesignServiceBlockingStub requireExplicitStub( } private GameDesignServiceGrpc.GameDesignServiceBlockingStub requirePublishedExplicitStub() { - return requirePublishedInitializedStub("test client is not initialized and available"); + return withPublishedInitializedStub( + "test client is not initialized and available", selected -> selected); } private GameDesignServiceGrpc.GameDesignServiceBlockingStub currentStub() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index 579cec4aed..ae42710f65 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -334,17 +334,16 @@ public long nanoTime() { } @Test - void explicitRemainingBudgetBoundsAStalledAccountCallAndExactRetryStillReplays() - throws Exception { + void explicitRemainingBudgetBoundsAStalledAccountCall() throws Exception { AtomicInteger calls = new AtomicInteger(); AtomicBoolean respond = new AtomicBoolean(true); - Server server = server("account", calls, false, new AtomicLong(), respond); + AtomicLong observedNanos = new AtomicLong(); + Server server = server("account", calls, false, observedNanos, respond); try (var client = client(server)) { client.init(); var request = CapacityAdmissionTestFixture.playerRequest(); - var first = client.commit(request, deadline()); + client.commit(request, deadline()); respond.set(false); - long started = System.nanoTime(); assertThatThrownBy( () -> client.commit(request, CapacityAdmissionTestFixture.NOW.toEpochMilli() + 1_000L)) @@ -354,9 +353,7 @@ void explicitRemainingBudgetBoundsAStalledAccountCallAndExactRetryStillReplays() assertThat(Status.fromThrowable(failure).getCode()) .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); assertThat(calls).hasValue(2); // The timed-out invocation reached the nonresponding handler. - assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(3_000L); - respond.set(true); - assertThat(client.commit(request, deadline())).isEqualTo(first); + assertThat(observedNanos.get()).isLessThanOrEqualTo(TimeUnit.SECONDS.toNanos(1)); } finally { stop(server); } @@ -416,14 +413,14 @@ void commitReachesItsTransportDeadlineWhileTlsReloadIsBlocked() throws Exception void incomingDeadlineBoundsAStalledAccountCall() throws Exception { AtomicInteger calls = new AtomicInteger(); AtomicBoolean respond = new AtomicBoolean(true); - Server server = server("account", calls, false, new AtomicLong(), respond); + AtomicLong observedNanos = new AtomicLong(); + Server server = server("account", calls, false, observedNanos, respond); var scheduler = Executors.newSingleThreadScheduledExecutor(); try (var client = client(server)) { client.init(); var request = CapacityAdmissionTestFixture.playerRequest(); client.commit(request, CapacityAdmissionTestFixture.NOW.toEpochMilli() + 60_000L); respond.set(false); - long started = System.nanoTime(); assertThatThrownBy( () -> Context.current() @@ -435,7 +432,7 @@ void incomingDeadlineBoundsAStalledAccountCall() throws Exception { assertThat(Status.fromThrowable(failure).getCode()) .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); assertThat(calls).hasValue(2); // The incoming deadline bounded an actual in-flight call. - assertThat(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)).isLessThan(3_000L); + assertThat(observedNanos.get()).isLessThanOrEqualTo(TimeUnit.SECONDS.toNanos(1)); } finally { scheduler.shutdownNow(); stop(server); @@ -625,9 +622,7 @@ public ManagedChannel buildChannel( if (!initialBuild.getAndSet(false)) { reloadStarted.countDown(); try { - if (!releaseReload.await(10, TimeUnit.SECONDS)) { - throw new SSLException("Test reload release timed out"); - } + releaseReload.await(); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new SSLException("Test reload wait interrupted", interrupted); From 7408cb03cae0357278d1094da116046071d49578 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:24:19 +1300 Subject: [PATCH 09/96] fix: retain exact smoke proof and sanitize capacity refusals --- .github/workflows/smoke.yml | 82 +++++++++++--- .../account-service/runtime-and-data.md | 2 +- .../pr-required-gate-context-contract.sh | 94 ++++++++++++---- .../AccountTenantCapacityRepository.java | 2 + .../AccountTenantCapacityGrpcService.java | 11 +- .../AccountTenantCapacityGrpcServiceTest.java | 33 ++++++ .../AbstractReloadingBlockingGrpcClient.java | 21 ++-- ...stractReloadingBlockingGrpcClientTest.java | 106 +++++++++++------- 8 files changed, 263 insertions(+), 88 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 9dde61ef10..02c8df1e59 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -565,6 +565,9 @@ jobs: const cancelledReplacementTimeoutMs = 5 * 60 * 1000; const sleepMs = 30000; const snapshotSleepMs = 15000; + // Reuse the overall prerequisite/queue allowance for Validation's dispatch callback. + const refreshDiscoveryTimeoutMs = prerequisiteAndQueueAllowanceMinutes * 60 * 1000; + const completedSnapshotTimeoutMs = 8 * snapshotSleepMs; const pullRequestCheckInterval = 2; const retryableStatuses = new Set([408, 425, 429, 500, 502, 503, 504]); let pollIteration = 0; @@ -933,6 +936,15 @@ jobs: // A failed original event is not replaced by arbitrary green history. Only // a newer exact typed refresh with independently proven canonical exception // evidence can recover this diagnostic gate; it never proves PLAY succeeded. + async function isCurrentCanonicalAttempt(run) { + const { data: latest } = await withTransientGitHubRetry( + "final canonical exception attempt lookup", + () => github.rest.actions.getWorkflowRun({owner, repo, run_id: run.id}) + ); + return latest.id === run.id && latest.run_attempt === run.run_attempt && + latest.status === "completed" && latest.conclusion === run.conclusion; + } + async function verifyFailedPullCanonicalRefresh(run, identity) { if (repositoryName !== "benhook1013/FireMUD" || context.payload.pull_request.head.repo?.full_name !== repositoryName || @@ -943,8 +955,9 @@ jobs: `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; const replacement = await findMatchingRuntimeImagesRun("repository_dispatch", title, identity); if (!replacement) return "absent"; - if (!positiveInteger(replacement.id) || !positiveInteger(replacement.run_attempt) || replacement.id <= run.id || + if (!positiveInteger(replacement.id) || !positiveInteger(replacement.run_attempt) || replacement.event !== "repository_dispatch") return false; + if (replacement.id <= run.id) return "absent"; // Pending exact refreshes are not proof, but must not fail the caller // before the asynchronous producer can finish within its existing deadline. if (["queued", "in_progress", "waiting", "pending", "requested"].includes(replacement.status)) { @@ -957,8 +970,14 @@ jobs: }) ); const candidate = jobs.find((job) => job.name === canonicalSmokeJobName); - if (!candidate || candidate.status !== "completed") return "pending"; - if (await verifyKnownPlayFailure(replacement, candidate, identity)) return true; + const proofRun = {id: replacement.id, run_attempt: replacement.run_attempt, + conclusion: replacement.conclusion}; + if (!candidate || candidate.status !== "completed") { + return {status: "snapshot-pending", run: proofRun}; + } + if (await verifyKnownPlayFailure(replacement, candidate, identity)) { + return {status: "verified", run: proofRun}; + } // A new attempt can start between list/proof reads. Invalid current proof // is terminal; only a verified newer attempt warrants bounded reselection. const { data: latest } = await withTransientGitHubRetry( @@ -1194,6 +1213,8 @@ jobs: } let currentIdentity = null; + let incompleteRefreshKey = null; + let incompleteRefreshObservedAt = null; let absentRefreshKey = null; let discoveredRefreshKey = null; let absentRefreshObservedAt = null; @@ -1286,6 +1307,7 @@ jobs: ["pull_request", "repository_dispatch"].includes(matching.event)) { let knownPlayVerified = false; let refreshVerified = false; + let verifiedRefreshRun = null; try { const jobs = await withTransientGitHubRetry("canonical transition PLAY failure jobs lookup", () => github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", { @@ -1312,16 +1334,16 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } - if (!liveIdentity.canonicalPlayEligible) { - core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); - return; - } if (identityKey({...liveIdentity, sourceEvent: currentIdentity.sourceEvent}) !== identityKey(currentIdentity)) { requireCurrentIdentity = true; currentIdentity = liveIdentity; continue smokeGatePolling; } + if (!liveIdentity.canonicalPlayEligible) { + core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); + return; + } } const refreshProof = await verifyFailedPullCanonicalRefresh(matching, currentIdentity); const refreshKey = `${matching.id}:${identityKey(currentIdentity)}`; @@ -1331,9 +1353,9 @@ jobs: absentRefreshKey = missingKey; absentRefreshObservedAt = Date.now(); } - if (Date.now() - absentRefreshObservedAt >= cancelledReplacementTimeoutMs) { + if (Date.now() - absentRefreshObservedAt >= refreshDiscoveryTimeoutMs) { core.setFailed(`Failed runtime-images run ${matching.id} has no exact canonical refresh ` + - `after ${cancelledReplacementTimeoutMs / 60000} minutes`); + `after ${refreshDiscoveryTimeoutMs / 60000} minutes`); return; } } else { @@ -1341,7 +1363,22 @@ jobs: absentRefreshKey = null; absentRefreshObservedAt = null; } - if (refreshProof === "pending" || refreshProof === "absent") { + const snapshotPending = refreshProof?.status === "snapshot-pending"; + if (snapshotPending) { + const snapshotKey = `${refreshKey}:${refreshProof.run.id}:${refreshProof.run.run_attempt}`; + if (incompleteRefreshKey !== snapshotKey) { + incompleteRefreshKey = snapshotKey; + incompleteRefreshObservedAt = Date.now(); + } + if (Date.now() - incompleteRefreshObservedAt >= completedSnapshotTimeoutMs) { + core.setFailed("Terminal canonical refresh did not expose complete smoke-job proof within the snapshot convergence allowance."); + return; + } + } else { + incompleteRefreshKey = null; + incompleteRefreshObservedAt = null; + } + if (refreshProof === "pending" || refreshProof === "absent" || snapshotPending) { core.info("Exact canonical refresh is pending; continuing within the existing smoke-gate deadline."); await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; @@ -1364,24 +1401,33 @@ jobs: continue smokeGatePolling; } } - knownPlayVerified = refreshProof === true; + knownPlayVerified = refreshProof?.status === "verified" && + positiveInteger(refreshProof.run?.id) && refreshProof.run.id > matching.id && + positiveInteger(refreshProof.run?.run_attempt) && + ["success", "failure"].includes(refreshProof.run?.conclusion); refreshVerified = knownPlayVerified; + if (refreshVerified) verifiedRefreshRun = refreshProof.run; } } catch (error) { if (error instanceof TerminalGitHubRequestError) throw error; core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); } if (knownPlayVerified) { - requireCurrentIdentity ||= refreshVerified; const freshIdentity = await resolveCurrentIdentity( - "Stopping stale canonical transition PLAY exception", requireCurrentIdentity); + "Stopping stale canonical transition PLAY exception", requireCurrentIdentity || refreshVerified); // Original event proof keeps its immutable tuple semantics. Refreshed // proof additionally requires the live base and test merge right now. const comparableFreshIdentity = refreshVerified && freshIdentity ? {...freshIdentity, sourceEvent: currentIdentity.sourceEvent} : freshIdentity; if (freshIdentity?.obsolete) return; - if (!freshIdentity || identityKey(comparableFreshIdentity) !== identityKey(currentIdentity)) { + if (!freshIdentity) { + // Unknown identity is not tuple movement: retain the failed-run age constraint. + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + if (identityKey(comparableFreshIdentity) !== identityKey(currentIdentity)) { + if (refreshVerified) requireCurrentIdentity = true; currentIdentity = freshIdentity; continue smokeGatePolling; } @@ -1389,6 +1435,10 @@ jobs: core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); return; } + if (!await isCurrentCanonicalAttempt(verifiedRefreshRun ?? matching)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } core.setOutput("known_play_exception", "true"); core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); await core.summary.addHeading("Canonical PLAY transition exception accepted") @@ -1540,6 +1590,10 @@ jobs: core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); return; } + if (!await isCurrentCanonicalAttempt(matching)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } core.setOutput("known_play_exception", "true"); core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); await core.summary.addHeading("Canonical PLAY transition exception accepted") diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index f591d0ba6a..c09e969038 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -88,7 +88,7 @@ Current public bootstrap, direct-scope, JOIN, connect-token and numeric entitlem Strict capacity follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). The prepared V1040 storage records immutable exact Account evaluation bytes, one stable outer request/reservation identity, the current attempt/digest and monotonic rearm/reservation fences, prior-attempt evidence, recovery claims, and durable held/used units. Deferred PostgreSQL constraints compare the complete reservation inventory with usage; eligibility reads and issuer-local counters cannot initialize or replace it. Zero usage is established only when the existing creator bootstrap commits against a genuinely new fresh-tenant association born in that same Account transaction, with the exact creation tuple and nonadmitting sequence-zero baseline. Earlier tenants are not backfilled. The actual player evaluator retains its complete bundle inside its final source transaction, so failed source commit exposes neither a capacity evaluation nor an entitlement result. Reservations use conservative microsecond expiry bounds without extending the evidence lifetime. The same prepared recovery schema retains its immutable read history and `capacity-recovery/1` retry budget. Deadline or budget exhaustion quarantines the original complete hold; it does not expire, release or replace it. No live recovery source/scheduler or quarantine-resolution authority is registered. -V1040.1 serializes the exact Account `ACCEPTED` and `NO_ACCEPT` origin decisions against reservation creation and rearm. A pre-V1040.1 writer cannot create a reservation after the guard applies. Upgrading a retained Account database requires independently verified [writer quiescence](../../system-architecture-database-migrations.md#version-aware-migration-checklist), including closed writer endpoints and exclusion of old writers. V1040.2 retains an exact quota denial under an explicitly installed finite tenant refusal limit. The same serializable owner transaction checks quota and chooses between a reservation and a denial. The denial carries no reservation and permanently excludes acceptance for the exact original. Exact replay returns the same decision even after capacity becomes available. An unavailable refusal budget or uncertain outcome leaves Game Session's reserve active. Account neither frees nor rearms an accepted reservation through this path. Before enabling any admission producer, the Account operator must provision every supported canonical tenant through `AccountCapacityRefusalBudgetRepository.provision` and call `requireReady` with the same explicit lifetime limit and the bounded admission cohort headroom in one writable owner transaction while producers remain quiescent. Commit only after both succeed; otherwise roll back the undersized installation so it does not permanently bind an unusable limit. Sizing is explicit: the finite lifetime limit must cover retained denials plus the planned denial cohort; it is not the gameplay capacity quota or an automatically replenished rate limit. Exact provisioning retries preserve the row and its historical evidence; a different limit conflicts. Missing, mismatched or insufficient budgets fail readiness. Readiness is a local observation, not a reservation or authority to admit, and the SQL trigger remains the runtime concurrency authority. Exhaustion requires stopping new admission and an independently designed retention-safe lifecycle, never deleting denials or resetting/increasing this immutable budget. These private methods do not register an endpoint, seed tenants automatically or activate the default-off capacity component. +V1040.1 serializes the exact Account `ACCEPTED` and `NO_ACCEPT` origin decisions against reservation creation and rearm. A pre-V1040.1 writer cannot create a reservation after the guard applies. Upgrading a retained Account database requires independently verified [writer quiescence](../../system-architecture-database-migrations.md#version-aware-migration-checklist), including closed writer endpoints and exclusion of old writers. V1040.2 retains an exact quota denial under an explicitly installed finite tenant refusal limit. The same serializable owner transaction checks quota and chooses between a reservation and a denial. The denial carries no reservation and permanently excludes acceptance for the exact original. Exact replay returns the same decision even after capacity becomes available. An unavailable refusal budget or uncertain outcome leaves Game Session's reserve active. Account neither frees nor rearms an accepted reservation through this path. Before enabling any admission producer, the Account operator must provision every supported canonical tenant through `AccountCapacityRefusalBudgetRepository.provision` and call `requireReady` with the same explicit lifetime limit and the bounded admission cohort headroom in one writable owner transaction while producers remain quiescent. Commit only after both succeed; otherwise roll back the undersized installation so it does not permanently bind an unusable limit. Sizing is explicit: the finite lifetime limit must cover retained denials plus the planned denial cohort; it is not the gameplay capacity quota or an automatically replenished rate limit. Exact provisioning retries preserve the row and its historical evidence; a different limit conflicts. Missing, mismatched or insufficient budgets fail readiness. Readiness is a local observation, not a reservation or authority to admit, and the SQL trigger remains the runtime concurrency authority. Exhaustion requires stopping new admission and an independently designed retention-safe lifecycle, never deleting denials or resetting/increasing this immutable budget. No exhaustion detector or admission-producer stop control is implemented by these private repositories: the positive reservation path does not consult refusal headroom. Qualifying that stop, including last-slot consumption followed by available capacity, is an unmet activation prerequisite; provisioning readiness alone cannot satisfy it. These private methods do not register an endpoint, seed tenants automatically or activate the default-off capacity component. The unregistered capacity owner requires exact retained evidence and current Account membership/issuance/scope source equality before creating a new positive player-binding reservation. Exact attempt retries replay before fresh-source or usage work; changed complete payloads conflict. The Account recovery component alone can finalize, release or rearm under its current durable claim and exact selected-owner readback; an ambiguous observation records only the bounded retry/deadline and retains the hold. No runtime readback producer or recovery client is registered. World lifecycle, authoritative prior-shape/zero-delta recovery, current selected-owner activation and complete end-to-end qualification remain held as detailed in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index afdd065e7f..8187b5a000 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3575,11 +3575,23 @@ async function verify(mutate = () => {}, event = "pull_request", knownPlay = tru if (accepted) assert.deepEqual(contentRequests, knownPlay ? [workflowPath, ...Object.keys(classifierDefinitions)] : [workflowPath]); return accepted; } +// Final attempt authority remains separate from PR identity and label authority. +async function finalAttemptCheck(latest) { + const start = script.indexOf("async function isCurrentCanonicalAttempt("); + const end = script.indexOf("async function verifyFailedPullCanonicalRefresh(", start); + const check = new Function("github", "withTransientGitHubRetry", "owner", "repo", + `${script.slice(start, end)}; return isCurrentCanonicalAttempt;`)( + {rest: {actions: {getWorkflowRun: async ({run_id}) => {assert.equal(run_id, 99); return {data: latest};}}}}, + (_label, call) => call(), "benhook1013", "FireMUD"); + return check({id: 99, run_attempt: 2, conclusion: "success"}); +} +assert.ok(script.includes("const refreshDiscoveryTimeoutMs = prerequisiteAndQueueAllowanceMinutes * 60 * 1000;")); +assert.ok(script.includes("const completedSnapshotTimeoutMs = 8 * snapshotSleepMs;")); // A failed original event may recover only through a newer exact verified exception. const refreshStart = script.indexOf("async function verifyFailedPullCanonicalRefresh("); const refreshEnd = script.indexOf("// Commit objects", refreshStart); const refreshFunction = script.slice(refreshStart, refreshEnd); -async function recoveredFailure(options = {}, selectedRun = null, selectedIdentity = identity) { +async function recoveredFailure(options = {}, selectedRun = null, selectedIdentity = identity, raw = false) { const original = selectedRun ?? {id: 98, event: "pull_request", status: "completed", conclusion: "failure", ...options.original}; const replacement = options.absent ? null : {id: original.id + 1, run_attempt: 2, event: "repository_dispatch", status: "completed", conclusion: "success", ...options.replacement}; @@ -3631,7 +3643,9 @@ async function recoveredFailure(options = {}, selectedRun = null, selectedIdenti if (options.mutateProof) options.mutateProof(data); }, "repository_dispatch"); }, {payload: {pull_request: {head: {repo: {full_name: options.headRepository || repositoryName}}}}}); - return {accepted: await recover(original, selectedIdentity), verified, queries}; + const proof = await recover(original, selectedIdentity); + return {accepted: raw ? proof : proof?.status === "verified" ? true + : proof?.status === "snapshot-pending" ? "snapshot-pending" : proof, verified, queries}; } // Proof errors in a successful exception attempt must fail closed. const failedStart = script.indexOf('// A continued probe'); @@ -3668,6 +3682,7 @@ async function failedLegacyProof(stage, error, event = "pull_request") { "canonicalSmokeJobName", "currentIdentity", "withTransientGitHubRetry", "verifyKnownPlayFailure", "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", "core", "verifyFailedPullCanonicalRefresh", "context", "resolveCurrentIdentity", "identityKey", `return (async () => { let absentRefreshKey = null, discoveredRefreshKey = null, absentRefreshObservedAt = null; + let incompleteRefreshKey = null, incompleteRefreshObservedAt = null; smokeGatePolling: while (true) { ${legacyFailedBranch} break; } })();`); await execute({...source, conclusion: "failure", event}, repositoryName, github, "benhook1013", "FireMUD", canonicalSmokeJobName, identity, (_label, call) => call(), async () => {throw error;}, async () => false, @@ -3684,7 +3699,7 @@ const loopStart = script.indexOf("let currentIdentity = null;"); const actualPollingLoop = script.slice(loopStart); async function pendingRefreshCaller(statuses, expires = false, options = {}) { const failures = [], outputs = []; - let sleeps = 0, polls = 0, writes = 0, now = 0, currentChecks = 0; + let sleeps = 0, polls = 0, writes = 0, now = 0, currentChecks = 0, finalChecks = 0, nullReads = 0; const proofLive = {baseSha: identity.baseSha, mergeSha: identity.mergeSha}; const core = {info: () => {}, warning: () => {}, setFailed: value => failures.push(value), setOutput: (...value) => outputs.push(value)}; @@ -3697,10 +3712,13 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { "core", "resolveCurrentIdentity", "identityKey", "setTimeout", "sleepMs", "Date", "started", "timeoutMs", "pullRequestCheckInterval", "findMatchingRuntimeImagesRun", "prNumber", "identityDiagnostic", "cancelledReplacementTimeoutMs", "context", + "refreshDiscoveryTimeoutMs", "completedSnapshotTimeoutMs", "positiveInteger", "isCurrentCanonicalAttempt", `return (async () => { let pollIteration = 0; ${actualPollingLoop} })();`); await execute(repositoryName, {rest: {actions: {listJobsForWorkflowRun: "jobs"}}, paginate: async () => { if (options.originalError) throw options.originalError; - return [candidate]; + const job = structuredClone(candidate); + if (options.ordinaryAfterDrift) job.steps.find(s => s.name.startsWith("Known canonical")).conclusion = "skipped"; + return [job]; }}, "benhook1013", "FireMUD", canonicalSmokeJobName, (_label, call) => call(), async run => { if (options.proofDrift && run.event === "repository_dispatch") { return verify(data => { @@ -3719,6 +3737,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { assert.equal(selectedIdentity.baseSha, identity.baseSha); assert.equal(selectedIdentity.mergeSha, identity.mergeSha); const status = statuses[Math.min(polls++, statuses.length - 1)]; + if (options.rejectedObject) return {status: "rejected", run: {id: 99, run_attempt: 2}}; if (options.proofDrift) { const result = await recoveredFailure({mutateProof(data) { Object.assign(proofLive, options.finalIdentity); @@ -3730,23 +3749,27 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { } return (await recoveredFailure(options.headRepository ? {headRepository: options.headRepository} : status === "absent" ? {absent: true} + : status === "older" ? {replacement: {id: 97}} : status === "superseded" ? {latest: {run_attempt: 3}, mutateProof: data => {data.latest.run_attempt = 3;}} : status === "missing-job" ? {noProducer: true} : status === "pending-job" ? {candidate: {status: "in_progress"}} : {replacement: {status, conclusion: status === "completed" ? "success" : null, run_attempt: statuses[0] === "superseded" && polls > 1 ? 3 : 2}}, - selectedRun, selectedIdentity)).accepted; + selectedRun, selectedIdentity, true)).accepted; }, async () => false, TerminalGitHubRequestError, core, async (_label, requireCurrent) => { + if (options.finalNull && _label === "Stopping stale canonical transition PLAY exception" && nullReads++ === 0) return null; + const eligible = !options.labelRemoved && !(options.withdrawDuringProof && polls > 0); if (requireCurrent) { currentChecks++; if (options.finalIdentity && polls > 0 && !options.recoverDrift) now += 30; - return {...identity, canonicalPlayEligible: !options.labelRemoved, - sourceEvent: "repository_dispatch", ...(options.proofDrift ? proofLive : polls > 0 ? options.finalIdentity : {})}; + return {...identity, canonicalPlayEligible: eligible, + sourceEvent: "repository_dispatch", ...(options.proofDrift ? proofLive : polls > 0 || options.ordinaryAfterDrift ? options.finalIdentity : {})}; } - return {...identity, canonicalPlayEligible: !options.labelRemoved}; + return {...identity, canonicalPlayEligible: eligible}; }, selected => { const {canonicalPlayEligible, ...tuple} = selected; return JSON.stringify(tuple); }, resolve => {sleeps++; now += 30; resolve();}, 30, {now: () => now}, 0, statuses.length * 30, 1, async (event, _title, selected) => { - if (options.recoverDrift && polls > 0 && event === "repository_dispatch") { + if (options.finalNull) assert.notEqual(event, "repository_dispatch", "unknown final identity must retain failed PR custody"); + if (options.recoverDrift && (polls > 0 || options.ordinaryAfterDrift) && event === "repository_dispatch") { assert.equal(event, "repository_dispatch"); assert.equal(selected.baseSha, options.finalIdentity.baseSha); assert.equal(selected.mergeSha, options.finalIdentity.mergeSha); @@ -3754,17 +3777,33 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { } return original; }, "3390", "test identity", 60, - {payload: {pull_request: {head: {repo: {full_name: options.headRepository || repositoryName}}}}}); - if (options.headRepository) { + {payload: {pull_request: {head: {repo: {full_name: options.headRepository || repositoryName}}}}}, + 120, 60, value => Number.isSafeInteger(value) && value > 0, async selected => { + finalChecks++; + if (!options.directProof && !options.recoverDrift) { + assert.equal(selected.id, 99); + assert.equal(selected.run_attempt, statuses[0] === "superseded" && polls > 1 ? 3 : 2); + } + return !options.rerunFinal || finalChecks > 1; + }); + if (options.ordinaryAfterDrift) { + assert.deepEqual(failures, []); assert.deepEqual(outputs, []); assert.equal(writes, 0); + } else if (options.rejectedObject) { + assert.deepEqual(failures, ["Runtime images run 98 did not complete successfully: run=failure"]); + assert.deepEqual(outputs, []); assert.equal(writes, 0); + } else if (options.snapshotExpires) { + assert.deepEqual(failures, ["Terminal canonical refresh did not expose complete smoke-job proof within the snapshot convergence allowance."]); + assert.deepEqual(outputs, []); assert.equal(writes, 0); + } else if (options.headRepository) { assert.deepEqual(failures, ["Runtime images run 98 did not complete successfully: run=failure"]); assert.deepEqual(outputs, []); assert.equal(writes, 0); - } else if (options.labelRemoved) { + } else if (options.labelRemoved || options.withdrawDuringProof) { assert.deepEqual(failures, ["Canonical PLAY transition exception label is absent or no longer eligible."]); assert.deepEqual(outputs, []); assert.equal(writes, 0); } else if (options.absentExpires) { - assert.deepEqual(failures, ["Failed runtime-images run 98 has no exact canonical refresh after 0.001 minutes"]); + assert.deepEqual(failures, ["Failed runtime-images run 98 has no exact canonical refresh after 0.002 minutes"]); assert.deepEqual(outputs, []); assert.equal(writes, 0); } else if (expires) { @@ -3778,8 +3817,11 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { assert.equal(writes, 1); assert.ok(options.directProof || currentChecks >= 1); } - assert.equal(polls, options.directProof || options.labelRemoved ? 0 : options.absentExpires ? 3 : options.recoverDrift ? 1 : statuses.length); - assert.equal(sleeps, options.labelRemoved ? 0 : options.absentExpires ? 2 : options.finalIdentity ? (statuses[0] === "absent" ? 1 : 0) + assert.equal(polls, options.ordinaryAfterDrift || options.directProof || options.labelRemoved ? 0 + : options.withdrawDuringProof || options.rejectedObject ? 1 : options.absentExpires ? 5 + : options.snapshotExpires ? 3 : options.recoverDrift ? 1 : statuses.length); + assert.equal(sleeps, options.ordinaryAfterDrift || options.labelRemoved || options.withdrawDuringProof || options.rejectedObject ? 0 + : options.absentExpires ? 4 : options.snapshotExpires ? 2 : options.finalIdentity ? (statuses[0] === "absent" ? 1 : 0) : expires ? statuses.length : statuses.length - 1); } // Exercise the real resolver, not merely a stub that honors requireCurrent. @@ -3844,6 +3886,11 @@ function markerAccepted(overrides = {}) { await assert.rejects(failedLegacyProof(stage, terminal), error => error === terminal); await assert.rejects(failedProof(terminal), error => error === terminal); } + const currentAttempt = {id: 99, run_attempt: 2, status: "completed", conclusion: "success"}; + assert.equal(await finalAttemptCheck(currentAttempt), true); + for (const change of [{run_attempt: 3}, {run_attempt: 1}, {id: 98}, {status: "in_progress"}, {conclusion: "failure"}]) { + assert.equal(await finalAttemptCheck({...currentAttempt, ...change}), false); + } assert.deepEqual(await recoveredFailure(), {accepted: true, verified: 1, queries: 1}); const alternateIdentity = {...identity, baseSha: "e".repeat(40), mergeSha: "f".repeat(40)}; assert.equal((await recoveredFailure({}, {...source, id: 199, conclusion: "failure"}, alternateIdentity)).accepted, true); @@ -3858,7 +3905,16 @@ function markerAccepted(overrides = {}) { assert.equal((await recoveredFailure({mutateProof: data => { data.jobs[0].steps.push(step("Start database", "failure")); }, latest: {run_attempt: 2}})).accepted, false); - await pendingRefreshCaller(["absent", "absent", "absent", "completed"], false, {absentExpires: true}); + await pendingRefreshCaller(["absent", "absent", "absent", "absent", "absent", "completed"], false, {absentExpires: true}); + await pendingRefreshCaller(["absent", "absent", "absent", "completed"]); // Validation may outlast the former5min-equivalent window. + await pendingRefreshCaller(["missing-job", "missing-job", "missing-job", "completed"], false, {snapshotExpires: true}); + await pendingRefreshCaller(["completed"], false, {rejectedObject: true}); + await pendingRefreshCaller(["completed", "older", "completed"], false, {finalNull: true}); + await pendingRefreshCaller(["older", "completed"]); + await pendingRefreshCaller(["completed", "queued", "completed"], false, {rerunFinal: true}); + await pendingRefreshCaller(["completed"], false, {withdrawDuringProof: true}); + await pendingRefreshCaller(["completed"], false, {recoverDrift: true, ordinaryAfterDrift: true, labelRemoved: true, + finalIdentity: {baseSha: "e".repeat(40), mergeSha: "f".repeat(40)}}); await pendingRefreshCaller(["absent", "queued", "in_progress", "in_progress", "completed"]); await pendingRefreshCaller(["absent", "queued", "absent", "absent", "absent", "completed"]); await pendingRefreshCaller(["superseded", "queued", "completed"]); @@ -3885,8 +3941,8 @@ function markerAccepted(overrides = {}) { await pendingRefreshCaller(["queued", "in_progress", "completed"]); await pendingRefreshCaller(["queued", "in_progress"], true); assert.equal((await recoveredFailure({absent: true})).accepted, "absent"); - assert.equal((await recoveredFailure({noProducer: true})).accepted, "pending"); - assert.equal((await recoveredFailure({candidate: {status: "in_progress"}})).accepted, "pending"); + assert.equal((await recoveredFailure({noProducer: true})).accepted, "snapshot-pending"); + assert.equal((await recoveredFailure({candidate: {status: "in_progress"}})).accepted, "snapshot-pending"); await pendingRefreshCaller(["absent", "queued", "completed"]); await pendingRefreshCaller(["missing-job", "pending-job", "completed"]); await pendingRefreshCaller(["absent", "absent"], true); @@ -3906,7 +3962,7 @@ function markerAccepted(overrides = {}) { for (const options of [ {repository: "attacker/FireMUD"}, {original: {event: "repository_dispatch"}}, {original: {status: "in_progress"}}, {original: {conclusion: "success"}}, - {original: {id: 0}}, {replacement: {id: 98}}, {replacement: {id: 97}}, + {original: {id: 0}}, {replacement: {run_attempt: 0}}, {replacement: {event: "pull_request"}}, {replacement: {status: "unknown"}}, {replacement: {conclusion: "cancelled"}}, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java index 012af3be5b..514c95dbe9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java @@ -256,6 +256,8 @@ public static final class CapacityException extends IllegalStateException { public CapacityException(Failure code) { super(code.name()); + if (code == Failure.CAPACITY_QUOTA_EXCEEDED) + throw new IllegalArgumentException("A quota refusal requires a durable denial"); this.code = code; this.durableDenialId = null; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java index 02b92e229b..5fb660e152 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java @@ -85,9 +85,14 @@ public void commitTenantCapacityAdmission( observer.onError(denied.code().toStatusException()); return; } - result = - TenantCapacityAdmissionGrpcCodec.toRefusal( - request, denied.code(), denied.durableDenialId()); + try { + result = + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, denied.code(), denied.durableDenialId()); + } catch (RuntimeException internal) { + observer.onError(Status.INTERNAL.asRuntimeException()); + return; + } } catch (org.jooq.exception.DataAccessException | org.springframework.dao.DataAccessException | org.springframework.transaction.TransactionException unavailable) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java index dd66d37954..53733ebc95 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -81,6 +81,39 @@ void unexpectedOwnerFailuresAreSanitizedInternal(RuntimeException cause) { } } + @Test + void quotaExceptionRequiresDurableDecisionIdentity() { + org.assertj.core.api.Assertions.assertThatThrownBy( + () -> { + throw new CapacityException(Failure.CAPACITY_QUOTA_EXCEEDED); + }) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void invalidDomainRefusalIsSanitizedInternal() { + // Noncreating evidence cannot authorize a quota refusal, even with a decision UUID. + var request = CapacityAdmissionTestFixture.playerRequest(false); + try (var guards = authenticatedCaller()) { + AccountTenantCapacityOwner owner = mock(); + when(owner.commit(request, CapacityAdmissionTestFixture.PEER)) + .thenThrow( + new CapacityException(Failure.CAPACITY_QUOTA_EXCEEDED, java.util.UUID.randomUUID())); + StreamObserver observer = mock(); + new AccountTenantCapacityGrpcService(owner, "prod") + .commitTenantCapacityAdmission( + TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); + var error = ArgumentCaptor.forClass(Throwable.class); + verify(observer).onError(error.capture()); + Status status = Status.fromThrowable(error.getValue()); + assertThat(status.getCode()).isEqualTo(Status.Code.INTERNAL); + assertThat(status.getDescription()).isNull(); + assertThat(status.getCause()).isNull(); + verify(observer, never()).onNext(any()); + verify(observer, never()).onCompleted(); + } + } + @Test void typedOwnerEvidenceUnavailableKeepsItsPublicFailure() { var request = CapacityAdmissionTestFixture.playerRequest(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java index 8a570e4cc6..2b13d1647e 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java @@ -168,15 +168,7 @@ protected final R withPublishedInitializedStub( selected.activeCalls--; shutdown = selected.retired && selected.activeCalls == 0; } - if (shutdown) { - try { - selected.channel.shutdown(); - } catch (RuntimeException shutdownFailure) { - // Retirement must not replace a completed RPC response or its original failure. - logger.warn( - "Failed to shut down retired gRPC channel after call completion", shutdownFailure); - } - } + if (shutdown) shutdownRetired(selected); } } @@ -298,7 +290,16 @@ private void retire(ChannelGeneration previous) { return; } } - previous.channel.shutdown(); + shutdownRetired(previous); + } + + private void shutdownRetired(ChannelGeneration retired) { + try { + retired.channel.shutdown(); + } catch (RuntimeException shutdownFailure) { + // Cleanup cannot invalidate a published replacement or replace an RPC outcome. + logger.warn("Failed to shut down retired gRPC channel", shutdownFailure); + } } private static final class ChannelGeneration { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java index 0c05bbc33d..4d10975cb5 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java @@ -137,53 +137,77 @@ public void ping(PingRequest request, StreamObserver observer) { }) .build() .start(); - var previous = - NettyChannelBuilder.forAddress("127.0.0.1", server.getPort()).usePlaintext().build(); - var replacement = - NettyChannelBuilder.forAddress("127.0.0.1", server.getPort()).usePlaintext().build(); + try { + var previous = + NettyChannelBuilder.forAddress("127.0.0.1", server.getPort()).usePlaintext().build(); + try { + var replacement = + NettyChannelBuilder.forAddress("127.0.0.1", server.getPort()).usePlaintext().build(); + var grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + var factory = mock(GrpcChannelFactory.class); + when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(previous, replacement); + var selected = new CountDownLatch(1); + var startCall = new CountDownLatch(1); + try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory); + var executor = Executors.newSingleThreadExecutor()) { + client.initExplicit(); + var result = + executor.submit( + () -> + client.withPublishedInitializedStub( + "test client has no stub", + stub -> { + assertThat(stub.getChannel()).isSameAs(previous); + selected.countDown(); + try { + assertThat(startCall.await(5, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError(interrupted); + } + return stub.withDeadlineAfter(5, TimeUnit.SECONDS) + .ping(PingRequest.getDefaultInstance()); + })); + try { + assertThat(selected.await(5, TimeUnit.SECONDS)).isTrue(); + client.reloadChannel(); + assertThat(client.requirePublishedExplicitStub().getChannel()).isSameAs(replacement); + assertThat(previous.isShutdown()).isFalse(); + assertThat(calls).hasValue(0); + } finally { + startCall.countDown(); + } + assertThat(result.get(5, TimeUnit.SECONDS)).isEqualTo(expectedResponse); + assertThat(calls).hasValue(1); + assertThat(previous.isShutdown()).isTrue(); + } finally { + replacement.shutdownNow(); + } + } finally { + previous.shutdownNow(); + } + } finally { + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + @Test + void idleRetirementFailureDoesNotInvalidatePublishedReplacement() throws Exception { var grpc = new CommonGrpcClientProperties(); grpc.setPlaintext(true); + var previous = mock(ManagedChannel.class); + var replacement = mock(ManagedChannel.class); var factory = mock(GrpcChannelFactory.class); when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) .thenReturn(previous, replacement); - var selected = new CountDownLatch(1); - var startCall = new CountDownLatch(1); - try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory); - var executor = Executors.newSingleThreadExecutor()) { + when(previous.shutdown()).thenThrow(new IllegalStateException("shutdown failure")); + try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory)) { client.initExplicit(); - var result = - executor.submit( - () -> - client.withPublishedInitializedStub( - "test client has no stub", - stub -> { - assertThat(stub.getChannel()).isSameAs(previous); - selected.countDown(); - try { - assertThat(startCall.await(5, TimeUnit.SECONDS)).isTrue(); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new AssertionError(interrupted); - } - return stub.withDeadlineAfter(5, TimeUnit.SECONDS) - .ping(PingRequest.getDefaultInstance()); - })); - try { - assertThat(selected.await(5, TimeUnit.SECONDS)).isTrue(); - client.reloadChannel(); - assertThat(client.requirePublishedExplicitStub().getChannel()).isSameAs(replacement); - assertThat(previous.isShutdown()).isFalse(); - assertThat(calls).hasValue(0); - } finally { - startCall.countDown(); - } - assertThat(result.get(5, TimeUnit.SECONDS)).isEqualTo(expectedResponse); - assertThat(calls).hasValue(1); - assertThat(previous.isShutdown()).isTrue(); - } finally { - previous.shutdownNow(); - replacement.shutdownNow(); - server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + client.reloadChannel(); + assertThat(client.requirePublishedExplicitStub().getChannel()).isSameAs(replacement); + verify(previous).shutdown(); } } From ec9f5caa6bcb050141c92fafc84c3b866a2d4f6a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:59:26 +1300 Subject: [PATCH 10/96] fix: preserve capacity authority after blocking writes and bound proof convergence --- .github/workflows/smoke.yml | 64 ++++--- .../game-session-service/runtime-and-data.md | 2 +- .../pr-required-gate-context-contract.sh | 44 ++++- .../AccountTenantCapacityRepository.java | 1 + .../service/AccountTenantCapacityOwner.java | 5 +- ..._origin_identity_before_refusal_budget.sql | 33 ++++ ...acityMigrationPostgresIntegrationTest.java | 158 ++++++++++++++++++ .../AccountTenantCapacityOwnerTest.java | 106 ++++++++++++ .../AccountTenantCapacityGrpcServiceTest.java | 1 + .../TenantCapacityAdmissionGrpcCodec.java | 3 +- .../TenantCapacityAdmissionGrpcCodecTest.java | 22 ++- .../AccountTenantCapacityClientMtlsTest.java | 2 +- 12 files changed, 405 insertions(+), 36 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V1040.5__arbitrate_origin_identity_before_refusal_budget.sql diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 02c8df1e59..b1cc34400e 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -812,7 +812,7 @@ jobs: } // Canonical-transition diagnostic acceptance never becomes passing producer proof. - async function verifyKnownPlayFailure(run, candidate, identity) { + async function verifyKnownPlayFailure(run, candidate, identity, allowIncompleteSteps = false) { if (repositoryName !== "benhook1013/FireMUD" || !["pull_request", "repository_dispatch"].includes(run.event)) return false; if (!positiveInteger(run.id) || !positiveInteger(run.run_attempt)) return false; @@ -868,18 +868,28 @@ jobs: ]; const markerName = "Known canonical transition PLAY failure with successful authenticated cleanup"; const steps = job.steps ?? []; - const exactlyOne = (name, conclusion) => steps.filter((step) => - step.name === name && step.status === "completed" && step.conclusion === conclusion - ).length === 1; - if (!exactlyOne(markerName, "success") || !exactlyOne("Stop smoke stack", "success") || - !exactlyOne("Export fixed-tag preview image artifact", "skipped") || - !exactlyOne("Upload preview image artifact", "skipped") || - expectedSuccessfulSteps.some((name) => !exactlyOne(name, source.conclusion)) || - steps.some((step) => step.status !== "completed" || - !["success", "skipped", "failure"].includes(step.conclusion) || - (step.conclusion === "failure" && !(source.conclusion === "failure" && expectedSuccessfulSteps.includes(step.name)))) || - jobs.some((other) => other.id !== job.id && - (other.status !== "completed" || !["success", "skipped"].includes(other.conclusion)))) return false; + const requiredSteps = new Map([ + [markerName, "success"], ["Stop smoke stack", "success"], + ["Export fixed-tag preview image artifact", "skipped"], + ["Upload preview image artifact", "skipped"], + ...expectedSuccessfulSteps.map((name) => [name, source.conclusion]), + ]); + let incompleteSteps = false; + for (const [name, conclusion] of requiredSteps) { + const matches = steps.filter((step) => step.name === name); + if (matches.length > 1) return false; + if (matches.length === 0 || matches[0].status !== "completed") { + incompleteSteps = true; + } else if (matches[0].conclusion !== conclusion) return false; + } + for (const step of steps) { + if (step.status !== "completed") incompleteSteps = true; + else if (!["success", "skipped", "failure"].includes(step.conclusion) || + (step.conclusion === "failure" && !(source.conclusion === "failure" && + expectedSuccessfulSteps.includes(step.name)))) return false; + } + if (jobs.some((other) => other.id !== job.id && + (other.status !== "completed" || !["success", "skipped"].includes(other.conclusion)))) return false; // Typed refresh workflow authority is its native default-branch revision; // the executed classifier source still belongs to the verified PR merge. const workflowSha = source.event === "pull_request" ? identity.mergeSha : source.head_sha; @@ -930,19 +940,27 @@ jobs: if (currentBase.ref !== `refs/heads/${identity.baseRef}` || currentBase.object?.sha !== identity.baseSha) return false; } - return true; + return incompleteSteps ? (allowIncompleteSteps ? "snapshot-pending" : false) : true; } // A failed original event is not replaced by arbitrary green history. Only // a newer exact typed refresh with independently proven canonical exception // evidence can recover this diagnostic gate; it never proves PLAY succeeded. async function isCurrentCanonicalAttempt(run) { - const { data: latest } = await withTransientGitHubRetry( - "final canonical exception attempt lookup", - () => github.rest.actions.getWorkflowRun({owner, repo, run_id: run.id}) - ); - return latest.id === run.id && latest.run_attempt === run.run_attempt && - latest.status === "completed" && latest.conclusion === run.conclusion; + try { + const { data: latest } = await withTransientGitHubRetry( + "final canonical exception attempt lookup", + () => github.rest.actions.getWorkflowRun({owner, repo, run_id: run.id}) + ); + return latest.id === run.id && latest.run_attempt === run.run_attempt && + latest.status === "completed" && latest.conclusion === run.conclusion; + } catch (error) { + if (error instanceof TerminalGitHubRequestError) throw error; + const status = error?.status ?? error?.response?.status; + if (status != null && !retryableStatuses.has(status)) throw error; + core.warning("Final canonical attempt is temporarily unavailable; retaining bounded polling without accepting proof."); + return false; + } } async function verifyFailedPullCanonicalRefresh(run, identity) { @@ -975,9 +993,9 @@ jobs: if (!candidate || candidate.status !== "completed") { return {status: "snapshot-pending", run: proofRun}; } - if (await verifyKnownPlayFailure(replacement, candidate, identity)) { - return {status: "verified", run: proofRun}; - } + const proof = await verifyKnownPlayFailure(replacement, candidate, identity, true); + if (proof === "snapshot-pending") return {status: "snapshot-pending", run: proofRun}; + if (proof === true) return {status: "verified", run: proofRun}; // A new attempt can start between list/proof reads. Invalid current proof // is terminal; only a verified newer attempt warrants bounded reselection. const { data: latest } = await withTransientGitHubRetry( diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index c002b1162b..5503e9e53c 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,7 +10,7 @@ The service runtime model assumes replaceable workers, not authoritative in-proc This is a target-only contract, not an enabled or runtime-qualified retirement path. -The exact current Game Session owner establishes irreversible closure of serving and resume for the admitted binding and retains settlement of applicable effects and indexes. Game Session supplies an authenticated terminal receipt linked to the original admission, FINAL evidence, binding lineage and Account reservation. [Account owns retirement of the corresponding used capacity](../account-service/runtime-and-data.md#finalized-capacity-usage-retirement). The terminal receipt remains durable and exactly readable after binding closure and worker replacement. A replacement owner recovers and redelivers that same receipt until Account's exact retirement acknowledgement is known; this recovery never reopens serving or resume. +The exact current Game Session owner establishes irreversible closure of serving and resume for the admitted binding and retains settlement of applicable effects and indexes. Game Session supplies an authenticated terminal receipt linked to the original admission, FINAL evidence, binding lineage and Account reservation. [Account owns retirement of the corresponding used capacity](../account-service/runtime-and-data.md#finalized-capacity-usage-retirement). Before irreversible closure or settlement can discard the original work state, Game Session must durably retain the exact teardown identity and progress evidence needed for a replacement owner to finish the same terminal receipt. A crash between closure/settlement and receipt retention resumes that original teardown without reopening the binding or inventing a new receipt identity. The terminal receipt remains durable and exactly readable after binding closure and worker replacement. A replacement owner recovers and redelivers that same receipt until Account's exact retirement acknowledgement is known; this recovery never reopens serving or resume. ## Implementation Status diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 8187b5a000..93340ccc1b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3529,7 +3529,7 @@ const candidate = {id: 123, run_id: 99, run_attempt: 2, head_sha: headSha, name: steps: [...failures.map(name => step(name, "success")), step("Stop smoke stack", "success"), step("Known canonical transition PLAY failure with successful authenticated cleanup", "success"), step("Export fixed-tag preview image artifact", "skipped"), step("Upload preview image artifact", "skipped")]}; -async function verify(mutate = () => {}, event = "pull_request", knownPlay = true) { +async function verify(mutate = () => {}, event = "pull_request", knownPlay = true, allowIncompleteSteps = false) { const data = structuredClone({pr: "3390", consumerRepository: repositoryName, run, identity, source, candidate, jobs: [candidate], latest: {...source}, eventHeadRepository: repositoryName, currentPullRequest: {state: "open", head: {sha: headSha, repo: {full_name: repositoryName}}, @@ -3565,7 +3565,7 @@ async function verify(mutate = () => {}, event = "pull_request", knownPlay = tru const verifier = knownPlay ? "verifyKnownPlayFailure" : "verifyCanonicalSmokeProducer"; const accepted = await new Function("github", "prNumber", "repositoryName", "canonicalSmokeJobName", "workflowPath", "canonicalRuntimeWorkflowSha256", "canonicalPreviousTrustedRefreshRuntimeWorkflowSha256", "canonicalLegacyRuntimeWorkflowSha256", "canonicalPlayClassifierSha256", "positiveInteger", "withTransientGitHubRetry", "context", "owner", "repo", "require", "data", - `${fn}; return ${verifier}(data.run, data.candidate, data.identity);`)( + `${fn}; return ${verifier}(data.run, data.candidate, data.identity, ${allowIncompleteSteps});`)( github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, canonicalPreviousTrustedRefreshRuntimeWorkflowSha256, data.legacyDefinition ? canonicalRuntimeWorkflowSha256 : canonicalLegacyRuntimeWorkflowSha256, canonicalPlayClassifierSha256, @@ -3576,13 +3576,16 @@ async function verify(mutate = () => {}, event = "pull_request", knownPlay = tru return accepted; } // Final attempt authority remains separate from PR identity and label authority. -async function finalAttemptCheck(latest) { +async function finalAttemptCheck(latest, error = null) { const start = script.indexOf("async function isCurrentCanonicalAttempt("); const end = script.indexOf("async function verifyFailedPullCanonicalRefresh(", start); const check = new Function("github", "withTransientGitHubRetry", "owner", "repo", + "TerminalGitHubRequestError", "retryableStatuses", "core", `${script.slice(start, end)}; return isCurrentCanonicalAttempt;`)( - {rest: {actions: {getWorkflowRun: async ({run_id}) => {assert.equal(run_id, 99); return {data: latest};}}}}, - (_label, call) => call(), "benhook1013", "FireMUD"); + {rest: {actions: {getWorkflowRun: async ({run_id}) => { + assert.equal(run_id, 99); if (error) throw error; return {data: latest}; + }}}}, (_label, call) => call(), "benhook1013", "FireMUD", TerminalGitHubRequestError, + new Set([408, 425, 429, 500, 502, 503, 504]), {warning: () => {}}); return check({id: 99, run_attempt: 2, conclusion: "success"}); } assert.ok(script.includes("const refreshDiscoveryTimeoutMs = prerequisiteAndQueueAllowanceMinutes * 60 * 1000;")); @@ -3618,7 +3621,7 @@ async function recoveredFailure(options = {}, selectedRun = null, selectedIdenti }, rest: {actions: {getWorkflowRun: async ({run_id}) => { assert.equal(run_id, replacement.id); return {data: {...replacement, ...options.latest}}; - }}}}, "benhook1013", "FireMUD", canonicalSmokeJobName, async (selected, job, proofIdentity) => { + }}}}, "benhook1013", "FireMUD", canonicalSmokeJobName, async (selected, job, proofIdentity, allowIncompleteSteps) => { verified++; assert.deepEqual(proofIdentity, selectedIdentity); assert.equal(selected, replacement); assert.deepEqual(job, selectedCandidate); @@ -3641,7 +3644,7 @@ async function recoveredFailure(options = {}, selectedRun = null, selectedIdenti } } if (options.mutateProof) options.mutateProof(data); - }, "repository_dispatch"); + }, "repository_dispatch", true, allowIncompleteSteps); }, {payload: {pull_request: {head: {repo: {full_name: options.headRepository || repositoryName}}}}}); const proof = await recover(original, selectedIdentity); return {accepted: raw ? proof : proof?.status === "verified" ? true @@ -3751,6 +3754,8 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { : status === "absent" ? {absent: true} : status === "older" ? {replacement: {id: 97}} : status === "superseded" ? {latest: {run_attempt: 3}, mutateProof: data => {data.latest.run_attempt = 3;}} + : status === "missing-step" ? {candidate: {steps: candidate.steps.filter(step => step.name !== "Stop smoke stack")}} + : status === "nonterminal-step" ? {candidate: {steps: candidate.steps.map(step => step.name === "Stop smoke stack" ? {...step, status: "in_progress", conclusion: null} : step)}} : status === "missing-job" ? {noProducer: true} : status === "pending-job" ? {candidate: {status: "in_progress"}} : {replacement: {status, conclusion: status === "completed" ? "success" : null, @@ -3784,6 +3789,9 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { assert.equal(selected.id, 99); assert.equal(selected.run_attempt, statuses[0] === "superseded" && polls > 1 ? 3 : 2); } + if (options.transientFinal && finalChecks === 1) { + return finalAttemptCheck(null, Object.assign(new Error("temporary"), {status: 502})); + } return !options.rerunFinal || finalChecks > 1; }); if (options.ordinaryAfterDrift) { @@ -3888,6 +3896,28 @@ function markerAccepted(overrides = {}) { } const currentAttempt = {id: 99, run_attempt: 2, status: "completed", conclusion: "success"}; assert.equal(await finalAttemptCheck(currentAttempt), true); + assert.equal(await finalAttemptCheck(null, Object.assign(new Error("temporary"), {status: 502})), false); + assert.equal(await finalAttemptCheck(null, new Error("network")), false); + const denied = new TerminalGitHubRequestError("denied"); + await assert.rejects(finalAttemptCheck(null, denied), error => error === denied); + const missing = Object.assign(new Error("missing"), {status: 404}); + await assert.rejects(finalAttemptCheck(null, missing), error => error === missing); + await pendingRefreshCaller(["completed", "completed"], false, {transientFinal: true}); + await pendingRefreshCaller(["missing-step", "completed"]); + await pendingRefreshCaller(["nonterminal-step", "completed"]); + await pendingRefreshCaller(["missing-step", "missing-step", "missing-step", "completed"], false, {snapshotExpires: true}); + const missingCleanup = candidate.steps.filter(step => step.name !== "Stop smoke stack"); + assert.equal((await recoveredFailure({candidate: {steps: missingCleanup}, mutateProof: data => { + data.definitions[workflowPath].content = Buffer.from("untrusted").toString("base64"); + }})).accepted, false, "missing step metadata cannot hide invalid workflow authority"); + assert.equal((await recoveredFailure({candidate: {steps: missingCleanup}, mutateProof: data => { + data.currentPullRequest.head.sha = "e".repeat(40); + }})).accepted, false, "missing steps cannot hide changed live identity"); + assert.equal((await recoveredFailure({candidate: {steps: candidate.steps.map(step => + step.name === "Stop smoke stack" ? {...step, conclusion: "failure"} : step)}})).accepted, false); + assert.equal((await recoveredFailure({candidate: {steps: candidate.steps.map(step => + step.name.startsWith("Known canonical") ? {...step, conclusion: "skipped"} : step)}})).accepted, false); + for (const change of [{run_attempt: 3}, {run_attempt: 1}, {id: 98}, {status: "in_progress"}, {conclusion: "failure"}]) { assert.equal(await finalAttemptCheck({...currentAttempt, ...change}), false); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java index 514c95dbe9..04c302b678 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityRepository.java @@ -149,6 +149,7 @@ public Optional createIfQuotaAvailable(Request request, Instant expiresA long occupied = Math.addExact(number(usage, "held_units"), number(usage, "used_units")); if (delta > request.evidence().quota() - occupied) return Optional.empty(); new AccountCapacityOriginDecisionRepository(dsl).accept(request); + requireCurrentLifetime(request.evidence(), clock.instant()); long held = Math.addExact(number(usage, "held_units"), delta); updateUsage(request, usage, held, number(usage, "used_units")); int created = diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index 350e9fbd83..d41db06436 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -121,7 +121,9 @@ public Result commit(Request request, String authenticatedCaller) { if (reservation.isPresent()) { return new CommitDecision(reservation.orElseThrow(), null); } - return new CommitDecision(null, originDecisions.refuseQuota(request)); + UUID denialId = originDecisions.refuseQuota(request); + requireCurrentLifetime(request.evidence(), clock.instant()); + return new CommitDecision(null, denialId); }); // Throw only after the transaction has committed the exact denial. if (decision.denialId() != null) @@ -164,6 +166,7 @@ Result rearm(Request prior, Request next, UUID recoveryOwner, long claimFence) { current(next); requireSupportedShape(next); originDecisions.accept(next); + requireClaim(row, recoveryOwner, claimFence, clock.instant()); requireCurrentLifetime(next.evidence(), clock.instant()); int history = dsl.execute( diff --git a/services/account-service/src/main/resources/db/migration/V1040.5__arbitrate_origin_identity_before_refusal_budget.sql b/services/account-service/src/main/resources/db/migration/V1040.5__arbitrate_origin_identity_before_refusal_budget.sql new file mode 100644 index 0000000000..863ff049dc --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1040.5__arbitrate_origin_identity_before_refusal_budget.sql @@ -0,0 +1,33 @@ +-- Arbitrate global attempt identity before checking a new refusal's budget. +-- AFTER INSERT runs only for an inserted row, not an ON CONFLICT replay, and +-- includes the new refusal in the bounded count. Failure rolls the insert back. +-- Retain the same-value budget update to serialize same-tenant refusal writers. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION require_account_capacity_origin_refusal_budget() RETURNS TRIGGER +LANGUAGE plpgsql AS $$ +DECLARE refusal_limit INTEGER; retained_count BIGINT; +BEGIN + IF NEW.decision <> 'NO_ACCEPT' THEN RETURN NEW; END IF; + UPDATE account_capacity_origin_refusal_budget + SET maximum_refusals = maximum_refusals + WHERE tenant_uuid = NEW.tenant_uuid + RETURNING maximum_refusals INTO refusal_limit; + IF NOT FOUND THEN + RAISE EXCEPTION 'Capacity refusal budget is unavailable' USING ERRCODE = '23514'; + END IF; + SELECT count(*) INTO retained_count FROM ( + SELECT 1 FROM account_capacity_origin_decisions + WHERE tenant_uuid = NEW.tenant_uuid AND decision = 'NO_ACCEPT' + LIMIT refusal_limit::BIGINT + 1 + ) retained; + IF retained_count > refusal_limit THEN + RAISE EXCEPTION 'Capacity refusal budget is exhausted' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +DROP TRIGGER account_capacity_origin_refusal_budget_required ON account_capacity_origin_decisions; +CREATE TRIGGER account_capacity_origin_refusal_budget_required + AFTER INSERT ON account_capacity_origin_decisions + FOR EACH ROW EXECUTE FUNCTION require_account_capacity_origin_refusal_budget(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index d53fc98b55..d5a3257952 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -357,6 +357,164 @@ void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { } } + @Test + void refusalBudgetRunsAfterIdentityArbitrationAndCountsTheInsertedLastSlot() throws Exception { + String schema = "capacity_arbitration_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); + var tenant = source(); + transaction.executeWithoutResult( + status -> { + new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(tenant); + new AccountCapacityRefusalBudgetRepository(dsl) + .provision(tenant.canonicalTenantId(), 1); + }); + UUID request = UUID.randomUUID(), + admission = UUID.randomUUID(), + attempt = UUID.randomUUID(), + decision = UUID.randomUUID(); + String insert = + """ + 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, refusal_code) + VALUES (?, ?, ?, 1, ?, ?, ?, 'NO_ACCEPT', ?, 'CAPACITY_QUOTA_EXCEEDED') + ON CONFLICT DO NOTHING + """; + Object[] original = { + tenant.canonicalTenantId(), + request, + admission, + attempt, + "a".repeat(64), + new byte[] {1}, + decision + }; + assertThat(dsl.execute(insert, original)).isEqualTo(1); + var retained = + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_decisions") + .intoMap(); + // Exact retry must not spend another slot or update the immutable evidence. + assertThat(dsl.execute(insert, original)).isZero(); + assertThatThrownBy( + () -> + dsl.execute( + insert, + tenant.canonicalTenantId(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "a".repeat(64), + new byte[] {1}, + UUID.randomUUID())) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + // A different outer identity with the same global attempt reaches conflict arbitration, + // not the missing budget guard. The repository then verifies exact retained identity. + assertThat( + dsl.execute( + insert, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + attempt, + "b".repeat(64), + new byte[] {2}, + UUID.randomUUID())) + .isZero(); + assertThat( + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_decisions") + .intoMap()) + .usingRecursiveComparison() + .isEqualTo(retained); + // A genuinely new refusal without a budget still fails and leaves no evidence. + assertThatThrownBy( + () -> + dsl.execute( + insert, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "b".repeat(64), + new byte[] {2}, + UUID.randomUUID())) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))).isEqualTo(1); + + var concurrentTenant = source(); + transaction.executeWithoutResult( + status -> { + new FreshTenantIdentityAssociationRepository(dsl, "prod") + .importVerified(concurrentTenant); + new AccountCapacityRefusalBudgetRepository(dsl) + .provision(concurrentTenant.canonicalTenantId(), 1); + }); + UUID concurrentAttempt = UUID.randomUUID(); + try (var stale = data.getConnection(); + var winner = data.getConnection()) { + stale.setTransactionIsolation(java.sql.Connection.TRANSACTION_SERIALIZABLE); + stale.setAutoCommit(false); + var staleDsl = DSL.using(stale, SQLDialect.POSTGRES); + // Establish the serializable snapshot before the winning global identity is committed. + assertThat(staleDsl.fetchCount(DSL.table("account_capacity_origin_decisions"))) + .isEqualTo(1); + assertThat( + DSL.using(winner, SQLDialect.POSTGRES) + .execute( + insert, + concurrentTenant.canonicalTenantId(), + UUID.randomUUID(), + UUID.randomUUID(), + concurrentAttempt, + "c".repeat(64), + new byte[] {3}, + UUID.randomUUID())) + .isEqualTo(1); + assertThatThrownBy( + () -> + staleDsl.execute( + insert, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + concurrentAttempt, + "d".repeat(64), + new byte[] {4}, + UUID.randomUUID())) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("40001")); + stale.rollback(); + } + assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))).isEqualTo(2); + assertThat( + dsl.fetchSingle( + "SELECT decision FROM account_capacity_origin_decisions WHERE admission_attempt_id = ?", + concurrentAttempt) + .get("decision")) + .isEqualTo("NO_ACCEPT"); + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + private static Account creator() { String suffix = UUID.randomUUID().toString().replace("-", ""); var account = new Account(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index e8fbe80818..a496e280e9 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -229,6 +229,112 @@ void durableQuotaDenialReplaysWithoutConsultingMutableCapacity() throws Exceptio .fetchOne(startsWith("SELECT * FROM account_tenant_capacity_usage "), any(Object[].class)); } + @Test + void expiryDuringOriginRetentionRollsBackAcceptanceAndRefusal() throws Exception { + for (boolean quotaFull : new boolean[] {false, true}) { + var f = new Fixture(false, qualifiedRequest(true)); + f.existing = false; + f.retained = true; + qualifySources(f); + Record usage = mock(Record.class); + when(usage.get("held_units", Long.class)) + .thenReturn(quotaFull ? f.request.evidence().quota() : 0L); + when(usage.get("used_units", Long.class)).thenReturn(0L); + org.mockito.Mockito.doReturn(usage) + .when(f.dsl) + .fetchOne( + startsWith("SELECT * FROM account_tenant_capacity_usage "), any(Object[].class)); + retainOriginThenAdvanceClock( + f, f.request, quotaFull ? "NO_ACCEPT" : "ACCEPTED", f.request.evidence().expiresAt()); + + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isInstanceOfSatisfying( + AccountTenantCapacityRepository.CapacityException.class, + failure -> assertThat(failure.code()).isEqualTo(Failure.CAPACITY_ADMISSION_STALE)); + verify(f.dsl) + .execute( + startsWith("INSERT INTO account_capacity_origin_decisions "), any(Object[].class)); + verify(f.dsl, never()) + .execute(startsWith("UPDATE account_tenant_capacity_usage "), any(Object[].class)); + verify(f.dsl, never()) + .execute( + startsWith("INSERT INTO account_tenant_capacity_reservations "), any(Object[].class)); + assertThat(f.originDecision).isNull(); + assertThat(f.pendingOriginDecision).isNull(); + } + } + + @Test + void claimExpiryDuringRearmAcceptanceRollsBackBeforeHistoryOrFenceMutation() throws Exception { + var f = new Fixture(false, qualifiedRequest(true)); + f.retained = true; + qualifySources(f); + var next = + new Request( + f.request.identity(), + UUID.randomUUID(), + 2, + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest(); + Record row = + java.util.Objects.requireNonNull( + f.dsl.fetchOne("SELECT * FROM account_tenant_capacity_reservations ", new Object[0])); + UUID claimOwner = UUID.randomUUID(); + var claimExpiry = CapacityAdmissionTestFixture.NOW.plusSeconds(2); + when(row.get("recovery_owner", UUID.class)).thenReturn(claimOwner); + when(row.get("recovery_claim_fence", Long.class)).thenReturn(7L); + when(row.get("recovery_claim_expires_at", java.time.OffsetDateTime.class)) + .thenReturn(AccountTenantCapacityRepository.at(claimExpiry)); + when(row.get("execution_status", String.class)).thenReturn("NOT_EXECUTED_AFTER_AUTHORIZATION"); + when(row.get("owner_readback", byte[].class)).thenReturn(new byte[] {1}); + retainOriginThenAdvanceClock(f, next, "ACCEPTED", claimExpiry); + var rearm = + AccountTenantCapacityOwner.class.getDeclaredMethod( + "rearm", Request.class, Request.class, UUID.class, long.class); + rearm.setAccessible(true); + assertThatThrownBy(() -> rearm.invoke(f.owner, f.request, next, claimOwner, 7L)) + .hasCauseInstanceOf(AccountTenantCapacityRepository.CapacityException.class) + .hasRootCauseMessage("IDEMPOTENCY_CONFLICT"); + verify(f.dsl) + .execute(startsWith("INSERT INTO account_capacity_origin_decisions "), any(Object[].class)); + verify(f.dsl, never()) + .execute( + startsWith("INSERT INTO account_tenant_capacity_attempt_history "), + any(Object[].class)); + verify(f.dsl, never()) + .execute(startsWith("UPDATE account_tenant_capacity_reservations "), any(Object[].class)); + assertThat(f.originDecision).isNull(); + assertThat(f.pendingOriginDecision).isNull(); + } + + private static void retainOriginThenAdvanceClock( + Fixture f, Request request, String decision, java.time.Instant afterWrite) { + Record retained = mock(Record.class); + when(retained.get("admission_attempt_id", UUID.class)).thenReturn(request.admissionAttemptId()); + when(retained.get("mutation_digest", String.class)).thenReturn(request.mutationDigest()); + when(retained.get("canonical_payload", byte[].class)) + .thenReturn(CapacityAdmissionDigest.preimage(request)); + when(retained.get("decision", String.class)).thenReturn(decision); + when(retained.get("decision_id", UUID.class)).thenReturn(UUID.randomUUID()); + when(retained.get("refusal_code", String.class)) + .thenReturn("NO_ACCEPT".equals(decision) ? "CAPACITY_QUOTA_EXCEEDED" : null); + when(f.dsl.execute( + startsWith("INSERT INTO account_capacity_origin_decisions "), any(Object[].class))) + .thenAnswer( + invocation -> { + f.pendingOriginDecision = retained; + when(f.clock.instant()).thenReturn(afterWrite); + return 1; + }); + } + @Test void repeatedSerializationFailuresRetryAndReplayInAFreshTransaction() throws Exception { var f = new Fixture(true); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java index 53733ebc95..b9f174bfd3 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -111,6 +111,7 @@ void invalidDomainRefusalIsSanitizedInternal() { assertThat(status.getCause()).isNull(); verify(observer, never()).onNext(any()); verify(observer, never()).onCompleted(); + verify(owner).commit(request, CapacityAdmissionTestFixture.PEER); } } diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java index 4195637e15..fd9e087a46 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java @@ -300,7 +300,8 @@ public static Optional readRefusalDetails( private static void requireRefusalAuthority(Request request, Refusal refusal) { if (refusal.code() == Failure.CAPACITY_QUOTA_EXCEEDED && (!request.evidence().permitsCreation() - || request.operation() != Operation.CAPACITY_CREATING)) throw invalid(); + || request.operation() != Operation.CAPACITY_CREATING + || request.capacityRearmFence() != 1)) throw invalid(); if (refusal.durableDenialId() != null && request.capacityRearmFence() != 1) throw invalid(); } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java index ae41571fa8..2e389978e9 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java @@ -173,7 +173,7 @@ void nonExpandingRequestCannotCarryQuotaRefusal() { } @Test - void matchedRearmCannotCarryDurableOriginalDenial() { + void matchedRearmCannotCarryOriginalQuotaDenial() { var original = CapacityAdmissionTestFixture.playerRequest(); var request = new Request( @@ -195,7 +195,25 @@ void matchedRearmCannotCarryDurableOriginalDenial() { TenantCapacityAdmissionGrpcCodec.toRefusal( request, Failure.CAPACITY_QUOTA_EXCEEDED, id)) .isInstanceOf(IllegalArgumentException.class); - var wire = TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.CAPACITY_QUOTA_EXCEEDED); + assertThatThrownBy( + () -> + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, Failure.CAPACITY_QUOTA_EXCEEDED)) + .isInstanceOf(IllegalArgumentException.class); + var billing = + TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.TENANT_BILLING_BLOCKED); + var wire = + billing.toBuilder() + .setRefusal( + 0, + billing.getRefusal(0).toBuilder() + .setCode( + 0, + net.firedevops.firemud.account.v1.TenantCapacityAdmissionRefusal.Code + .CAPACITY_QUOTA_EXCEEDED)) + .build(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, wire)) + .isInstanceOf(IllegalArgumentException.class); var forged = wire.toBuilder() .setRefusal(0, wire.getRefusal(0).toBuilder().addDurableDenialId(id.toString())) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index ae42710f65..6bea95a973 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -522,10 +522,10 @@ private static Server server( public void commitTenantCapacityAdmission( CommitTenantCapacityAdmissionRequest wire, StreamObserver observer) { - calls.incrementAndGet(); observedNanos.set( Objects.requireNonNull(Context.current().getDeadline()) .timeRemaining(TimeUnit.NANOSECONDS)); + calls.incrementAndGet(); if (!respond.get()) return; assertServerSide( serverFailure, From 5b452f6e7d8a46e8c394ab6816dc7a343d61aec6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:40:55 +1300 Subject: [PATCH 11/96] fix: reconcile skipped runtime refreshes after original producer failure --- .github/actionlint.yaml | 8 +- .../workflows/publish-pr-runtime-images.yml | 148 +++++++ .github/workflows/runtime-images.yml | 115 ++++-- .github/workflows/smoke.yml | 2 +- .../architecture/system-architecture-cicd.md | 2 + .../pr-required-gate-context-contract.sh | 105 +++++ .../tests/pr-retarget-workflow-contract.sh | 367 +++++++----------- 7 files changed, 480 insertions(+), 267 deletions(-) diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml index a9dd088ee8..3f78f9e163 100644 --- a/.github/actionlint.yaml +++ b/.github/actionlint.yaml @@ -4,7 +4,7 @@ self-hosted-runner: # GitHub Actions added concurrency.queue in May 2026. The repository-pinned # actionlint release does not parse it, so suppress only that known parser lag -# in workflows that use the shared preview lifecycle queue. +# in workflows that use the shared preview or trusted runtime dispatch queue. paths: .github/workflows/preview.yml: ignore: @@ -23,3 +23,9 @@ paths: # pinned actionlint release recognizes it. ignore: - 'label "ubuntu-26\.04" is unknown.*' + .github/workflows/runtime-images.yml: + ignore: + - '^unexpected key "queue" for "concurrency" section\. expected one of "cancel-in-progress", "group"$' + .github/workflows/publish-pr-runtime-images.yml: + ignore: + - '^unexpected key "queue" for "concurrency" section\. expected one of "cancel-in-progress", "group"$' diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 1054d88508..1e0e47662a 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -12,6 +12,154 @@ run-name: Publish PR Runtime Images ${{ github.event.workflow_run.display_title permissions: {} jobs: + reconcile-failed-pr-runtime: + name: Reconcile Failed Original PR Runtime + if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && contains(fromJSON('["failure","cancelled","timed_out"]'), github.event.workflow_run.conclusion) && github.event.workflow_run.head_repository.full_name == github.repository }} + runs-on: ubuntu-latest + timeout-minutes: 5 + concurrency: + group: runtime-pr-refresh-dispatch + queue: max + permissions: + actions: read + pull-requests: read + contents: write + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - name: Reconcile exact failed original runtime + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + const repository = `${context.repo.owner}/${context.repo.repo}`; + const event = context.payload.workflow_run; + const positive = value => Number.isSafeInteger(value) && value > 0; + const sha = value => typeof value === "string" && /^[0-9a-f]{40}$/.test(value); + const titlePattern = /^Build Runtime Images secure-pr-artifact pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40}) merge-([0-9a-f]{40}) mode-required$/; + if (context.eventName !== "workflow_run" || event?.event !== "pull_request" || + event.status !== "completed" || !["failure", "cancelled", "timed_out"].includes(event.conclusion) || + event.repository?.full_name !== repository || event.head_repository?.full_name !== repository || + !positive(event.id) || !positive(event.run_attempt)) return; + const {data: workflow} = await github.rest.actions.getWorkflow({...context.repo, workflow_id: "runtime-images.yml"}); + if (!positive(workflow.id) || workflow.path !== ".github/workflows/runtime-images.yml" || + workflow.name !== "Build Runtime Images") throw new Error("Untrusted runtime workflow identity"); + const matchesPath = (path, expected) => path === expected || + (typeof path === "string" && path.startsWith(`${expected}@refs/`) && + !/[\s~^:?*[\\]/.test(path.slice(expected.length + 1)) && !path.includes("..") && !path.includes("@{")); + const trusted = run => run?.workflow_id === workflow.id && matchesPath(run.path, workflow.path) && + run.repository?.full_name === repository && run.head_repository?.full_name === repository && + [workflow.name, run.display_title].includes(run.name) && positive(run.id) && positive(run.run_attempt); + const match = titlePattern.exec(event.display_title || ""); + if (!match) return; + const [ , number, base, head, merge] = match; + const sourceCurrent = async () => { + const {data: run} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: event.id}); + return trusted(run) && run.id === event.id && run.run_attempt === event.run_attempt && + run.event === "pull_request" && run.status === "completed" && run.conclusion === event.conclusion && + run.head_sha === head && run.display_title === event.display_title && run.head_branch === event.head_branch; + }; + if (!await sourceCurrent()) return; + const currentTuple = async () => { + const {data: pr} = await github.rest.pulls.get({...context.repo, pull_number: Number(number)}); + if (pr.state !== "open" || pr.head?.repo?.full_name !== repository || pr.base?.repo?.full_name !== repository || + pr.head?.sha !== head || pr.head?.ref !== event.head_branch || pr.base?.sha !== base || + typeof pr.base?.ref !== "string" || !pr.base.ref || pr.mergeable !== true || pr.merge_commit_sha !== merge) return null; + const {data: ref} = await github.rest.git.getRef({...context.repo, ref: `heads/${pr.base.ref}`}); + const {data: commit} = await github.rest.repos.getCommit({...context.repo, ref: merge}); + if (ref.object?.sha !== base || commit.sha !== merge || commit.parents?.length !== 2 || + commit.parents[0]?.sha !== base || commit.parents[1]?.sha !== head) return null; + return pr.base.ref; + }; + const baseRef = await currentTuple(); + if (!baseRef) return; + // Inventory incompleteness is unknown, never permission to dispatch duplicates. + const inventory = async (workflowId, filter) => { + const runs = [], ids = new Set(); + let total; + for (let page = 1; page <= 10; page++) { + const {data} = await github.rest.actions.listWorkflowRuns({ + ...context.repo, workflow_id: workflowId, per_page: 100, page, ...filter, + }); + total ??= data?.total_count; + if (!Number.isInteger(total) || total < 0 || total > 1000 || data?.total_count !== total || + !Array.isArray(data.workflow_runs) || data.workflow_runs.length !== Math.min(100, total - runs.length)) { + throw new Error("Reconciliation inventory is incomplete; no dispatch issued"); + } + for (const run of data.workflow_runs) { + if (!positive(run.id) || ids.has(run.id)) throw new Error("Reconciliation inventory shifted; no dispatch issued"); + ids.add(run.id); runs.push(run); + } + if (runs.length === total) return runs; + } + throw new Error("Reconciliation inventory exceeds bounded pagination"); + }; + const originalSuperseded = async () => { + const runs = await inventory("runtime-images.yml", {event: "pull_request", head_sha: head}); + return runs.some(run => run.display_title === event.display_title && run.id > event.id); + }; + if (await originalSuperseded()) return; + const {data: ciWorkflow} = await github.rest.actions.getWorkflow({...context.repo, workflow_id: "ci.yml"}); + if (!positive(ciWorkflow.id) || ciWorkflow.path !== ".github/workflows/ci.yml" || ciWorkflow.name !== "CI — Validation") { + throw new Error("Untrusted CI workflow identity"); + } + const ciTitle = `CI — Validation pr-${number} base-${base} head-${head}`; + const ciRuns = (await inventory("ci.yml", {event: "pull_request", head_sha: head})) + .filter(run => run.display_title === ciTitle).sort((a, b) => b.id - a.id); + const ci = ciRuns[0]; + const matchesCi = run => run && run.id === ci?.id && run.run_attempt === ci?.run_attempt && positive(run.run_attempt) && + run.workflow_id === ciWorkflow.id && matchesPath(run.path, ciWorkflow.path) && + run.event === "pull_request" && run.status === "completed" && + run.repository?.full_name === repository && run.head_repository?.full_name === repository && + run.head_sha === head && run.head_branch === event.head_branch && run.display_title === ciTitle && + [ciWorkflow.name, ciTitle].includes(run.name); + if (!ci || !positive(ci.id) || !matchesCi(ci)) return; // Later substantive CI callback owns unfinished CI. + const {data: ciNative} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); + if (!matchesCi(ciNative)) return; + const jobs = await github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + {...context.repo, run_id: ci.id, attempt_number: ci.run_attempt, per_page: 100}); + const gates = jobs.filter(job => job.name === "Validation Gate"); + const gate = gates.length === 1 ? gates[0] : null; + const preservation = gate?.steps?.filter(step => step.name === "Preserve successful required gate on metadata-only edit") || []; + const enforcement = gate?.steps?.filter(step => step.name === "Enforce validation success") || []; + const checkPrefix = `https://api.github.com/repos/${repository}/check-runs/`; + if (!gate || !positive(gate.id) || gate.run_id !== ci.id || gate.run_attempt !== ci.run_attempt || + gate.head_sha !== head || ![ciWorkflow.name, ciTitle].includes(gate.workflow_name) || gate.status !== "completed" || + typeof gate.check_run_url !== "string" || !gate.check_run_url.startsWith(checkPrefix) || + !/^[1-9][0-9]*$/.test(gate.check_run_url.slice(checkPrefix.length)) || + preservation.length !== 1 || preservation[0].status !== "completed" || preservation[0].conclusion !== "skipped" || + enforcement.length !== 1 || enforcement[0].status !== "completed" || + !["success", "failure"].includes(enforcement[0].conclusion)) return; + const newerRefresh = async (createdSince = event.created_at) => { + const runs = await inventory("runtime-images.yml", {event: "repository_dispatch", created: `${createdSince}..*`}); + const exact = runs.filter(run => run.display_title === event.display_title && run.id > event.id); + for (const run of exact) { + if (!trusted(run) || run.event !== "repository_dispatch" || + run.head_branch !== context.payload.repository.default_branch || !sha(run.head_sha)) { + throw new Error("Exact refresh has conflicting native provenance"); + } + } + // Completed refresh also owns this recovery; never retry a refresh from its completion callback. + return exact.length > 0; + }; + if (typeof event.created_at !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(event.created_at) || + !Number.isFinite(Date.parse(event.created_at))) throw new Error("Invalid original run creation timestamp"); + if (await newerRefresh()) return; + const {data: finalCi} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); + if (!matchesCi(finalCi) || !await sourceCurrent() || await originalSuperseded() || await currentTuple() !== baseRef) return; + const dispatchStarted = new Date(Date.now() - 1000).toISOString(); + await github.rest.repos.createDispatchEvent({...context.repo, event_type: "pr-runtime-base-refresh", client_payload: { + pr_number: number, base_ref: baseRef, base_sha: base, head_sha: head, merge_sha: merge, + }}); + // Keep the shared dispatcher lock until the accepted handoff is observable. Never blindly retry POST. + const deadline = Date.now() + 120000; + while (!await newerRefresh(dispatchStarted)) { + if (Date.now() >= deadline) throw new Error("Refresh dispatch accepted but visibility is unknown; no retry issued"); + await new Promise(resolve => setTimeout(resolve, 5000)); + } + core.info(`Reconciled failed original runtime for PR #${number}; exact refresh is visible.`); + source: name: Resolve Exact Runtime Publication Source if: ${{ (github.event_name == 'workflow_run' && (github.event.workflow_run.event == 'pull_request' || github.event.workflow_run.event == 'repository_dispatch') && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_repository.full_name == github.repository) || (github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-image-publication' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) }} diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index d3d85fa62b..80c28cea3d 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -428,6 +428,9 @@ jobs: dispatch-pr-base-refreshes: name: Dispatch PR Base Refreshes + concurrency: + group: runtime-pr-refresh-dispatch + queue: max if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.status == 'completed' && (github.event.workflow_run.event == 'pull_request' || (github.event.workflow_run.event == 'push' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop'))) && github.event.workflow_run.head_repository.full_name == github.repository }} runs-on: ubuntu-latest timeout-minutes: 15 @@ -645,28 +648,37 @@ jobs: let complete = true; let incompleteReason = null; for (const event of runtimeRunEvents) { - const response = await github.rest.actions.listWorkflowRuns({ - ...context.repo, - workflow_id: "runtime-images.yml", - event, - created: `${createdSince}..*`, - per_page: runtimeRunPageSize, - page: 1, - }); - const payload = response?.data; - if (!payload || !Number.isInteger(payload.total_count) || - payload.total_count < 0 || !Array.isArray(payload.workflow_runs)) { - throw new Error(`runtime-images ${event} recent run inventory is malformed`); - } - if (payload.total_count > runtimeRunPageSize) { - complete = false; - incompleteReason ??= `runtime-images ${event} has more than ${runtimeRunPageSize} runs since ${createdSince}`; - } - const expectedPageLength = Math.min(payload.total_count, runtimeRunPageSize); - if (payload.workflow_runs.length !== expectedPageLength) { - throw new Error(`runtime-images ${event} recent run inventory is incomplete`); + let total; + const eventRuns = [], ids = new Set(); + for (let page = 1; page <= 10; page += 1) { + const response = await github.rest.actions.listWorkflowRuns({ + ...context.repo, workflow_id: "runtime-images.yml", event, + created: `${createdSince}..*`, per_page: runtimeRunPageSize, page, + }); + const payload = response?.data; + total ??= payload?.total_count; + if (!Number.isInteger(total) || total < 0 || !Array.isArray(payload?.workflow_runs) || + payload.total_count !== total) throw new Error(`runtime-images ${event} inventory shifted or is malformed`); + if (total > 1000) { + complete = false; + incompleteReason ??= `runtime-images ${event} exceeds 1000-run bound`; + // Retain this untrusted sample only for the existing conservative in-flight refinement. + // It is never treated as a complete inventory or dispatch authority. + eventRuns.push(...payload.workflow_runs); + break; + } + if (payload.workflow_runs.length !== Math.min(runtimeRunPageSize, total - eventRuns.length)) { + throw new Error(`runtime-images ${event} recent run inventory is incomplete`); + } + for (const run of payload.workflow_runs) { + if (!Number.isSafeInteger(run.id) || run.id <= 0 || ids.has(run.id)) { + throw new Error(`runtime-images ${event} inventory has duplicate or invalid run IDs`); + } + ids.add(run.id); eventRuns.push(run); + } + if (eventRuns.length === total) break; } - inventory.push(...payload.workflow_runs); + inventory.push(...eventRuns); } return {complete, runs: inventory, reason: incompleteReason}; }; @@ -789,7 +801,11 @@ jobs: return [newest]; } if (newest.status === "completed") { - // Completed source success does not prove publication remains usable; preserve recovery dispatch. + // A refresh created after this CI completed already owns this callback's recovery. + // A later substantive CI signal may still recover publication from an older producer. + const ciCompleted = Date.parse(workflowRun.updated_at || ""); + if (newest.event === "repository_dispatch" && Number.isFinite(ciCompleted) && + Date.parse(newest.created_at) >= ciCompleted) return [newest]; return []; } throw new Error(`run ${newest.id} has an unknown status and cannot be classified`); @@ -979,9 +995,10 @@ jobs: } } if (fallbackReason) { - core.warning( - `Cannot verify recent runtime producer evidence for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}); falling back to the required refresh dispatch: ${fallbackReason}` - ); + core.setFailed(`Cannot verify exact runtime producer inventory for PR #${tuple.prNumber}; no dispatch issued: ${fallbackReason}`); + runtimeInventoryPromise = undefined; + runtimeInventoryError = null; + continue; } if (existingProducers.length > 0) { const producer = existingProducers[0]; @@ -990,17 +1007,43 @@ jobs: ); } else { core.info(`No reusable in-flight exact producer was verified in the bounded recent inventory; dispatching required PR runtime refresh for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); - await github.rest.repos.createDispatchEvent({ - ...context.repo, - event_type: "pr-runtime-base-refresh", - client_payload: { - pr_number: tuple.prNumber, - base_ref: tuple.baseRef, - base_sha: tuple.baseSha, - head_sha: tuple.headSha, - merge_sha: tuple.mergeSha, - }, - }); + // Refresh tuple custody after preceding fan-out/API work under the shared dispatcher lock. + const current = await resolveExactMerge(tuple.prNumber, tuple.baseRef, tuple.baseSha, tuple.headSha); + const {data: currentBase} = await github.rest.git.getRef({...context.repo, ref: `heads/${tuple.baseRef}`}); + if (!current || current.tuple.mergeSha !== tuple.mergeSha || currentBase.object?.sha !== tuple.baseSha) { + core.info(`Skipping changed runtime tuple for PR #${tuple.prNumber}.`); + continue; + } + const previousIds = new Set(inventory?.runs?.map(run => run.id) || []); + try { + await github.rest.repos.createDispatchEvent({ + ...context.repo, + event_type: "pr-runtime-base-refresh", + client_payload: { + pr_number: tuple.prNumber, + base_ref: tuple.baseRef, + base_sha: tuple.baseSha, + head_sha: tuple.headSha, + merge_sha: tuple.mergeSha, + }, + }); + // No retry of an ambiguous POST. Hold only this API dispatcher lock for bounded visibility. + const visibilityDeadline = Date.now() + 120000; + for (;;) { + const observed = await loadExistingRuntimeRuns(); + if (!observed.complete) throw new Error("Accepted refresh has incomplete visibility; no retry issued"); + const exactTitle = `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; + if (observed.runs.some(run => run.event === "repository_dispatch" && + run.display_title === exactTitle && !previousIds.has(run.id))) break; + if (Date.now() >= visibilityDeadline) throw new Error("Refresh dispatch accepted but visibility is unknown; no retry issued"); + await new Promise(resolve => setTimeout(resolve, 5000)); + } + } catch (error) { + core.setFailed(`Runtime refresh handoff for PR #${tuple.prNumber} is uncertain; no retry issued: ${error.message || error}`); + runtimeInventoryPromise = undefined; + continue; + } + runtimeInventoryPromise = undefined; } } else { core.info(`Skipping PR runtime image refresh for #${tuple.prNumber}: no runtime-changing files.`); diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index b1cc34400e..3ce9026fe3 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -611,7 +611,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b"; + const canonicalRuntimeWorkflowSha256 = "1d5cb2928f55a45069ab251889e6cd5fc9c9d5df15b27bb94d4d40a2ea030d02"; // Trusted refreshes can still execute the previous successful default-branch definition. const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = "ea6ade0f69718573aeac4e4b5a1e9050e53e1e3cef3426b8791f182d8d49e112"; // Retain the exact fail-red producer still executed by trusted base refreshes. diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 6bf3ae1299..81d5059b4c 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -88,6 +88,8 @@ A typed runtime refresh hands off publication explicitly after its required cred The publisher's no-checkout, Actions-read-only resolver reads only the supplied exact source run and owning runtime workflow identity. A dispatch can arrive before its source workflow finishes, so the resolver waits for actual terminal success within a two-minute budget; malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. The resolver never substitutes a successful status. Both trigger paths retain the same exact source, current PR/base/head/merge, artifact provenance, and immutable-tag validation. Publishing jobs serialize on the verified merge-bound source title across both paths; duplicate publication preserves identical existing images and rejects conflicting image bytes. Explicit dispatch avoids relying on a workflow-run callback from a token-origin refresh without weakening the source or registry boundary. +The trusted publisher also reconciles a failed, cancelled, or timed-out original same-repository PR runtime run when substantive Validation already completed. This API-only job has `contents: write` solely to request an exact typed refresh; it never checks out PR code. It verifies current native source and CI attempts, the live base/head/merge tuple, and absence of a newer original or typed refresh before dispatch. Typed-refresh and nested workflow callbacks cannot recursively invoke this recovery. The CI dispatcher and completion reconciler share an API-job concurrency group with `queue: max`; runtime builds remain parallel. Unknown inventory fails closed, and an uncertain dispatch is not blindly repeated. The accepted handoff has a 120-second visibility budget; a failed target does not automatically suppress independent later targets. This is bounded coordination, not exactly-once delivery or an unbounded no-starvation guarantee: GitHub admits at most 100 pending jobs in the group, inventories and job durations are bounded, and existing superseding base callbacks can cancel obsolete work. Remaining unknown outcomes require fresh evidence rather than presumed success. + Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard. Ordinary runtime qualification requires both Actions-native outcomes to be `success` and the transition-exception marker to be explicitly skipped. Missing marker metadata cannot use the native-job fallback: a successful job alone may instead represent the bounded exception described below. Skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify as real runtime proof. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. A separate, temporary diagnostic exception lets the required Smoke Gate succeed for a same-repository `benhook1013/FireMUD` pull request whose current live PR carries the `canonical-play-transition` label. A `pull_request` producer also requires the source event label and exact verified PR-event base/head/merge tuple. A typed `pr-runtime-base-refresh` producer instead derives label authority from its verified live same-repository PR, never dispatch payload labels, and requires the exact current base/head/merge tuple again at consumption. Both paths require the latest successful CI attempt with its explicit exception marker while the PR head and base branch remain current. During the default-branch workflow rollout, the exact previous fail-red producer fingerprint remains accepted only with its original failed smoke and terminal guard plus successful marker and cleanup; it supplies the same diagnostic exception and no runtime qualification. The smoke invocation retains its failed Actions-native outcome through step-level continuation; only the exact label, classifier and successful authenticated cleanup can make the mandatory final guard accept that failed probe. Every other probe failure still fails CI. GitHub reports the continued step conclusion as success, so the consumer verifies the immutable marker rather than treating that conclusion as runtime proof. The fingerprinted producer must attest the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, with successful authenticated cleanup. The executing workflow is fingerprinted at the PR merge revision or typed refresh's native default-branch revision, respectively; classifiers, held-admission qualification, authenticated cleanup, certificate setup, and their checked-in environment and Compose inputs are always fingerprinted at the tested PR merge. Its original smoke failure remains visible in the probe logs, summary and Actions-native outcome; unrelated failures still block, and image export and upload must be skipped. The typed publication handoff also requires a real successful image upload. A trusted workflow-run publisher detects the exception marker before exposing a publication source and skips its privileged job; a successful CI conclusion under exception does not authorize registry access or preview images. This is gate acceptance for the nonproduction canonical cutover, not successful smoke, runtime qualification, branch-image promotion, hosted preview eligibility, or production activation. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception; after the cutover merges, branch images remain on hold until the Account entitlement path is repaired. Remove the label-based marker and consumer exception when fresh-image backend `LOGIN` → `PLAY` → `LOOK` passes, then remove this transitional contract. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. The producer guarantee, independent of smoke-step metadata but requiring an explicit skipped exception marker, is bound to a SHA-256 fingerprint of the entire immutable source workflow definition, including its surrounding YAML execution context. Pull-request attempts use the verified event test-merge revision, and typed refresh attempts use their native default-branch `head_sha`. During producer rollout, only verified typed refreshes can also use the reviewed previous successful workflow definition. Both paths keep the existing marker, attempt, and execution proof requirements. Missing, unavailable, altered, or unattributable definitions cannot use this guarantee. Every change to [runtime-images.yml](../../.github/workflows/runtime-images.yml) requires review of the producer guarantee and an update of `canonicalRuntimeWorkflowSha256` in [smoke.yml](../../.github/workflows/smoke.yml). The existing [required-gate contract](../../dev-tools/tests/pr-required-gate-context-contract.sh) computes the expected fingerprint and reports the exact update when it is stale; it also exercises native outcome rejection, immutable revision/attempt attribution, and the retained older step-proof path. Every change to a fingerprinted classifier, qualification or cleanup script, certificate setup, environment defaults, or Compose input also requires review and an update of `canonicalPlayClassifierSha256` in `smoke.yml`; the required-gate contract reports each stale value. These fingerprints remain part of the owning workflows, not a separate proof registry. diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 93340ccc1b..8a6a7647a6 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -4120,3 +4120,108 @@ function markerAccepted(overrides = {}) { console.log("Canonical PLAY transition exception positive and negative contracts passed."); })().catch(error => {console.error(error); process.exitCode = 1;}); NODE + + +# Exercise the actual trusted completion-reconciler script without provider calls. +python3 - "$ROOT_DIR" "$smoke_clock_fixture.reconcile" <<'PY' +import sys +from pathlib import Path +import yaml +root = Path(sys.argv[1]) +publisher = yaml.load((root / ".github/workflows/publish-pr-runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +runtime = yaml.load((root / ".github/workflows/runtime-images.yml").read_text(), Loader=yaml.BaseLoader) +job = publisher["jobs"]["reconcile-failed-pr-runtime"] +assert job["permissions"] == {"actions": "read", "pull-requests": "read", "contents": "write"} +assert job["concurrency"] == runtime["jobs"]["dispatch-pr-base-refreshes"]["concurrency"] == {"group": "runtime-pr-refresh-dispatch", "queue": "max"} +assert "concurrency" not in runtime["jobs"]["image-meta"] +def queue_paths(value, prefix=()): + if not isinstance(value, dict): + return [] + return [prefix + (key,) for key in value if key == "queue"] + [path for key, child in value.items() for path in queue_paths(child, prefix + (key,))] +assert queue_paths(publisher) == [("jobs", "reconcile-failed-pr-runtime", "concurrency", "queue")] +assert queue_paths(runtime) == [("jobs", "dispatch-pr-base-refreshes", "concurrency", "queue")] + +assert all("checkout" not in step.get("uses", "") for step in job["steps"]) +assert "github.event.workflow_run.event == 'pull_request'" in job["if"] +Path(sys.argv[2]).write_text(next(step["with"]["script"] for step in job["steps"] if "github-script" in step.get("uses", ""))) +PY +node - "$smoke_clock_fixture.reconcile" <<'NODE' +const assert = require("node:assert/strict"), fs = require("node:fs"); +const execute = new Function("github", "context", "core", "Date", "setTimeout", + `return (async () => {${fs.readFileSync(process.argv[2], "utf8")}\n})()`); +async function run(kind, shared = {visible: false, posts: 0}) { + const base = "b".repeat(40), head = "a".repeat(40), merge = "c".repeat(40), repository = "example/firemud"; + const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; + const source = {id: 100, run_attempt: 1, workflow_id: 7, name: "Build Runtime Images", path: ".github/workflows/runtime-images.yml", + display_title: title, head_sha: head, head_branch: "feature", event: "pull_request", status: "completed", conclusion: "failure", + repository: {full_name: repository}, head_repository: {full_name: repository}, created_at: "2026-11-18T00:00:00Z"}; + const ci = {...source, id: 90, workflow_id: 8, path: ".github/workflows/ci.yml", name: "CI — Validation", + display_title: `CI — Validation pr-42 base-${base} head-${head}`}; + const refresh = {...source, id: 110, event: "repository_dispatch", head_branch: "develop", head_sha: "d".repeat(40)}; + const event = structuredClone(source); + if (kind === "typed-callback") event.event = "repository_dispatch"; + if (kind === "nested-callback") event.event = "workflow_run"; + if (kind === "fork") event.head_repository.full_name = "fork/repo"; + if (kind === "success") event.conclusion = "success"; + let clock = 0, tupleReads = 0, sourceReads = 0; + const github = {rest: { + actions: { + getWorkflow: async ({workflow_id}) => ({data: workflow_id === "ci.yml" + ? {id: 8, path: ".github/workflows/ci.yml", name: "CI — Validation"} + : {id: 7, path: source.path, name: source.name}}), + getWorkflowRun: async ({run_id}) => { + if (run_id === 90) return {data: {...ci, ...(kind === "ci-rerun" ? {run_attempt: 2} : {})}}; + sourceReads++; + return {data: {...source, ...((kind === "stale-attempt" || kind === "late-rerun" && sourceReads > 1) ? {run_attempt: 2} : {})}}; + }, + listWorkflowRuns: async ({workflow_id, page, event: runEvent}) => { + let runs = workflow_id === "ci.yml" ? [{...ci, ...(kind === "ci-pending" ? {status: "in_progress"} : {})}] + : shared.visible ? [refresh] : []; + if (workflow_id === "runtime-images.yml" && runEvent === "pull_request") { + runs = kind === "newer-original" ? [{...source, id: 105, status: "in_progress"}] : [source]; + } + if (workflow_id === "runtime-images.yml" && runEvent === "repository_dispatch" && kind === "second-page") { + runs = Array.from({length: 100}, (_, i) => ({...refresh, id: 1000 + i, display_title: "unrelated"})).concat(refresh); + } + return {data: {total_count: kind === "incomplete" ? 1001 : runs.length, workflow_runs: runs.slice((page - 1) * 100, page * 100)}}; + }, + }, + pulls: {get: async () => { tupleReads++; return {data: {state: "open", mergeable: true, merge_commit_sha: merge, + head: {sha: head, ref: "feature", repo: {full_name: repository}}, + base: {ref: "develop", sha: kind === "late-drift" && tupleReads > 1 ? head : base, repo: {full_name: repository}}}};}}, + git: {getRef: async () => ({data: {object: {sha: base}}})}, + repos: { + getCommit: async () => ({data: {sha: merge, parents: [{sha: base}, {sha: head}]}}), + createDispatchEvent: async () => { + shared.posts++; + if (kind === "ambiguous-post") throw new Error("unknown POST outcome"); + if (kind !== "invisible") shared.visible = true; + }, + }, + }, paginate: async () => [{id: 30, run_id: 90, run_attempt: 1, head_sha: head, name: "Validation Gate", + workflow_name: "CI — Validation", status: "completed", check_run_url: `https://api.github.com/repos/${repository}/check-runs/30`, + steps: [{name: "Preserve successful required gate on metadata-only edit", status: "completed", conclusion: kind === "metadata" ? "success" : "skipped"}, + {name: "Enforce validation success", status: "completed", conclusion: "failure"}]}]}; + await execute(github, {repo: {owner: "example", repo: "firemud"}, eventName: "workflow_run", + payload: {workflow_run: event, repository: {default_branch: "develop"}}}, {info: () => {}}, + class extends Date { static now() { return clock; } }, callback => {clock += 5000; callback();}); + return shared.posts; +} +(async () => { + assert.equal(await run("valid"), 1); + for (const scenario of ["typed-callback", "nested-callback", "fork", "success", "stale-attempt", "late-rerun", "ci-rerun", "ci-pending", "metadata", "late-drift", "second-page", "newer-original"]) { + assert.equal(await run(scenario), 0, scenario); + } + for (const scenario of ["incomplete", "ambiguous-post", "invisible"]) { + const state = {visible: false, posts: 0}; + await assert.rejects(run(scenario, state)); + assert.equal(state.posts, scenario === "incomplete" ? 0 : 1, "never retry unknown POST"); + } + // Under the shared job mutex, a CI-first visible refresh suppresses completion recovery. + assert.equal(await run("valid", {visible: true, posts: 0}), 0); + // Repeated completion callbacks, including after terminal refresh failure, dispatch at most once. + const shared = {visible: false, posts: 0}; + await run("valid", shared); await run("valid", shared); assert.equal(shared.posts, 1); + console.log("Failed original runtime reconciliation contracts passed (offline serialized model, not GitHub delivery proof)."); +})().catch(error => {console.error(error); process.exitCode = 1;}); +NODE diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index b47d12f249..a3313f16a8 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -677,6 +677,12 @@ concurrency_group = runtime["concurrency"]["group"] if "&& 'metadata' || 'required'" not in concurrency_group: raise SystemExit("metadata-only runtime events can cancel substantive runtime builds") +dispatch_queue = runtime_jobs["dispatch-pr-base-refreshes"]["concurrency"] +assert dispatch_queue == {"group": "runtime-pr-refresh-dispatch", "queue": "max"}, "API dispatch callbacks must share the non-evicting queue" +for name, job in runtime_jobs.items(): + if name != "dispatch-pr-base-refreshes": + assert job.get("concurrency", {}).get("group") != dispatch_queue["group"], "runtime build jobs must not occupy the API dispatcher queue" + dispatch_condition = runtime_jobs["dispatch-pr-base-refreshes"].get("if", "") if "github.event_name == 'workflow_run'" not in dispatch_condition: raise SystemExit("runtime refresh dispatch is not isolated from pull-request metadata events") @@ -884,22 +890,14 @@ const runsDescending = (event, firstCreatedAt) => Array.from({ length: 100 }, (_ head_repository: { full_name: repository }, created_at: new Date(Date.parse(firstCreatedAt) - index * 1000).toISOString(), })); -const assertCompleteRefinementPreservesEligibleInitialRuns = (initialRuns, cutoff, refinedRuns, label) => { - const createdFloor = Date.parse(cutoff); - const eligibleIds = initialRuns - .filter((run) => typeof run?.created_at === "string" && Number.isFinite(Date.parse(run.created_at)) - && Date.parse(run.created_at) >= createdFloor) - .map((run) => `${run.event}:${run.id}`); - const refinedIds = new Set(refinedRuns.map((run) => `${run.event}:${run.id}`)); - assert(eligibleIds.every((id) => refinedIds.has(id)), - `${label} must retain every returned initial run at or after its refinement cutoff`); -}; - async function runDispatcher({ tuples, inventories = {}, apiFailure = null, sourceTuples = [], callback = {}, branchHeads = {}, branchErrors = {}, pullOverrides = {}, mergeParents = {}, ciEvidence = {}, + hideDispatchVisibility = false, filesByPr = {}, postFailurePr = null, }) { const dispatches = []; + const postedRuns = []; + const pullReads = new Map(); const errors = []; const infos = []; const warnings = []; @@ -968,11 +966,17 @@ async function runDispatcher({ .filter((tuple) => request.head || tuple.baseRef === request.base) .map(pullRequestFor) }; }, - get: async ({ pull_number }) => ({ data: { - ...pullRequestFor(tupleByNumber.get(String(pull_number))), - ...(pullOverrides[String(pull_number)] ?? {}), - } }), - listFiles: async () => ({ data: [{ filename: "services/example/src/Main.java" }] }), + get: async ({ pull_number }) => { + const number = String(pull_number); + const reads = (pullReads.get(number) ?? 0) + 1; + pullReads.set(number, reads); + const override = pullOverrides[number]; + return { data: { + ...pullRequestFor(tupleByNumber.get(number)), + ...(typeof override === "function" ? override(reads) : override ?? {}), + } }; + }, + listFiles: async ({ pull_number }) => ({ data: filesByPr[String(pull_number)] ?? [{ filename: "services/example/src/Main.java" }] }), }, repos: { getCommit: async ({ ref }) => { @@ -980,7 +984,21 @@ async function runDispatcher({ return { data: { sha: ref, parents: (mergeParents[ref] ?? [tuple.baseSha, tuple.headSha]) .map((parent) => ({ sha: parent })) } }; }, - createDispatchEvent: async (request) => { dispatches.push(request); }, + createDispatchEvent: async (request) => { + dispatches.push(request); + if (request.event_type === "pr-runtime-base-refresh" && request.client_payload.pr_number === postFailurePr) { + throw new Error("ambiguous POST timeout"); + } + if (request.event_type === "pr-runtime-base-refresh" && !hideDispatchVisibility) { + const payload = request.client_payload; + postedRuns.push(producer({ + prNumber: payload.pr_number, baseSha: payload.base_sha, + headSha: payload.head_sha, mergeSha: payload.merge_sha, + }, "repository_dispatch", "queued", null, { + id: 900000 + postedRuns.length, created_at: "2026-01-08T00:00:00Z", + })); + } + }, }, actions: { getWorkflow: async () => ({ data: { @@ -992,7 +1010,9 @@ async function runDispatcher({ }, listWorkflowRuns: async (request) => { inventoryCalls.push(request); - if (apiFailure === request.event) throw new Error("fixture API unavailable"); + if (apiFailure === request.event || (typeof apiFailure === "function" && apiFailure(request, inventoryCalls.length))) { + throw new Error("fixture API unavailable"); + } const callNumber = (eventInventoryCalls.get(request.event) ?? 0) + 1; eventInventoryCalls.set(request.event, callNumber); const inventory = inventories[request.event] ?? []; @@ -1000,9 +1020,10 @@ async function runDispatcher({ return { data: { malformed: true } }; } const refinement = callNumber > 1 && !Array.isArray(inventory) && Array.isArray(inventory.refined); - const runs = Array.isArray(inventory) + const suppliedRuns = Array.isArray(inventory) ? inventory : refinement ? inventory.refined : inventory.initial ?? inventory.runs ?? []; + const runs = [...suppliedRuns, ...(request.event === "repository_dispatch" ? postedRuns : [])]; const createdMatch = /^(.+)\.\.\*$/.exec(request.created ?? ""); const createdFloor = createdMatch ? Date.parse(createdMatch[1]) : Number.NaN; const filteredRuns = Number.isFinite(createdFloor) @@ -1041,8 +1062,9 @@ async function runDispatcher({ }; const originalDateNow = Date.now; const originalSetTimeout = global.setTimeout; - global.setTimeout = (resolve) => { resolve(); }; - Date.now = () => Date.parse("2026-01-08T00:00:00Z"); + let fakeNow = Date.parse("2026-01-08T00:00:00Z"); + global.setTimeout = (resolve, millis) => { fakeNow += millis; resolve(); }; + Date.now = () => fakeNow; try { await new AsyncFunction("github", "context", "core", dispatcherScript)(github, context, core); } finally { @@ -1254,8 +1276,8 @@ async function runDispatcher({ path: `.github/workflows/runtime-images.yml@${invalidRef}`, })] }, }); - assert.equal(invalidRefPath.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - `an invalid Git ref ${invalidRef} must not suppress the required dispatch`); + assert.equal(invalidRefPath.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 0, + `an invalid Git ref ${invalidRef} must not authorize another dispatch`); } const wrongWorkflowPath = await runDispatcher({ tuples: [tuple], @@ -1263,10 +1285,10 @@ async function runDispatcher({ path: ".github/workflows/other.yml@refs/heads/develop", })] }, }); - assert.equal(wrongWorkflowPath.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - "an unrelated workflow path must not suppress the required dispatch"); - assert(wrongWorkflowPath.warnings.some((message) => message.includes("falling back to the required refresh dispatch")), - "an exact-tuple producer with an unrelated workflow path must emit a fallback warning"); + assert.equal(wrongWorkflowPath.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 0, + "an unrelated workflow path must fail closed"); + assert(wrongWorkflowPath.errors.some((message) => message.includes("no dispatch issued")), + "an exact-tuple producer with an unrelated workflow path must emit an error"); for (const [status, conclusion] of [ ["completed", "failure"], @@ -1319,10 +1341,10 @@ async function runDispatcher({ producer(tuple, "pull_request", "completed", "failure", { id: 10104 }), ] }, }); - assert.equal(ambiguousNewest.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - "ambiguous equal-time exact producers must fall back to the required refresh dispatch"); - assert(ambiguousNewest.warnings.some((message) => message.includes("ambiguous created_at timestamp")), - "ambiguous producer ordering must emit an explicit fallback diagnostic"); + assert.equal(ambiguousNewest.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 0, + "ambiguous equal-time exact producers must fail closed"); + assert(ambiguousNewest.errors.some((message) => message.includes("ambiguous created_at timestamp")), + "ambiguous producer ordering must emit an explicit error"); const staleTuple = tupleFor(101, "a", "c", sha("d")); const stale = await runDispatcher({ @@ -1341,214 +1363,99 @@ async function runDispatcher({ "a changed base requires a fresh exact tuple producer"); const sibling = tupleFor(102, "f", "d"); - const independent = await runDispatcher({ + const numbers = (result) => runtimeDispatches(result).map(item => item.client_payload.pr_number); + const existingFirst = await runDispatcher({ tuples: [tuple, sibling], - inventories: { - pull_request: [null, { id: "malformed-unrelated-record", display_title: "historical unrelated record" }, - producer(tuple, "pull_request", "in_progress")], - repository_dispatch: [], - }, - }); - const independentRefreshNumbers = independent.dispatches - .filter((item) => item.event_type === "pr-runtime-base-refresh") - .map((item) => item.client_payload.pr_number) - .sort(); - assert.deepEqual(independentRefreshNumbers, ["102"], - "unrelated malformed history must not block an independent sibling refresh or prevent reuse of the valid active producer"); - assert.equal(independent.inventoryCalls.length, 2, "multiple PRs must reuse one shared inventory"); - - const partialSibling = tupleFor(103, "7", "8"); - const recentRuns = runsDescending("pull_request", "2026-01-02T00:00:00Z"); - recentRuns[0] = producer(tuple, "pull_request", "in_progress", null, { - created_at: "2026-01-02T00:00:00Z", - }); - const recentRefinedRuns = [producer(tuple, "pull_request", "in_progress", null, { - created_at: "2026-01-02T00:00:00Z", - })]; - assertCompleteRefinementPreservesEligibleInitialRuns(recentRuns, "2026-01-02T00:00:00Z", recentRefinedRuns, - "truncated positive refinement"); - const truncatedPositive = await runDispatcher({ - tuples: [tuple, partialSibling], - inventories: { - pull_request: { - total_count: 101, - runs: recentRuns, - refined: recentRefinedRuns, - refinedTotalCount: 1, - }, - repository_dispatch: [], - }, - }); - const truncatedRefreshNumbers = truncatedPositive.dispatches - .filter((item) => item.event_type === "pr-runtime-base-refresh") - .map((item) => item.client_payload.pr_number) - .sort(); - assert.deepEqual(truncatedRefreshNumbers, ["103"], - "complete refinement must prove the exact candidate while an unmatched sibling uses required dispatch"); - assert.equal(truncatedPositive.inventoryCalls.length, 4, - "truncated inventory must use at most one cached refinement pair for all siblings"); - assert(truncatedPositive.inventoryCalls.slice(2).every((request) => - request.created === "2026-01-02T00:00:00Z..*" - ), "the refinement pair must use the inclusive exact lower bound of returned in-flight candidates"); - - const refinedSiblings = [tupleFor(107, "5", "6"), tupleFor(108, "7", "9")]; - const siblingPage = runsDescending("pull_request", "2026-01-04T00:00:00Z"); - siblingPage[0] = producer(refinedSiblings[0], "pull_request", "in_progress", null, { - created_at: "2026-01-04T00:00:00Z", - }); - siblingPage[1] = producer(refinedSiblings[1], "pull_request", "queued", null, { - created_at: "2026-01-03T23:59:59Z", - }); - assertCompleteRefinementPreservesEligibleInitialRuns(siblingPage, "2026-01-03T23:59:59Z", siblingPage.slice(0, 2), - "shared sibling refinement"); - const refinedSiblingReuse = await runDispatcher({ - tuples: refinedSiblings, - inventories: { - pull_request: { - total_count: 101, - runs: siblingPage, - refined: siblingPage.slice(0, 2), - refinedTotalCount: 2, - }, - repository_dispatch: [], - }, - }); - assert.equal(refinedSiblingReuse.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 0, - "the shared refined inventory must cover each initially observed in-flight sibling"); - assert.equal(refinedSiblingReuse.inventoryCalls.length, 4, - "all sibling decisions must reuse one refinement pair rather than scan per PR"); - assert(refinedSiblingReuse.inventoryCalls.slice(2).every((request) => - request.created === "2026-01-03T23:59:59Z..*" - ), "the shared sibling refinement must start at the earliest returned in-flight timestamp"); - - const truncatedRefinementTuple = tupleFor(109, "a", "e"); - const truncatedRefinementPage = runsDescending("pull_request", "2026-01-05T00:03:00Z"); - truncatedRefinementPage[0] = producer(truncatedRefinementTuple, "pull_request", "in_progress", null, { - created_at: "2026-01-05T00:00:00Z", + inventories: { pull_request: [producer(tuple, "pull_request", "in_progress")] }, }); - const truncatedRefinement = await runDispatcher({ - tuples: [truncatedRefinementTuple], - inventories: { - pull_request: { - total_count: 101, - runs: truncatedRefinementPage, - refined: truncatedRefinementPage, - refinedTotalCount: 101, - }, - repository_dispatch: [], - }, + assert.deepEqual(numbers(existingFirst), ["102"], "existing first PR must not starve second"); + assert.equal(existingFirst.errors.length, 0); + const skippedFirst = await runDispatcher({ + tuples: [tuple, sibling], filesByPr: { "101": [{ filename: "README.md" }] }, }); - assert.equal(truncatedRefinement.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - "a still-truncated refinement must use baseline dispatch"); - assert(truncatedRefinement.warnings.some((message) => message.includes("falling back to the required refresh dispatch")), - "a truncated refinement must report its required-dispatch fallback"); - assert.equal(truncatedRefinement.inventoryCalls.length, 4, - "a failed refinement must stop after the single bounded shared refinement pair"); - - const completedTruncatedTuple = tupleFor(110, "b", "f"); - const completedTruncatedPage = runsDescending("pull_request", "2026-01-06T00:00:00Z"); - completedTruncatedPage[0] = producer(completedTruncatedTuple, "pull_request", "completed", "success", { - created_at: "2026-01-06T00:00:00Z", + assert.deepEqual(numbers(skippedFirst), ["102"], "non-runtime first PR must not starve second"); + const failedPost = await runDispatcher({ tuples: [tuple, sibling], postFailurePr: "101" }); + assert.deepEqual(numbers(failedPost), ["101", "102"], "ambiguous first POST must not retry or starve second"); + assert(failedPost.errors.some(message => message.includes("ambiguous POST timeout"))); + const transientFirst = await runDispatcher({ + tuples: [tuple, sibling], apiFailure: (_request, count) => count === 1, }); - const completedTruncated = await runDispatcher({ - tuples: [completedTruncatedTuple], - inventories: { - pull_request: { total_count: 101, runs: completedTruncatedPage }, - repository_dispatch: [], - }, + assert.deepEqual(numbers(transientFirst), ["102"], "transient inventory error for first PR must not poison later independent targets"); + assert(transientFirst.errors.some(message => message.includes("PR #101") && message.includes("no dispatch issued"))); + const changedFirst = await runDispatcher({ + tuples: [tuple, sibling], + pullOverrides: { "101": reads => reads > 1 ? { state: "closed" } : {} }, }); - assert.equal(completedTruncated.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - "completed source results must preserve required recovery dispatch"); - assert.equal(completedTruncated.inventoryCalls.length, 2, - "completed-only truncated inventories need no refinement because they never suppress dispatch"); - - const hiddenNewerFailureTuple = tupleFor(105, "1", "2"); - const crossEventHiddenNewer = await runDispatcher({ - tuples: [hiddenNewerFailureTuple], - inventories: { - pull_request: [producer(hiddenNewerFailureTuple, "pull_request", "in_progress", null, { - created_at: "2026-01-01T10:00:00Z", - })], - // The initial dispatch page omits this newer exact terminal producer; bounded refinement must reveal it. - repository_dispatch: { - total_count: 101, - runs: runsDescending("repository_dispatch", "2026-01-01T09:00:00Z"), - refined: [producer(hiddenNewerFailureTuple, "repository_dispatch", "completed", "failure", { - created_at: "2026-01-01T10:30:00Z", - })], - refinedTotalCount: 1, - }, - }, + assert.deepEqual(numbers(changedFirst), ["102"], "changed first PR must not starve second"); + assert(changedFirst.infos.some(message => message.includes("Skipping changed runtime tuple"))); + const unknownFirst = await runDispatcher({ + tuples: [tuple, sibling], + inventories: { pull_request: [producer(tuple, "pull_request", "in_progress", null, { + repository: { full_name: "other/repo" }, + })] }, }); - assert.equal(crossEventHiddenNewer.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - "refinement must reveal the newer cross-event terminal producer and preserve required dispatch"); - assert.equal(crossEventHiddenNewer.inventoryCalls.length, 4, - "one refinement pair must cover both event types when another event could contain a newer terminal run"); - - const safeOlderOmittedTuple = tupleFor(106, "3", "4"); - const safelyOlderOmitted = await runDispatcher({ - tuples: [safeOlderOmittedTuple], - inventories: { - pull_request: [producer(safeOlderOmittedTuple, "pull_request", "in_progress", null, { - created_at: "2026-01-03T10:00:00Z", - })], - repository_dispatch: { - total_count: 101, - runs: runsDescending("repository_dispatch", "2026-01-02T10:00:00Z"), - refined: [], - refinedTotalCount: 0, - }, - }, + assert.deepEqual(numbers(unknownFirst), ["102"], "invalid first PR evidence must not starve second"); + assert(unknownFirst.errors.some(message => message.includes("PR #101") && message.includes("no dispatch issued"))); + + const secondPageRuns = runsDescending("pull_request", "2026-01-02T00:00:00Z"); + secondPageRuns.push(producer(tuple, "pull_request", "in_progress")); + const secondPage = await runDispatcher({ tuples: [tuple], inventories: { pull_request: secondPageRuns } }); + assert.deepEqual(numbers(secondPage), [], "exact page-two producer must suppress duplicate"); + assert(secondPage.inventoryCalls.some(request => request.event === "pull_request" && request.page === 2)); + assert(secondPage.inventoryCalls.every(request => request.page <= 10)); + + const overBoundPage = runsDescending("pull_request", "2026-01-02T00:00:00Z"); + overBoundPage[0] = producer(tuple, "pull_request", "in_progress", null, { + created_at: "2026-01-02T00:00:00Z", }); - assert.equal(safelyOlderOmitted.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 0, - "complete refinement from the candidate creation time proves apparently older omissions cannot mask it"); - assert.equal(safelyOlderOmitted.inventoryCalls.length, 4, - "complete refinement must stay within the one additional shared pair"); - - const validSibling = tupleFor(104, "9", "0"); - const relevantMalformed = await runDispatcher({ - tuples: [tuple, validSibling], - inventories: { - pull_request: [ - producer(tuple, "pull_request", "in_progress", null, { repository: { full_name: "other/repo" } }), - producer(validSibling, "pull_request", "in_progress"), - ], - repository_dispatch: [], - }, + const refinedBound = await runDispatcher({ + tuples: [tuple], inventories: { pull_request: { + total_count: 1001, runs: overBoundPage, refined: [overBoundPage[0]], refinedTotalCount: 1, + } }, }); - const relevantMalformedRefreshNumbers = relevantMalformed.dispatches - .filter((item) => item.event_type === "pr-runtime-base-refresh") - .map((item) => item.client_payload.pr_number) - .sort(); - assert.deepEqual(relevantMalformedRefreshNumbers, ["101"], - "relevant malformed evidence must fall back for its own tuple while a valid active sibling producer remains reusable"); - - for (const uncertain of [ - await runDispatcher({ tuples: [tuple], inventories: { pull_request: { total_count: 101, runs: [] } } }), - await runDispatcher({ tuples: [tuple], inventories: { pull_request: { total_count: 1, runs: [] } } }), - await runDispatcher({ tuples: [tuple], apiFailure: "pull_request" }), - await runDispatcher({ tuples: [tuple], inventories: { pull_request: { malformed: true } } }), - await runDispatcher({ - tuples: [tuple], - inventories: { pull_request: [producer(tuple, "pull_request", "in_progress", null, { - repository: { full_name: "other/repo" }, - })] }, - }), - await runDispatcher({ - tuples: [tuple], - inventories: { pull_request: [producer(tuple, "pull_request", "completed", "success", { - created_at: "not-a-workflow-run-timestamp", - })] }, - }), + assert.deepEqual(numbers(refinedBound), [], "complete bounded refinement retains exact in-flight producer"); + assert.equal(refinedBound.errors.length, 0); + assert(refinedBound.inventoryCalls.some(request => request.created === "2026-01-02T00:00:00Z..*")); + + for (const args of [ + { inventories: { pull_request: { + total_count: 1001, runs: overBoundPage, refined: overBoundPage, refinedTotalCount: 1001, + } } }, + { inventories: { pull_request: { + total_count: 1001, runs: overBoundPage, refined: [], refinedTotalCount: 0, + } } }, + { inventories: { pull_request: { + initial: secondPageRuns, initialTotalCount: 101, refined: secondPageRuns, refinedTotalCount: 102, + } } }, + { inventories: { pull_request: { total_count: 101, runs: [] } } }, + { inventories: { pull_request: { total_count: 1, runs: [] } } }, + { apiFailure: "pull_request" }, + { inventories: { pull_request: { malformed: true } } }, + { inventories: { pull_request: [null] } }, + { inventories: { pull_request: [producer(tuple, "pull_request", "completed", "success", { + created_at: "not-a-workflow-run-timestamp", + })] } }, + { inventories: { pull_request: [producer(tuple, "pull_request", "queued"), producer(tuple, "pull_request", "queued")] } }, + { inventories: { pull_request: { total_count: 1001, runs: runsDescending("pull_request", "2026-01-02T00:00:00Z") } } }, ]) { - assert.equal(uncertain.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, - "incomplete, unavailable, or relevant malformed evidence must fall back to required dispatch"); - assert.equal(uncertain.dispatches.filter((item) => item.event_type === "preview-deploy").length, 1, - "inventory uncertainty must not block independent preview reconciliation"); - assert(uncertain.warnings.some((message) => message.includes("falling back to the required refresh dispatch")), - "inventory uncertainty must produce a concrete fallback diagnostic"); + const uncertain = await runDispatcher({ tuples: [tuple], ...args }); + assert.deepEqual(numbers(uncertain), [], "unknown inventory must never dispatch runtime work"); + assert(uncertain.errors.some(message => message.includes("no dispatch issued")), + "unknown inventory must be an explicit error, not apparent success"); } + for (const [signalAt, expected] of [["2026-01-02T00:00:00Z", 0], ["2026-01-04T00:00:00Z", 1]]) { + const result = await runDispatcher({ + tuples: [tuple], callback: { updated_at: signalAt }, + inventories: { repository_dispatch: [producer(tuple, "repository_dispatch", "completed", "success", { + created_at: "2026-01-03T00:00:00Z", + })] }, + }); + assert.equal(numbers(result).length, expected, "completed refresh suppresses only an earlier signal"); + } + const invisible = await runDispatcher({ tuples: [tuple], hideDispatchVisibility: true }); + assert.deepEqual(numbers(invisible), ["101"], "accepted invisible POST must never be repeated"); + assert(invisible.errors.some(message => message.includes("visibility is unknown"))); process.stdout.write("runtime refresh deduplication fixtures passed\n"); })().catch((error) => { process.stderr.write(`${error.stack || error}\n`); @@ -1591,7 +1498,9 @@ assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'github.rest.a assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'actions: read' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'runtimeRunPageSize = 100' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'runtimeRunLookbackMilliseconds' -assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'falling back to the required refresh dispatch' +assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'no dispatch issued:' +assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'queue: max' +assert_job_excludes runtime-images.yml dispatch-pr-base-refreshes 'cancel-in-progress: true' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'Skipping duplicate PR runtime refresh' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'currentBaseRef !== baseBranch' assert_job_contains runtime-images.yml dispatch-pr-base-refreshes 'parents.length !== 2' From 51445158abd20445b90190883c5f106b26367475 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:22:00 +1300 Subject: [PATCH 12/96] fix: preserve bounded exact runtime recovery across fanout --- .../workflows/publish-pr-runtime-images.yml | 64 +++++++---- .github/workflows/runtime-images.yml | 102 ++++++++++++------ .github/workflows/smoke.yml | 33 ++++-- .../account-service/api-contracts.md | 2 +- .../architecture/system-architecture-cicd.md | 2 +- .../pr-required-gate-context-contract.sh | 73 ++++++++++--- .../tests/pr-retarget-workflow-contract.sh | 54 +++++++++- .../AccountTenantCapacityGrpcServiceTest.java | 3 + .../AccountTenantCapacityClientMtlsTest.java | 8 +- 9 files changed, 255 insertions(+), 86 deletions(-) diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 1e0e47662a..a0dc57799a 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -62,7 +62,13 @@ jobs: }; if (!await sourceCurrent()) return; const currentTuple = async () => { - const {data: pr} = await github.rest.pulls.get({...context.repo, pull_number: Number(number)}); + let pr; + for (let attempt = 0; attempt < 6; attempt++) { + ({data: pr} = await github.rest.pulls.get({...context.repo, pull_number: Number(number)})); + if (pr.state !== "open" || pr.head?.sha !== head || pr.base?.sha !== base || + pr.mergeable !== null || attempt === 5) break; + await new Promise(resolve => setTimeout(resolve, 2000)); + } if (pr.state !== "open" || pr.head?.repo?.full_name !== repository || pr.base?.repo?.full_name !== repository || pr.head?.sha !== head || pr.head?.ref !== event.head_branch || pr.base?.sha !== base || typeof pr.base?.ref !== "string" || !pr.base.ref || pr.mergeable !== true || pr.merge_commit_sha !== merge) return null; @@ -83,7 +89,7 @@ jobs: ...context.repo, workflow_id: workflowId, per_page: 100, page, ...filter, }); total ??= data?.total_count; - if (!Number.isInteger(total) || total < 0 || total > 1000 || data?.total_count !== total || + if (!Number.isInteger(total) || total < 0 || total >= 1000 || data?.total_count !== total || !Array.isArray(data.workflow_runs) || data.workflow_runs.length !== Math.min(100, total - runs.length)) { throw new Error("Reconciliation inventory is incomplete; no dispatch issued"); } @@ -107,30 +113,48 @@ jobs: const ciTitle = `CI — Validation pr-${number} base-${base} head-${head}`; const ciRuns = (await inventory("ci.yml", {event: "pull_request", head_sha: head})) .filter(run => run.display_title === ciTitle).sort((a, b) => b.id - a.id); - const ci = ciRuns[0]; + let ci; const matchesCi = run => run && run.id === ci?.id && run.run_attempt === ci?.run_attempt && positive(run.run_attempt) && run.workflow_id === ciWorkflow.id && matchesPath(run.path, ciWorkflow.path) && run.event === "pull_request" && run.status === "completed" && run.repository?.full_name === repository && run.head_repository?.full_name === repository && run.head_sha === head && run.head_branch === event.head_branch && run.display_title === ciTitle && [ciWorkflow.name, ciTitle].includes(run.name); - if (!ci || !positive(ci.id) || !matchesCi(ci)) return; // Later substantive CI callback owns unfinished CI. - const {data: ciNative} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); - if (!matchesCi(ciNative)) return; - const jobs = await github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", - {...context.repo, run_id: ci.id, attempt_number: ci.run_attempt, per_page: 100}); - const gates = jobs.filter(job => job.name === "Validation Gate"); - const gate = gates.length === 1 ? gates[0] : null; - const preservation = gate?.steps?.filter(step => step.name === "Preserve successful required gate on metadata-only edit") || []; - const enforcement = gate?.steps?.filter(step => step.name === "Enforce validation success") || []; - const checkPrefix = `https://api.github.com/repos/${repository}/check-runs/`; - if (!gate || !positive(gate.id) || gate.run_id !== ci.id || gate.run_attempt !== ci.run_attempt || - gate.head_sha !== head || ![ciWorkflow.name, ciTitle].includes(gate.workflow_name) || gate.status !== "completed" || - typeof gate.check_run_url !== "string" || !gate.check_run_url.startsWith(checkPrefix) || - !/^[1-9][0-9]*$/.test(gate.check_run_url.slice(checkPrefix.length)) || - preservation.length !== 1 || preservation[0].status !== "completed" || preservation[0].conclusion !== "skipped" || - enforcement.length !== 1 || enforcement[0].status !== "completed" || - !["success", "failure"].includes(enforcement[0].conclusion)) return; + // Metadata-only completions cannot conceal an earlier substantive attempt for this exact tuple. + for (const candidate of ciRuns) { + ci = candidate; + if (!positive(ci.id) || !matchesCi(ci)) return; // Unfinished/new unclassified CI owns its later callback. + const {data: ciNative} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); + if (!matchesCi(ciNative)) return; + const jobs = await github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + {...context.repo, run_id: ci.id, attempt_number: ci.run_attempt, per_page: 100}); + const gates = jobs.filter(job => job.name === "Validation Gate"); + const gate = gates.length === 1 ? gates[0] : null; + const preservation = gate?.steps?.filter(step => step.name === "Preserve successful required gate on metadata-only edit") || []; + const enforcement = gate?.steps?.filter(step => step.name === "Enforce validation success") || []; + const checkPrefix = `https://api.github.com/repos/${repository}/check-runs/`; + if (!gate || !positive(gate.id) || gate.run_id !== ci.id || gate.run_attempt !== ci.run_attempt || + gate.head_sha !== head || ![ciWorkflow.name, ciTitle].includes(gate.workflow_name) || gate.status !== "completed" || + typeof gate.check_run_url !== "string" || !gate.check_run_url.startsWith(checkPrefix) || + !/^[1-9][0-9]*$/.test(gate.check_run_url.slice(checkPrefix.length)) || + preservation.length !== 1 || preservation[0].status !== "completed" || preservation[0].conclusion !== "skipped" || + enforcement.length !== 1 || enforcement[0].status !== "completed" || + !["success", "failure"].includes(enforcement[0].conclusion)) { + // Skip only proven metadata preservation, never malformed or unfinished evidence. + if (gate && positive(gate.id) && gate.run_id === ci.id && gate.run_attempt === ci.run_attempt && + gate.head_sha === head && [ciWorkflow.name, ciTitle].includes(gate.workflow_name) && + gate.status === "completed" && typeof gate.check_run_url === "string" && + gate.check_run_url.startsWith(checkPrefix) && /^[1-9][0-9]*$/.test(gate.check_run_url.slice(checkPrefix.length)) && + preservation.length === 1 && preservation[0].status === "completed" && preservation[0].conclusion === "success" && + enforcement.length === 1 && enforcement[0].status === "completed" && enforcement[0].conclusion === "skipped") { + ci = null; + continue; + } + return; + } + break; + } + if (!ci) return; const newerRefresh = async (createdSince = event.created_at) => { const runs = await inventory("runtime-images.yml", {event: "repository_dispatch", created: `${createdSince}..*`}); const exact = runs.filter(run => run.display_title === event.display_title && run.id > event.id); diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 80c28cea3d..75da17048c 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -659,7 +659,7 @@ jobs: total ??= payload?.total_count; if (!Number.isInteger(total) || total < 0 || !Array.isArray(payload?.workflow_runs) || payload.total_count !== total) throw new Error(`runtime-images ${event} inventory shifted or is malformed`); - if (total > 1000) { + if (total >= 1000) { complete = false; incompleteReason ??= `runtime-images ${event} exceeds 1000-run bound`; // Retain this untrusted sample only for the existing conservative in-flight refinement. @@ -706,9 +706,10 @@ jobs: }; } - const refinementSince = inFlightRuns - .map((run) => run.created_at) - .sort()[0]; + const ciCompletedAt = workflowRun.updated_at; + if (!validTimestamp(ciCompletedAt)) return initial; + const refinementSince = [...inFlightRuns.map(run => run.created_at), ciCompletedAt] + .sort((a, b) => Date.parse(a) - Date.parse(b))[0]; // The inclusive created lower bound makes the refined pages a complete candidate set without relying on API ordering. const refined = await readInventory(refinementSince); if (!refined.complete) { @@ -963,11 +964,12 @@ jobs: } } } + const pendingVisibility = []; let runtimeInventoryPromise; let runtimeInventoryError = null; for (const resolved of refreshTargets) { const {tuple, pullRequest} = resolved; - if (await hasRuntimeChange(pullRequest)) { + runtimeRefresh: if (await hasRuntimeChange(pullRequest)) { let existingProducers = []; let fallbackReason = null; let inventory; @@ -998,7 +1000,7 @@ jobs: core.setFailed(`Cannot verify exact runtime producer inventory for PR #${tuple.prNumber}; no dispatch issued: ${fallbackReason}`); runtimeInventoryPromise = undefined; runtimeInventoryError = null; - continue; + break runtimeRefresh; } if (existingProducers.length > 0) { const producer = existingProducers[0]; @@ -1009,8 +1011,18 @@ jobs: core.info(`No reusable in-flight exact producer was verified in the bounded recent inventory; dispatching required PR runtime refresh for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); // Refresh tuple custody after preceding fan-out/API work under the shared dispatcher lock. const current = await resolveExactMerge(tuple.prNumber, tuple.baseRef, tuple.baseSha, tuple.headSha); - const {data: currentBase} = await github.rest.git.getRef({...context.repo, ref: `heads/${tuple.baseRef}`}); - if (!current || current.tuple.mergeSha !== tuple.mergeSha || currentBase.object?.sha !== tuple.baseSha) { + if (!current || current.tuple.mergeSha !== tuple.mergeSha) { + core.info(`Skipping changed runtime tuple for PR #${tuple.prNumber}.`); + continue; + } + let currentBase; + try { + ({data: currentBase} = await github.rest.git.getRef({...context.repo, ref: `heads/${tuple.baseRef}`})); + } catch (error) { + core.setFailed(`Cannot read current base for PR #${tuple.prNumber}: ${error.message || error}`); + continue; + } + if (currentBase.object?.sha !== tuple.baseSha) { core.info(`Skipping changed runtime tuple for PR #${tuple.prNumber}.`); continue; } @@ -1027,45 +1039,67 @@ jobs: merge_sha: tuple.mergeSha, }, }); - // No retry of an ambiguous POST. Hold only this API dispatcher lock for bounded visibility. - const visibilityDeadline = Date.now() + 120000; - for (;;) { - const observed = await loadExistingRuntimeRuns(); - if (!observed.complete) throw new Error("Accepted refresh has incomplete visibility; no retry issued"); - const exactTitle = `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; - if (observed.runs.some(run => run.event === "repository_dispatch" && - run.display_title === exactTitle && !previousIds.has(run.id))) break; - if (Date.now() >= visibilityDeadline) throw new Error("Refresh dispatch accepted but visibility is unknown; no retry issued"); - await new Promise(resolve => setTimeout(resolve, 5000)); - } + // Collect handoffs first so one slow visibility response cannot starve later PRs. + pendingVisibility.push({tuple, previousIds}); } catch (error) { core.setFailed(`Runtime refresh handoff for PR #${tuple.prNumber} is uncertain; no retry issued: ${error.message || error}`); runtimeInventoryPromise = undefined; - continue; + break runtimeRefresh; } runtimeInventoryPromise = undefined; } } else { core.info(`Skipping PR runtime image refresh for #${tuple.prNumber}: no runtime-changing files.`); } - if (!isPreviewEligible(pullRequest)) { + // Preview has its own exact-image proof. An uncertain runtime handoff must not suppress it. + const previewCurrent = await resolveExactMerge(tuple.prNumber, tuple.baseRef, tuple.baseSha, tuple.headSha); + if (!previewCurrent || previewCurrent.tuple.mergeSha !== tuple.mergeSha) continue; + if (!isPreviewEligible(previewCurrent.pullRequest)) { core.info(`Skipping preview deploy reconciliation for #${tuple.prNumber}: target is not preview-eligible.`); continue; } core.info(`Dispatching preview deploy reconciliation for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); - await github.rest.repos.createDispatchEvent({ - ...context.repo, - event_type: "preview-deploy", - client_payload: { - action: "deploy", - pr_number: tuple.prNumber, - base_ref: tuple.baseRef, - base_sha: tuple.baseSha, - head_sha: tuple.headSha, - merge_sha: tuple.mergeSha, - preview_domain: "preview.firedevops.net", - }, - }); + try { + await github.rest.repos.createDispatchEvent({ + ...context.repo, + event_type: "preview-deploy", + client_payload: { + action: "deploy", + pr_number: tuple.prNumber, + base_ref: tuple.baseRef, + base_sha: tuple.baseSha, + head_sha: tuple.headSha, + merge_sha: tuple.mergeSha, + preview_domain: "preview.firedevops.net", + }, + }); + } catch (error) { + core.setFailed(`Preview reconciliation handoff for PR #${tuple.prNumber} is uncertain; no retry issued: ${error.message || error}`); + } + } + // One shared bounded observation window, not 120 seconds multiplied by the fan-out size. + // The dispatcher lock remains held; no POST is retried even when visibility is uncertain. + const visibilityDeadline = Date.now() + 120000; + while (pendingVisibility.length > 0) { + try { + const observed = await loadExistingRuntimeRuns(); + if (!observed.complete) throw new Error("Accepted refresh has incomplete visibility; no retry issued"); + for (let index = pendingVisibility.length - 1; index >= 0; index--) { + const {tuple, previousIds} = pendingVisibility[index]; + const exactTitle = `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; + if (observed.runs.some(run => run.event === "repository_dispatch" && + run.display_title === exactTitle && !previousIds.has(run.id))) pendingVisibility.splice(index, 1); + } + } catch (error) { + core.setFailed(`Runtime refresh visibility is uncertain; no retry issued: ${error.message || error}`); + break; + } + if (pendingVisibility.length === 0) break; + if (Date.now() >= visibilityDeadline) { + core.setFailed(`Refresh dispatch accepted but visibility is unknown for PRs ${pendingVisibility.map(item => item.tuple.prNumber).join(", ")}; no retry issued`); + break; + } + await new Promise(resolve => setTimeout(resolve, 5000)); } build-base-image: diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 3ce9026fe3..58db1bea31 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -611,7 +611,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "1d5cb2928f55a45069ab251889e6cd5fc9c9d5df15b27bb94d4d40a2ea030d02"; + const canonicalRuntimeWorkflowSha256 = "41ee9bca3d7b982a648384c68471aa5cc7f9a7ff1ef9a9f942c5d4116242aae3"; // Trusted refreshes can still execute the previous successful default-branch definition. const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = "ea6ade0f69718573aeac4e4b5a1e9050e53e1e3cef3426b8791f182d8d49e112"; // Retain the exact fail-red producer still executed by trusted base refreshes. @@ -888,8 +888,11 @@ jobs: (step.conclusion === "failure" && !(source.conclusion === "failure" && expectedSuccessfulSteps.includes(step.name)))) return false; } - if (jobs.some((other) => other.id !== job.id && - (other.status !== "completed" || !["success", "skipped"].includes(other.conclusion)))) return false; + for (const other of jobs) { + if (other.id === job.id) continue; + if (["queued", "in_progress", "waiting", "pending", "requested"].includes(other.status)) incompleteSteps = true; + else if (other.status !== "completed" || !["success", "skipped"].includes(other.conclusion)) return false; + } // Typed refresh workflow authority is its native default-branch revision; // the executed classifier source still belongs to the verified PR merge. const workflowSha = source.event === "pull_request" ? identity.mergeSha : source.head_sha; @@ -967,7 +970,7 @@ jobs: if (repositoryName !== "benhook1013/FireMUD" || context.payload.pull_request.head.repo?.full_name !== repositoryName || run.event !== "pull_request" || - run.status !== "completed" || run.conclusion !== "failure" || + run.status !== "completed" || !["failure", "timed_out"].includes(run.conclusion) || !positiveInteger(run.id)) return false; const title = `Build Runtime Images secure-pr-artifact pr-${prNumber} ` + `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; @@ -1321,7 +1324,7 @@ jobs: if (await isCurrentPullRequestObsolete("Stopping obsolete failed smoke gate for")) { return; } - if (matching.conclusion === "failure" && repositoryName === "benhook1013/FireMUD" && + if (["failure", "timed_out"].includes(matching.conclusion) && repositoryName === "benhook1013/FireMUD" && ["pull_request", "repository_dispatch"].includes(matching.event)) { let knownPlayVerified = false; let refreshVerified = false; @@ -1333,8 +1336,24 @@ jobs: }) ); const candidate = jobs.find((job) => job.name === canonicalSmokeJobName); - knownPlayVerified = Boolean(candidate) && - await verifyKnownPlayFailure(matching, candidate, currentIdentity); + const directRefresh = matching.event === "repository_dispatch" && matching.conclusion === "failure"; + const directProof = matching.conclusion !== "failure" ? false + : directRefresh && (!candidate || candidate.status !== "completed") ? "snapshot-pending" + : Boolean(candidate) && await verifyKnownPlayFailure(matching, candidate, currentIdentity, directRefresh); + knownPlayVerified = directProof === true; + if (directRefresh && directProof === "snapshot-pending") { + const snapshotKey = `direct:${identityKey(currentIdentity)}:${matching.id}:${matching.run_attempt}`; + if (incompleteRefreshKey !== snapshotKey) { + incompleteRefreshKey = snapshotKey; + incompleteRefreshObservedAt = Date.now(); + } + if (Date.now() - incompleteRefreshObservedAt >= completedSnapshotTimeoutMs) { + core.setFailed("Terminal canonical refresh did not expose complete smoke-job proof within the snapshot convergence allowance."); + return; + } + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } } catch (error) { if (error instanceof TerminalGitHubRequestError) throw error; core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 604453d6f1..55ee2236fc 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -233,7 +233,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 canonical Account UUIDs. Account resolves known subjects through one local UUID batch query with the same persisted provenance and source-row checks as scalar identity reads, then returns policies keyed by UUID. Unknown or unproven entries are intentionally omitted so Social applies complete `PRIVATE` redaction. - `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current gRPC adapter returns `FAILED_PRECONDITION` before selector parsing or owner reads; this does not implement the target export operation. -- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns the typed `TENANT_BILLING_BLOCKED` response. Fresh creation-eligible evidence with checked insufficient capacity returns the typed `CAPACITY_QUOTA_EXCEEDED` response only after the exact durable `NO_ACCEPT` decision commits. If its refusal budget is missing or exhausted, Account returns non-OK `ENTITLEMENT_UNAVAILABLE` instead; no quota receipt or settlement authority is issued. Each refusal is bound to the exact original attempt, mutation digest, snapshot and evaluation. A quota refusal includes the immutable Account decision UUID only after an exact durable `NO_ACCEPT` commits. A matching exact retry returns the retained receipt. A quota refusal without that receipt grants no evidence settlement authority. The response contains exactly one commitment or one typed refusal. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a changed exact retry. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns the typed `TENANT_BILLING_BLOCKED` response. This billing refusal does not consume the quota-refusal budget or create a durable decision receipt; it remains available when no refusal-budget row exists. Fresh creation-eligible evidence with checked insufficient capacity returns the typed `CAPACITY_QUOTA_EXCEEDED` response only after the exact durable `NO_ACCEPT` decision commits. If its refusal budget is missing or exhausted, Account returns non-OK `ENTITLEMENT_UNAVAILABLE` instead; no quota receipt or settlement authority is issued. Each refusal is bound to the exact original attempt, mutation digest, snapshot and evaluation. A quota refusal includes the immutable Account decision UUID only after an exact durable `NO_ACCEPT` commits. A matching exact retry returns the retained receipt. A quota refusal without that receipt grants no evidence settlement authority. The response contains exactly one commitment or one typed refusal. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a changed exact retry. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact attempt-and-fence retries replay; a changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. The shared [capacity-admission/v1 schema](../../../../services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json) declares the exact ADR 0047 seven-field mapping and bounds. Its `accountEvidence` member is canonical padded base64 of the complete existing Account bundle bytes, validated by the closed variant codec with canonical re-encoding equality before hashing. This binds every evidence field and cutoff/checkpoint byte, not a digest or reconstructed subset. `capacity_delta` is `optional int64`; missing presence is invalid and a present zero remains distinct. The Game Session and World alternatives retain distinct typed contexts. The ordinary registered Account receiver does not expose this private composition, and no route is enabled by adding the proto. diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 81d5059b4c..c817f21f4c 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -88,7 +88,7 @@ A typed runtime refresh hands off publication explicitly after its required cred The publisher's no-checkout, Actions-read-only resolver reads only the supplied exact source run and owning runtime workflow identity. A dispatch can arrive before its source workflow finishes, so the resolver waits for actual terminal success within a two-minute budget; malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. The resolver never substitutes a successful status. Both trigger paths retain the same exact source, current PR/base/head/merge, artifact provenance, and immutable-tag validation. Publishing jobs serialize on the verified merge-bound source title across both paths; duplicate publication preserves identical existing images and rejects conflicting image bytes. Explicit dispatch avoids relying on a workflow-run callback from a token-origin refresh without weakening the source or registry boundary. -The trusted publisher also reconciles a failed, cancelled, or timed-out original same-repository PR runtime run when substantive Validation already completed. This API-only job has `contents: write` solely to request an exact typed refresh; it never checks out PR code. It verifies current native source and CI attempts, the live base/head/merge tuple, and absence of a newer original or typed refresh before dispatch. Typed-refresh and nested workflow callbacks cannot recursively invoke this recovery. The CI dispatcher and completion reconciler share an API-job concurrency group with `queue: max`; runtime builds remain parallel. Unknown inventory fails closed, and an uncertain dispatch is not blindly repeated. The accepted handoff has a 120-second visibility budget; a failed target does not automatically suppress independent later targets. This is bounded coordination, not exactly-once delivery or an unbounded no-starvation guarantee: GitHub admits at most 100 pending jobs in the group, inventories and job durations are bounded, and existing superseding base callbacks can cancel obsolete work. Remaining unknown outcomes require fresh evidence rather than presumed success. +The trusted publisher also reconciles a failed, cancelled, or timed-out original same-repository PR runtime run when substantive Validation already completed. This API-only job has `contents: write` solely to request an exact typed refresh; it never checks out PR code. It verifies current native source and CI attempts, the live base/head/merge tuple, and absence of a newer original or typed refresh before dispatch. Typed-refresh and nested workflow callbacks cannot recursively invoke this recovery. The CI dispatcher and completion reconciler share an API-job concurrency group with `queue: max`; runtime builds remain parallel. Unknown inventory fails closed, and an uncertain dispatch is not blindly repeated. Accepted handoffs share one 120-second visibility window after fan-out rather than delaying each later target in turn. Preview reconciliation checks its own current tuple independently of runtime handoff uncertainty; a failed target does not automatically suppress independent later targets. This is bounded coordination, not exactly-once delivery or an unbounded no-starvation guarantee: GitHub admits at most 100 pending jobs in the group, inventories and job durations are bounded, and existing superseding base callbacks can cancel obsolete work. Remaining unknown outcomes require fresh evidence rather than presumed success. Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard. Ordinary runtime qualification requires both Actions-native outcomes to be `success` and the transition-exception marker to be explicitly skipped. Missing marker metadata cannot use the native-job fallback: a successful job alone may instead represent the bounded exception described below. Skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify as real runtime proof. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. A separate, temporary diagnostic exception lets the required Smoke Gate succeed for a same-repository `benhook1013/FireMUD` pull request whose current live PR carries the `canonical-play-transition` label. A `pull_request` producer also requires the source event label and exact verified PR-event base/head/merge tuple. A typed `pr-runtime-base-refresh` producer instead derives label authority from its verified live same-repository PR, never dispatch payload labels, and requires the exact current base/head/merge tuple again at consumption. Both paths require the latest successful CI attempt with its explicit exception marker while the PR head and base branch remain current. During the default-branch workflow rollout, the exact previous fail-red producer fingerprint remains accepted only with its original failed smoke and terminal guard plus successful marker and cleanup; it supplies the same diagnostic exception and no runtime qualification. The smoke invocation retains its failed Actions-native outcome through step-level continuation; only the exact label, classifier and successful authenticated cleanup can make the mandatory final guard accept that failed probe. Every other probe failure still fails CI. GitHub reports the continued step conclusion as success, so the consumer verifies the immutable marker rather than treating that conclusion as runtime proof. The fingerprinted producer must attest the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, with successful authenticated cleanup. The executing workflow is fingerprinted at the PR merge revision or typed refresh's native default-branch revision, respectively; classifiers, held-admission qualification, authenticated cleanup, certificate setup, and their checked-in environment and Compose inputs are always fingerprinted at the tested PR merge. Its original smoke failure remains visible in the probe logs, summary and Actions-native outcome; unrelated failures still block, and image export and upload must be skipped. The typed publication handoff also requires a real successful image upload. A trusted workflow-run publisher detects the exception marker before exposing a publication source and skips its privileged job; a successful CI conclusion under exception does not authorize registry access or preview images. This is gate acceptance for the nonproduction canonical cutover, not successful smoke, runtime qualification, branch-image promotion, hosted preview eligibility, or production activation. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception; after the cutover merges, branch images remain on hold until the Account entitlement path is repaired. Remove the label-based marker and consumer exception when fresh-image backend `LOGIN` → `PLAY` → `LOOK` passes, then remove this transitional contract. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 8a6a7647a6..8c7c247d4d 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3702,13 +3702,13 @@ const loopStart = script.indexOf("let currentIdentity = null;"); const actualPollingLoop = script.slice(loopStart); async function pendingRefreshCaller(statuses, expires = false, options = {}) { const failures = [], outputs = []; - let sleeps = 0, polls = 0, writes = 0, now = 0, currentChecks = 0, finalChecks = 0, nullReads = 0; + let sleeps = 0, polls = 0, writes = 0, now = 0, currentChecks = 0, finalChecks = 0, nullReads = 0, directReads = 0; const proofLive = {baseSha: identity.baseSha, mergeSha: identity.mergeSha}; const core = {info: () => {}, warning: () => {}, setFailed: value => failures.push(value), setOutput: (...value) => outputs.push(value)}; core.summary = {addHeading() {return this;}, addRaw() {return this;}, async write() {writes++;}}; - const original = {...source, id: 98, event: "pull_request", status: "completed", conclusion: "failure"}; + const original = {...source, id: 98, event: "pull_request", status: "completed", conclusion: options.originalConclusion || "failure"}; const execute = new Function("repositoryName", "github", "owner", "repo", "canonicalSmokeJobName", "withTransientGitHubRetry", "verifyKnownPlayFailure", "verifyFailedPullCanonicalRefresh", "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", @@ -3723,6 +3723,10 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { if (options.ordinaryAfterDrift) job.steps.find(s => s.name.startsWith("Known canonical")).conclusion = "skipped"; return [job]; }}, "benhook1013", "FireMUD", canonicalSmokeJobName, (_label, call) => call(), async run => { + if (options.directSnapshots && run.event === "repository_dispatch") { + const status = options.directSnapshots[Math.min(directReads++, options.directSnapshots.length - 1)]; + return status === "complete" ? true : status === "invalid" ? false : "snapshot-pending"; + } if (options.proofDrift && run.event === "repository_dispatch") { return verify(data => { Object.assign(data.identity, proofLive); @@ -3735,6 +3739,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { return Boolean(options.directProof || (options.recoverDrift && run.event === "repository_dispatch")); }, async (selectedRun, selectedIdentity) => { + if (options.directSnapshots && selectedRun.event === "repository_dispatch") return false; assert.equal(selectedRun.id, original.id); assert.equal(selectedIdentity.headSha, identity.headSha); assert.equal(selectedIdentity.baseSha, identity.baseSha); @@ -3778,7 +3783,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { assert.equal(event, "repository_dispatch"); assert.equal(selected.baseSha, options.finalIdentity.baseSha); assert.equal(selected.mergeSha, options.finalIdentity.mergeSha); - return {...source, event: "repository_dispatch", status: "completed", conclusion: "success"}; + return {...source, event: "repository_dispatch", status: "completed", conclusion: options.directSnapshots ? "failure" : "success"}; } return original; }, "3390", "test identity", 60, @@ -3796,6 +3801,9 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { }); if (options.ordinaryAfterDrift) { assert.deepEqual(failures, []); assert.deepEqual(outputs, []); assert.equal(writes, 0); + } else if (options.directInvalid) { + assert.deepEqual(failures, ["Runtime images run 99 did not complete successfully: run=failure"]); + assert.deepEqual(outputs, []); assert.equal(writes, 0); } else if (options.rejectedObject) { assert.deepEqual(failures, ["Runtime images run 98 did not complete successfully: run=failure"]); assert.deepEqual(outputs, []); assert.equal(writes, 0); @@ -3825,10 +3833,10 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { assert.equal(writes, 1); assert.ok(options.directProof || currentChecks >= 1); } - assert.equal(polls, options.ordinaryAfterDrift || options.directProof || options.labelRemoved ? 0 + assert.equal(polls, options.directSnapshots ? 1 : options.ordinaryAfterDrift || options.directProof || options.labelRemoved ? 0 : options.withdrawDuringProof || options.rejectedObject ? 1 : options.absentExpires ? 5 : options.snapshotExpires ? 3 : options.recoverDrift ? 1 : statuses.length); - assert.equal(sleeps, options.ordinaryAfterDrift || options.labelRemoved || options.withdrawDuringProof || options.rejectedObject ? 0 + assert.equal(sleeps, options.directSnapshots ? (options.snapshotExpires ? 2 : options.directSnapshots.length - 1) : options.ordinaryAfterDrift || options.labelRemoved || options.withdrawDuringProof || options.rejectedObject ? 0 : options.absentExpires ? 4 : options.snapshotExpires ? 2 : options.finalIdentity ? (statuses[0] === "absent" ? 1 : 0) : expires ? statuses.length : statuses.length - 1); } @@ -3903,6 +3911,26 @@ function markerAccepted(overrides = {}) { const missing = Object.assign(new Error("missing"), {status: 404}); await assert.rejects(finalAttemptCheck(null, missing), error => error === missing); await pendingRefreshCaller(["completed", "completed"], false, {transientFinal: true}); + assert.equal((await recoveredFailure({original: {conclusion: "timed_out"}})).accepted, true); + await pendingRefreshCaller(["queued", "completed"], false, {originalConclusion: "timed_out"}); + for (const siblingStatus of ["in_progress", "queued"]) { + assert.equal(await verify(data => {data.jobs.push({id: 999, status: siblingStatus, conclusion: null});}, + "repository_dispatch", true, true), "snapshot-pending"); + } + assert.equal(await verify(data => {data.jobs.push({id: 999, status: "completed", conclusion: "skipped"});}, + "repository_dispatch", true, true), true); + assert.equal(await verify(data => {data.jobs.push({id: 999, status: "completed", conclusion: "failure"});}, + "repository_dispatch", true, true), false); + assert.equal(await verify(data => { + data.jobs.push({id: 999, status: "in_progress", conclusion: null}); + data.currentPullRequest.head.sha = "e".repeat(40); + }, "repository_dispatch", true, true), false, "unfinished sibling cannot hide invalid live identity"); + for (const directSnapshots of [["pending", "complete"], ["pending", "pending", "pending", "complete"], ["invalid"]]) { + await pendingRefreshCaller(["completed", "completed", "completed", "completed"], false, { + recoverDrift: true, finalIdentity: {baseSha: "d".repeat(40), mergeSha: "e".repeat(40)}, directSnapshots, + snapshotExpires: directSnapshots.length === 4, directInvalid: directSnapshots[0] === "invalid", + }); + } await pendingRefreshCaller(["missing-step", "completed"]); await pendingRefreshCaller(["nonterminal-step", "completed"]); await pendingRefreshCaller(["missing-step", "missing-step", "missing-step", "completed"], false, {snapshotExpires: true}); @@ -4170,25 +4198,30 @@ async function run(kind, shared = {visible: false, posts: 0}) { ? {id: 8, path: ".github/workflows/ci.yml", name: "CI — Validation"} : {id: 7, path: source.path, name: source.name}}), getWorkflowRun: async ({run_id}) => { - if (run_id === 90) return {data: {...ci, ...(kind === "ci-rerun" ? {run_attempt: 2} : {})}}; + if (run_id === 90 || run_id === 91) return {data: {...ci, id: run_id, ...(kind === "ci-rerun" ? {run_attempt: 2} : {})}}; sourceReads++; return {data: {...source, ...((kind === "stale-attempt" || kind === "late-rerun" && sourceReads > 1) ? {run_attempt: 2} : {})}}; }, listWorkflowRuns: async ({workflow_id, page, event: runEvent}) => { let runs = workflow_id === "ci.yml" ? [{...ci, ...(kind === "ci-pending" ? {status: "in_progress"} : {})}] : shared.visible ? [refresh] : []; + if (workflow_id === "ci.yml" && ["metadata-newer", "unclassified-newer", "pending-newer"].includes(kind)) { + runs = [{...ci, id: 91, ...(kind === "pending-newer" ? {status: "in_progress"} : {})}, ci]; + } if (workflow_id === "runtime-images.yml" && runEvent === "pull_request") { runs = kind === "newer-original" ? [{...source, id: 105, status: "in_progress"}] : [source]; } if (workflow_id === "runtime-images.yml" && runEvent === "repository_dispatch" && kind === "second-page") { runs = Array.from({length: 100}, (_, i) => ({...refresh, id: 1000 + i, display_title: "unrelated"})).concat(refresh); } - return {data: {total_count: kind === "incomplete" ? 1001 : runs.length, workflow_runs: runs.slice((page - 1) * 100, page * 100)}}; + return {data: {total_count: kind === "incomplete" ? 1001 : kind === "at-cap" ? 1000 : runs.length, workflow_runs: runs.slice((page - 1) * 100, page * 100)}}; }, }, - pulls: {get: async () => { tupleReads++; return {data: {state: "open", mergeable: true, merge_commit_sha: merge, + pulls: {get: async () => { tupleReads++; return {data: {state: "open", + mergeable: kind === "merge-conflict" ? false : kind === "merge-unknown" || kind === "merge-drift" || kind === "merge-pending" && tupleReads === 1 ? null : true, + merge_commit_sha: merge, head: {sha: head, ref: "feature", repo: {full_name: repository}}, - base: {ref: "develop", sha: kind === "late-drift" && tupleReads > 1 ? head : base, repo: {full_name: repository}}}};}}, + base: {ref: "develop", sha: (kind === "late-drift" || kind === "merge-drift") && tupleReads > 1 ? head : base, repo: {full_name: repository}}}};}}, git: {getRef: async () => ({data: {object: {sha: base}}})}, repos: { getCommit: async () => ({data: {sha: merge, parents: [{sha: base}, {sha: head}]}}), @@ -4198,24 +4231,32 @@ async function run(kind, shared = {visible: false, posts: 0}) { if (kind !== "invisible") shared.visible = true; }, }, - }, paginate: async () => [{id: 30, run_id: 90, run_attempt: 1, head_sha: head, name: "Validation Gate", - workflow_name: "CI — Validation", status: "completed", check_run_url: `https://api.github.com/repos/${repository}/check-runs/30`, - steps: [{name: "Preserve successful required gate on metadata-only edit", status: "completed", conclusion: kind === "metadata" ? "success" : "skipped"}, - {name: "Enforce validation success", status: "completed", conclusion: "failure"}]}]}; + }, paginate: async (_route, request) => { + const metadata = kind === "metadata" || kind === "metadata-newer" && request.run_id === 91; + return [{id: 30, run_id: request.run_id, run_attempt: 1, head_sha: head, name: "Validation Gate", + workflow_name: "CI — Validation", status: "completed", check_run_url: `https://api.github.com/repos/${repository}/check-runs/30`, + steps: kind === "unclassified-newer" && request.run_id === 91 ? [] : [ + {name: "Preserve successful required gate on metadata-only edit", status: "completed", conclusion: metadata ? "success" : "skipped"}, + {name: "Enforce validation success", status: "completed", conclusion: metadata ? "skipped" : "failure"}]}]; + }}; await execute(github, {repo: {owner: "example", repo: "firemud"}, eventName: "workflow_run", payload: {workflow_run: event, repository: {default_branch: "develop"}}}, {info: () => {}}, class extends Date { static now() { return clock; } }, callback => {clock += 5000; callback();}); + if (kind === "merge-unknown") assert.equal(tupleReads, 6, "unresolved mergeability retries are bounded"); + if (kind === "merge-pending") assert.equal(tupleReads, 3, "one convergence retry plus final current tuple fence"); return shared.posts; } (async () => { assert.equal(await run("valid"), 1); - for (const scenario of ["typed-callback", "nested-callback", "fork", "success", "stale-attempt", "late-rerun", "ci-rerun", "ci-pending", "metadata", "late-drift", "second-page", "newer-original"]) { + assert.equal(await run("metadata-newer"), 1, "proven metadata completion cannot hide substantive CI"); + assert.equal(await run("merge-pending"), 1, "mergeability may converge without tuple changes"); + for (const scenario of ["typed-callback", "nested-callback", "fork", "success", "stale-attempt", "late-rerun", "ci-rerun", "ci-pending", "metadata", "late-drift", "second-page", "newer-original", "unclassified-newer", "pending-newer", "merge-unknown", "merge-conflict", "merge-drift"]) { assert.equal(await run(scenario), 0, scenario); } - for (const scenario of ["incomplete", "ambiguous-post", "invisible"]) { + for (const scenario of ["incomplete", "at-cap", "ambiguous-post", "invisible"]) { const state = {visible: false, posts: 0}; await assert.rejects(run(scenario, state)); - assert.equal(state.posts, scenario === "incomplete" ? 0 : 1, "never retry unknown POST"); + assert.equal(state.posts, ["incomplete", "at-cap"].includes(scenario) ? 0 : 1, "never retry unknown POST"); } // Under the shared job mutex, a CI-first visible refresh suppresses completion recovery. assert.equal(await run("valid", {visible: true, posts: 0}), 0); diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index a3313f16a8..bb7acbcd03 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -893,7 +893,7 @@ const runsDescending = (event, firstCreatedAt) => Array.from({ length: 100 }, (_ async function runDispatcher({ tuples, inventories = {}, apiFailure = null, sourceTuples = [], callback = {}, branchHeads = {}, branchErrors = {}, pullOverrides = {}, mergeParents = {}, ciEvidence = {}, - hideDispatchVisibility = false, filesByPr = {}, postFailurePr = null, + hideDispatchVisibility = false, filesByPr = {}, postFailurePr = null, previewFailurePr = null, }) { const dispatches = []; const postedRuns = []; @@ -902,6 +902,7 @@ async function runDispatcher({ const infos = []; const warnings = []; const inventoryCalls = []; + const observationPostCounts = []; const eventInventoryCalls = new Map(); const currentBaseSha = tuples[0]?.baseSha ?? baseSha; const allTuples = [...tuples, ...sourceTuples]; @@ -952,7 +953,8 @@ async function runDispatcher({ git: { getRef: async ({ ref }) => { refRequests.push(ref); - if (branchErrors[ref]) throw Object.assign(new Error("fixture branch lookup failed"), { status: branchErrors[ref] }); + const branchError = typeof branchErrors[ref] === "function" ? branchErrors[ref](refRequests.length) : branchErrors[ref]; + if (branchError) throw Object.assign(new Error("fixture branch lookup failed"), { status: branchError }); return { data: { object: { sha: branchHeads[ref] ?? allTuples.find((tuple) => `heads/${tuple.baseRef}` === ref)?.baseSha ?? callback.head_sha ?? currentBaseSha, @@ -986,6 +988,9 @@ async function runDispatcher({ }, createDispatchEvent: async (request) => { dispatches.push(request); + if (request.event_type === "preview-deploy" && request.client_payload.pr_number === previewFailurePr) { + throw new Error("ambiguous preview POST timeout"); + } if (request.event_type === "pr-runtime-base-refresh" && request.client_payload.pr_number === postFailurePr) { throw new Error("ambiguous POST timeout"); } @@ -1010,6 +1015,7 @@ async function runDispatcher({ }, listWorkflowRuns: async (request) => { inventoryCalls.push(request); + observationPostCounts.push(dispatches.filter(item => item.event_type === "pr-runtime-base-refresh").length); if (apiFailure === request.event || (typeof apiFailure === "function" && apiFailure(request, inventoryCalls.length))) { throw new Error("fixture API unavailable"); } @@ -1071,7 +1077,7 @@ async function runDispatcher({ Date.now = originalDateNow; global.setTimeout = originalSetTimeout; } - return { dispatches, errors, infos, warnings, inventoryCalls, ciJobRequests, pullListRequests, refRequests }; + return { dispatches, errors, infos, warnings, inventoryCalls, observationPostCounts, ciJobRequests, pullListRequests, refRequests }; } (async () => { @@ -1278,6 +1284,8 @@ async function runDispatcher({ }); assert.equal(invalidRefPath.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 0, `an invalid Git ref ${invalidRef} must not authorize another dispatch`); + assert(invalidRefPath.errors.some(message => message.includes("no dispatch issued")), + "invalid ref must be explicit rejection, not successful reuse"); } const wrongWorkflowPath = await runDispatcher({ tuples: [tuple], @@ -1388,6 +1396,11 @@ async function runDispatcher({ }); assert.deepEqual(numbers(changedFirst), ["102"], "changed first PR must not starve second"); assert(changedFirst.infos.some(message => message.includes("Skipping changed runtime tuple"))); + const vanishedBase = await runDispatcher({ + tuples: [tuple, sibling], branchErrors: {"heads/develop": count => count === 2 ? 404 : null}, + }); + assert.deepEqual(numbers(vanishedBase), ["102"], "base disappearing at first target must not abort later targets"); + assert(vanishedBase.errors.some(message => message.includes("Cannot read current base for PR #101"))); const unknownFirst = await runDispatcher({ tuples: [tuple, sibling], inventories: { pull_request: [producer(tuple, "pull_request", "in_progress", null, { @@ -1409,7 +1422,7 @@ async function runDispatcher({ created_at: "2026-01-02T00:00:00Z", }); const refinedBound = await runDispatcher({ - tuples: [tuple], inventories: { pull_request: { + tuples: [tuple], callback: {updated_at: "2026-01-03T00:00:00Z"}, inventories: { pull_request: { total_count: 1001, runs: overBoundPage, refined: [overBoundPage[0]], refinedTotalCount: 1, } }, }); @@ -1417,6 +1430,20 @@ async function runDispatcher({ assert.equal(refinedBound.errors.length, 0); assert(refinedBound.inventoryCalls.some(request => request.created === "2026-01-02T00:00:00Z..*")); + const unrelatedInflight = producer(sibling, "pull_request", "in_progress", null, {created_at: "2026-01-02T00:00:00Z"}); + const refinedCompleted = await runDispatcher({ + tuples: [tuple], callback: {updated_at: "2026-01-01T06:00:00Z"}, + inventories: { + pull_request: {total_count: 1001, runs: [unrelatedInflight], + refined: [unrelatedInflight], refinedTotalCount: 1}, + repository_dispatch: [producer(tuple, "repository_dispatch", "completed", "success", { + created_at: "2026-01-01T12:00:00Z", + })], + }, + }); + assert.deepEqual(numbers(refinedCompleted), [], "refinement must retain completed refresh between CI completion and sampled inflight floor"); + assert(refinedCompleted.inventoryCalls.some(request => request.created === "2026-01-01T06:00:00Z..*")); + for (const args of [ { inventories: { pull_request: { total_count: 1001, runs: overBoundPage, refined: overBoundPage, refinedTotalCount: 1001, @@ -1427,6 +1454,7 @@ async function runDispatcher({ { inventories: { pull_request: { initial: secondPageRuns, initialTotalCount: 101, refined: secondPageRuns, refinedTotalCount: 102, } } }, + { inventories: { pull_request: { total_count: 1000, runs: [] } } }, { inventories: { pull_request: { total_count: 101, runs: [] } } }, { inventories: { pull_request: { total_count: 1, runs: [] } } }, { apiFailure: "pull_request" }, @@ -1456,6 +1484,24 @@ async function runDispatcher({ const invisible = await runDispatcher({ tuples: [tuple], hideDispatchVisibility: true }); assert.deepEqual(numbers(invisible), ["101"], "accepted invisible POST must never be repeated"); assert(invisible.errors.some(message => message.includes("visibility is unknown"))); + const many = Array.from({length: 12}, (_, index) => tupleFor(201 + index, "a", "c")); + const manyInvisible = await runDispatcher({tuples: many, hideDispatchVisibility: true}); + assert.deepEqual(numbers(manyInvisible), many.map(item => item.prNumber), + "all eligible targets receive one handoff before the single shared visibility wait"); + assert(manyInvisible.errors.some(message => message.includes("visibility is unknown"))); + const previewTuple = {...tuple, labels: [{name: "preview"}]}; + const previewUnknown = await runDispatcher({tuples: [previewTuple], apiFailure: "pull_request"}); + assert.equal(runtimeDispatches(previewUnknown).length, 0); + assert.equal(previewDispatches(previewUnknown).length, 1, "uncertain runtime inventory must not suppress independent preview reconciliation"); + const previewFailed = await runDispatcher({tuples: [previewTuple, sibling], previewFailurePr: "101"}); + assert.deepEqual(numbers(previewFailed), ["101", "102"], "preview POST uncertainty must preserve later runtime targets"); + assert(previewFailed.errors.some(message => message.includes("ambiguous preview POST timeout"))); + assert.equal(previewDispatches(previewFailed).filter(item => item.client_payload.pr_number === "101").length, 1, + "uncertain preview POST is attempted exactly once, never retried"); + assert(previewFailed.observationPostCounts.includes(2), "visibility observation runs after the final runtime POST"); + assert(!previewFailed.errors.some(message => message.includes("visibility is unknown")), "accepted runtime handoffs still observed after preview failure"); + const previewInvisible = await runDispatcher({tuples: [previewTuple], hideDispatchVisibility: true}); + assert.equal(previewDispatches(previewInvisible).length, 1, "invisible accepted runtime handoff must preserve preview reconciliation"); process.stdout.write("runtime refresh deduplication fixtures passed\n"); })().catch((error) => { process.stderr.write(`${error.stack || error}\n`); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java index b9f174bfd3..4646c67d7b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -8,6 +8,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import io.grpc.Status; @@ -149,6 +150,7 @@ void producedBillingDenialReturnsAnExactTypedResponse() { .contains(new Refusal(code, null)); ordered.verify(observer).onCompleted(); verify(observer, never()).onError(any()); + verifyNoMoreInteractions(observer); } } @@ -171,6 +173,7 @@ void retainedQuotaDenialCarriesTheExactAccountDecision() { .contains(new Refusal(Failure.CAPACITY_QUOTA_EXCEEDED, decisionId)); ordered.verify(observer).onCompleted(); verify(observer, never()).onError(any()); + verifyNoMoreInteractions(observer); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index 6bea95a973..6da4bf40e9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -240,12 +240,14 @@ void successfulRpcPropagatesMinimumOfExplicitIncomingAndMaximumDeadline( long explicitMillis, long incomingMillis, long expectedMaximumMillis) throws Exception { AtomicInteger calls = new AtomicInteger(); AtomicLong observedNanos = new AtomicLong(); - // Each case owns one server and one successful RPC, so no other call can supply its sample. + // Warm the channel, then reset the sample before the measured RPC. Server server = server("account", calls, false, observedNanos, new AtomicBoolean(true)); var scheduler = Executors.newSingleThreadScheduledExecutor(); try (var client = client(server)) { client.init(); var request = CapacityAdmissionTestFixture.playerRequest(); + client.commit(request, deadline()); + observedNanos.set(0); try (var context = Context.current().withDeadlineAfter(incomingMillis, TimeUnit.MILLISECONDS, scheduler)) { var result = @@ -255,9 +257,9 @@ void successfulRpcPropagatesMinimumOfExplicitIncomingAndMaximumDeadline( request, CapacityAdmissionTestFixture.NOW.toEpochMilli() + explicitMillis)); assertThat(result.identity()).isEqualTo(request.identity()); } - assertThat(calls).hasValue(1); + assertThat(calls).hasValue(2); assertThat(observedNanos.get()) - .isPositive() + .isGreaterThan(TimeUnit.MILLISECONDS.toNanos(expectedMaximumMillis - 1_000L)) .isLessThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(expectedMaximumMillis)); } finally { scheduler.shutdownNow(); From 7911ac51abd8320e6ba20fb6d51dcc644b4412a8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:02:08 +1300 Subject: [PATCH 13/96] fix(ci): accept proven metadata-only validation shapes --- .../workflows/publish-pr-runtime-images.yml | 29 +++++++++++++- .../pr-required-gate-context-contract.sh | 39 +++++++++++++++++-- 2 files changed, 63 insertions(+), 5 deletions(-) diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index a0dc57799a..9cd929ef21 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -128,11 +128,36 @@ jobs: if (!matchesCi(ciNative)) return; const jobs = await github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", {...context.repo, run_id: ci.id, attempt_number: ci.run_attempt, per_page: 100}); + const metadataName = "PR Metadata Edit (Validation Gate)"; + const metadataExpression = "github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Validation Gate)' || 'Validation Gate'"; + const normalizedName = name => { + if (typeof name !== "string") return ""; + const trimmed = name.trim(); + const wrapped = trimmed.match(/^\$\{\{([\s\S]*)\}\}$/); + return (wrapped ? wrapped[1].trim() : trimmed).replace(/\s+/g, " "); + }; + const metadata = jobs.filter(job => job.name === metadataName || + normalizedName(job.name) === metadataExpression); + const checkPrefix = `https://api.github.com/repos/${repository}/check-runs/`; + const nativeJob = job => job && positive(job.id) && job.run_id === ci.id && + job.run_attempt === ci.run_attempt && job.head_sha === head && + [ciWorkflow.name, ciTitle].includes(job.workflow_name) && job.status === "completed" && + typeof job.check_run_url === "string" && job.check_run_url.startsWith(checkPrefix) && + /^[1-9][0-9]*$/.test(job.check_run_url.slice(checkPrefix.length)); const gates = jobs.filter(job => job.name === "Validation Gate"); + if (metadata.length) { + // Only one positively skipped native metadata job can be ignored. + // Unknown/mixed identities must never reveal an older CI result. + if (metadata.length !== 1 || gates.length || !nativeJob(metadata[0]) || + metadata[0].conclusion !== "skipped") return; + const {data: latestMetadata} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); + if (!matchesCi(latestMetadata)) return; + ci = null; + continue; + } const gate = gates.length === 1 ? gates[0] : null; const preservation = gate?.steps?.filter(step => step.name === "Preserve successful required gate on metadata-only edit") || []; const enforcement = gate?.steps?.filter(step => step.name === "Enforce validation success") || []; - const checkPrefix = `https://api.github.com/repos/${repository}/check-runs/`; if (!gate || !positive(gate.id) || gate.run_id !== ci.id || gate.run_attempt !== ci.run_attempt || gate.head_sha !== head || ![ciWorkflow.name, ciTitle].includes(gate.workflow_name) || gate.status !== "completed" || typeof gate.check_run_url !== "string" || !gate.check_run_url.startsWith(checkPrefix) || @@ -147,6 +172,8 @@ jobs: gate.check_run_url.startsWith(checkPrefix) && /^[1-9][0-9]*$/.test(gate.check_run_url.slice(checkPrefix.length)) && preservation.length === 1 && preservation[0].status === "completed" && preservation[0].conclusion === "success" && enforcement.length === 1 && enforcement[0].status === "completed" && enforcement[0].conclusion === "skipped") { + const {data: latestMetadata} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); + if (!matchesCi(latestMetadata)) return; ci = null; continue; } diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 8c7c247d4d..5c7c7efb79 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -4191,22 +4191,25 @@ async function run(kind, shared = {visible: false, posts: 0}) { if (kind === "nested-callback") event.event = "workflow_run"; if (kind === "fork") event.head_repository.full_name = "fork/repo"; if (kind === "success") event.conclusion = "success"; - let clock = 0, tupleReads = 0, sourceReads = 0; + let clock = 0, tupleReads = 0, sourceReads = 0, metadataReads = 0; const github = {rest: { actions: { getWorkflow: async ({workflow_id}) => ({data: workflow_id === "ci.yml" ? {id: 8, path: ".github/workflows/ci.yml", name: "CI — Validation"} : {id: 7, path: source.path, name: source.name}}), getWorkflowRun: async ({run_id}) => { - if (run_id === 90 || run_id === 91) return {data: {...ci, id: run_id, ...(kind === "ci-rerun" ? {run_attempt: 2} : {})}}; + if (run_id === 91) metadataReads++; + if (run_id === 90 || run_id === 91) return {data: {...ci, id: run_id, + ...(kind === "ci-rerun" || ["new-meta-rerun", "old-meta-rerun"].includes(kind) && run_id === 91 && metadataReads > 1 ? {run_attempt: 2} : {})}}; sourceReads++; return {data: {...source, ...((kind === "stale-attempt" || kind === "late-rerun" && sourceReads > 1) ? {run_attempt: 2} : {})}}; }, listWorkflowRuns: async ({workflow_id, page, event: runEvent}) => { let runs = workflow_id === "ci.yml" ? [{...ci, ...(kind === "ci-pending" ? {status: "in_progress"} : {})}] : shared.visible ? [refresh] : []; - if (workflow_id === "ci.yml" && ["metadata-newer", "unclassified-newer", "pending-newer"].includes(kind)) { + if (workflow_id === "ci.yml" && (["metadata-newer", "old-meta-rerun", "unclassified-newer", "pending-newer"].includes(kind) || kind.startsWith("new-meta"))) { runs = [{...ci, id: 91, ...(kind === "pending-newer" ? {status: "in_progress"} : {})}, ci]; + if (kind === "new-meta-only") runs = runs.slice(0, 1); } if (workflow_id === "runtime-images.yml" && runEvent === "pull_request") { runs = kind === "newer-original" ? [{...source, id: 105, status: "in_progress"}] : [source]; @@ -4232,7 +4235,27 @@ async function run(kind, shared = {visible: false, posts: 0}) { }, }, }, paginate: async (_route, request) => { - const metadata = kind === "metadata" || kind === "metadata-newer" && request.run_id === 91; + assert.equal(_route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); + assert.equal(request.attempt_number, 1); + if (kind.startsWith("new-meta") && request.run_id === 91) { + const expression = "github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Validation Gate)' || 'Validation Gate'"; + const job = {id: 31, run_id: 91, run_attempt: 1, head_sha: head, + name: kind === "new-meta-expression" ? expression : kind === "new-meta-wrapped" ? "${{ " + expression + " }}" : "PR Metadata Edit (Validation Gate)", + workflow_name: "CI — Validation", status: "completed", conclusion: "skipped", + check_run_url: `https://api.github.com/repos/${repository}/check-runs/31`}; + if (kind === "new-meta-wrong-attempt") job.run_attempt = 2; + if (kind === "new-meta-wrong-head") job.head_sha = base; + if (kind === "new-meta-wrong-url") job.check_run_url = "https://api.github.com/repos/foreign/repo/check-runs/31"; + if (kind === "new-meta-pending") job.status = "in_progress"; + if (kind === "new-meta-success") job.conclusion = "success"; + if (kind === "new-meta-unknown") job.name = "unknown " + expression; + if (kind === "new-meta-open-wrapper") job.name = "${{ " + expression; + if (kind === "new-meta-close-wrapper") job.name = expression + " }}"; + if (kind === "new-meta-duplicate") return [job, {...job, id: 32}]; + if (kind === "new-meta-mixed") return [job, {...job, id: 32, name: "Validation Gate"}]; + return [job]; + } + const metadata = kind === "metadata" || ["metadata-newer", "old-meta-rerun"].includes(kind) && request.run_id === 91; return [{id: 30, run_id: request.run_id, run_attempt: 1, head_sha: head, name: "Validation Gate", workflow_name: "CI — Validation", status: "completed", check_run_url: `https://api.github.com/repos/${repository}/check-runs/30`, steps: kind === "unclassified-newer" && request.run_id === 91 ? [] : [ @@ -4249,6 +4272,14 @@ async function run(kind, shared = {visible: false, posts: 0}) { (async () => { assert.equal(await run("valid"), 1); assert.equal(await run("metadata-newer"), 1, "proven metadata completion cannot hide substantive CI"); + for (const scenario of ["new-meta", "new-meta-expression", "new-meta-wrapped"]) { + assert.equal(await run(scenario), 1, scenario); + } + for (const scenario of ["new-meta-only", "new-meta-wrong-attempt", "new-meta-wrong-head", "new-meta-wrong-url", + "new-meta-pending", "new-meta-success", "new-meta-unknown", "new-meta-duplicate", "new-meta-mixed", "new-meta-rerun", + "old-meta-rerun", "new-meta-open-wrapper", "new-meta-close-wrapper"]) { + assert.equal(await run(scenario), 0, scenario); + } assert.equal(await run("merge-pending"), 1, "mergeability may converge without tuple changes"); for (const scenario of ["typed-callback", "nested-callback", "fork", "success", "stale-attempt", "late-rerun", "ci-rerun", "ci-pending", "metadata", "late-drift", "second-page", "newer-original", "unclassified-newer", "pending-newer", "merge-unknown", "merge-conflict", "merge-drift"]) { assert.equal(await run(scenario), 0, scenario); From 325980fc2a782e841d5fea435b4556f09440f096 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:33:11 +1300 Subject: [PATCH 14/96] fix(ci): verify runtime recovery against authoritative live tuple --- .../workflows/publish-pr-runtime-images.yml | 6 +++--- .../tests/pr-required-gate-context-contract.sh | 18 ++++++++++++------ 2 files changed, 15 insertions(+), 9 deletions(-) diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 9cd929ef21..f0210cefc0 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -65,16 +65,16 @@ jobs: let pr; for (let attempt = 0; attempt < 6; attempt++) { ({data: pr} = await github.rest.pulls.get({...context.repo, pull_number: Number(number)})); - if (pr.state !== "open" || pr.head?.sha !== head || pr.base?.sha !== base || + if (pr.state !== "open" || pr.head?.sha !== head || pr.mergeable !== null || attempt === 5) break; await new Promise(resolve => setTimeout(resolve, 2000)); } if (pr.state !== "open" || pr.head?.repo?.full_name !== repository || pr.base?.repo?.full_name !== repository || - pr.head?.sha !== head || pr.head?.ref !== event.head_branch || pr.base?.sha !== base || + pr.head?.sha !== head || pr.head?.ref !== event.head_branch || typeof pr.base?.ref !== "string" || !pr.base.ref || pr.mergeable !== true || pr.merge_commit_sha !== merge) return null; const {data: ref} = await github.rest.git.getRef({...context.repo, ref: `heads/${pr.base.ref}`}); const {data: commit} = await github.rest.repos.getCommit({...context.repo, ref: merge}); - if (ref.object?.sha !== base || commit.sha !== merge || commit.parents?.length !== 2 || + if (ref.ref !== `refs/heads/${pr.base.ref}` || ref.object?.sha !== base || commit.sha !== merge || commit.parents?.length !== 2 || commit.parents[0]?.sha !== base || commit.parents[1]?.sha !== head) return null; return pr.base.ref; }; diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 5c7c7efb79..40eceb0855 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -4222,13 +4222,15 @@ async function run(kind, shared = {visible: false, posts: 0}) { }, pulls: {get: async () => { tupleReads++; return {data: {state: "open", mergeable: kind === "merge-conflict" ? false : kind === "merge-unknown" || kind === "merge-drift" || kind === "merge-pending" && tupleReads === 1 ? null : true, - merge_commit_sha: merge, - head: {sha: head, ref: "feature", repo: {full_name: repository}}, - base: {ref: "develop", sha: (kind === "late-drift" || kind === "merge-drift") && tupleReads > 1 ? head : base, repo: {full_name: repository}}}};}}, - git: {getRef: async () => ({data: {object: {sha: base}}})}, + merge_commit_sha: kind === "merge-moved" ? head : merge, + head: {sha: kind === "head-moved" ? base : head, ref: "feature", repo: {full_name: repository}}, + base: {ref: kind === "base-ref-moved" && tupleReads > 1 ? "main" : "develop", sha: kind === "cached-base-stale" || kind === "merge-drift" && tupleReads > 1 ? head : base, repo: {full_name: repository}}}};}}, + git: {getRef: async ({ref}) => ({data: {ref: `refs/${kind === "wrong-ref" ? "heads/main" : ref}`, object: {sha: kind === "ref-moved" || kind === "late-drift" && tupleReads > 1 ? head : base}}})}, repos: { - getCommit: async () => ({data: {sha: merge, parents: [{sha: base}, {sha: head}]}}), - createDispatchEvent: async () => { + getCommit: async () => ({data: {sha: merge, parents: kind === "parents-reversed" ? [{sha: head}, {sha: base}] : [{sha: base}, {sha: head}]}}), + createDispatchEvent: async (request) => { + assert.deepEqual(request, {owner: "example", repo: "firemud", event_type: "pr-runtime-base-refresh", + client_payload: {pr_number: "42", base_ref: "develop", base_sha: base, head_sha: head, merge_sha: merge}}); shared.posts++; if (kind === "ambiguous-post") throw new Error("unknown POST outcome"); if (kind !== "invisible") shared.visible = true; @@ -4280,6 +4282,10 @@ async function run(kind, shared = {visible: false, posts: 0}) { "old-meta-rerun", "new-meta-open-wrapper", "new-meta-close-wrapper"]) { assert.equal(await run(scenario), 0, scenario); } + assert.equal(await run("cached-base-stale"), 1, "live ref and ordered parents override cached PR base SHA"); + for (const scenario of ["head-moved", "merge-moved", "ref-moved", "wrong-ref", "parents-reversed", "base-ref-moved"]) { + assert.equal(await run(scenario), 0, scenario); + } assert.equal(await run("merge-pending"), 1, "mergeability may converge without tuple changes"); for (const scenario of ["typed-callback", "nested-callback", "fork", "success", "stale-attempt", "late-rerun", "ci-rerun", "ci-pending", "metadata", "late-drift", "second-page", "newer-original", "unclassified-newer", "pending-newer", "merge-unknown", "merge-conflict", "merge-drift"]) { assert.equal(await run(scenario), 0, scenario); From ab092d12203cb8c39593c5e5fb6b849ae3c0e0c4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:44:25 +1300 Subject: [PATCH 15/96] fix(ci): bind smoke exception acceptance to selected producer --- .github/workflows/smoke.yml | 21 ++++++---- .../pr-required-gate-context-contract.sh | 39 ++++++++++++++++--- 2 files changed, 48 insertions(+), 12 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 58db1bea31..12033df969 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -1146,7 +1146,7 @@ jobs: // independently verified current tuple's trusted refresh. const validEventTuple = /^[0-9a-f]{40}$/.test(eventBaseSha ?? "") && /^[0-9a-f]{40}$/.test(eventMergeSha ?? ""); - const mergeCommit = validEventTuple + const mergeCommit = !requireCurrent && validEventTuple ? await immutableCommit(eventMergeSha, "event test-merge lookup") : null; const parents = mergeCommit?.parents ?? []; @@ -1450,11 +1450,13 @@ jobs: core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); } if (knownPlayVerified) { + const selectedProofRun = verifiedRefreshRun ?? matching; + const needsLiveTuple = refreshVerified || matching.event === "repository_dispatch"; const freshIdentity = await resolveCurrentIdentity( - "Stopping stale canonical transition PLAY exception", requireCurrentIdentity || refreshVerified); + "Stopping stale canonical transition PLAY exception", requireCurrentIdentity || needsLiveTuple); // Original event proof keeps its immutable tuple semantics. Refreshed // proof additionally requires the live base and test merge right now. - const comparableFreshIdentity = refreshVerified && freshIdentity + const comparableFreshIdentity = needsLiveTuple && freshIdentity ? {...freshIdentity, sourceEvent: currentIdentity.sourceEvent} : freshIdentity; if (freshIdentity?.obsolete) return; @@ -1464,7 +1466,7 @@ jobs: continue smokeGatePolling; } if (identityKey(comparableFreshIdentity) !== identityKey(currentIdentity)) { - if (refreshVerified) requireCurrentIdentity = true; + if (needsLiveTuple) requireCurrentIdentity = true; currentIdentity = freshIdentity; continue smokeGatePolling; } @@ -1472,7 +1474,7 @@ jobs: core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); return; } - if (!await isCurrentCanonicalAttempt(verifiedRefreshRun ?? matching)) { + if (!await isCurrentCanonicalAttempt(selectedProofRun)) { await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } @@ -1617,9 +1619,14 @@ jobs: core.setFailed("Canonical PLAY transition exception could not be verified; runtime qualification remains blocked."); return; } - const freshIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception", requireCurrentIdentity); + const needsLiveTuple = matching.event === "repository_dispatch"; + const freshIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception", requireCurrentIdentity || needsLiveTuple); + const comparableFreshIdentity = needsLiveTuple && freshIdentity + ? {...freshIdentity, sourceEvent: currentIdentity.sourceEvent} + : freshIdentity; if (freshIdentity?.obsolete) return; - if (!freshIdentity || identityKey(freshIdentity) !== identityKey(currentIdentity)) { + if (!freshIdentity || identityKey(comparableFreshIdentity) !== identityKey(currentIdentity)) { + if (needsLiveTuple) requireCurrentIdentity = true; currentIdentity = freshIdentity; continue smokeGatePolling; } diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 40eceb0855..8d4dcdd253 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3669,6 +3669,28 @@ async function failedProof(error, event = "pull_request") { assert.match(warnings[0], /^Canonical PLAY transition exception proof is unavailable:/); assert.deepEqual(outputs, []); } +async function selectedProducerFinalFence(event, moved = false) { + const outputs = [], failures = [], required = []; + const core = {warning: () => {}, setFailed: x => failures.push(x), setOutput: (...x) => outputs.push(x)}; + core.summary = {addHeading() {return this;}, addRaw() {return this;}, async write() {}}; + const execute = new Function("fullSmokeJob", "matching", "canonicalSmokeJobName", "currentIdentity", + "verifyKnownPlayFailure", "TerminalGitHubRequestError", "core", "resolveCurrentIdentity", + "identityKey", "isCurrentCanonicalAttempt", "setTimeout", "sleepMs", + `return (async () => { let requireCurrentIdentity = false, iterations = 0; + smokeGatePolling: while (iterations++ < 1) { ${failedBranch} break; } })();`); + await execute(candidate, {...source, event}, canonicalSmokeJobName, identity, async () => true, + TerminalGitHubRequestError, core, async (_label, current) => { + required.push(current); + return {...identity, canonicalPlayEligible: true, + ...(current ? {sourceEvent: "repository_dispatch"} : {}), + ...(current && moved ? {baseSha: "e".repeat(40), mergeSha: "f".repeat(40)} : {})}; + }, selected => { const {canonicalPlayEligible, ...tuple} = selected; return JSON.stringify(tuple); }, + async () => true, resolve => resolve(), 0); + assert.deepEqual(required, [event === "repository_dispatch"]); + assert.deepEqual(failures, []); + assert.equal(outputs.length, event === "repository_dispatch" && moved ? 0 : 1, + "selected typed producer must reject base movement after proof, original retains immutable event semantics"); +} // Execute the failed-run branch so proof errors retain the deterministic failure diagnostic. const legacyFailedStart = script.indexOf('if (matching.conclusion !== "success")'); const legacyFailedEnd = script.indexOf("const latestIdentity", legacyFailedStart); @@ -3841,7 +3863,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { : expires ? statuses.length : statuses.length - 1); } // Exercise the real resolver, not merely a stub that honors requireCurrent. -async function refreshFinalIdentity() { +async function refreshFinalIdentity(eventUnavailable = false) { const start = script.indexOf("async function resolveCurrentIdentity("); const end = script.indexOf("async function isCurrentPullRequestObsolete", start); const resolver = script.slice(start, end); @@ -3857,16 +3879,18 @@ async function refreshFinalIdentity() { git: {getRef: async () => ({data: {object: {sha: movedBase}}})}, }}, "benhook1013", "FireMUD", "3390", () => false, () => {}, TerminalGitHubRequestError, {info: () => {}, warning: () => {}}, identity.baseSha, identity.mergeSha, identity.headSha, - identity.baseRef, async sha => ({sha, parents: [{sha: sha === movedMerge ? movedBase : identity.baseSha}, - {sha: identity.headSha}]}), repositoryName); - assert.equal((await resolve("original")).mergeSha, identity.mergeSha); + identity.baseRef, async sha => { + if (eventUnavailable && sha === identity.mergeSha) throw new Error("old event commit unavailable"); + return {sha, parents: [{sha: sha === movedMerge ? movedBase : identity.baseSha}, {sha: identity.headSha}]}; + }, repositoryName); + if (!eventUnavailable) assert.equal((await resolve("original")).mergeSha, identity.mergeSha); const fresh = await resolve("refresh", true); assert.equal(fresh.baseSha, movedBase); assert.equal(fresh.mergeSha, movedMerge); assert.equal(fresh.canonicalPlayEligible, true); livePull.labels = []; assert.equal((await resolve("withdrawn refresh", true)).canonicalPlayEligible, false); - assert.equal((await resolve("withdrawn direct event")).canonicalPlayEligible, false); + if (!eventUnavailable) assert.equal((await resolve("withdrawn direct event")).canonicalPlayEligible, false); } const markerExpression = fs.readFileSync(process.argv[2] + ".marker", "utf8").trim().slice(3, -2); const markerValues = { @@ -4006,6 +4030,11 @@ function markerAccepted(overrides = {}) { await pendingRefreshCaller(["absent", "absent"], true); await pendingRefreshCaller(["completed"], false, {originalError: Object.assign(new Error("missing"), {status: 404})}); await refreshFinalIdentity(); + await refreshFinalIdentity(true); + for (const event of ["pull_request", "repository_dispatch"]) { + await selectedProducerFinalFence(event); + await selectedProducerFinalFence(event, true); + } await pendingRefreshCaller(["completed"], true, {finalIdentity: {baseSha: "d".repeat(40)}}); await pendingRefreshCaller(["completed"], true, {finalIdentity: {mergeSha: "e".repeat(40)}}); await pendingRefreshCaller(["completed", "completed"], false, { From fc17e2b85b50998d5bc7d6f96ce803d5b363b233 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:57:00 +1300 Subject: [PATCH 16/96] fix(ci): recheck validation selection before recovery dispatch --- .../workflows/publish-pr-runtime-images.yml | 126 ++++++++++-------- .../pr-required-gate-context-contract.sh | 18 ++- 2 files changed, 82 insertions(+), 62 deletions(-) diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index f0210cefc0..81cf404d4e 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -111,8 +111,6 @@ jobs: throw new Error("Untrusted CI workflow identity"); } const ciTitle = `CI — Validation pr-${number} base-${base} head-${head}`; - const ciRuns = (await inventory("ci.yml", {event: "pull_request", head_sha: head})) - .filter(run => run.display_title === ciTitle).sort((a, b) => b.id - a.id); let ci; const matchesCi = run => run && run.id === ci?.id && run.run_attempt === ci?.run_attempt && positive(run.run_attempt) && run.workflow_id === ciWorkflow.id && matchesPath(run.path, ciWorkflow.path) && @@ -120,67 +118,74 @@ jobs: run.repository?.full_name === repository && run.head_repository?.full_name === repository && run.head_sha === head && run.head_branch === event.head_branch && run.display_title === ciTitle && [ciWorkflow.name, ciTitle].includes(run.name); - // Metadata-only completions cannot conceal an earlier substantive attempt for this exact tuple. - for (const candidate of ciRuns) { - ci = candidate; - if (!positive(ci.id) || !matchesCi(ci)) return; // Unfinished/new unclassified CI owns its later callback. - const {data: ciNative} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); - if (!matchesCi(ciNative)) return; - const jobs = await github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", - {...context.repo, run_id: ci.id, attempt_number: ci.run_attempt, per_page: 100}); - const metadataName = "PR Metadata Edit (Validation Gate)"; - const metadataExpression = "github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Validation Gate)' || 'Validation Gate'"; - const normalizedName = name => { - if (typeof name !== "string") return ""; - const trimmed = name.trim(); - const wrapped = trimmed.match(/^\$\{\{([\s\S]*)\}\}$/); - return (wrapped ? wrapped[1].trim() : trimmed).replace(/\s+/g, " "); - }; - const metadata = jobs.filter(job => job.name === metadataName || - normalizedName(job.name) === metadataExpression); - const checkPrefix = `https://api.github.com/repos/${repository}/check-runs/`; - const nativeJob = job => job && positive(job.id) && job.run_id === ci.id && - job.run_attempt === ci.run_attempt && job.head_sha === head && - [ciWorkflow.name, ciTitle].includes(job.workflow_name) && job.status === "completed" && - typeof job.check_run_url === "string" && job.check_run_url.startsWith(checkPrefix) && - /^[1-9][0-9]*$/.test(job.check_run_url.slice(checkPrefix.length)); - const gates = jobs.filter(job => job.name === "Validation Gate"); - if (metadata.length) { - // Only one positively skipped native metadata job can be ignored. - // Unknown/mixed identities must never reveal an older CI result. - if (metadata.length !== 1 || gates.length || !nativeJob(metadata[0]) || - metadata[0].conclusion !== "skipped") return; - const {data: latestMetadata} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); - if (!matchesCi(latestMetadata)) return; - ci = null; - continue; - } - const gate = gates.length === 1 ? gates[0] : null; - const preservation = gate?.steps?.filter(step => step.name === "Preserve successful required gate on metadata-only edit") || []; - const enforcement = gate?.steps?.filter(step => step.name === "Enforce validation success") || []; - if (!gate || !positive(gate.id) || gate.run_id !== ci.id || gate.run_attempt !== ci.run_attempt || - gate.head_sha !== head || ![ciWorkflow.name, ciTitle].includes(gate.workflow_name) || gate.status !== "completed" || - typeof gate.check_run_url !== "string" || !gate.check_run_url.startsWith(checkPrefix) || - !/^[1-9][0-9]*$/.test(gate.check_run_url.slice(checkPrefix.length)) || - preservation.length !== 1 || preservation[0].status !== "completed" || preservation[0].conclusion !== "skipped" || - enforcement.length !== 1 || enforcement[0].status !== "completed" || - !["success", "failure"].includes(enforcement[0].conclusion)) { - // Skip only proven metadata preservation, never malformed or unfinished evidence. - if (gate && positive(gate.id) && gate.run_id === ci.id && gate.run_attempt === ci.run_attempt && - gate.head_sha === head && [ciWorkflow.name, ciTitle].includes(gate.workflow_name) && - gate.status === "completed" && typeof gate.check_run_url === "string" && - gate.check_run_url.startsWith(checkPrefix) && /^[1-9][0-9]*$/.test(gate.check_run_url.slice(checkPrefix.length)) && - preservation.length === 1 && preservation[0].status === "completed" && preservation[0].conclusion === "success" && - enforcement.length === 1 && enforcement[0].status === "completed" && enforcement[0].conclusion === "skipped") { + const selectCi = async () => { + ci = null; + const ciRuns = (await inventory("ci.yml", {event: "pull_request", head_sha: head})) + .filter(run => run.display_title === ciTitle).sort((a, b) => b.id - a.id); + // Metadata-only completions cannot conceal an earlier substantive attempt for this exact tuple. + for (const candidate of ciRuns) { + ci = candidate; + if (!positive(ci.id) || !matchesCi(ci)) return null; // Unfinished/new unclassified CI owns its later callback. + const {data: ciNative} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); + if (!matchesCi(ciNative)) return null; + const jobs = await github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + {...context.repo, run_id: ci.id, attempt_number: ci.run_attempt, per_page: 100}); + const metadataName = "PR Metadata Edit (Validation Gate)"; + const metadataExpression = "github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Validation Gate)' || 'Validation Gate'"; + const normalizedName = name => { + if (typeof name !== "string") return ""; + const trimmed = name.trim(); + const wrapped = trimmed.match(/^\$\{\{([\s\S]*)\}\}$/); + return (wrapped ? wrapped[1].trim() : trimmed).replace(/\s+/g, " "); + }; + const metadata = jobs.filter(job => job.name === metadataName || + normalizedName(job.name) === metadataExpression); + const checkPrefix = `https://api.github.com/repos/${repository}/check-runs/`; + const nativeJob = job => job && positive(job.id) && job.run_id === ci.id && + job.run_attempt === ci.run_attempt && job.head_sha === head && + [ciWorkflow.name, ciTitle].includes(job.workflow_name) && job.status === "completed" && + typeof job.check_run_url === "string" && job.check_run_url.startsWith(checkPrefix) && + /^[1-9][0-9]*$/.test(job.check_run_url.slice(checkPrefix.length)); + const gates = jobs.filter(job => job.name === "Validation Gate"); + if (metadata.length) { + // Only one positively skipped native metadata job can be ignored. + // Unknown/mixed identities must never reveal an older CI result. + if (metadata.length !== 1 || gates.length || !nativeJob(metadata[0]) || + metadata[0].conclusion !== "skipped") return null; const {data: latestMetadata} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); - if (!matchesCi(latestMetadata)) return; + if (!matchesCi(latestMetadata)) return null; ci = null; continue; } - return; + const gate = gates.length === 1 ? gates[0] : null; + const preservation = gate?.steps?.filter(step => step.name === "Preserve successful required gate on metadata-only edit") || []; + const enforcement = gate?.steps?.filter(step => step.name === "Enforce validation success") || []; + if (!gate || !positive(gate.id) || gate.run_id !== ci.id || gate.run_attempt !== ci.run_attempt || + gate.head_sha !== head || ![ciWorkflow.name, ciTitle].includes(gate.workflow_name) || gate.status !== "completed" || + typeof gate.check_run_url !== "string" || !gate.check_run_url.startsWith(checkPrefix) || + !/^[1-9][0-9]*$/.test(gate.check_run_url.slice(checkPrefix.length)) || + preservation.length !== 1 || preservation[0].status !== "completed" || preservation[0].conclusion !== "skipped" || + enforcement.length !== 1 || enforcement[0].status !== "completed" || + !["success", "failure"].includes(enforcement[0].conclusion)) { + // Skip only proven metadata preservation, never malformed or unfinished evidence. + if (gate && positive(gate.id) && gate.run_id === ci.id && gate.run_attempt === ci.run_attempt && + gate.head_sha === head && [ciWorkflow.name, ciTitle].includes(gate.workflow_name) && + gate.status === "completed" && typeof gate.check_run_url === "string" && + gate.check_run_url.startsWith(checkPrefix) && /^[1-9][0-9]*$/.test(gate.check_run_url.slice(checkPrefix.length)) && + preservation.length === 1 && preservation[0].status === "completed" && preservation[0].conclusion === "success" && + enforcement.length === 1 && enforcement[0].status === "completed" && enforcement[0].conclusion === "skipped") { + const {data: latestMetadata} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); + if (!matchesCi(latestMetadata)) return null; + ci = null; + continue; + } + return null; + } + break; } - break; - } + return ci; + }; + ci = await selectCi(); if (!ci) return; const newerRefresh = async (createdSince = event.created_at) => { const runs = await inventory("runtime-images.yml", {event: "repository_dispatch", created: `${createdSince}..*`}); @@ -197,6 +202,11 @@ jobs: if (typeof event.created_at !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(event.created_at) || !Number.isFinite(Date.parse(event.created_at))) throw new Error("Invalid original run creation timestamp"); if (await newerRefresh()) return; + // Re-list the complete exact-tuple CI inventory before the POST: a newer + // pending/substantive attempt may have appeared since the first selection. + const selectedCi = ci; + const currentCi = await selectCi(); + if (!currentCi || currentCi.id !== selectedCi.id || currentCi.run_attempt !== selectedCi.run_attempt) return; const {data: finalCi} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); if (!matchesCi(finalCi) || !await sourceCurrent() || await originalSuperseded() || await currentTuple() !== baseRef) return; const dispatchStarted = new Date(Date.now() - 1000).toISOString(); diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 8d4dcdd253..ad4f5ca2c2 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -4220,7 +4220,7 @@ async function run(kind, shared = {visible: false, posts: 0}) { if (kind === "nested-callback") event.event = "workflow_run"; if (kind === "fork") event.head_repository.full_name = "fork/repo"; if (kind === "success") event.conclusion = "success"; - let clock = 0, tupleReads = 0, sourceReads = 0, metadataReads = 0; + let clock = 0, tupleReads = 0, sourceReads = 0, metadataReads = 0, ciInventoryReads = 0; const github = {rest: { actions: { getWorkflow: async ({workflow_id}) => ({data: workflow_id === "ci.yml" @@ -4234,12 +4234,16 @@ async function run(kind, shared = {visible: false, posts: 0}) { return {data: {...source, ...((kind === "stale-attempt" || kind === "late-rerun" && sourceReads > 1) ? {run_attempt: 2} : {})}}; }, listWorkflowRuns: async ({workflow_id, page, event: runEvent}) => { + if (workflow_id === "ci.yml") ciInventoryReads++; let runs = workflow_id === "ci.yml" ? [{...ci, ...(kind === "ci-pending" ? {status: "in_progress"} : {})}] : shared.visible ? [refresh] : []; if (workflow_id === "ci.yml" && (["metadata-newer", "old-meta-rerun", "unclassified-newer", "pending-newer"].includes(kind) || kind.startsWith("new-meta"))) { runs = [{...ci, id: 91, ...(kind === "pending-newer" ? {status: "in_progress"} : {})}, ci]; if (kind === "new-meta-only") runs = runs.slice(0, 1); } + if (workflow_id === "ci.yml" && ciInventoryReads > 1 && kind.startsWith("late-ci-")) { + runs = kind === "late-ci-absent" ? [] : [{...ci, id: 91, ...(kind === "late-ci-pending" ? {status: "in_progress"} : {})}, ci]; + } if (workflow_id === "runtime-images.yml" && runEvent === "pull_request") { runs = kind === "newer-original" ? [{...source, id: 105, status: "in_progress"}] : [source]; } @@ -4268,7 +4272,7 @@ async function run(kind, shared = {visible: false, posts: 0}) { }, paginate: async (_route, request) => { assert.equal(_route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); assert.equal(request.attempt_number, 1); - if (kind.startsWith("new-meta") && request.run_id === 91) { + if ((kind.startsWith("new-meta") || kind === "late-ci-new-metadata") && request.run_id === 91) { const expression = "github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Validation Gate)' || 'Validation Gate'"; const job = {id: 31, run_id: 91, run_attempt: 1, head_sha: head, name: kind === "new-meta-expression" ? expression : kind === "new-meta-wrapped" ? "${{ " + expression + " }}" : "PR Metadata Edit (Validation Gate)", @@ -4286,10 +4290,10 @@ async function run(kind, shared = {visible: false, posts: 0}) { if (kind === "new-meta-mixed") return [job, {...job, id: 32, name: "Validation Gate"}]; return [job]; } - const metadata = kind === "metadata" || ["metadata-newer", "old-meta-rerun"].includes(kind) && request.run_id === 91; + const metadata = kind === "metadata" || ["metadata-newer", "old-meta-rerun", "late-ci-old-metadata"].includes(kind) && request.run_id === 91; return [{id: 30, run_id: request.run_id, run_attempt: 1, head_sha: head, name: "Validation Gate", workflow_name: "CI — Validation", status: "completed", check_run_url: `https://api.github.com/repos/${repository}/check-runs/30`, - steps: kind === "unclassified-newer" && request.run_id === 91 ? [] : [ + steps: ["unclassified-newer", "late-ci-unknown"].includes(kind) && request.run_id === 91 ? [] : [ {name: "Preserve successful required gate on metadata-only edit", status: "completed", conclusion: metadata ? "success" : "skipped"}, {name: "Enforce validation success", status: "completed", conclusion: metadata ? "skipped" : "failure"}]}]; }}; @@ -4311,6 +4315,12 @@ async function run(kind, shared = {visible: false, posts: 0}) { "old-meta-rerun", "new-meta-open-wrapper", "new-meta-close-wrapper"]) { assert.equal(await run(scenario), 0, scenario); } + for (const scenario of ["late-ci-pending", "late-ci-substantive", "late-ci-unknown", "late-ci-absent"]) { + assert.equal(await run(scenario), 0, "newer exact CI owns recovery: " + scenario); + } + for (const scenario of ["late-ci-old-metadata", "late-ci-new-metadata"]) { + assert.equal(await run(scenario), 1, "proven newer metadata must not hide selected substantive CI: " + scenario); + } assert.equal(await run("cached-base-stale"), 1, "live ref and ordered parents override cached PR base SHA"); for (const scenario of ["head-moved", "merge-moved", "ref-moved", "wrong-ref", "parents-reversed", "base-ref-moved"]) { assert.equal(await run(scenario), 0, scenario); From 73d24b2736ff49a7c2ce1ec9b1928b02eb447a48 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:57:00 +1300 Subject: [PATCH 17/96] fix(ci): preserve runtime inventory and fanout failure boundaries --- .github/workflows/runtime-images.yml | 24 +++++++--- .github/workflows/smoke.yml | 2 +- .../tests/pr-retarget-workflow-contract.sh | 45 +++++++++++++++++-- 3 files changed, 62 insertions(+), 9 deletions(-) diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 75da17048c..ca1e8252ca 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -710,7 +710,7 @@ jobs: if (!validTimestamp(ciCompletedAt)) return initial; const refinementSince = [...inFlightRuns.map(run => run.created_at), ciCompletedAt] .sort((a, b) => Date.parse(a) - Date.parse(b))[0]; - // The inclusive created lower bound makes the refined pages a complete candidate set without relying on API ordering. + // Refinement can confirm a producer, but cannot prove absence outside its narrower range. const refined = await readInventory(refinementSince); if (!refined.complete) { return { @@ -726,7 +726,7 @@ jobs: reason: "refined inventory did not retain every initially observed in-flight run", }; } - return refined; + return {...refined, absenceProven: false}; }; const findExactExistingProducer = (tuple, inventory) => { @@ -991,6 +991,8 @@ jobs: // The REST contract does not specify a sort order, so a truncated page cannot prove omitted runs are older. existingProducers = []; fallbackReason = inventory.reason || "recent run inventory is incomplete"; + } else if (existingProducers.length === 0 && inventory.absenceProven === false) { + fallbackReason = "truncated initial inventory cannot prove exact producer absence from a narrower refinement"; } } catch (error) { fallbackReason = error.message || String(error); @@ -1010,7 +1012,13 @@ jobs: } else { core.info(`No reusable in-flight exact producer was verified in the bounded recent inventory; dispatching required PR runtime refresh for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); // Refresh tuple custody after preceding fan-out/API work under the shared dispatcher lock. - const current = await resolveExactMerge(tuple.prNumber, tuple.baseRef, tuple.baseSha, tuple.headSha); + let current; + try { + current = await resolveExactMerge(tuple.prNumber, tuple.baseRef, tuple.baseSha, tuple.headSha); + } catch (error) { + core.setFailed(`Cannot verify runtime tuple for PR #${tuple.prNumber}; no dispatch issued: ${error.message || error}`); + break runtimeRefresh; + } if (!current || current.tuple.mergeSha !== tuple.mergeSha) { core.info(`Skipping changed runtime tuple for PR #${tuple.prNumber}.`); continue; @@ -1020,7 +1028,7 @@ jobs: ({data: currentBase} = await github.rest.git.getRef({...context.repo, ref: `heads/${tuple.baseRef}`})); } catch (error) { core.setFailed(`Cannot read current base for PR #${tuple.prNumber}: ${error.message || error}`); - continue; + break runtimeRefresh; } if (currentBase.object?.sha !== tuple.baseSha) { core.info(`Skipping changed runtime tuple for PR #${tuple.prNumber}.`); @@ -1052,7 +1060,13 @@ jobs: core.info(`Skipping PR runtime image refresh for #${tuple.prNumber}: no runtime-changing files.`); } // Preview has its own exact-image proof. An uncertain runtime handoff must not suppress it. - const previewCurrent = await resolveExactMerge(tuple.prNumber, tuple.baseRef, tuple.baseSha, tuple.headSha); + let previewCurrent; + try { + previewCurrent = await resolveExactMerge(tuple.prNumber, tuple.baseRef, tuple.baseSha, tuple.headSha); + } catch (error) { + core.setFailed(`Cannot verify preview tuple for PR #${tuple.prNumber}; no dispatch issued: ${error.message || error}`); + continue; + } if (!previewCurrent || previewCurrent.tuple.mergeSha !== tuple.mergeSha) continue; if (!isPreviewEligible(previewCurrent.pullRequest)) { core.info(`Skipping preview deploy reconciliation for #${tuple.prNumber}: target is not preview-eligible.`); diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 12033df969..386d7c1bb3 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -611,7 +611,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "41ee9bca3d7b982a648384c68471aa5cc7f9a7ff1ef9a9f942c5d4116242aae3"; + const canonicalRuntimeWorkflowSha256 = "db66016c01ef69ff28c6385d96dc545397167d5d4054afb7117892ad7b15c95c"; // Trusted refreshes can still execute the previous successful default-branch definition. const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = "ea6ade0f69718573aeac4e4b5a1e9050e53e1e3cef3426b8791f182d8d49e112"; // Retain the exact fail-red producer still executed by trusted base refreshes. diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index bb7acbcd03..1f86b09dca 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -903,6 +903,8 @@ async function runDispatcher({ const warnings = []; const inventoryCalls = []; const observationPostCounts = []; + const timerPostCounts = []; + let waitedMillis = 0; const eventInventoryCalls = new Map(); const currentBaseSha = tuples[0]?.baseSha ?? baseSha; const allTuples = [...tuples, ...sourceTuples]; @@ -1069,7 +1071,10 @@ async function runDispatcher({ const originalDateNow = Date.now; const originalSetTimeout = global.setTimeout; let fakeNow = Date.parse("2026-01-08T00:00:00Z"); - global.setTimeout = (resolve, millis) => { fakeNow += millis; resolve(); }; + global.setTimeout = (resolve, millis) => { + timerPostCounts.push(dispatches.filter(item => item.event_type === "pr-runtime-base-refresh").length); + waitedMillis += millis; fakeNow += millis; resolve(); + }; Date.now = () => fakeNow; try { await new AsyncFunction("github", "context", "core", dispatcherScript)(github, context, core); @@ -1077,7 +1082,7 @@ async function runDispatcher({ Date.now = originalDateNow; global.setTimeout = originalSetTimeout; } - return { dispatches, errors, infos, warnings, inventoryCalls, observationPostCounts, ciJobRequests, pullListRequests, refRequests }; + return { dispatches, errors, infos, warnings, inventoryCalls, observationPostCounts, timerPostCounts, waitedMillis, ciJobRequests, pullListRequests, refRequests }; } (async () => { @@ -1444,6 +1449,14 @@ async function runDispatcher({ assert.deepEqual(numbers(refinedCompleted), [], "refinement must retain completed refresh between CI completion and sampled inflight floor"); assert(refinedCompleted.inventoryCalls.some(request => request.created === "2026-01-01T06:00:00Z..*")); + const narrowedAbsence = await runDispatcher({ + tuples: [tuple], callback: {updated_at: "2026-01-03T00:00:00Z"}, + inventories: {pull_request: {total_count: 1001, runs: [unrelatedInflight], + refined: [unrelatedInflight], refinedTotalCount: 1}}, + }); + assert.deepEqual(numbers(narrowedAbsence), [], "narrowed empty exact-producer slice cannot exclude older omitted producers"); + assert(narrowedAbsence.errors.some(message => message.includes("truncated initial inventory"))); + for (const args of [ { inventories: { pull_request: { total_count: 1001, runs: overBoundPage, refined: overBoundPage, refinedTotalCount: 1001, @@ -1488,7 +1501,11 @@ async function runDispatcher({ const manyInvisible = await runDispatcher({tuples: many, hideDispatchVisibility: true}); assert.deepEqual(numbers(manyInvisible), many.map(item => item.prNumber), "all eligible targets receive one handoff before the single shared visibility wait"); - assert(manyInvisible.errors.some(message => message.includes("visibility is unknown"))); + assert.deepEqual(manyInvisible.errors.filter(message => message.includes("visibility is unknown")), [ + `Refresh dispatch accepted but visibility is unknown for PRs ${many.map(item => item.prNumber).join(", ")}; no retry issued`, + ], "one timeout must identify every invisible handoff"); + assert.equal(manyInvisible.timerPostCounts[0], 12, "all runtime POSTs precede the first visibility wait"); + assert.equal(manyInvisible.waitedMillis, 120000, "fan-out shares exactly one visibility window"); const previewTuple = {...tuple, labels: [{name: "preview"}]}; const previewUnknown = await runDispatcher({tuples: [previewTuple], apiFailure: "pull_request"}); assert.equal(runtimeDispatches(previewUnknown).length, 0); @@ -1500,6 +1517,28 @@ async function runDispatcher({ "uncertain preview POST is attempted exactly once, never retried"); assert(previewFailed.observationPostCounts.includes(2), "visibility observation runs after the final runtime POST"); assert(!previewFailed.errors.some(message => message.includes("visibility is unknown")), "accepted runtime handoffs still observed after preview failure"); + const runtimeBaseFailure = await runDispatcher({ + tuples: [previewTuple, sibling], branchErrors: {"heads/develop": count => count === 2 ? 502 : null}, + }); + assert.deepEqual(numbers(runtimeBaseFailure), ["102"], "runtime base read failure suppresses only its runtime handoff"); + assert.deepEqual(previewDispatches(runtimeBaseFailure).filter(item => item.client_payload.pr_number === "101").map(item => item.client_payload.pr_number), ["101"], + "preview independently revalidates after runtime-only base failure"); + assert(runtimeBaseFailure.errors.some(message => message.includes("Cannot read current base"))); + for (const failedRead of [2, 3]) { + const lookupFailure = await runDispatcher({ + tuples: [previewTuple, sibling], pullOverrides: {"101": reads => { + if (reads === failedRead) throw new Error("fixture tuple lookup 502"); + return {}; + }}, + }); + assert.deepEqual(numbers(lookupFailure), failedRead === 2 ? ["102"] : ["101", "102"], + "each runtime/preview lookup failure preserves later targets"); + assert.equal(previewDispatches(lookupFailure).filter(item => item.client_payload.pr_number === "101").length, failedRead === 2 ? 1 : 0); + assert(lookupFailure.errors.some(message => message.includes("fixture tuple lookup 502"))); + assert(lookupFailure.observationPostCounts.includes(failedRead === 2 ? 1 : 2), + "accepted handoffs are observed after target lookup failure"); + assert(!lookupFailure.errors.some(message => message.includes("visibility is unknown"))); + } const previewInvisible = await runDispatcher({tuples: [previewTuple], hideDispatchVisibility: true}); assert.equal(previewDispatches(previewInvisible).length, 1, "invisible accepted runtime handoff must preserve preview reconciliation"); process.stdout.write("runtime refresh deduplication fixtures passed\n"); From 87b2821473f6abbd33b32a8e0113bab1f72236b6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:32:52 +1300 Subject: [PATCH 18/96] fix(ci): bound canonical smoke evidence convergence --- .github/workflows/smoke.yml | 59 +++++++++++++----- .../pr-required-gate-context-contract.sh | 60 +++++++++++++++++-- 2 files changed, 100 insertions(+), 19 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 386d7c1bb3..b72fa11bd8 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -854,27 +854,32 @@ jobs: ) ); const producers = jobs.filter((job) => job.name === canonicalSmokeJobName); - if (producers.length !== 1) return false; + if (producers.length > 1 || (producers.length === 0 && !allowIncompleteSteps)) return false; const job = producers[0]; - if ( - !positiveInteger(job.id) || job.id !== candidate.id || - job.run_id !== source.id || job.run_attempt !== source.run_attempt || - job.head_sha !== source.head_sha || job.status !== "completed" || job.conclusion !== source.conclusion || - job.check_run_url !== `https://api.github.com/repos/${repositoryName}/check-runs/${job.id}` - ) return false; + let incompleteSteps = !job || job.status !== "completed"; + if (job) { + if (!positiveInteger(job.id) || job.id !== candidate?.id || + job.run_id !== source.id || job.run_attempt !== source.run_attempt || + job.head_sha !== source.head_sha || + job.check_run_url !== `https://api.github.com/repos/${repositoryName}/check-runs/${job.id}`) return false; + if (job.status === "completed") { + if (job.conclusion !== source.conclusion) return false; + } else if (!allowIncompleteSteps || + !["queued", "in_progress", "waiting", "pending", "requested"].includes(job.status) || + job.conclusion != null) return false; + } const expectedSuccessfulSteps = [ "Run credential-free full-stack smoke", "Require successful runtime smoke and authenticated cleanup", ]; const markerName = "Known canonical transition PLAY failure with successful authenticated cleanup"; - const steps = job.steps ?? []; + const steps = job?.steps ?? []; const requiredSteps = new Map([ [markerName, "success"], ["Stop smoke stack", "success"], ["Export fixed-tag preview image artifact", "skipped"], ["Upload preview image artifact", "skipped"], ...expectedSuccessfulSteps.map((name) => [name, source.conclusion]), ]); - let incompleteSteps = false; for (const [name, conclusion] of requiredSteps) { const matches = steps.filter((step) => step.name === name); if (matches.length > 1) return false; @@ -889,7 +894,7 @@ jobs: expectedSuccessfulSteps.includes(step.name)))) return false; } for (const other of jobs) { - if (other.id === job.id) continue; + if (other.id === job?.id) continue; if (["queued", "in_progress", "waiting", "pending", "requested"].includes(other.status)) incompleteSteps = true; else if (other.status !== "completed" || !["success", "skipped"].includes(other.conclusion)) return false; } @@ -1293,13 +1298,25 @@ jobs: currentIdentity ); if (!replacement) { - if (Date.now() - cancelledRunObservedAt >= cancelledReplacementTimeoutMs) { + // Only native same-repository originals eligible for the trusted + // Validation dispatcher reuse its existing prerequisite allowance. + const recoverableCancellation = matching.event === "pull_request" && + matching.repository?.full_name === repositoryName && + matching.head_repository?.full_name === repositoryName && + matching.path === workflowPath && positiveInteger(matching.workflow_id) && + positiveInteger(matching.id) && positiveInteger(matching.run_attempt) && + matching.head_sha === currentIdentity.headSha && matching.display_title === expectedDisplayTitle && + typeof matching.head_branch === "string" && matching.head_branch.length > 0 && + matching.head_branch === context.payload.pull_request.head.ref; + const cancellationDiscoveryMs = recoverableCancellation + ? refreshDiscoveryTimeoutMs : cancelledReplacementTimeoutMs; + if (Date.now() - cancelledRunObservedAt >= cancellationDiscoveryMs) { if (await isCurrentPullRequestObsolete("Stopping obsolete cancelled-run smoke gate for")) { return; } core.setFailed( `Cancelled runtime-images run ${cancelledRunId} has no exact repository_dispatch replacement ` + - `after ${cancelledReplacementTimeoutMs / 60000} minutes` + `after ${cancellationDiscoveryMs / 60000} minutes` ); return; } @@ -1610,12 +1627,26 @@ jobs: markers[0].conclusion === "success") { let knownPlayVerified = false; try { - knownPlayVerified = await verifyKnownPlayFailure(matching, fullSmokeJob, currentIdentity); + knownPlayVerified = await verifyKnownPlayFailure( + matching, fullSmokeJob, currentIdentity, matching.event === "repository_dispatch"); } catch (error) { if (error instanceof TerminalGitHubRequestError) throw error; core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); } - if (!knownPlayVerified) { + if (knownPlayVerified === "snapshot-pending") { + const snapshotKey = `successful:${matching.id}:${matching.run_attempt}:${identityKey(currentIdentity)}`; + if (incompleteRefreshKey !== snapshotKey) { + incompleteRefreshKey = snapshotKey; + incompleteRefreshObservedAt = Date.now(); + } + if (Date.now() - incompleteRefreshObservedAt >= completedSnapshotTimeoutMs) { + core.setFailed("Terminal canonical refresh did not expose complete smoke-job proof within the snapshot convergence allowance."); + return; + } + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + if (knownPlayVerified !== true) { core.setFailed("Canonical PLAY transition exception could not be verified; runtime qualification remains blocked."); return; } diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index ad4f5ca2c2..7100f846e4 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -622,7 +622,7 @@ assert.equal(cancellationInventory.length, 13); assert.deepEqual([...cancellationInventory].sort(), canonicalCancellationInventory.sort(), "bounded cancellation inventory must match all canonical runtime workflow job names"); const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, - payload: { pull_request: { number: 42, head: { sha: head, repo: {full_name: "example/firemud"}}, + payload: { pull_request: { number: 42, head: { sha: head, ref: "feature", repo: {full_name: "example/firemud"}}, base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); async function scenario(outcome, completedAtMinutes, selectionCase = "single") { @@ -666,12 +666,21 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single") { github.paginate.iterator = async function* (method, input) { assert.equal(method, listRuns); assert.equal(input.workflow_id, "runtime-images.yml"); - if (input.event === "repository_dispatch") { yield { data: [] }; return; } + if (input.event === "repository_dispatch") { + const ready = selectionCase === "recoverable-delayed" && now - start >= 6 * 60 * 1000; + yield {data: ready ? [{id: 44, workflow_id: 7, run_attempt: 1, event: "repository_dispatch", + head_sha: "d".repeat(40), head_branch: "develop", display_title: title, + status: "completed", conclusion: "success", created_at: "2026-09-01T00:00:01Z"}] : []}; + return; + } assert.equal(input.head_sha, head); const complete = now - start >= completedAtMinutes * 60 * 1000; const makeRun = (id, createdAt, status, conclusion) => ({id, workflow_id: 7, run_attempt: 1, event: "pull_request", head_sha: head, display_title: title, created_at: createdAt, - pull_requests: [{number: 42, head: {sha: head}}], status, conclusion}); + pull_requests: [{number: 42, head: {sha: head}}], status, conclusion, + ...(selectionCase.startsWith("recoverable-") ? {repository: {full_name: "example/firemud"}, + head_repository: {full_name: "example/firemud"}, head_branch: "feature", + path: ".github/workflows/runtime-images.yml"} : {})}); const active = makeRun(42, "2026-09-01T00:00:00Z", complete ? "completed" : "in_progress", complete ? outcome : null); const cancelled = makeRun(43, "2026-09-01T00:00:00Z", "completed", "cancelled"); if (selectionCase === "duplicate" || selectionCase === "cancelled-higher-id") { @@ -753,6 +762,15 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single") { assert.equal(cancelled.failures.length, 1); assert.match(cancelled.failures[0], /cancelled/i); assert.ok(cancelled.minutes <= 5.25, "cancelled source without an exact replacement remains bounded"); + const recoverable = await scenario("cancelled", 0, "recoverable-missing"); + assert.equal(recoverable.minutes, 45, "eligible cancellation reuses existing prerequisite allowance only"); + assert.equal(recoverable.failures.length, 1); + const delayedRecovery = await scenario("cancelled", 0, "recoverable-delayed"); + assert.deepEqual(delayedRecovery.failures, []); + assert.equal(delayedRecovery.minutes, 6, "Validation may dispatch an exact replacement after five minutes"); + const lateCancellation = await scenario("cancelled", 80, "recoverable-missing"); + assert.equal(lateCancellation.minutes, 90, "late cancellation cannot extend global deadline"); + assert.match(lateCancellation.failures[0], /Timed out waiting for the exact/); const deadline = await scenario("success", Infinity); assert.equal(deadline.failures.length, 1); assert.match(deadline.failures[0], /Timed out waiting for the exact/); @@ -3805,7 +3823,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { assert.equal(event, "repository_dispatch"); assert.equal(selected.baseSha, options.finalIdentity.baseSha); assert.equal(selected.mergeSha, options.finalIdentity.mergeSha); - return {...source, event: "repository_dispatch", status: "completed", conclusion: options.directSnapshots ? "failure" : "success"}; + return {...source, event: "repository_dispatch", status: "completed", conclusion: options.successfulSnapshots ? "success" : options.directSnapshots ? "failure" : "success"}; } return original; }, "3390", "test identity", 60, @@ -3824,7 +3842,9 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { if (options.ordinaryAfterDrift) { assert.deepEqual(failures, []); assert.deepEqual(outputs, []); assert.equal(writes, 0); } else if (options.directInvalid) { - assert.deepEqual(failures, ["Runtime images run 99 did not complete successfully: run=failure"]); + assert.deepEqual(failures, [options.successfulSnapshots + ? "Canonical PLAY transition exception could not be verified; runtime qualification remains blocked." + : "Runtime images run 99 did not complete successfully: run=failure"]); assert.deepEqual(outputs, []); assert.equal(writes, 0); } else if (options.rejectedObject) { assert.deepEqual(failures, ["Runtime images run 98 did not complete successfully: run=failure"]); @@ -3954,6 +3974,11 @@ function markerAccepted(overrides = {}) { recoverDrift: true, finalIdentity: {baseSha: "d".repeat(40), mergeSha: "e".repeat(40)}, directSnapshots, snapshotExpires: directSnapshots.length === 4, directInvalid: directSnapshots[0] === "invalid", }); + await pendingRefreshCaller(["completed", "completed", "completed", "completed"], false, { + recoverDrift: true, finalIdentity: {baseSha: "d".repeat(40), mergeSha: "e".repeat(40)}, directSnapshots, + successfulSnapshots: true, + snapshotExpires: directSnapshots.length === 4, directInvalid: directSnapshots[0] === "invalid", + }); } await pendingRefreshCaller(["missing-step", "completed"]); await pendingRefreshCaller(["nonterminal-step", "completed"]); @@ -4029,6 +4054,31 @@ function markerAccepted(overrides = {}) { await pendingRefreshCaller(["missing-job", "pending-job", "completed"]); await pendingRefreshCaller(["absent", "absent"], true); await pendingRefreshCaller(["completed"], false, {originalError: Object.assign(new Error("missing"), {status: 404})}); + for (const change of [ + data => {data.jobs = [];}, + data => {data.jobs[0].status = "in_progress"; data.jobs[0].conclusion = null;}, + ]) { + assert.equal(await verify(change, "repository_dispatch", true, true), "snapshot-pending"); + assert.equal(await verify(change, "repository_dispatch", true, false), false); + for (const invalidate of [ + data => {data.currentPullRequest.labels = [];}, + data => {data.currentPullRequest.head.sha = "e".repeat(40);}, + data => {data.currentBase.object.sha = "e".repeat(40);}, + data => {data.latest.run_attempt++;}, + data => {data.definitions[workflowPath].size++;}, + ]) { + assert.equal(await verify(data => {change(data); invalidate(data);}, "repository_dispatch", true, true), false, + "incomplete producer must not hide failed identity/definition/currentness"); + } + } + for (const invalidate of [ + data => {data.jobs.push({...data.jobs[0], id: 124});}, + data => {data.jobs[0].head_sha = "e".repeat(40);}, + data => {data.jobs[0].conclusion = "failure";}, + data => {data.jobs[0].status = "unrecognized";}, + data => {data.jobs[0].status = "in_progress";}, + ]) assert.equal(await verify(invalidate, "repository_dispatch", true, true), false, + "duplicates, provenance, terminal mismatch and contradictory nonterminal conclusion never become pending"); await refreshFinalIdentity(); await refreshFinalIdentity(true); for (const event of ["pull_request", "repository_dispatch"]) { From dc998e2bfd53db751f9b536d3365fff526e9428e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:15:54 +1300 Subject: [PATCH 19/96] fix(ci): narrow accepted runtime refresh observation --- .github/workflows/runtime-images.yml | 94 ++++++++++--------- .github/workflows/smoke.yml | 2 +- .../tests/pr-retarget-workflow-contract.sh | 35 +++++++ 3 files changed, 86 insertions(+), 45 deletions(-) diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index ca1e8252ca..42ae6318ce 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -642,47 +642,52 @@ jobs: return null; }; - const loadExistingRuntimeRuns = async () => { - const readInventory = async (createdSince) => { - const inventory = []; - let complete = true; - let incompleteReason = null; - for (const event of runtimeRunEvents) { - let total; - const eventRuns = [], ids = new Set(); - for (let page = 1; page <= 10; page += 1) { - const response = await github.rest.actions.listWorkflowRuns({ - ...context.repo, workflow_id: "runtime-images.yml", event, - created: `${createdSince}..*`, per_page: runtimeRunPageSize, page, - }); - const payload = response?.data; - total ??= payload?.total_count; - if (!Number.isInteger(total) || total < 0 || !Array.isArray(payload?.workflow_runs) || - payload.total_count !== total) throw new Error(`runtime-images ${event} inventory shifted or is malformed`); - if (total >= 1000) { - complete = false; - incompleteReason ??= `runtime-images ${event} exceeds 1000-run bound`; - // Retain this untrusted sample only for the existing conservative in-flight refinement. - // It is never treated as a complete inventory or dispatch authority. - eventRuns.push(...payload.workflow_runs); - break; - } - if (payload.workflow_runs.length !== Math.min(runtimeRunPageSize, total - eventRuns.length)) { - throw new Error(`runtime-images ${event} recent run inventory is incomplete`); - } - for (const run of payload.workflow_runs) { - if (!Number.isSafeInteger(run.id) || run.id <= 0 || ids.has(run.id)) { - throw new Error(`runtime-images ${event} inventory has duplicate or invalid run IDs`); - } - ids.add(run.id); eventRuns.push(run); + const validTimestamp = (value) => typeof value === "string" && + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(value) && + Number.isFinite(Date.parse(value)); + + const readInventory = async (createdSince, events = runtimeRunEvents) => { + const inventory = []; + let complete = true; + let incompleteReason = null; + for (const event of events) { + let total; + const eventRuns = [], ids = new Set(); + for (let page = 1; page <= 10; page += 1) { + const response = await github.rest.actions.listWorkflowRuns({ + ...context.repo, workflow_id: "runtime-images.yml", event, + created: `${createdSince}..*`, per_page: runtimeRunPageSize, page, + }); + const payload = response?.data; + total ??= payload?.total_count; + if (!Number.isInteger(total) || total < 0 || !Array.isArray(payload?.workflow_runs) || + payload.total_count !== total) throw new Error(`runtime-images ${event} inventory shifted or is malformed`); + if (total >= 1000) { + complete = false; + incompleteReason ??= `runtime-images ${event} exceeds 1000-run bound`; + // Retain this untrusted sample only for the existing conservative in-flight refinement. + // It is never treated as a complete inventory or dispatch authority. + eventRuns.push(...payload.workflow_runs); + break; + } + if (payload.workflow_runs.length !== Math.min(runtimeRunPageSize, total - eventRuns.length)) { + throw new Error(`runtime-images ${event} recent run inventory is incomplete`); + } + for (const run of payload.workflow_runs) { + if (!Number.isSafeInteger(run.id) || run.id <= 0 || ids.has(run.id)) { + throw new Error(`runtime-images ${event} inventory has duplicate or invalid run IDs`); } - if (eventRuns.length === total) break; + ids.add(run.id); eventRuns.push(run); } - inventory.push(...eventRuns); + if (eventRuns.length === total) break; } - return {complete, runs: inventory, reason: incompleteReason}; - }; + inventory.push(...eventRuns); + } + return {complete, runs: inventory, reason: incompleteReason}; + }; + + const loadExistingRuntimeRuns = async () => { const createdSince = new Date(Date.now() - runtimeRunLookbackMilliseconds).toISOString(); const initial = await readInventory(createdSince); if (initial.complete) { @@ -695,9 +700,6 @@ jobs: return initial; } - const validTimestamp = (value) => typeof value === "string" && - /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(value) && - Number.isFinite(Date.parse(value)); if (inFlightRuns.some((run) => !runtimeRunEvents.includes(run.event) || !Number.isSafeInteger(run.id) || run.id <= 0 || !validTimestamp(run.created_at))) { return { @@ -965,6 +967,7 @@ jobs: } } const pendingVisibility = []; + let visibilitySince; let runtimeInventoryPromise; let runtimeInventoryError = null; for (const resolved of refreshTargets) { @@ -1035,6 +1038,7 @@ jobs: continue; } const previousIds = new Set(inventory?.runs?.map(run => run.id) || []); + const dispatchSince = new Date(Date.now() - 1000).toISOString(); try { await github.rest.repos.createDispatchEvent({ ...context.repo, @@ -1048,7 +1052,8 @@ jobs: }, }); // Collect handoffs first so one slow visibility response cannot starve later PRs. - pendingVisibility.push({tuple, previousIds}); + visibilitySince ??= dispatchSince; + pendingVisibility.push({tuple, previousIds, dispatchSince}); } catch (error) { core.setFailed(`Runtime refresh handoff for PR #${tuple.prNumber} is uncertain; no retry issued: ${error.message || error}`); runtimeInventoryPromise = undefined; @@ -1096,13 +1101,14 @@ jobs: const visibilityDeadline = Date.now() + 120000; while (pendingVisibility.length > 0) { try { - const observed = await loadExistingRuntimeRuns(); + const observed = await readInventory(visibilitySince, ["repository_dispatch"]); if (!observed.complete) throw new Error("Accepted refresh has incomplete visibility; no retry issued"); for (let index = pendingVisibility.length - 1; index >= 0; index--) { - const {tuple, previousIds} = pendingVisibility[index]; + const {tuple, previousIds, dispatchSince} = pendingVisibility[index]; const exactTitle = `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; if (observed.runs.some(run => run.event === "repository_dispatch" && - run.display_title === exactTitle && !previousIds.has(run.id))) pendingVisibility.splice(index, 1); + run.display_title === exactTitle && !previousIds.has(run.id) && + validTimestamp(run.created_at) && Date.parse(run.created_at) >= Date.parse(dispatchSince))) pendingVisibility.splice(index, 1); } } catch (error) { core.setFailed(`Runtime refresh visibility is uncertain; no retry issued: ${error.message || error}`); diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index b72fa11bd8..155253b375 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -611,7 +611,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "db66016c01ef69ff28c6385d96dc545397167d5d4054afb7117892ad7b15c95c"; + const canonicalRuntimeWorkflowSha256 = "9c5525ba20ef046aaadb800b0fdf2adb460e4b0a2baef992938aa7f17fcfa872"; // Trusted refreshes can still execute the previous successful default-branch definition. const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = "ea6ade0f69718573aeac4e4b5a1e9050e53e1e3cef3426b8791f182d8d49e112"; // Retain the exact fail-red producer still executed by trusted base refreshes. diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 1f86b09dca..9978983ebd 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -894,6 +894,7 @@ async function runDispatcher({ tuples, inventories = {}, apiFailure = null, sourceTuples = [], callback = {}, branchHeads = {}, branchErrors = {}, pullOverrides = {}, mergeParents = {}, ciEvidence = {}, hideDispatchVisibility = false, filesByPr = {}, postFailurePr = null, previewFailurePr = null, + visibilityResponse = null, }) { const dispatches = []; const postedRuns = []; @@ -1018,6 +1019,11 @@ async function runDispatcher({ listWorkflowRuns: async (request) => { inventoryCalls.push(request); observationPostCounts.push(dispatches.filter(item => item.event_type === "pr-runtime-base-refresh").length); + if (visibilityResponse && request.created === "2026-01-07T23:59:59.000Z..*") { + assert.equal(request.event, "repository_dispatch"); + const response = visibilityResponse(request, postedRuns); + if (response) return {data: response}; + } if (apiFailure === request.event || (typeof apiFailure === "function" && apiFailure(request, inventoryCalls.length))) { throw new Error("fixture API unavailable"); } @@ -1506,6 +1512,35 @@ async function runDispatcher({ ], "one timeout must identify every invisible handoff"); assert.equal(manyInvisible.timerPostCounts[0], 12, "all runtime POSTs precede the first visibility wait"); assert.equal(manyInvisible.waitedMillis, 120000, "fan-out shares exactly one visibility window"); + const visibilityFloor = "2026-01-07T23:59:59.000Z..*"; + const observations = manyInvisible.inventoryCalls.filter(request => request.created === visibilityFloor); + assert.equal(observations.length, 25, "each five-second observation queries one narrow dispatch page"); + assert(observations.every(request => request.event === "repository_dispatch" && request.page === 1 && request.per_page === 100)); + assert(manyInvisible.inventoryCalls.some(request => request.event === "pull_request" && request.created !== visibilityFloor), + "broad preflight still checks native producers"); + assert(manyInvisible.inventoryCalls.some(request => request.event === "repository_dispatch" && request.created !== visibilityFloor), + "broad preflight still checks existing dispatch producers"); + const multiPageObservation = await runDispatcher({tuples: [tuple], visibilityResponse: ({page}, [posted]) => ({ + total_count: 101, + workflow_runs: page === 1 ? Array.from({length: 100}, (_, index) => ({ + ...posted, id: 700000 + index, display_title: "unrelated" + })) : [posted], + })}); + assert.deepEqual(multiPageObservation.inventoryCalls.filter(request => request.created === visibilityFloor).map(request => request.page), [1, 2]); + assert.equal(multiPageObservation.errors.length, 0, "an exact newly visible dispatch on the second page is accepted"); + const shiftedObservation = await runDispatcher({tuples: [tuple], visibilityResponse: ({page}, [posted]) => ({ + total_count: page === 1 ? 101 : 102, + workflow_runs: page === 1 ? Array.from({length: 100}, (_, index) => ({ + ...posted, id: 700000 + index, display_title: "unrelated" + })) : [posted], + })}); + assert.deepEqual(numbers(shiftedObservation), ["101"], "a shifting observation inventory never retries the accepted POST"); + assert(shiftedObservation.errors.some(error => error.includes("visibility is uncertain"))); + const staleObservation = await runDispatcher({tuples: [tuple], visibilityResponse: (_request, [posted]) => ({ + total_count: 1, workflow_runs: [{...posted, created_at: "2026-01-07T23:59:58Z"}], + })}); + assert.deepEqual(numbers(staleObservation), ["101"], "an out-of-window row cannot confirm or retry an accepted dispatch"); + assert(staleObservation.errors.some(error => error.includes("visibility is unknown"))); const previewTuple = {...tuple, labels: [{name: "preview"}]}; const previewUnknown = await runDispatcher({tuples: [previewTuple], apiFailure: "pull_request"}); assert.equal(runtimeDispatches(previewUnknown).length, 0); From c53733341ff77f655b72ad191b0e43099b0acb8d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:32:40 +1300 Subject: [PATCH 20/96] test(account): require direct sanitized capacity error --- .../service/impl/AccountTenantCapacityGrpcServiceTest.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java index 4646c67d7b..60b858b516 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -12,6 +12,7 @@ import static org.mockito.Mockito.when; import io.grpc.Status; +import io.grpc.StatusRuntimeException; import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; import java.util.UUID; @@ -106,7 +107,10 @@ void invalidDomainRefusalIsSanitizedInternal() { TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); var error = ArgumentCaptor.forClass(Throwable.class); verify(observer).onError(error.capture()); - Status status = Status.fromThrowable(error.getValue()); + Throwable thrown = error.getValue(); + assertThat(thrown).isInstanceOf(StatusRuntimeException.class); + assertThat(thrown.getCause()).isNull(); + Status status = ((StatusRuntimeException) thrown).getStatus(); assertThat(status.getCode()).isEqualTo(Status.Code.INTERNAL); assertThat(status.getDescription()).isNull(); assertThat(status.getCause()).isNull(); From 6e7d225657d5de987ff383ae722dd18f4a8b24dd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:04:34 +1300 Subject: [PATCH 21/96] fix(capacity): retry rearm and preserve exact RPC deadline --- .../service/AccountTenantCapacityOwner.java | 2 +- .../AccountTenantCapacityOwnerTest.java | 31 ++++++++++++++++ .../client/AccountTenantCapacityClient.java | 30 ++++++++-------- .../AccountTenantCapacityClientMtlsTest.java | 35 ++++++++++++++++--- 4 files changed, 77 insertions(+), 21 deletions(-) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index d41db06436..ee825686ee 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -148,7 +148,7 @@ Result rearm(Request prior, Request next, UUID recoveryOwner, long claimFence) { || !Objects.equals( prior.evidence().fields().get("authorityTuple"), next.evidence().fields().get("authorityTuple"))) throw conflict(); - return inTransaction( + return commitWithFreshSnapshot( () -> { lockPlayerAccount(next); Record row = capacity.find(prior.identity()); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index a496e280e9..1993fc61db 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -335,6 +335,37 @@ private static void retainOriginThenAdvanceClock( }); } + @Test + void rearmRetriesSerializationInFreshTransactionThenRechecksAccount() throws Exception { + var f = new Fixture(false, qualifiedRequest(true)); + var next = + new Request( + f.request.identity(), + UUID.randomUUID(), + 2, + f.request.targetNamespace(), + f.request.context(), + f.request.operation(), + f.request.priorShape(), + f.request.requestedShape(), + f.request.evidence(), + f.request.capacityDelta(), + null) + .withDigest(); + var aborted = serializationFailure(); + when(f.accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) + .thenThrow(aborted) + .thenReturn(java.util.Optional.empty()); + var rearm = + AccountTenantCapacityOwner.class.getDeclaredMethod( + "rearm", Request.class, Request.class, UUID.class, long.class); + rearm.setAccessible(true); + assertThatThrownBy(() -> rearm.invoke(f.owner, f.request, next, UUID.randomUUID(), 7L)) + .hasCauseInstanceOf(AccountTenantCapacityRepository.CapacityException.class); + verify(f.accounts, times(2)).findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT); + verify(f.dsl, never()).execute(anyString(), any(Object[].class)); + } + @Test void repeatedSerializationFailuresRetryAndReplayInAFreshTransaction() throws Exception { var f = new Fixture(true); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java index 4d5feeafe7..7977e66532 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java @@ -7,6 +7,8 @@ import io.grpc.StatusRuntimeException; import java.io.IOException; import java.time.Clock; +import java.time.Duration; +import java.time.Instant; import java.util.Objects; import java.util.UUID; import java.util.concurrent.TimeUnit; @@ -71,7 +73,7 @@ public Result commit(Request request, long absoluteDeadlineMillis) { // Anchor conversion near the wall-clock sample, not at invocation entry. A pause // during sampling can only shorten the bound; it must never extend the caller budget. Deadline sampledAt = Deadline.after(0, TimeUnit.NANOSECONDS); - long sampledMillis = clock.millis(); + Instant sampledInstant = clock.instant(); request.requireStructurallyValid(); if (request.context().owner() != TenantCapacityAdmission.Owner.GAME_SESSION || !namespace.equals(request.targetNamespace())) @@ -82,7 +84,7 @@ public Result commit(Request request, long absoluteDeadlineMillis) { sampledAt, Context.current().getDeadline(), absoluteDeadlineMillis, - sampledMillis); + sampledInstant); var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); CommitTenantCapacityAdmissionResponse response; try { @@ -119,19 +121,17 @@ static Deadline selectDeadline( Deadline sampledAt, Deadline incoming, long absoluteDeadlineMillis, - long sampledMillis) { - long maximumMillis = - TimeUnit.SECONDS.toMillis(TenantCapacityAdmissionGrpcCodec.CALL_DEADLINE_SECONDS); - long remainingMillis = 0; - if (absoluteDeadlineMillis > sampledMillis) { - // A positive difference can overflow only across the signed long boundary. - // Such a future deadline is beyond the invocation cap, not an expired budget. - long difference = absoluteDeadlineMillis - sampledMillis; - remainingMillis = difference < 0 ? maximumMillis : Math.min(maximumMillis, difference); - } - Deadline absoluteDeadline = - sampledAt.offset( - Math.max(0L, Math.min(maximumMillis, remainingMillis)), TimeUnit.MILLISECONDS); + Instant sampledInstant) { + Duration maximumBudget = + Duration.ofSeconds(TenantCapacityAdmissionGrpcCodec.CALL_DEADLINE_SECONDS); + Duration remaining = + Duration.between(sampledInstant, Instant.ofEpochMilli(absoluteDeadlineMillis)); + // Cap before converting to nanos: extreme epoch-millisecond deadlines may exceed long nanos. + long remainingNanos = + remaining.isNegative() + ? 0 + : (remaining.compareTo(maximumBudget) > 0 ? maximumBudget : remaining).toNanos(); + Deadline absoluteDeadline = sampledAt.offset(remainingNanos, TimeUnit.NANOSECONDS); Deadline selected = maximum.minimum(absoluteDeadline); return incoming == null ? selected : selected.minimum(incoming); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index 6da4bf40e9..852475be6c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -283,7 +283,8 @@ public long nanoTime() { var incoming = Deadline.after(incomingMillis, TimeUnit.MILLISECONDS, ticker); var sample = Deadline.after(0, TimeUnit.NANOSECONDS, ticker); var selected = - AccountTenantCapacityClient.selectDeadline(maximum, sample, incoming, explicitMillis, 0); + AccountTenantCapacityClient.selectDeadline( + maximum, sample, incoming, explicitMillis, java.time.Instant.EPOCH); assertThat(selected.timeRemaining(TimeUnit.MILLISECONDS)).isEqualTo(expectedMillis); } @@ -302,11 +303,32 @@ public long nanoTime() { var maximum = Deadline.after(5, TimeUnit.SECONDS, ticker); assertThat( AccountTenantCapacityClient.selectDeadline( - maximum, sample, null, absoluteMillis, sampledMillis) + maximum, + sample, + null, + absoluteMillis, + java.time.Instant.ofEpochMilli(sampledMillis)) .timeRemaining(TimeUnit.MILLISECONDS)) .isEqualTo(expectedMillis); } + @Test + void fractionalWallClockSampleDoesNotExtendTheCallerBudget() { + var ticker = + new Deadline.Ticker() { + @Override + public long nanoTime() { + return 0; + } + }; + var sample = Deadline.after(0, TimeUnit.NANOSECONDS, ticker); + var maximum = Deadline.after(5, TimeUnit.SECONDS, ticker); + var selected = + AccountTenantCapacityClient.selectDeadline( + maximum, sample, null, 1001, java.time.Instant.ofEpochMilli(1000).plusNanos(900_000)); + assertThat(selected.timeRemaining(TimeUnit.NANOSECONDS)).isEqualTo(100_000); + } + @Test void setupDelayIsNotDeductedTwiceAndOriginalInvocationCapStillApplies() { var nanos = new AtomicLong(); @@ -321,16 +343,19 @@ public long nanoTime() { nanos.set(TimeUnit.SECONDS.toNanos(1)); // Pause before the paired conversion samples. var sample = Deadline.after(0, TimeUnit.NANOSECONDS, ticker); assertThat( - AccountTenantCapacityClient.selectDeadline(maximum, sample, null, 3000, 1000) + AccountTenantCapacityClient.selectDeadline( + maximum, sample, null, 3000, java.time.Instant.ofEpochMilli(1000)) .timeRemaining(TimeUnit.MILLISECONDS)) .isEqualTo(2000); assertThat( - AccountTenantCapacityClient.selectDeadline(maximum, sample, null, 60000, 1000) + AccountTenantCapacityClient.selectDeadline( + maximum, sample, null, 60000, java.time.Instant.ofEpochMilli(1000)) .timeRemaining(TimeUnit.MILLISECONDS)) .isEqualTo(4000); nanos.addAndGet(TimeUnit.MILLISECONDS.toNanos(200)); // Delay after sampling consumes budget. assertThat( - AccountTenantCapacityClient.selectDeadline(maximum, sample, null, 3000, 1000) + AccountTenantCapacityClient.selectDeadline( + maximum, sample, null, 3000, java.time.Instant.ofEpochMilli(1000)) .timeRemaining(TimeUnit.MILLISECONDS)) .isEqualTo(1800); } From 26e0844fcdfec9f920d8c93d815ef5cd2b5afd95 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:36:34 +1300 Subject: [PATCH 22/96] fix(ci): isolate runtime changed-file lookup failures --- .github/workflows/runtime-images.yml | 10 ++++- .github/workflows/smoke.yml | 2 +- .../tests/pr-retarget-workflow-contract.sh | 45 +++++++++++++------ 3 files changed, 40 insertions(+), 17 deletions(-) diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 42ae6318ce..9e409aae9a 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -972,7 +972,13 @@ jobs: let runtimeInventoryError = null; for (const resolved of refreshTargets) { const {tuple, pullRequest} = resolved; - runtimeRefresh: if (await hasRuntimeChange(pullRequest)) { + let runtimeChanges; + try { + runtimeChanges = await hasRuntimeChange(pullRequest); + } catch (error) { + core.setFailed(`Cannot verify runtime changed files for PR #${tuple.prNumber}; no dispatch issued: ${error.message || error}`); + } + runtimeRefresh: if (runtimeChanges) { let existingProducers = []; let fallbackReason = null; let inventory; @@ -1061,7 +1067,7 @@ jobs: } runtimeInventoryPromise = undefined; } - } else { + } else if (runtimeChanges === false) { core.info(`Skipping PR runtime image refresh for #${tuple.prNumber}: no runtime-changing files.`); } // Preview has its own exact-image proof. An uncertain runtime handoff must not suppress it. diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 155253b375..5a79763ced 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -611,7 +611,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "9c5525ba20ef046aaadb800b0fdf2adb460e4b0a2baef992938aa7f17fcfa872"; + const canonicalRuntimeWorkflowSha256 = "04e7129e537960b2838dc266057955611075bf60d3eb3e9d3f33ad30317f3d75"; // Trusted refreshes can still execute the previous successful default-branch definition. const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = "ea6ade0f69718573aeac4e4b5a1e9050e53e1e3cef3426b8791f182d8d49e112"; // Retain the exact fail-red producer still executed by trusted base refreshes. diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 9978983ebd..7c71dc0923 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -894,7 +894,7 @@ async function runDispatcher({ tuples, inventories = {}, apiFailure = null, sourceTuples = [], callback = {}, branchHeads = {}, branchErrors = {}, pullOverrides = {}, mergeParents = {}, ciEvidence = {}, hideDispatchVisibility = false, filesByPr = {}, postFailurePr = null, previewFailurePr = null, - visibilityResponse = null, + visibilityResponse = null, filesFailurePr = null, }) { const dispatches = []; const postedRuns = []; @@ -906,7 +906,6 @@ async function runDispatcher({ const observationPostCounts = []; const timerPostCounts = []; let waitedMillis = 0; - const eventInventoryCalls = new Map(); const currentBaseSha = tuples[0]?.baseSha ?? baseSha; const allTuples = [...tuples, ...sourceTuples]; const tupleByNumber = new Map(allTuples.map((tuple) => [tuple.prNumber, tuple])); @@ -981,7 +980,10 @@ async function runDispatcher({ ...(typeof override === "function" ? override(reads) : override ?? {}), } }; }, - listFiles: async ({ pull_number }) => ({ data: filesByPr[String(pull_number)] ?? [{ filename: "services/example/src/Main.java" }] }), + listFiles: async ({ pull_number }) => { + if (String(pull_number) === filesFailurePr) throw new Error("fixture changed-files lookup failed"); + return { data: filesByPr[String(pull_number)] ?? [{ filename: "services/example/src/Main.java" }] }; + }, }, repos: { getCommit: async ({ ref }) => { @@ -1027,13 +1029,12 @@ async function runDispatcher({ if (apiFailure === request.event || (typeof apiFailure === "function" && apiFailure(request, inventoryCalls.length))) { throw new Error("fixture API unavailable"); } - const callNumber = (eventInventoryCalls.get(request.event) ?? 0) + 1; - eventInventoryCalls.set(request.event, callNumber); const inventory = inventories[request.event] ?? []; if (!Array.isArray(inventory) && inventory.malformed) { return { data: { malformed: true } }; } - const refinement = callNumber > 1 && !Array.isArray(inventory) && Array.isArray(inventory.refined); + const refinement = !Array.isArray(inventory) && Array.isArray(inventory.refined) && + request.created === inventory.refinedCreated; const suppliedRuns = Array.isArray(inventory) ? inventory : refinement ? inventory.refined : inventory.initial ?? inventory.runs ?? []; @@ -1053,7 +1054,7 @@ async function runDispatcher({ ? filteredRuns.length : refinement ? inventory.refinedTotalCount ?? filteredRuns.length - : inventory.initialTotalCount ?? inventory.total_count ?? filteredRuns.length; + : inventory.initialPageTotals?.[request.page] ?? inventory.initialTotalCount ?? inventory.total_count ?? filteredRuns.length; return { data: { total_count: filteredTotalCount, workflow_runs: filteredRuns.slice((request.page - 1) * 100, request.page * 100) } }; }, }, @@ -1423,8 +1424,11 @@ async function runDispatcher({ const secondPageRuns = runsDescending("pull_request", "2026-01-02T00:00:00Z"); secondPageRuns.push(producer(tuple, "pull_request", "in_progress")); - const secondPage = await runDispatcher({ tuples: [tuple], inventories: { pull_request: secondPageRuns } }); + const secondPage = await runDispatcher({ tuples: [tuple], inventories: { pull_request: { + initial: secondPageRuns, refined: [], refinedCreated: "2026-01-02T00:00:00Z..*", + } } }); assert.deepEqual(numbers(secondPage), [], "exact page-two producer must suppress duplicate"); + assert.equal(secondPage.errors.length, 0, "page two at the original cutoff must not be treated as malformed refinement"); assert(secondPage.inventoryCalls.some(request => request.event === "pull_request" && request.page === 2)); assert(secondPage.inventoryCalls.every(request => request.page <= 10)); @@ -1434,7 +1438,7 @@ async function runDispatcher({ }); const refinedBound = await runDispatcher({ tuples: [tuple], callback: {updated_at: "2026-01-03T00:00:00Z"}, inventories: { pull_request: { - total_count: 1001, runs: overBoundPage, refined: [overBoundPage[0]], refinedTotalCount: 1, + total_count: 1001, runs: overBoundPage, refinedCreated: "2026-01-02T00:00:00Z..*", refined: [overBoundPage[0]], refinedTotalCount: 1, } }, }); assert.deepEqual(numbers(refinedBound), [], "complete bounded refinement retains exact in-flight producer"); @@ -1445,7 +1449,7 @@ async function runDispatcher({ const refinedCompleted = await runDispatcher({ tuples: [tuple], callback: {updated_at: "2026-01-01T06:00:00Z"}, inventories: { - pull_request: {total_count: 1001, runs: [unrelatedInflight], + pull_request: {total_count: 1001, runs: [unrelatedInflight], refinedCreated: "2026-01-01T06:00:00Z..*", refined: [unrelatedInflight], refinedTotalCount: 1}, repository_dispatch: [producer(tuple, "repository_dispatch", "completed", "success", { created_at: "2026-01-01T12:00:00Z", @@ -1457,7 +1461,7 @@ async function runDispatcher({ const narrowedAbsence = await runDispatcher({ tuples: [tuple], callback: {updated_at: "2026-01-03T00:00:00Z"}, - inventories: {pull_request: {total_count: 1001, runs: [unrelatedInflight], + inventories: {pull_request: {total_count: 1001, runs: [unrelatedInflight], refinedCreated: "2026-01-02T00:00:00Z..*", refined: [unrelatedInflight], refinedTotalCount: 1}}, }); assert.deepEqual(numbers(narrowedAbsence), [], "narrowed empty exact-producer slice cannot exclude older omitted producers"); @@ -1465,13 +1469,13 @@ async function runDispatcher({ for (const args of [ { inventories: { pull_request: { - total_count: 1001, runs: overBoundPage, refined: overBoundPage, refinedTotalCount: 1001, + total_count: 1001, runs: overBoundPage, refinedCreated: "2026-01-02T00:00:00Z..*", refined: overBoundPage, refinedTotalCount: 1001, } } }, { inventories: { pull_request: { - total_count: 1001, runs: overBoundPage, refined: [], refinedTotalCount: 0, + total_count: 1001, runs: overBoundPage, refinedCreated: "2026-01-02T00:00:00Z..*", refined: [], refinedTotalCount: 0, } } }, { inventories: { pull_request: { - initial: secondPageRuns, initialTotalCount: 101, refined: secondPageRuns, refinedTotalCount: 102, + initial: secondPageRuns, initialPageTotals: {1: 101, 2: 102}, } } }, { inventories: { pull_request: { total_count: 1000, runs: [] } } }, { inventories: { pull_request: { total_count: 101, runs: [] } } }, @@ -1542,6 +1546,19 @@ async function runDispatcher({ assert.deepEqual(numbers(staleObservation), ["101"], "an out-of-window row cannot confirm or retry an accepted dispatch"); assert(staleObservation.errors.some(error => error.includes("visibility is unknown"))); const previewTuple = {...tuple, labels: [{name: "preview"}]}; + const changedFilesFailure = await runDispatcher({ + tuples: [tuple, {...sibling, labels: [{name: "preview"}]}, tupleFor(103, "d", "e")], + filesFailurePr: "102", + }); + assert.deepEqual(numbers(changedFilesFailure), ["101", "103"], + "a changed-file lookup failure denies only the unproven runtime target"); + assert(previewDispatches(changedFilesFailure).some(item => item.client_payload.pr_number === "102"), + "the failed runtime target still permits independent eligible preview reconciliation"); + assert(changedFilesFailure.inventoryCalls.some((request, index) => + request.created === visibilityFloor && changedFilesFailure.observationPostCounts[index] === 2), + "accepted handoffs before and after the failed target are still observed"); + assert(changedFilesFailure.errors.some(error => error.includes("Cannot verify runtime changed files for PR #102"))); + assert(!changedFilesFailure.errors.some(error => error.includes("visibility is unknown"))); const previewUnknown = await runDispatcher({tuples: [previewTuple], apiFailure: "pull_request"}); assert.equal(runtimeDispatches(previewUnknown).length, 0); assert.equal(previewDispatches(previewUnknown).length, 1, "uncertain runtime inventory must not suppress independent preview reconciliation"); From 6b4c33d57a6c44c44258bdbfdae6aa3f59b31ecf Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:50:04 +1300 Subject: [PATCH 23/96] fix(ci): observe uncertain runtime dispatch before unlock --- .../workflows/publish-pr-runtime-images.yml | 23 ++++++++++---- .github/workflows/runtime-images.yml | 26 ++++++++++++---- .github/workflows/smoke.yml | 2 +- .../pr-required-gate-context-contract.sh | 27 +++++++++++++++-- .../tests/pr-retarget-workflow-contract.sh | 30 +++++++++++++++---- 5 files changed, 89 insertions(+), 19 deletions(-) diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 81cf404d4e..a23a9746b7 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -210,13 +210,26 @@ jobs: const {data: finalCi} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); if (!matchesCi(finalCi) || !await sourceCurrent() || await originalSuperseded() || await currentTuple() !== baseRef) return; const dispatchStarted = new Date(Date.now() - 1000).toISOString(); - await github.rest.repos.createDispatchEvent({...context.repo, event_type: "pr-runtime-base-refresh", client_payload: { - pr_number: number, base_ref: baseRef, base_sha: base, head_sha: head, merge_sha: merge, - }}); - // Keep the shared dispatcher lock until the accepted handoff is observable. Never blindly retry POST. + let responseUnknown = false; + try { + await github.rest.repos.createDispatchEvent({...context.repo, event_type: "pr-runtime-base-refresh", client_payload: { + pr_number: number, base_ref: baseRef, base_sha: base, head_sha: head, merge_sha: merge, + }}); + } catch (error) { + // A documented repository-dispatch 404/422 or authentication 401 is not a lost response. + if ([401, 404, 422].includes(error?.status) && error.response?.status === error.status && + !error.response.headers?.["retry-after"] && error.response.headers?.["x-ratelimit-remaining"] !== "0") throw error; + responseUnknown = true; + core.setFailed(`Runtime refresh POST response is unknown; no retry issued: ${error.message || error}`); + } + // Keep the shared lock during observation even when the one POST response was lost. const deadline = Date.now() + 120000; while (!await newerRefresh(dispatchStarted)) { - if (Date.now() >= deadline) throw new Error("Refresh dispatch accepted but visibility is unknown; no retry issued"); + if (Date.now() >= deadline) { + throw new Error(responseUnknown + ? "Refresh dispatch attempted but visibility is unknown; no retry issued" + : "Refresh dispatch accepted but visibility is unknown; no retry issued"); + } await new Promise(resolve => setTimeout(resolve, 5000)); } core.info(`Reconciled failed original runtime for PR #${number}; exact refresh is visible.`); diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 9e409aae9a..1e54a955e4 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1045,6 +1045,9 @@ jobs: } const previousIds = new Set(inventory?.runs?.map(run => run.id) || []); const dispatchSince = new Date(Date.now() - 1000).toISOString(); + const pending = {tuple, previousIds, dispatchSince, responseUnknown: false}; + visibilitySince ??= dispatchSince; + pendingVisibility.push(pending); try { await github.rest.repos.createDispatchEvent({ ...context.repo, @@ -1057,10 +1060,17 @@ jobs: merge_sha: tuple.mergeSha, }, }); - // Collect handoffs first so one slow visibility response cannot starve later PRs. - visibilitySince ??= dispatchSince; - pendingVisibility.push({tuple, previousIds, dispatchSince}); } catch (error) { + // Repository dispatch documents 404 and 422 as rejected requests; 401 is invalid authentication. + // A transport error or retryable response is not proof of rejection. + if ([401, 404, 422].includes(error?.status) && error.response?.status === error.status && + !error.response.headers?.["retry-after"] && error.response.headers?.["x-ratelimit-remaining"] !== "0") { + pendingVisibility.pop(); + if (!pendingVisibility.length) visibilitySince = undefined; + core.setFailed(`Runtime refresh POST rejected for PR #${tuple.prNumber}; no retry issued: ${error.message || error}`); + break runtimeRefresh; + } + pending.responseUnknown = true; core.setFailed(`Runtime refresh handoff for PR #${tuple.prNumber} is uncertain; no retry issued: ${error.message || error}`); runtimeInventoryPromise = undefined; break runtimeRefresh; @@ -1110,11 +1120,14 @@ jobs: const observed = await readInventory(visibilitySince, ["repository_dispatch"]); if (!observed.complete) throw new Error("Accepted refresh has incomplete visibility; no retry issued"); for (let index = pendingVisibility.length - 1; index >= 0; index--) { - const {tuple, previousIds, dispatchSince} = pendingVisibility[index]; + const {tuple, previousIds, dispatchSince, responseUnknown} = pendingVisibility[index]; const exactTitle = `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; if (observed.runs.some(run => run.event === "repository_dispatch" && run.display_title === exactTitle && !previousIds.has(run.id) && - validTimestamp(run.created_at) && Date.parse(run.created_at) >= Date.parse(dispatchSince))) pendingVisibility.splice(index, 1); + validTimestamp(run.created_at) && Date.parse(run.created_at) >= Date.parse(dispatchSince))) { + pendingVisibility.splice(index, 1); + if (responseUnknown) core.info(`Runtime refresh for PR #${tuple.prNumber} became visible after an unknown POST response.`); + } } } catch (error) { core.setFailed(`Runtime refresh visibility is uncertain; no retry issued: ${error.message || error}`); @@ -1122,7 +1135,8 @@ jobs: } if (pendingVisibility.length === 0) break; if (Date.now() >= visibilityDeadline) { - core.setFailed(`Refresh dispatch accepted but visibility is unknown for PRs ${pendingVisibility.map(item => item.tuple.prNumber).join(", ")}; no retry issued`); + const dispatchState = pendingVisibility.some(item => item.responseUnknown) ? "attempted" : "accepted"; + core.setFailed(`Refresh dispatch ${dispatchState} but visibility is unknown for PRs ${pendingVisibility.map(item => item.tuple.prNumber).join(", ")}; no retry issued`); break; } await new Promise(resolve => setTimeout(resolve, 5000)); diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 5a79763ced..1fd7cf744a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -611,7 +611,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "04e7129e537960b2838dc266057955611075bf60d3eb3e9d3f33ad30317f3d75"; + const canonicalRuntimeWorkflowSha256 = "107a7bc895f890173161ea09f707ce93d8e170093aa8c8c528fc5f98430e1bac"; // Trusted refreshes can still execute the previous successful default-branch definition. const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = "ea6ade0f69718573aeac4e4b5a1e9050e53e1e3cef3426b8791f182d8d49e112"; // Retain the exact fail-red producer still executed by trusted base refreshes. diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 7100f846e4..8497256624 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -4297,6 +4297,13 @@ async function run(kind, shared = {visible: false, posts: 0}) { if (workflow_id === "runtime-images.yml" && runEvent === "pull_request") { runs = kind === "newer-original" ? [{...source, id: 105, status: "in_progress"}] : [source]; } + if (workflow_id === "runtime-images.yml" && runEvent === "repository_dispatch" && shared.posts) { + shared.observations = (shared.observations || 0) + 1; + if (kind === "ambiguous-visible" && clock >= 5000) { + shared.visible = true; + runs = [refresh]; + } + } if (workflow_id === "runtime-images.yml" && runEvent === "repository_dispatch" && kind === "second-page") { runs = Array.from({length: 100}, (_, i) => ({...refresh, id: 1000 + i, display_title: "unrelated"})).concat(refresh); } @@ -4315,7 +4322,8 @@ async function run(kind, shared = {visible: false, posts: 0}) { assert.deepEqual(request, {owner: "example", repo: "firemud", event_type: "pr-runtime-base-refresh", client_payload: {pr_number: "42", base_ref: "develop", base_sha: base, head_sha: head, merge_sha: merge}}); shared.posts++; - if (kind === "ambiguous-post") throw new Error("unknown POST outcome"); + if (["ambiguous-post", "ambiguous-visible"].includes(kind)) throw new Error("unknown POST outcome"); + if (kind === "rejected-post") throw Object.assign(new Error("validation rejected"), {status: 422, response: {status: 422}}); if (kind !== "invisible") shared.visible = true; }, }, @@ -4348,7 +4356,8 @@ async function run(kind, shared = {visible: false, posts: 0}) { {name: "Enforce validation success", status: "completed", conclusion: metadata ? "skipped" : "failure"}]}]; }}; await execute(github, {repo: {owner: "example", repo: "firemud"}, eventName: "workflow_run", - payload: {workflow_run: event, repository: {default_branch: "develop"}}}, {info: () => {}}, + payload: {workflow_run: event, repository: {default_branch: "develop"}}}, + {info: () => {}, setFailed: message => { shared.failure = message; }}, class extends Date { static now() { return clock; } }, callback => {clock += 5000; callback();}); if (kind === "merge-unknown") assert.equal(tupleReads, 6, "unresolved mergeability retries are bounded"); if (kind === "merge-pending") assert.equal(tupleReads, 3, "one convergence retry plus final current tuple fence"); @@ -4384,6 +4393,20 @@ async function run(kind, shared = {visible: false, posts: 0}) { await assert.rejects(run(scenario, state)); assert.equal(state.posts, ["incomplete", "at-cap"].includes(scenario) ? 0 : 1, "never retry unknown POST"); } + const rejectedPost = {visible: false, posts: 0}; + await assert.rejects(run("rejected-post", rejectedPost), /validation rejected/); + assert.equal(rejectedPost.posts, 1); + assert.equal(rejectedPost.observations, undefined, "a documented rejection must not hold the mutex for observation"); + const ambiguousInvisible = {visible: false, posts: 0}; + await assert.rejects(run("ambiguous-post", ambiguousInvisible), /attempted but visibility is unknown/); + assert.equal(ambiguousInvisible.posts, 1); + assert.equal(ambiguousInvisible.observations, 25, "ambiguous invisible POST holds lock for the existing bounded observation"); + const ambiguousVisible = {visible: false, posts: 0}; + assert.equal(await run("ambiguous-visible", ambiguousVisible), 1); + assert.equal(ambiguousVisible.observations, 2, "observe an exact late handoff after losing the POST response"); + assert.match(ambiguousVisible.failure, /response is unknown; no retry issued/); + await run("valid", ambiguousVisible); + assert.equal(ambiguousVisible.posts, 1, "the next serialized callback sees the exact handoff and does not retry"); // Under the shared job mutex, a CI-first visible refresh suppresses completion recovery. assert.equal(await run("valid", {visible: true, posts: 0}), 0); // Repeated completion callbacks, including after terminal refresh failure, dispatch at most once. diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 7c71dc0923..68043e1e3b 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -894,7 +894,7 @@ async function runDispatcher({ tuples, inventories = {}, apiFailure = null, sourceTuples = [], callback = {}, branchHeads = {}, branchErrors = {}, pullOverrides = {}, mergeParents = {}, ciEvidence = {}, hideDispatchVisibility = false, filesByPr = {}, postFailurePr = null, previewFailurePr = null, - visibilityResponse = null, filesFailurePr = null, + visibilityResponse = null, filesFailurePr = null, postFailureVisible = false, postFailureStatus = null, }) { const dispatches = []; const postedRuns = []; @@ -996,10 +996,10 @@ async function runDispatcher({ if (request.event_type === "preview-deploy" && request.client_payload.pr_number === previewFailurePr) { throw new Error("ambiguous preview POST timeout"); } - if (request.event_type === "pr-runtime-base-refresh" && request.client_payload.pr_number === postFailurePr) { - throw new Error("ambiguous POST timeout"); - } - if (request.event_type === "pr-runtime-base-refresh" && !hideDispatchVisibility) { + const ambiguousRuntimePost = request.event_type === "pr-runtime-base-refresh" && + request.client_payload.pr_number === postFailurePr; + if (request.event_type === "pr-runtime-base-refresh" && !hideDispatchVisibility && + (!ambiguousRuntimePost || postFailureVisible)) { const payload = request.client_payload; postedRuns.push(producer({ prNumber: payload.pr_number, baseSha: payload.base_sha, @@ -1008,6 +1008,11 @@ async function runDispatcher({ id: 900000 + postedRuns.length, created_at: "2026-01-08T00:00:00Z", })); } + if (ambiguousRuntimePost) { + const error = new Error(postFailureStatus ? "fixture HTTP rejection" : "ambiguous POST timeout"); + if (postFailureStatus) Object.assign(error, {status: postFailureStatus, response: {status: postFailureStatus}}); + throw error; + } }, }, actions: { @@ -1397,6 +1402,21 @@ async function runDispatcher({ const failedPost = await runDispatcher({ tuples: [tuple, sibling], postFailurePr: "101" }); assert.deepEqual(numbers(failedPost), ["101", "102"], "ambiguous first POST must not retry or starve second"); assert(failedPost.errors.some(message => message.includes("ambiguous POST timeout"))); + assert.equal(failedPost.waitedMillis, 120000, "observe unknown handoff through the same bounded shared window"); + assert(failedPost.errors.some(message => message.includes("attempted but visibility is unknown for PRs 101"))); + const deniedPost = await runDispatcher({tuples: [tuple, sibling], postFailurePr: "101", postFailureStatus: 422}); + assert.deepEqual(numbers(deniedPost), ["101", "102"]); + assert.equal(deniedPost.waitedMillis, 0, "a documented rejection must not extend the shared observation"); + assert(deniedPost.errors.some(error => error.includes("POST rejected for PR #101"))); + const observedAmbiguousPost = await runDispatcher({ + tuples: [{...tuple, labels: [{name: "preview"}]}, sibling], postFailurePr: "101", postFailureVisible: true, + }); + assert.deepEqual(numbers(observedAmbiguousPost), ["101", "102"], "visible ambiguous handoff must not retransmit"); + assert(previewDispatches(observedAmbiguousPost).some(item => item.client_payload.pr_number === "101")); + assert(observedAmbiguousPost.infos.some(message => message.includes("became visible after an unknown POST response"))); + assert(observedAmbiguousPost.errors.some(message => message.includes("ambiguous POST timeout")), + "visibility does not conceal the transport failure"); + assert(!observedAmbiguousPost.errors.some(message => message.includes("visibility is unknown"))); const transientFirst = await runDispatcher({ tuples: [tuple, sibling], apiFailure: (_request, count) => count === 1, }); From fd4c6db067f40ac6f19e231f377461616af29e6d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:15:52 +1300 Subject: [PATCH 24/96] fix(account): preserve endpoint default and original refusal fence --- .../TenantCapacityAdmissionGrpcCodec.java | 5 ++--- .../TenantCapacityAdmissionGrpcCodecTest.java | 19 +++++++++++++++-- .../client/AccountTenantCapacityClient.java | 3 ++- .../AccountTenantCapacityClientMtlsTest.java | 21 +++++++++++++++++++ 4 files changed, 42 insertions(+), 6 deletions(-) diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java index fd9e087a46..0091c13db8 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java @@ -298,11 +298,10 @@ public static Optional readRefusalDetails( } private static void requireRefusalAuthority(Request request, Refusal refusal) { + if (request.capacityRearmFence() != 1) throw invalid(); if (refusal.code() == Failure.CAPACITY_QUOTA_EXCEEDED && (!request.evidence().permitsCreation() - || request.operation() != Operation.CAPACITY_CREATING - || request.capacityRearmFence() != 1)) throw invalid(); - if (refusal.durableDenialId() != null && request.capacityRearmFence() != 1) throw invalid(); + || request.operation() != Operation.CAPACITY_CREATING)) throw invalid(); } private static TenantCapacityShape shape(Shape value) { diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java index 2e389978e9..7b8a12a2f0 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java @@ -173,7 +173,7 @@ void nonExpandingRequestCannotCarryQuotaRefusal() { } @Test - void matchedRearmCannotCarryOriginalQuotaDenial() { + void matchedRearmCannotCarryEitherOriginalRefusal() { var original = CapacityAdmissionTestFixture.playerRequest(); var request = new Request( @@ -200,8 +200,23 @@ void matchedRearmCannotCarryOriginalQuotaDenial() { TenantCapacityAdmissionGrpcCodec.toRefusal( request, Failure.CAPACITY_QUOTA_EXCEEDED)) .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.TENANT_BILLING_BLOCKED)) + .isInstanceOf(IllegalArgumentException.class); + var originalBilling = + TenantCapacityAdmissionGrpcCodec.toRefusal(original, Failure.TENANT_BILLING_BLOCKED); var billing = - TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.TENANT_BILLING_BLOCKED); + originalBilling.toBuilder() + .setRefusal( + 0, + originalBilling.getRefusal(0).toBuilder() + .setAdmissionAttemptId(0, request.admissionAttemptId().toString()) + .setCapacityRearmFence(0, request.capacityRearmFence()) + .setMutationDigest(0, request.mutationDigest())) + .build(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, billing)) + .isInstanceOf(IllegalArgumentException.class); var wire = billing.toBuilder() .setRefusal( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java index 7977e66532..77da188f4b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java @@ -167,7 +167,8 @@ public UUID durableDenialId() { @Override protected String configuredTarget(ServiceEndpointsProperties endpoints) { - return endpoints.getAccountService(); + String target = endpoints.getAccountService(); + return target == null || target.isBlank() ? null : target; } @Override diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index 852475be6c..3df512b368 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -74,6 +74,27 @@ static void certificates() throws Exception { "wrong", "spiffe://firemud/ns/prod/sa/world-management-service", true)); } + @Test + void blankEndpointIsUnsetAndExplicitAccountEndpointIsPreserved() throws Exception { + var endpoints = new ServiceEndpointsProperties(); + var factory = new GrpcChannelFactory(); + try (var client = + new AccountTenantCapacityClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + factory, + "prod", + Clock.fixed(CapacityAdmissionTestFixture.NOW, ZoneOffset.UTC))) { + assertThat(client.defaultTarget()).isEqualTo("account-service:6565"); + for (String blank : new String[] {null, "", " \t "}) { + endpoints.setAccountService(blank); + assertThat(client.configuredTarget(endpoints)).isNull(); + } + endpoints.setAccountService("account.internal:7443"); + assertThat(client.configuredTarget(endpoints)).isEqualTo("account.internal:7443"); + } + } + @Test void exactAccountPeerReceivesCompleteRequestAndExactRetryKeepsReservation() throws Exception { AtomicInteger calls = new AtomicInteger(); From a7967e5d64868802714de15b4d3a11bc6c60f7e8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:25:27 +1300 Subject: [PATCH 25/96] Tighten exact review workflow recovery and capacity proofs --- .../workflows/publish-pr-runtime-images.yml | 43 +++- .github/workflows/smoke.yml | 123 +++++++-- .../game-session-service/runtime-and-data.md | 4 + .../pr-required-gate-context-contract.sh | 143 +++++++++-- ...acityMigrationPostgresIntegrationTest.java | 24 +- ...titlementOwnerPostgresIntegrationTest.java | 237 +++++++++++++++++- .../AccountTenantCapacityOwnerTest.java | 18 +- ...stractReloadingBlockingGrpcClientTest.java | 18 +- .../AccountTenantCapacityClientMtlsTest.java | 3 +- 9 files changed, 558 insertions(+), 55 deletions(-) diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index a23a9746b7..a2d4cef347 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -122,6 +122,7 @@ jobs: ci = null; const ciRuns = (await inventory("ci.yml", {event: "pull_request", head_sha: head})) .filter(run => run.display_title === ciTitle).sort((a, b) => b.id - a.id); + let skippedPreEnforcementCancellation = false; // Metadata-only completions cannot conceal an earlier substantive attempt for this exact tuple. for (const candidate of ciRuns) { ci = candidate; @@ -130,6 +131,7 @@ jobs: if (!matchesCi(ciNative)) return null; const jobs = await github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", {...context.repo, run_id: ci.id, attempt_number: ci.run_attempt, per_page: 100}); + if (!Array.isArray(jobs) || jobs.some(job => !job || typeof job.name !== "string" || !job.name.trim())) return null; const metadataName = "PR Metadata Edit (Validation Gate)"; const metadataExpression = "github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Validation Gate)' || 'Validation Gate'"; const normalizedName = name => { @@ -150,16 +152,48 @@ jobs: if (metadata.length) { // Only one positively skipped native metadata job can be ignored. // Unknown/mixed identities must never reveal an older CI result. - if (metadata.length !== 1 || gates.length || !nativeJob(metadata[0]) || + if (metadata.length !== 1 || jobs.length !== 1 || gates.length || !nativeJob(metadata[0]) || metadata[0].conclusion !== "skipped") return null; const {data: latestMetadata} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); - if (!matchesCi(latestMetadata)) return null; + if (!matchesCi(latestMetadata) || latestMetadata.conclusion !== ci.conclusion || + ciNative.conclusion !== ci.conclusion) return null; ci = null; continue; } const gate = gates.length === 1 ? gates[0] : null; const preservation = gate?.steps?.filter(step => step.name === "Preserve successful required gate on metadata-only edit") || []; const enforcement = gate?.steps?.filter(step => step.name === "Enforce validation success") || []; + // Only an exact native cancelled attempt with a uniquely identified, + // explicitly never-started enforcement step may reveal older success. + if (ci.conclusion === "cancelled" && ciNative.conclusion === "cancelled" && + nativeJob(gate) && gate.conclusion === "cancelled" && + preservation.length === 1 && preservation[0].status === "completed" && + preservation[0].conclusion === "skipped" && + enforcement.length === 1 && enforcement[0].status === "completed" && + enforcement[0].conclusion === "skipped" && enforcement[0].started_at === null) { + // The aggregator can be cancelled before enforcement even after a + // substantive upstream job failed. Only a coherent, terminal native + // inventory without failures or unexplained work may reveal older proof. + const seenJobIds = new Set(); + const seenChecks = new Set(); + for (const job of jobs) { + if (!nativeJob(job) || seenJobIds.has(job.id) || seenChecks.has(job.check_run_url) || + !["success", "skipped", "cancelled"].includes(job.conclusion) || !Array.isArray(job.steps)) return null; + seenJobIds.add(job.id); + seenChecks.add(job.check_run_url); + for (const step of job.steps) { + if (!step || typeof step.name !== "string" || !step.name.trim() || step.status !== "completed" || + !["success", "skipped", "cancelled"].includes(step.conclusion) || + (step.conclusion === "cancelled" && step.started_at !== null)) return null; + } + } + const {data: latestCancelled} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); + if (!matchesCi(latestCancelled) || latestCancelled.conclusion !== "cancelled") return null; + skippedPreEnforcementCancellation = true; + ci = null; + continue; + } + if (ci.conclusion === "cancelled" || ciNative.conclusion === "cancelled") return null; if (!gate || !positive(gate.id) || gate.run_id !== ci.id || gate.run_attempt !== ci.run_attempt || gate.head_sha !== head || ![ciWorkflow.name, ciTitle].includes(gate.workflow_name) || gate.status !== "completed" || typeof gate.check_run_url !== "string" || !gate.check_run_url.startsWith(checkPrefix) || @@ -181,6 +215,9 @@ jobs: } return null; } + if (skippedPreEnforcementCancellation && + (ci.conclusion !== "success" || ciNative.conclusion !== "success" || + gate.conclusion !== "success" || enforcement[0].conclusion !== "success")) return null; break; } return ci; @@ -208,7 +245,7 @@ jobs: const currentCi = await selectCi(); if (!currentCi || currentCi.id !== selectedCi.id || currentCi.run_attempt !== selectedCi.run_attempt) return; const {data: finalCi} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); - if (!matchesCi(finalCi) || !await sourceCurrent() || await originalSuperseded() || await currentTuple() !== baseRef) return; + if (!matchesCi(finalCi) || finalCi.conclusion !== ci.conclusion || !await sourceCurrent() || await originalSuperseded() || await currentTuple() !== baseRef) return; const dispatchStarted = new Date(Date.now() - 1000).toISOString(); let responseUnknown = false; try { diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 1fd7cf744a..5ff6ad3eb3 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -812,7 +812,7 @@ jobs: } // Canonical-transition diagnostic acceptance never becomes passing producer proof. - async function verifyKnownPlayFailure(run, candidate, identity, allowIncompleteSteps = false) { + async function verifyKnownPlayFailure(run, candidate, identity, allowIncompleteSteps = false, allowOrdinary = false) { if (repositoryName !== "benhook1013/FireMUD" || !["pull_request", "repository_dispatch"].includes(run.event)) return false; if (!positiveInteger(run.id) || !positiveInteger(run.run_attempt)) return false; @@ -826,7 +826,7 @@ jobs: `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; if ( source.id !== run.id || source.run_attempt !== run.run_attempt || - source.status !== "completed" || !["success", "failure"].includes(source.conclusion) || + source.status !== "completed" || source.conclusion !== run.conclusion || !["success", "failure"].includes(source.conclusion) || source.path !== workflowPath || source.repository?.full_name !== repositoryName || !positiveInteger(source.workflow_id) || source.display_title !== expectedTitle || source.event !== run.event @@ -858,7 +858,7 @@ jobs: const job = producers[0]; let incompleteSteps = !job || job.status !== "completed"; if (job) { - if (!positiveInteger(job.id) || job.id !== candidate?.id || + if (!positiveInteger(job.id) || (candidate && job.id !== candidate.id) || job.run_id !== source.id || job.run_attempt !== source.run_attempt || job.head_sha !== source.head_sha || job.check_run_url !== `https://api.github.com/repos/${repositoryName}/check-runs/${job.id}`) return false; @@ -874,12 +874,22 @@ jobs: ]; const markerName = "Known canonical transition PLAY failure with successful authenticated cleanup"; const steps = job?.steps ?? []; + const markers = steps.filter((step) => step.name === markerName); + if (markers.length > 1) return false; + const ordinaryCandidate = allowOrdinary && source.event === "repository_dispatch" && + source.conclusion === "success"; + const ordinary = ordinaryCandidate && markers[0]?.status === "completed" && + markers[0].conclusion === "skipped"; + const unknownDisposition = ordinaryCandidate && + (!markers.length || markers[0].status !== "completed"); const requiredSteps = new Map([ - [markerName, "success"], ["Stop smoke stack", "success"], - ["Export fixed-tag preview image artifact", "skipped"], - ["Upload preview image artifact", "skipped"], + [markerName, ordinary ? "skipped" : "success"], ["Stop smoke stack", "success"], ...expectedSuccessfulSteps.map((name) => [name, source.conclusion]), ]); + if (!ordinary && !unknownDisposition) { + requiredSteps.set("Export fixed-tag preview image artifact", "skipped"); + requiredSteps.set("Upload preview image artifact", "skipped"); + } for (const [name, conclusion] of requiredSteps) { const matches = steps.filter((step) => step.name === name); if (matches.length > 1) return false; @@ -937,8 +947,8 @@ jobs: currentPullRequest.base?.repo?.full_name === repositoryName && currentPullRequest.head?.sha === identity.headSha && currentPullRequest.base?.ref === identity.baseRef && - Array.isArray(currentPullRequest.labels) && - currentPullRequest.labels.some((label) => label?.name === "canonical-play-transition"))) return false; + (ordinary || unknownDisposition || (Array.isArray(currentPullRequest.labels) && + currentPullRequest.labels.some((label) => label?.name === "canonical-play-transition"))))) return false; if (source.event === "repository_dispatch") { if (currentPullRequest.merge_commit_sha !== identity.mergeSha) return false; const { data: currentBase } = await withTransientGitHubRetry( @@ -948,7 +958,7 @@ jobs: if (currentBase.ref !== `refs/heads/${identity.baseRef}` || currentBase.object?.sha !== identity.baseSha) return false; } - return incompleteSteps ? (allowIncompleteSteps ? "snapshot-pending" : false) : true; + return incompleteSteps ? (allowIncompleteSteps ? "snapshot-pending" : false) : ordinary ? "ordinary" : true; } // A failed original event is not replaced by arbitrary green history. Only @@ -998,10 +1008,8 @@ jobs: const candidate = jobs.find((job) => job.name === canonicalSmokeJobName); const proofRun = {id: replacement.id, run_attempt: replacement.run_attempt, conclusion: replacement.conclusion}; - if (!candidate || candidate.status !== "completed") { - return {status: "snapshot-pending", run: proofRun}; - } - const proof = await verifyKnownPlayFailure(replacement, candidate, identity, true); + const proof = await verifyKnownPlayFailure(replacement, candidate, identity, true, true); + if (proof === "ordinary") return {status: "ordinary", run: proofRun}; if (proof === "snapshot-pending") return {status: "snapshot-pending", run: proofRun}; if (proof === true) return {status: "verified", run: proofRun}; // A new attempt can start between list/proof reads. Invalid current proof @@ -1247,6 +1255,7 @@ jobs: let requireCurrentIdentity = false; let cancelledRunId = null; let cancelledRunObservedAt = null; + let cancelledRecoveryMoved = false; smokeGatePolling: while (Date.now() - started < timeoutMs) { if (pollIteration % pullRequestCheckInterval === 0 || !currentIdentity) { const resolvedIdentity = await resolveCurrentIdentity( @@ -1308,6 +1317,17 @@ jobs: matching.head_sha === currentIdentity.headSha && matching.display_title === expectedDisplayTitle && typeof matching.head_branch === "string" && matching.head_branch.length > 0 && matching.head_branch === context.payload.pull_request.head.ref; + if (recoverableCancellation && (pollIteration === 1 || pollIteration % pullRequestCheckInterval === 0)) { + const liveIdentity = await resolveCurrentIdentity("Resolving live cancelled-run recovery tuple", true); + if (liveIdentity?.obsolete) return; + if (liveIdentity && identityKey({...liveIdentity, sourceEvent: currentIdentity.sourceEvent}) !== + identityKey(currentIdentity)) { + cancelledRecoveryMoved = true; + requireCurrentIdentity = true; + currentIdentity = liveIdentity; + continue smokeGatePolling; + } + } const cancellationDiscoveryMs = recoverableCancellation ? refreshDiscoveryTimeoutMs : cancelledReplacementTimeoutMs; if (Date.now() - cancelledRunObservedAt >= cancellationDiscoveryMs) { @@ -1355,8 +1375,7 @@ jobs: const candidate = jobs.find((job) => job.name === canonicalSmokeJobName); const directRefresh = matching.event === "repository_dispatch" && matching.conclusion === "failure"; const directProof = matching.conclusion !== "failure" ? false - : directRefresh && (!candidate || candidate.status !== "completed") ? "snapshot-pending" - : Boolean(candidate) && await verifyKnownPlayFailure(matching, candidate, currentIdentity, directRefresh); + : (directRefresh || Boolean(candidate)) && await verifyKnownPlayFailure(matching, candidate, currentIdentity, directRefresh); knownPlayVerified = directProof === true; if (directRefresh && directProof === "snapshot-pending") { const snapshotKey = `direct:${identityKey(currentIdentity)}:${matching.id}:${matching.run_attempt}`; @@ -1394,10 +1413,6 @@ jobs: currentIdentity = liveIdentity; continue smokeGatePolling; } - if (!liveIdentity.canonicalPlayEligible) { - core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); - return; - } } const refreshProof = await verifyFailedPullCanonicalRefresh(matching, currentIdentity); const refreshKey = `${matching.id}:${identityKey(currentIdentity)}`; @@ -1455,6 +1470,23 @@ jobs: continue smokeGatePolling; } } + if (refreshProof?.status === "ordinary") { + const freshIdentity = await resolveCurrentIdentity("Fencing exact passing typed smoke recovery", true); + if (freshIdentity?.obsolete) return; + if (!freshIdentity || identityKey({...freshIdentity, sourceEvent: currentIdentity.sourceEvent}) !== + identityKey(currentIdentity)) { + if (freshIdentity) { + requireCurrentIdentity = true; + currentIdentity = freshIdentity; + } + continue smokeGatePolling; + } + if (!await isCurrentCanonicalAttempt(refreshProof.run)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + return; + } knownPlayVerified = refreshProof?.status === "verified" && positiveInteger(refreshProof.run?.id) && refreshProof.run.id > matching.id && positiveInteger(refreshProof.run?.run_attempt) && @@ -1523,6 +1555,43 @@ jobs: continue; } + if (cancelledRecoveryMoved && matching.event === "repository_dispatch") { + const proof = await verifyKnownPlayFailure(matching, null, currentIdentity, true, true); + if (proof === "snapshot-pending") { + const snapshotKey = `cancelled-move:${matching.id}:${matching.run_attempt}:${identityKey(currentIdentity)}`; + if (incompleteRefreshKey !== snapshotKey) { + incompleteRefreshKey = snapshotKey; + incompleteRefreshObservedAt = Date.now(); + } + if (Date.now() - incompleteRefreshObservedAt >= completedSnapshotTimeoutMs) { + core.setFailed("Moved cancelled-run recovery timed out waiting for authenticated smoke proof."); + return; + } + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + if (proof !== "ordinary" && proof !== true) { + core.setFailed("Moved cancelled-run recovery did not supply authenticated smoke proof."); + return; + } + const freshIdentity = await resolveCurrentIdentity("Fencing moved cancelled-run recovery", true); + if (freshIdentity?.obsolete) return; + if (!freshIdentity || identityKey(freshIdentity) !== identityKey(currentIdentity) || + !await isCurrentCanonicalAttempt(matching)) { + if (freshIdentity) currentIdentity = freshIdentity; + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + if (proof === "ordinary") return; + if (!freshIdentity.canonicalPlayEligible) { + core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); + return; + } + core.setOutput("known_play_exception", "true"); + core.warning("Canonical PLAY transition exception accepted; no runtime qualification or image publication."); + return; + } + let fullSmokeJob = null; let fullSmokeStep = null; let canonicalProducerVerified = false; @@ -1623,6 +1692,22 @@ jobs: const markers = (fullSmokeJob.steps ?? []).filter((step) => step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" ); + if (matching.event === "repository_dispatch" && + (markers.length === 0 || (markers.length === 1 && markers[0].status !== "completed"))) { + const markerProof = await verifyKnownPlayFailure( + matching, fullSmokeJob, currentIdentity, true, true); + if (["snapshot-pending", "ordinary", true].includes(markerProof)) { + const snapshotKey = `marker:${matching.id}:${matching.run_attempt}:${identityKey(currentIdentity)}`; + if (incompleteRefreshKey !== snapshotKey) { + incompleteRefreshKey = snapshotKey; + incompleteRefreshObservedAt = Date.now(); + } + if (Date.now() - incompleteRefreshObservedAt < completedSnapshotTimeoutMs) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + } + } if (markers.length === 1 && markers[0].status === "completed" && markers[0].conclusion === "success") { let knownPlayVerified = false; diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 5503e9e53c..e6225b0e8e 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -12,6 +12,10 @@ This is a target-only contract, not an enabled or runtime-qualified retirement p The exact current Game Session owner establishes irreversible closure of serving and resume for the admitted binding and retains settlement of applicable effects and indexes. Game Session supplies an authenticated terminal receipt linked to the original admission, FINAL evidence, binding lineage and Account reservation. [Account owns retirement of the corresponding used capacity](../account-service/runtime-and-data.md#finalized-capacity-usage-retirement). Before irreversible closure or settlement can discard the original work state, Game Session must durably retain the exact teardown identity and progress evidence needed for a replacement owner to finish the same terminal receipt. A crash between closure/settlement and receipt retention resumes that original teardown without reopening the binding or inventing a new receipt identity. The terminal receipt remains durable and exactly readable after binding closure and worker replacement. A replacement owner recovers and redelivers that same receipt until Account's exact retirement acknowledgement is known; this recovery never reopens serving or resume. +The target Game Session owner persists the teardown identity and progress in its own PostgreSQL storage, then retains the immutable terminal evidence under that same identity. A replacement worker reads the persisted progress and exact receipt rather than reconstructing either from Redis, an in-memory job or the current binding alone. The receipt binds the original admission, FINAL evidence, binding lineage and exact Account reservation; conflicting identities or stale owner fences must be refused. + +Qualification must prove restart before send, Account commit followed by response loss and worker restart, and exact receipt replay without a second decrement. Account—not Game Session—atomically retains the retirement receipt and decrements used capacity. Wrong identity or fence must fail closed, and no failure or retry may reopen serving or resume. These are acceptance requirements, not claims that the target path or its restart proof exists today. + ## Implementation Status The manually composed initial region bridge preserves either PRESEEDED assignment provenance or the separate PLAYER_CREATED creation origin. It selects the matching authenticated Entity reader and exact purpose-versioned World placement; a sealed reference is constructed only after authenticated response validation. Preparation and bridge rows retain the closed origin independently from operation IDs, and created rows keep assignment columns NULL. Current acquisition, retry, ACK, definitive abort and final commit preserve each bridge’s own authenticated actor origin. The first actor matches its exact timeline preparation; later distinct actor transitions use that same installed region source and protected incarnation while retaining their own origins, without replacing the first preparation or its actor-bound read digest. The shared numeric runtime ID remains a scoped projection, never a creation/assignment UUID or a credential. This path is unregistered and supplies no production custody, first-OPEN or activation authority. diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 8497256624..af94cf014c 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -646,6 +646,7 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single") { const github = { rest: { pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + git: {getRef: async () => ({data: {ref: "refs/heads/develop", object: {sha: base}}})}, actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs, getWorkflow: async () => ({data: {id: 7, path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images"}}), getWorkflowRun: async ({run_id}) => ({data: {id: run_id, @@ -3536,7 +3537,7 @@ const classifierDefinitions = JSON.parse(fs.readFileSync(process.argv[2] + ".cla const headSha = "a".repeat(40), baseSha = "b".repeat(40), mergeSha = "c".repeat(40); const workflowSha = "d".repeat(40); const identity = {headSha, baseSha, mergeSha, baseRef: "develop"}; -const run = {id: 99, run_attempt: 2, event: "pull_request"}; +const run = {id: 99, run_attempt: 2, event: "pull_request", conclusion: "success"}; const failures = ["Run credential-free full-stack smoke", "Require successful runtime smoke and authenticated cleanup"]; const step = (name, conclusion) => ({name, conclusion, status: "completed"}); const source = {...run, status: "completed", conclusion: "success", path: workflowPath, @@ -3547,7 +3548,7 @@ const candidate = {id: 123, run_id: 99, run_attempt: 2, head_sha: headSha, name: steps: [...failures.map(name => step(name, "success")), step("Stop smoke stack", "success"), step("Known canonical transition PLAY failure with successful authenticated cleanup", "success"), step("Export fixed-tag preview image artifact", "skipped"), step("Upload preview image artifact", "skipped")]}; -async function verify(mutate = () => {}, event = "pull_request", knownPlay = true, allowIncompleteSteps = false) { +async function verify(mutate = () => {}, event = "pull_request", knownPlay = true, allowIncompleteSteps = false, allowOrdinary = false) { const data = structuredClone({pr: "3390", consumerRepository: repositoryName, run, identity, source, candidate, jobs: [candidate], latest: {...source}, eventHeadRepository: repositoryName, currentPullRequest: {state: "open", head: {sha: headSha, repo: {full_name: repositoryName}}, @@ -3583,7 +3584,7 @@ async function verify(mutate = () => {}, event = "pull_request", knownPlay = tru const verifier = knownPlay ? "verifyKnownPlayFailure" : "verifyCanonicalSmokeProducer"; const accepted = await new Function("github", "prNumber", "repositoryName", "canonicalSmokeJobName", "workflowPath", "canonicalRuntimeWorkflowSha256", "canonicalPreviousTrustedRefreshRuntimeWorkflowSha256", "canonicalLegacyRuntimeWorkflowSha256", "canonicalPlayClassifierSha256", "positiveInteger", "withTransientGitHubRetry", "context", "owner", "repo", "require", "data", - `${fn}; return ${verifier}(data.run, data.candidate, data.identity, ${allowIncompleteSteps});`)( + `${fn}; return ${verifier}(data.run, data.candidate, data.identity, ${allowIncompleteSteps}, ${allowOrdinary});`)( github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, canonicalPreviousTrustedRefreshRuntimeWorkflowSha256, data.legacyDefinition ? canonicalRuntimeWorkflowSha256 : canonicalLegacyRuntimeWorkflowSha256, canonicalPlayClassifierSha256, @@ -3639,10 +3640,10 @@ async function recoveredFailure(options = {}, selectedRun = null, selectedIdenti }, rest: {actions: {getWorkflowRun: async ({run_id}) => { assert.equal(run_id, replacement.id); return {data: {...replacement, ...options.latest}}; - }}}}, "benhook1013", "FireMUD", canonicalSmokeJobName, async (selected, job, proofIdentity, allowIncompleteSteps) => { + }}}}, "benhook1013", "FireMUD", canonicalSmokeJobName, async (selected, job, proofIdentity, allowIncompleteSteps, allowOrdinary) => { verified++; assert.deepEqual(proofIdentity, selectedIdentity); - assert.equal(selected, replacement); assert.deepEqual(job, selectedCandidate); + assert.equal(selected, replacement); assert.deepEqual(job, options.noProducer ? undefined : selectedCandidate); return verify(data => { data.identity = structuredClone(selectedIdentity); Object.assign(data.run, replacement); @@ -3651,6 +3652,7 @@ async function recoveredFailure(options = {}, selectedRun = null, selectedIdenti }); Object.assign(data.candidate, structuredClone(selectedCandidate)); Object.assign(data.jobs[0], structuredClone(selectedCandidate)); + if (options.noProducer) data.jobs = []; data.currentPullRequest.head.sha = selectedIdentity.headSha; data.currentPullRequest.base.ref = selectedIdentity.baseRef; data.currentPullRequest.merge_commit_sha = selectedIdentity.mergeSha; @@ -3662,7 +3664,7 @@ async function recoveredFailure(options = {}, selectedRun = null, selectedIdenti } } if (options.mutateProof) options.mutateProof(data); - }, "repository_dispatch", true, allowIncompleteSteps); + }, "repository_dispatch", true, allowIncompleteSteps, allowOrdinary); }, {payload: {pull_request: {head: {repo: {full_name: options.headRepository || repositoryName}}}}}); const proof = await recover(original, selectedIdentity); return {accepted: raw ? proof : proof?.status === "verified" ? true @@ -3802,7 +3804,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { : status === "missing-step" ? {candidate: {steps: candidate.steps.filter(step => step.name !== "Stop smoke stack")}} : status === "nonterminal-step" ? {candidate: {steps: candidate.steps.map(step => step.name === "Stop smoke stack" ? {...step, status: "in_progress", conclusion: null} : step)}} : status === "missing-job" ? {noProducer: true} - : status === "pending-job" ? {candidate: {status: "in_progress"}} + : status === "pending-job" ? {candidate: {status: "in_progress", conclusion: null}} : {replacement: {status, conclusion: status === "completed" ? "success" : null, run_attempt: statuses[0] === "superseded" && polls > 1 ? 3 : 2}}, selectedRun, selectedIdentity, true)).accepted; @@ -3857,7 +3859,12 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { assert.deepEqual(outputs, []); assert.equal(writes, 0); } else if (options.labelRemoved || options.withdrawDuringProof) { - assert.deepEqual(failures, ["Canonical PLAY transition exception label is absent or no longer eligible."]); + if (options.labelRemoved && statuses[0] === "absent") { + assert.equal(failures.length, 1); + assert.match(failures[0], /^Timed out waiting for the exact runtime-images/); + } else { + assert.deepEqual(failures, ["Canonical PLAY transition exception label is absent or no longer eligible."]); + } assert.deepEqual(outputs, []); assert.equal(writes, 0); } else if (options.absentExpires) { @@ -3875,13 +3882,52 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { assert.equal(writes, 1); assert.ok(options.directProof || currentChecks >= 1); } - assert.equal(polls, options.directSnapshots ? 1 : options.ordinaryAfterDrift || options.directProof || options.labelRemoved ? 0 + assert.equal(polls, options.directSnapshots ? 1 : options.ordinaryAfterDrift || options.directProof ? 0 : options.withdrawDuringProof || options.rejectedObject ? 1 : options.absentExpires ? 5 : options.snapshotExpires ? 3 : options.recoverDrift ? 1 : statuses.length); - assert.equal(sleeps, options.directSnapshots ? (options.snapshotExpires ? 2 : options.directSnapshots.length - 1) : options.ordinaryAfterDrift || options.labelRemoved || options.withdrawDuringProof || options.rejectedObject ? 0 - : options.absentExpires ? 4 : options.snapshotExpires ? 2 : options.finalIdentity ? (statuses[0] === "absent" ? 1 : 0) + assert.equal(sleeps, options.directSnapshots ? (options.snapshotExpires ? 2 : options.directSnapshots.length - 1) : options.ordinaryAfterDrift || options.labelRemoved && statuses[0] !== "absent" || options.withdrawDuringProof || options.rejectedObject ? 0 + : options.labelRemoved && statuses[0] === "absent" ? 1 : options.absentExpires ? 4 : options.snapshotExpires ? 2 : options.finalIdentity ? (statuses[0] === "absent" ? 1 : 0) : expires ? statuses.length : statuses.length - 1); } +// Exercise the exact production loop through cancellation of an old tuple and +// a successful refresh of the new tuple. Only independently verified ordinary +// proof is accepted; a title match and green job are insufficient. +async function movedCancellation(ordinaryProof) { + let now = 0, typedReads = 0, proofReads = 0, finalReads = 0; + const eventIdentity = {...identity, sourceEvent: "pull_request"}; + const moved = {...identity, baseSha: "d".repeat(40), mergeSha: "e".repeat(40), sourceEvent: "repository_dispatch"}; + const old = {...source, id: 98, event: "pull_request", status: "completed", conclusion: "cancelled", + head_sha: identity.headSha, head_branch: "feature", + display_title: `Build Runtime Images secure-pr-artifact pr-3390 base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`}; + const refresh = {...source, event: "repository_dispatch", status: "completed", conclusion: "success"}; + const failures = [], outputs = []; + const core = {info() {}, warning() {}, setFailed: x => failures.push(x), setOutput: (...x) => outputs.push(x)}; + const execute = new Function("repositoryName", "workflowPath", "canonicalSmokeJobName", "withTransientGitHubRetry", + "verifyKnownPlayFailure", "isCurrentPullRequestObsolete", "core", "resolveCurrentIdentity", "identityKey", + "setTimeout", "sleepMs", "Date", "started", "timeoutMs", "pullRequestCheckInterval", "findMatchingRuntimeImagesRun", + "prNumber", "identityDiagnostic", "cancelledReplacementTimeoutMs", "context", + "refreshDiscoveryTimeoutMs", "completedSnapshotTimeoutMs", "positiveInteger", "isCurrentCanonicalAttempt", + `return (async () => { let pollIteration = 0; ${actualPollingLoop} })();`); + await execute(repositoryName, workflowPath, canonicalSmokeJobName, (_label, call) => call(), + async (run, candidate, selected, incomplete, ordinary) => { + proofReads++; assert.equal(run, refresh); assert.equal(candidate, null); + assert.deepEqual(selected, moved); assert.equal(incomplete, true); assert.equal(ordinary, true); + return ordinaryProof ? "ordinary" : false; + }, async () => false, core, async (_label, live) => live ? moved : eventIdentity, + selected => JSON.stringify(selected), resolve => {now += 10; resolve();}, 10, + {now: () => now}, 0, 100, 1, async (event, _title, selected) => { + if (event === "pull_request") return old; + typedReads++; + return selected.mergeSha === moved.mergeSha ? refresh : null; + }, "3390", "test identity", 20, + {payload: {pull_request: {head: {ref: "feature", repo: {full_name: repositoryName}}}}}, + 60, 30, value => Number.isSafeInteger(value) && value > 0, async run => { + finalReads++; assert.equal(run, refresh); return true; + }); + assert.equal(typedReads, 2); assert.equal(proofReads, 1); assert.equal(finalReads, ordinaryProof ? 1 : 0); + assert.deepEqual(outputs, [], "ordinary proof never publishes an exception output"); + assert.deepEqual(failures, ordinaryProof ? [] : ["Moved cancelled-run recovery did not supply authenticated smoke proof."]); +} // Exercise the real resolver, not merely a stub that honors requireCurrent. async function refreshFinalIdentity(eventUnavailable = false) { const start = script.indexOf("async function resolveCurrentIdentity("); @@ -3955,6 +4001,8 @@ function markerAccepted(overrides = {}) { const missing = Object.assign(new Error("missing"), {status: 404}); await assert.rejects(finalAttemptCheck(null, missing), error => error === missing); await pendingRefreshCaller(["completed", "completed"], false, {transientFinal: true}); + await movedCancellation(true); + await movedCancellation(false); assert.equal((await recoveredFailure({original: {conclusion: "timed_out"}})).accepted, true); await pendingRefreshCaller(["queued", "completed"], false, {originalConclusion: "timed_out"}); for (const siblingStatus of ["in_progress", "queued"]) { @@ -3993,7 +4041,7 @@ function markerAccepted(overrides = {}) { assert.equal((await recoveredFailure({candidate: {steps: candidate.steps.map(step => step.name === "Stop smoke stack" ? {...step, conclusion: "failure"} : step)}})).accepted, false); assert.equal((await recoveredFailure({candidate: {steps: candidate.steps.map(step => - step.name.startsWith("Known canonical") ? {...step, conclusion: "skipped"} : step)}})).accepted, false); + step.name.startsWith("Known canonical") ? {...step, conclusion: "skipped"} : step)}})).accepted.status, "ordinary"); for (const change of [{run_attempt: 3}, {run_attempt: 1}, {id: 98}, {status: "in_progress"}, {conclusion: "failure"}]) { assert.equal(await finalAttemptCheck({...currentAttempt, ...change}), false); @@ -4049,7 +4097,23 @@ function markerAccepted(overrides = {}) { await pendingRefreshCaller(["queued", "in_progress"], true); assert.equal((await recoveredFailure({absent: true})).accepted, "absent"); assert.equal((await recoveredFailure({noProducer: true})).accepted, "snapshot-pending"); - assert.equal((await recoveredFailure({candidate: {status: "in_progress"}})).accepted, "snapshot-pending"); + assert.equal((await recoveredFailure({noProducer: true, mutateProof(data) { + data.definitions[workflowPath].content = Buffer.from("wrong immutable producer").toString("base64"); + data.definitions[workflowPath].size = Buffer.byteLength("wrong immutable producer"); + }})).accepted, false, "an untrusted typed run must fail before waiting for omitted jobs"); + const marker = "Known canonical transition PLAY failure with successful authenticated cleanup"; + const ordinary = candidate.steps.map(step => step.name === marker + ? {...step, conclusion: "skipped"} : {...step}); + const ordinaryOptions = {candidate: {steps: ordinary}, mutateProof(data) {data.currentPullRequest.labels = [];}}; + assert.equal((await recoveredFailure(ordinaryOptions, null, identity, true)).accepted.status, "ordinary", + "an authenticated passing typed run with explicitly skipped exception needs no label"); + const ordinaryMissingCleanup = ordinary.map(step => step.name === "Stop smoke stack" + ? {...step, conclusion: "failure"} : step); + assert.equal((await recoveredFailure({...ordinaryOptions, candidate: {steps: ordinaryMissingCleanup}})).accepted, false, + "a typed recovery with unsuccessful cleanup is not ordinary proof"); + assert.equal((await recoveredFailure({...ordinaryOptions, candidate: {steps: ordinary.concat(ordinary.find(step => step.name === marker))}})).accepted, false, + "duplicate exception markers are terminal"); + assert.equal((await recoveredFailure({candidate: {status: "in_progress", conclusion: null}})).accepted, "snapshot-pending"); await pendingRefreshCaller(["absent", "queued", "completed"]); await pendingRefreshCaller(["missing-job", "pending-job", "completed"]); await pendingRefreshCaller(["absent", "absent"], true); @@ -4115,7 +4179,6 @@ function markerAccepted(overrides = {}) { d => {d.source.head_branch = "other";}, d => {d.latest.run_attempt++;}, d => {d.candidate.steps.find(s => s.name === "Stop smoke stack").conclusion = "failure";}, - d => {d.candidate.steps.find(s => s.name.startsWith("Known canonical transition")).conclusion = "skipped";}, d => {d.candidate.steps.find(s => s.name === "Export fixed-tag preview image artifact").conclusion = "success";}, d => {d.definitions[workflowPath].content = Buffer.from("untrusted workflow").toString("base64");}, ]) assert.equal((await recoveredFailure({mutateProof})).accepted, false); @@ -4146,7 +4209,7 @@ function markerAccepted(overrides = {}) { for (const event of ["pull_request", "repository_dispatch"]) { assert.equal(await verify(d => { d.legacyDefinition = true; - d.source.conclusion = d.latest.conclusion = d.candidate.conclusion = "failure"; + d.run.conclusion = d.source.conclusion = d.latest.conclusion = d.candidate.conclusion = "failure"; for (const step of d.candidate.steps) if (failures.includes(step.name)) step.conclusion = "failure"; }, event), true, "exact old fail-red default-branch producer remains a diagnostic exception only"); } @@ -4264,6 +4327,9 @@ async function run(kind, shared = {visible: false, posts: 0}) { repository: {full_name: repository}, head_repository: {full_name: repository}, created_at: "2026-11-18T00:00:00Z"}; const ci = {...source, id: 90, workflow_id: 8, path: ".github/workflows/ci.yml", name: "CI — Validation", display_title: `CI — Validation pr-42 base-${base} head-${head}`}; + const cancelledCase = kind.startsWith("cancel-"); + const olderCi = cancelledCase && kind !== "cancel-older-failed" ? {...ci, conclusion: "success"} : ci; + const newerCancelled = {...ci, id: 91, conclusion: "cancelled"}; const refresh = {...source, id: 110, event: "repository_dispatch", head_branch: "develop", head_sha: "d".repeat(40)}; const event = structuredClone(source); if (kind === "typed-callback") event.event = "repository_dispatch"; @@ -4278,6 +4344,10 @@ async function run(kind, shared = {visible: false, posts: 0}) { : {id: 7, path: source.path, name: source.name}}), getWorkflowRun: async ({run_id}) => { if (run_id === 91) metadataReads++; + if (cancelledCase && run_id === 90) return {data: olderCi}; + if (cancelledCase && run_id === 91) return {data: {...newerCancelled, + ...(kind === "cancel-rerun" && metadataReads > 1 ? {run_attempt: 2} : {}), + ...(kind === "cancel-native-failure" ? {conclusion: "failure"} : {})}}; if (run_id === 90 || run_id === 91) return {data: {...ci, id: run_id, ...(kind === "ci-rerun" || ["new-meta-rerun", "old-meta-rerun"].includes(kind) && run_id === 91 && metadataReads > 1 ? {run_attempt: 2} : {})}}; sourceReads++; @@ -4291,6 +4361,7 @@ async function run(kind, shared = {visible: false, posts: 0}) { runs = [{...ci, id: 91, ...(kind === "pending-newer" ? {status: "in_progress"} : {})}, ci]; if (kind === "new-meta-only") runs = runs.slice(0, 1); } + if (workflow_id === "ci.yml" && cancelledCase) runs = [newerCancelled, olderCi]; if (workflow_id === "ci.yml" && ciInventoryReads > 1 && kind.startsWith("late-ci-")) { runs = kind === "late-ci-absent" ? [] : [{...ci, id: 91, ...(kind === "late-ci-pending" ? {status: "in_progress"} : {})}, ci]; } @@ -4348,6 +4419,40 @@ async function run(kind, shared = {visible: false, posts: 0}) { if (kind === "new-meta-mixed") return [job, {...job, id: 32, name: "Validation Gate"}]; return [job]; } + if (cancelledCase) { + const newer = request.run_id === 91; + const result = newer ? "cancelled" : olderCi.conclusion; + const step = {name: "Enforce validation success", status: "completed", + conclusion: newer ? kind === "cancel-enforced" ? "failure" : "skipped" : result, + ...(kind === "cancel-missing-time" ? {} : {started_at: kind === "cancel-started" ? "2026-11-18T00:01:00Z" : null})}; + const gate = {id: 30, run_id: request.run_id, run_attempt: 1, head_sha: head, name: "Validation Gate", + workflow_name: "CI — Validation", status: "completed", + conclusion: newer && kind === "cancel-gate-failed" ? "failure" : result, + check_run_url: `https://api.github.com/repos/${repository}/check-runs/30`, + steps: [{name: "Preserve successful required gate on metadata-only edit", status: "completed", conclusion: "skipped"}, + ...(newer && kind === "cancel-missing-step" ? [] : [step])]}; + if (!newer) return [gate]; + if (kind === "cancel-upstream-malformed") return [gate, null]; + const upstream = {...gate, id: kind === "cancel-upstream-duplicate" ? gate.id : 31, + name: "Build and Test (account-service / 3)", + run_attempt: kind === "cancel-upstream-wrong-attempt" ? 2 : 1, + check_run_url: `https://api.github.com/repos/${repository}/check-runs/31`, + conclusion: ({ + "cancel-upstream-failure": "failure", "cancel-upstream-timeout": "timed_out", + "cancel-upstream-action": "action_required", "cancel-upstream-startup": "startup_failure", + "cancel-upstream-in-flight": "cancelled", + })[kind] ?? "success", + steps: kind === "cancel-upstream-step-failed" + ? [{name: "Run tests", status: "completed", conclusion: "failure"}] + : kind === "cancel-upstream-in-flight" + ? [{name: "Run tests", status: "completed", conclusion: "cancelled", started_at: "2026-11-18T00:01:00Z"}] + : [{name: "Run tests", status: "completed", conclusion: "success"}]}; + if (kind === "cancel-metadata-upstream-failure") return [ + {...gate, name: "PR Metadata Edit (Validation Gate)", conclusion: "skipped", steps: []}, + {...upstream, conclusion: "failure"}, + ]; + return [gate, upstream]; + } const metadata = kind === "metadata" || ["metadata-newer", "old-meta-rerun", "late-ci-old-metadata"].includes(kind) && request.run_id === 91; return [{id: 30, run_id: request.run_id, run_attempt: 1, head_sha: head, name: "Validation Gate", workflow_name: "CI — Validation", status: "completed", check_run_url: `https://api.github.com/repos/${repository}/check-runs/30`, @@ -4365,6 +4470,14 @@ async function run(kind, shared = {visible: false, posts: 0}) { } (async () => { assert.equal(await run("valid"), 1); + assert.equal(await run("cancel-before-enforcement"), 1); + for (const scenario of ["cancel-older-failed", "cancel-native-failure", "cancel-enforced", + "cancel-missing-time", "cancel-started", "cancel-rerun", "cancel-gate-failed", "cancel-missing-step", + "cancel-upstream-failure", "cancel-upstream-timeout", "cancel-upstream-action", "cancel-upstream-startup", + "cancel-upstream-step-failed", "cancel-upstream-in-flight", "cancel-upstream-duplicate", + "cancel-upstream-wrong-attempt", "cancel-upstream-malformed", "cancel-metadata-upstream-failure"]) { + assert.equal(await run(scenario), 0, scenario); + } assert.equal(await run("metadata-newer"), 1, "proven metadata completion cannot hide substantive CI"); for (const scenario of ["new-meta", "new-meta-expression", "new-meta-wrapped"]) { assert.equal(await run(scenario), 1, scenario); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index d5a3257952..6e45d425f2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -167,7 +167,14 @@ void budgetConflictDoesNotMaskRetainedHistoryAndFirstInstallStillChecksIt() { () -> transaction.executeWithoutResult( status -> budgets.provision(tenant.canonicalTenantId(), 2))) - .isInstanceOf(org.jooq.exception.DataAccessException.class); + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> { + assertThat(failure.sqlState()).isEqualTo("23514"); + assertThat(failure) + .hasMessageContaining( + "Capacity refusal budget cannot exclude retained evidence"); + }); assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_refusal_budget"))).isZero(); assertThatThrownBy( () -> @@ -406,8 +413,19 @@ void refusalBudgetRunsAfterIdentityArbitrationAndCountsTheInsertedLastSlot() thr dsl.fetchSingle( "SELECT *, xmin::text AS row_version FROM account_capacity_origin_decisions") .intoMap(); - // Exact retry must not spend another slot or update the immutable evidence. - assertThat(dsl.execute(insert, original)).isZero(); + var retainedBudget = + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget") + .intoMap(); + // The repository generates a new candidate decision ID on an exact retry. + Object[] retry = original.clone(); + retry[retry.length - 1] = UUID.randomUUID(); + assertThat(dsl.execute(insert, retry)).isZero(); + assertThat( + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget") + .intoMap()) + .isEqualTo(retainedBudget); assertThatThrownBy( () -> dsl.execute( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index 32b82b90e3..936a509cd8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -18,6 +18,7 @@ import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; import java.util.HexFormat; import java.util.Map; import java.util.Optional; @@ -37,6 +38,7 @@ import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountCapacityRefusalBudgetRepository; import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBinding; @@ -50,6 +52,11 @@ import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.CapacityException; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Completion; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation; import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -61,7 +68,10 @@ import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; @@ -71,6 +81,8 @@ import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.ContextClaims; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; @@ -362,6 +374,124 @@ void actualFirstJoinRetainsItsPositiveMembershipAndExactScopeBinding() { assertThat(value.toString()).doesNotContain(f.scope.connectScopeId(), CONTROLLED_COMPACT_TOKEN); } + @Test + void exactCapacityRefusalCommitsAndReplaysAfterHeadroomReturns() { + Fixture f = fixture(true, true); + var request = capacityRequest(f); + long quota = request.evidence().quota(); + assertThat(quota).isBetween(1L, 10L); + TenantCapacityAdmission.Request firstHold = null; + for (long used = 0; used < quota; used++) { + var occupying = capacityRequest(f); + assertThat(f.capacityOwner.commit(occupying, PEER).state()) + .isEqualTo(TenantCapacityAdmission.State.RESERVED); + if (firstHold == null) { + firstHold = occupying; + } + } + String readHeld = + "SELECT held_units FROM account_tenant_capacity_usage" + + " WHERE tenant_uuid=? AND owner_service='game-session-service'"; + assertThat(f.dsl.fetchSingle(readHeld, f.tenantId).get("held_units", Long.class)) + .isEqualTo(quota); + UUID requestId = request.identity().requestId(); + var decision = new java.util.concurrent.atomic.AtomicReference(); + assertThatThrownBy(() -> f.capacityOwner.commit(request, PEER)) + .isInstanceOfSatisfying( + CapacityException.class, + error -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(error.code()).isEqualTo(Failure.CAPACITY_QUOTA_EXCEEDED); + assertThat(error.durableDenialId()).isNotNull(); + decision.set(error.durableDenialId()); + }); + String readDenial = + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_decisions" + + " WHERE tenant_uuid=? AND request_id=? AND admission_id=?"; + Object[] identity = {f.tenantId, requestId, request.identity().admissionId()}; + var retained = f.dsl.fetchSingle(readDenial, identity).intoMap(); + assertThat(retained) + .containsEntry("decision", "NO_ACCEPT") + .containsEntry("refusal_code", "CAPACITY_QUOTA_EXCEEDED") + .containsEntry("decision_id", decision.get()); + String countDeniedReservations = + "SELECT count(*) AS n FROM account_tenant_capacity_reservations" + + " WHERE tenant_uuid=? AND request_id=? AND admission_id=?"; + assertThat(f.dsl.fetchSingle(countDeniedReservations, identity).get("n", Long.class)).isZero(); + + // The external no-execution observation is controlled; all Account storage mutations are real. + var recovery = + new AccountTenantCapacityRecoveryWorker( + f.capacityOwner, + f.dsl, + (occupying, reservation, deadline) -> + new AccountTenantCapacityRecoveryWorker.Observation( + PEER, + reservation, + net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest.preimage( + occupying), + AccountTenantCapacityRecoveryWorker.Disposition + .NOT_EXECUTED_AFTER_AUTHORIZATION, + occupying.admissionAttemptId(), + 7, + "sha256:" + "e".repeat(64), + "controlled-owner-no-execution".getBytes(StandardCharsets.US_ASCII)), + Clock.fixed(f.now, ZoneOffset.UTC)); + assertThat( + recovery + .reconcile( + java.util.Objects.requireNonNull(firstHold), + AccountTenantCapacityRecoveryWorker.NoCommitAction.RELEASE) + .state()) + .isEqualTo(TenantCapacityAdmission.State.RELEASED); + assertThat(f.dsl.fetchSingle(readHeld, f.tenantId).get("held_units", Long.class)) + .isEqualTo(quota - 1); + assertThatThrownBy(() -> f.capacityOwner.commit(request, PEER)) + .isInstanceOfSatisfying( + CapacityException.class, + error -> { + assertThat(error.code()).isEqualTo(Failure.CAPACITY_QUOTA_EXCEEDED); + assertThat(error.durableDenialId()).isEqualTo(decision.get()); + }); + assertThat(f.dsl.fetchSingle(readDenial, identity).intoMap()) + .usingRecursiveComparison() + .isEqualTo(retained); + assertThat(f.dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))) + .isEqualTo(Math.toIntExact(quota + 1)); + assertThat(f.dsl.fetchSingle(countDeniedReservations, identity).get("n", Long.class)).isZero(); + } + + private static TenantCapacityAdmission.Request capacityRequest(Fixture f) { + var entitlementRequest = f.request(); + var entitlement = f.owner.evaluate(entitlementRequest, CONTROLLED_COMPACT_TOKEN); + var evidence = + TenantCapacityAdmission.Evidence.parse( + entitlement.canonicalBytes(), TenantCapacityAdmission.Owner.GAME_SESSION); + UUID requestId = entitlementRequest.requestId(); + return new TenantCapacityAdmission.Request( + new TenantCapacityAdmission.Identity(f.tenantId, requestId, UUID.randomUUID()), + UUID.randomUUID(), + 1, + NAMESPACE, + new TenantCapacityAdmission.PlayerContext( + f.account.getAccountUuid(), + f.tenantId, + f.scope.playableStateNamespaceId(), + f.scope.gameInstanceId(), + UUID.randomUUID(), + UUID.randomUUID(), + f.scope.realmId(), + requestId, + f.scope.playableStateScope()), + TenantCapacityAdmission.Operation.CAPACITY_CREATING, + new TenantCapacityAdmission.Shape(0, 0, 0), + new TenantCapacityAdmission.Shape(1, 0, 0), + evidence, + 1L, + null) + .withDigest(); + } + @Test void blockedAccountSourceReadIsCancelledWithinOwnerTransactionBudget() throws Exception { Fixture f = fixture(false); @@ -442,6 +572,10 @@ public void beforeCommit(boolean readOnly) { } private Fixture fixture(boolean join) { + return fixture(join, false); + } + + private Fixture fixture(boolean join, boolean initializeCapacity) { String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); schemas.add(schema); DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); @@ -453,7 +587,7 @@ private Fixture fixture(boolean join) { .locations("classpath:db/migration") .load() .migrate(); - return new Fixture(dataSource, join); + return new Fixture(dataSource, join, initializeCapacity); } /** Controlled protected-client double: no physical GS/World source provenance is claimed. */ @@ -549,6 +683,7 @@ private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClien private static final class Fixture { private final DriverManagerDataSource dataSource; private final DSLContext dsl; + private final Instant now; private final TransactionTemplate transaction; private final AccountRepository accounts; private final AccountTenantMembershipRepository memberships; @@ -557,9 +692,11 @@ private static final class Fixture { private final UUID tenantId = UUID.randomUUID(); private final CanonicalJoinScopeV2 scope; private final AccountPlayerAdmissionEntitlementOwner owner; + private final AccountTenantCapacityOwner capacityOwner; - private Fixture(DriverManagerDataSource dataSource, boolean join) { + private Fixture(DriverManagerDataSource dataSource, boolean join, boolean initializeCapacity) { this.dataSource = dataSource; + now = initializeCapacity ? Instant.now().truncatedTo(ChronoUnit.MICROS) : NOW; dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); var transactions = new DataSourceTransactionManager(dataSource); transaction = new TransactionTemplate(transactions); @@ -647,13 +784,19 @@ private Fixture(DriverManagerDataSource dataSource, boolean join) { UUID.randomUUID(), 7, 3, - NOW.minusSeconds(20).toString(), - NOW.plusSeconds(120).toString()); + now.minusSeconds(20).toString(), + now.plusSeconds(120).toString()); String joinRequestId = UUID.randomUUID().toString(); String callerBinding = "controlled-join-caller"; transaction.execute( status -> { tenants.importVerified(tenantSource); + if (initializeCapacity) { + var bootstrap = new AccountTenantCreationBootstrapOperationRepository(dsl); + var claim = claimBootstrap(bootstrap, account, tenantSource); + bootstrap.complete(claim.requestId(), completion(claim)); + new AccountCapacityRefusalBudgetRepository(dsl).provision(tenantId, 1); + } sources.initializeIssuerIfAbsent(ISSUER); generations.initializeTenantIfAbsent(tenantId); generations.initialize( @@ -710,9 +853,9 @@ private Fixture(DriverManagerDataSource dataSource, boolean join) { mock(AccountGameplayCredentialRequestBinding.class), "a".repeat(64), UUID.randomUUID(), - NOW.minusSeconds(10).getEpochSecond(), - NOW.minusSeconds(10).getEpochSecond(), - NOW.plusSeconds(120).getEpochSecond()); + now.minusSeconds(10).getEpochSecond(), + now.minusSeconds(10).getEpochSecond(), + now.plusSeconds(120).getEpochSecond()); var candidate = mock(CommittedCandidateVerificationData.class); when(candidate.identity()).thenReturn(identity); when(candidate.authoritySnapshot()) @@ -745,6 +888,16 @@ private Fixture(DriverManagerDataSource dataSource, boolean join) { .isEqualTo(Connection.TRANSACTION_SERIALIZABLE)); return Optional.of(candidate); }); + capacityOwner = + new AccountTenantCapacityOwner( + dsl, + accounts, + snapshots, + issuances, + scopes, + transactions, + Clock.fixed(now, ZoneOffset.UTC), + NAMESPACE); var targets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); controlledTarget(targets); owner = @@ -761,7 +914,7 @@ private Fixture(DriverManagerDataSource dataSource, boolean join) { tenantEvents, targets, transactions, - Clock.fixed(NOW, ZoneOffset.UTC), + Clock.fixed(now, ZoneOffset.UTC), NAMESPACE); } @@ -786,6 +939,74 @@ private Request request() { } } + private static StoredOperation claimBootstrap( + AccountTenantCreationBootstrapOperationRepository operations, + Account creator, + FreshTenantCreationEvidence creation) { + UUID accountId = creator.getAccountUuid(); + UUID authorizationId = UUID.randomUUID(); + String authorizationDigest = + AccountTenantCreationBootstrapDigest.sha256( + "fixture authorization".getBytes(StandardCharsets.UTF_8)); + var evidence = + new FreshTenantCreatorEvidence( + 1, + creation, + accountId, + authorizationId, + authorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, accountId, authorizationId, authorizationDigest)); + byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence); + byte[] sourcePayload = "fixture source snapshot".getBytes(StandardCharsets.UTF_8); + byte[] requestPayload = + AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, sourcePayload); + var claim = + operations.claim( + evidence, + creatorPayload, + sourcePayload, + AccountTenantCreationBootstrapDigest.sha256(sourcePayload), + requestPayload, + AccountTenantCreationBootstrapDigest.sha256(requestPayload), + 1, + 1); + assertThat(claim.claimed()).isTrue(); + return claim.operation(); + } + + private static Completion completion(StoredOperation operation) { + // Controlled completion receipts exercise the real storage owner's guarded transition. + byte[] event = "fixture membership event".getBytes(StandardCharsets.UTF_8); + byte[] audit = "fixture bootstrap audit".getBytes(StandardCharsets.UTF_8); + byte[] result = "fixture bootstrap result".getBytes(StandardCharsets.UTF_8); + return new Completion( + 1, + operation.baselineMembershipVersion() + 1, + operation.baselineMembershipAuthorityGeneration(), + "ACTIVE", + false, + "[\"tenantAdmin\"]".getBytes(StandardCharsets.UTF_8), + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + operation.initiatingAccountUuid() + + "/" + + operation.tenantUuid(), + operation.requestId().toString(), + 1, + "fixture-membership-event", + AccountTenantCreationBootstrapDigest.sha256(event), + false, + event, + UUID.randomUUID(), + "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED", + Instant.now().truncatedTo(ChronoUnit.MICROS), + AccountTenantCreationBootstrapDigest.sha256(audit), + audit, + result, + AccountTenantCreationBootstrapDigest.sha256(result)); + } + private static FreshTenantCreationEvidence tenantSource(UUID tenantId) { UUID requestId = UUID.randomUUID(); UUID operationId = UUID.randomUUID(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index 1993fc61db..8a6c253430 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -18,6 +18,8 @@ import java.sql.SQLException; import java.time.Clock; import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; @@ -353,15 +355,24 @@ void rearmRetriesSerializationInFreshTransactionThenRechecksAccount() throws Exc null) .withDigest(); var aborted = serializationFailure(); + var lookups = new AtomicInteger(); when(f.accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) - .thenThrow(aborted) - .thenReturn(java.util.Optional.empty()); + .thenAnswer( + invocation -> { + f.transactionEvents.add("lookup"); + if (lookups.incrementAndGet() == 1) { + throw aborted; + } + return Optional.empty(); + }); var rearm = AccountTenantCapacityOwner.class.getDeclaredMethod( "rearm", Request.class, Request.class, UUID.class, long.class); rearm.setAccessible(true); assertThatThrownBy(() -> rearm.invoke(f.owner, f.request, next, UUID.randomUUID(), 7L)) .hasCauseInstanceOf(AccountTenantCapacityRepository.CapacityException.class); + assertThat(f.transactionEvents) + .containsExactly("begin", "lookup", "rollback", "begin", "lookup", "rollback"); verify(f.accounts, times(2)).findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT); verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } @@ -846,6 +857,7 @@ private static void qualifySources(Fixture f) { } private static final class Fixture { + private final List transactionEvents = new ArrayList<>(); private final DSLContext dsl = mock(DSLContext.class); private final AccountRepository accounts = mock(AccountRepository.class); private final AccountCanonicalRuntimeMembershipSnapshotRepository memberships = @@ -962,6 +974,7 @@ public TransactionStatus getTransaction( .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); assertThat(definition.getTimeout()).isEqualTo(5); assertThat(definition.isReadOnly()).isFalse(); + fixture.transactionEvents.add("begin"); fixture.pendingOriginDecision = null; TransactionSynchronizationManager.setActualTransactionActive(true); return new SimpleTransactionStatus(); @@ -977,6 +990,7 @@ public void commit(TransactionStatus status) { @Override public void rollback(TransactionStatus status) { + fixture.transactionEvents.add("rollback"); fixture.pendingOriginDecision = null; TransactionSynchronizationManager.setActualTransactionActive(false); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java index 4d10975cb5..5fe46d79f0 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java @@ -34,6 +34,8 @@ import net.firedevops.firemud.gamedesign.v1.PingResponse; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.springframework.boot.health.contributor.Health; class AbstractReloadingBlockingGrpcClientTest { @@ -120,8 +122,10 @@ void replacementStubIsPublishedWhenPreviousChannelStartsShutdown() throws Except verify(replacement).shutdown(); } - @Test - void selectedChannelSurvivesReplacementUntilTheBlockingCallReturns() throws Exception { + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void selectedChannelSurvivesReplacementOrCloseUntilTheBlockingCallReturns(boolean close) + throws Exception { var calls = new AtomicInteger(); var expectedResponse = PingResponse.getDefaultInstance(); var server = @@ -172,8 +176,14 @@ public void ping(PingRequest request, StreamObserver observer) { })); try { assertThat(selected.await(5, TimeUnit.SECONDS)).isTrue(); - client.reloadChannel(); - assertThat(client.requirePublishedExplicitStub().getChannel()).isSameAs(replacement); + if (close) { + client.close(); + assertThatThrownBy(client::requirePublishedExplicitStub) + .isInstanceOf(IllegalStateException.class); + } else { + client.reloadChannel(); + assertThat(client.requirePublishedExplicitStub().getChannel()).isSameAs(replacement); + } assertThat(previous.isShutdown()).isFalse(); assertThat(calls).hasValue(0); } finally { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index 3df512b368..c2fe219825 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -279,8 +279,9 @@ void successfulRpcPropagatesMinimumOfExplicitIncomingAndMaximumDeadline( assertThat(result.identity()).isEqualTo(request.identity()); } assertThat(calls).hasValue(2); + // Delivery can consume any portion of the budget; the controlled ticker asserts selection. assertThat(observedNanos.get()) - .isGreaterThan(TimeUnit.MILLISECONDS.toNanos(expectedMaximumMillis - 1_000L)) + .isPositive() .isLessThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(expectedMaximumMillis)); } finally { scheduler.shutdownNow(); From 1419755e3bbe22bd0fa26d7ce65041d172eeed34 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:33:37 +1300 Subject: [PATCH 26/96] Resolve seven Hosted review findings --- .../workflows/publish-pr-runtime-images.yml | 118 +++++++++++++----- .github/workflows/smoke.yml | 67 +++++++--- .../pr-required-gate-context-contract.sh | 106 ++++++++++++++-- .../AccountTenantCapacityGrpcServiceTest.java | 20 ++- .../AbstractReloadingBlockingGrpcClient.java | 23 ++-- ...stractReloadingBlockingGrpcClientTest.java | 96 ++++++++++---- 6 files changed, 335 insertions(+), 95 deletions(-) diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index a2d4cef347..ff01e3ec03 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -2,7 +2,7 @@ name: Publish PR Runtime Images on: workflow_run: - workflows: [Build Runtime Images] + workflows: [Build Runtime Images, "CI — Validation"] types: [completed] repository_dispatch: types: [pr-runtime-image-publication] @@ -14,7 +14,7 @@ permissions: {} jobs: reconcile-failed-pr-runtime: name: Reconcile Failed Original PR Runtime - if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && contains(fromJSON('["failure","cancelled","timed_out"]'), github.event.workflow_run.conclusion) && github.event.workflow_run.head_repository.full_name == github.repository }} + if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && ((github.event.workflow_run.path == '.github/workflows/runtime-images.yml' && contains(fromJSON('["failure","cancelled","timed_out"]'), github.event.workflow_run.conclusion)) || (github.event.workflow_run.path == '.github/workflows/ci.yml' && github.event.workflow_run.conclusion == 'cancelled')) && github.event.workflow_run.head_repository.full_name == github.repository }} runs-on: ubuntu-latest timeout-minutes: 5 concurrency: @@ -34,7 +34,8 @@ jobs: with: script: | const repository = `${context.repo.owner}/${context.repo.repo}`; - const event = context.payload.workflow_run; + const callback = context.payload.workflow_run; + let event = callback; const positive = value => Number.isSafeInteger(value) && value > 0; const sha = value => typeof value === "string" && /^[0-9a-f]{40}$/.test(value); const titlePattern = /^Build Runtime Images secure-pr-artifact pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40}) merge-([0-9a-f]{40}) mode-required$/; @@ -51,6 +52,68 @@ jobs: const trusted = run => run?.workflow_id === workflow.id && matchesPath(run.path, workflow.path) && run.repository?.full_name === repository && run.head_repository?.full_name === repository && [workflow.name, run.display_title].includes(run.name) && positive(run.id) && positive(run.run_attempt); + // Inventory incompleteness is unknown, never permission to dispatch duplicates. + const inventory = async (workflowId, filter) => { + const runs = [], ids = new Set(); + let total; + for (let page = 1; page <= 10; page++) { + const {data} = await github.rest.actions.listWorkflowRuns({ + ...context.repo, workflow_id: workflowId, per_page: 100, page, ...filter, + }); + total ??= data?.total_count; + if (!Number.isInteger(total) || total < 0 || total >= 1000 || data?.total_count !== total || + !Array.isArray(data.workflow_runs) || data.workflow_runs.length !== Math.min(100, total - runs.length)) { + throw new Error("Reconciliation inventory is incomplete; no dispatch issued"); + } + for (const run of data.workflow_runs) { + if (!positive(run.id) || ids.has(run.id)) throw new Error("Reconciliation inventory shifted; no dispatch issued"); + ids.add(run.id); runs.push(run); + } + if (runs.length === total) return runs; + } + throw new Error("Reconciliation inventory exceeds bounded pagination"); + }; + const validationTitle = /^CI — Validation pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40})$/; + const validationWake = validationTitle.exec(callback.display_title || ""); + let ciWorkflow = null; + let wakeCurrent = async () => true; + if (validationWake) { + const [, wakeNumber, wakeBase, wakeHead] = validationWake; + if (callback.conclusion !== "cancelled" || callback.head_sha !== wakeHead || + typeof callback.head_branch !== "string" || !callback.head_branch || + !positive(Number(wakeNumber))) return; + ({data: ciWorkflow} = await github.rest.actions.getWorkflow({...context.repo, workflow_id: "ci.yml"})); + if (!positive(ciWorkflow.id) || ciWorkflow.path !== ".github/workflows/ci.yml" || + ciWorkflow.name !== "CI — Validation") throw new Error("Untrusted CI workflow identity"); + const matchesWake = run => run?.id === callback.id && run.run_attempt === callback.run_attempt && + run.workflow_id === ciWorkflow.id && matchesPath(run.path, ciWorkflow.path) && + run.event === "pull_request" && run.status === "completed" && run.conclusion === "cancelled" && + run.repository?.full_name === repository && run.head_repository?.full_name === repository && + run.head_sha === wakeHead && run.head_branch === callback.head_branch && + run.display_title === callback.display_title && [ciWorkflow.name, callback.display_title].includes(run.name); + if (!matchesWake(callback)) return; + wakeCurrent = async () => { + const {data: current} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: callback.id}); + return matchesWake(current); + }; + if (!await wakeCurrent()) return; + let pr; + for (let attempt = 0; attempt < 6; attempt++) { + ({data: pr} = await github.rest.pulls.get({...context.repo, pull_number: Number(wakeNumber)})); + if (pr.state !== "open" || pr.head?.sha !== wakeHead || + pr.mergeable !== null || attempt === 5) break; + await new Promise(resolve => setTimeout(resolve, 2000)); + } + if (pr.state !== "open" || pr.head?.repo?.full_name !== repository || + pr.base?.repo?.full_name !== repository || pr.head?.sha !== wakeHead || + pr.head?.ref !== callback.head_branch || pr.mergeable !== true || !sha(pr.merge_commit_sha)) return; + const exactTitle = `Build Runtime Images secure-pr-artifact pr-${wakeNumber} base-${wakeBase} head-${wakeHead} merge-${pr.merge_commit_sha} mode-required`; + const runs = await inventory("runtime-images.yml", {event: "pull_request", head_sha: wakeHead}); + event = runs.filter(run => run.display_title === exactTitle).sort((a, b) => b.id - a.id)[0]; + if (!trusted(event) || event.event !== "pull_request" || event.status !== "completed" || + !["failure", "cancelled", "timed_out"].includes(event.conclusion) || + event.head_sha !== wakeHead || event.head_branch !== callback.head_branch) return; + } const match = titlePattern.exec(event.display_title || ""); if (!match) return; const [ , number, base, head, merge] = match; @@ -80,33 +143,12 @@ jobs: }; const baseRef = await currentTuple(); if (!baseRef) return; - // Inventory incompleteness is unknown, never permission to dispatch duplicates. - const inventory = async (workflowId, filter) => { - const runs = [], ids = new Set(); - let total; - for (let page = 1; page <= 10; page++) { - const {data} = await github.rest.actions.listWorkflowRuns({ - ...context.repo, workflow_id: workflowId, per_page: 100, page, ...filter, - }); - total ??= data?.total_count; - if (!Number.isInteger(total) || total < 0 || total >= 1000 || data?.total_count !== total || - !Array.isArray(data.workflow_runs) || data.workflow_runs.length !== Math.min(100, total - runs.length)) { - throw new Error("Reconciliation inventory is incomplete; no dispatch issued"); - } - for (const run of data.workflow_runs) { - if (!positive(run.id) || ids.has(run.id)) throw new Error("Reconciliation inventory shifted; no dispatch issued"); - ids.add(run.id); runs.push(run); - } - if (runs.length === total) return runs; - } - throw new Error("Reconciliation inventory exceeds bounded pagination"); - }; const originalSuperseded = async () => { const runs = await inventory("runtime-images.yml", {event: "pull_request", head_sha: head}); return runs.some(run => run.display_title === event.display_title && run.id > event.id); }; if (await originalSuperseded()) return; - const {data: ciWorkflow} = await github.rest.actions.getWorkflow({...context.repo, workflow_id: "ci.yml"}); + if (!ciWorkflow) ({data: ciWorkflow} = await github.rest.actions.getWorkflow({...context.repo, workflow_id: "ci.yml"})); if (!positive(ciWorkflow.id) || ciWorkflow.path !== ".github/workflows/ci.yml" || ciWorkflow.name !== "CI — Validation") { throw new Error("Untrusted CI workflow identity"); } @@ -123,6 +165,7 @@ jobs: const ciRuns = (await inventory("ci.yml", {event: "pull_request", head_sha: head})) .filter(run => run.display_title === ciTitle).sort((a, b) => b.id - a.id); let skippedPreEnforcementCancellation = false; + let skippedExactWake = false; // Metadata-only completions cannot conceal an earlier substantive attempt for this exact tuple. for (const candidate of ciRuns) { ci = candidate; @@ -190,6 +233,10 @@ jobs: const {data: latestCancelled} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); if (!matchesCi(latestCancelled) || latestCancelled.conclusion !== "cancelled") return null; skippedPreEnforcementCancellation = true; + if (validationWake && !skippedExactWake) { + if (ci.id !== callback.id || ci.run_attempt !== callback.run_attempt) return null; + skippedExactWake = true; + } ci = null; continue; } @@ -220,7 +267,7 @@ jobs: gate.conclusion !== "success" || enforcement[0].conclusion !== "success")) return null; break; } - return ci; + return validationWake && !skippedExactWake ? null : ci; }; ci = await selectCi(); if (!ci) return; @@ -245,7 +292,7 @@ jobs: const currentCi = await selectCi(); if (!currentCi || currentCi.id !== selectedCi.id || currentCi.run_attempt !== selectedCi.run_attempt) return; const {data: finalCi} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); - if (!matchesCi(finalCi) || finalCi.conclusion !== ci.conclusion || !await sourceCurrent() || await originalSuperseded() || await currentTuple() !== baseRef) return; + if (!matchesCi(finalCi) || finalCi.conclusion !== ci.conclusion || !await wakeCurrent() || !await sourceCurrent() || await originalSuperseded() || await currentTuple() !== baseRef) return; const dispatchStarted = new Date(Date.now() - 1000).toISOString(); let responseUnknown = false; try { @@ -261,19 +308,30 @@ jobs: } // Keep the shared lock during observation even when the one POST response was lost. const deadline = Date.now() + 120000; - while (!await newerRefresh(dispatchStarted)) { + for (;;) { + try { + if (await newerRefresh(dispatchStarted)) break; + } catch (error) { + const status = error?.status ?? error?.response?.status; + const code = error?.code ?? error?.cause?.code; + const transient = [408, 425, 429, 500, 502, 503, 504].includes(status) || + (status == null && ["ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", + "ENETUNREACH", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"].includes(code)); + if (!transient) throw error; + core.warning("Exact refresh visibility read is temporarily unavailable; keep observing without retrying the POST."); + } if (Date.now() >= deadline) { throw new Error(responseUnknown ? "Refresh dispatch attempted but visibility is unknown; no retry issued" : "Refresh dispatch accepted but visibility is unknown; no retry issued"); } - await new Promise(resolve => setTimeout(resolve, 5000)); + await new Promise(resolve => setTimeout(resolve, Math.min(5000, deadline - Date.now()))); } core.info(`Reconciled failed original runtime for PR #${number}; exact refresh is visible.`); source: name: Resolve Exact Runtime Publication Source - if: ${{ (github.event_name == 'workflow_run' && (github.event.workflow_run.event == 'pull_request' || github.event.workflow_run.event == 'repository_dispatch') && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_repository.full_name == github.repository) || (github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-image-publication' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) }} + if: ${{ (github.event_name == 'workflow_run' && github.event.workflow_run.path == '.github/workflows/runtime-images.yml' && (github.event.workflow_run.event == 'pull_request' || github.event.workflow_run.event == 'repository_dispatch') && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_repository.full_name == github.repository) || (github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-image-publication' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 5ff6ad3eb3..a5ce914160 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -1306,17 +1306,19 @@ jobs: expectedDisplayTitle, currentIdentity ); + // Only native same-repository originals eligible for the trusted + // Validation dispatcher reuse its existing prerequisite allowance. + const recoverableCancellation = matching.event === "pull_request" && + matching.repository?.full_name === repositoryName && + matching.head_repository?.full_name === repositoryName && + matching.path === workflowPath && positiveInteger(matching.workflow_id) && + positiveInteger(matching.id) && positiveInteger(matching.run_attempt) && + matching.head_sha === currentIdentity.headSha && matching.display_title === expectedDisplayTitle && + typeof matching.head_branch === "string" && matching.head_branch.length > 0 && + matching.head_branch === context.payload.pull_request.head.ref; + const cancellationDiscoveryMs = recoverableCancellation + ? refreshDiscoveryTimeoutMs : cancelledReplacementTimeoutMs; if (!replacement) { - // Only native same-repository originals eligible for the trusted - // Validation dispatcher reuse its existing prerequisite allowance. - const recoverableCancellation = matching.event === "pull_request" && - matching.repository?.full_name === repositoryName && - matching.head_repository?.full_name === repositoryName && - matching.path === workflowPath && positiveInteger(matching.workflow_id) && - positiveInteger(matching.id) && positiveInteger(matching.run_attempt) && - matching.head_sha === currentIdentity.headSha && matching.display_title === expectedDisplayTitle && - typeof matching.head_branch === "string" && matching.head_branch.length > 0 && - matching.head_branch === context.payload.pull_request.head.ref; if (recoverableCancellation && (pollIteration === 1 || pollIteration % pullRequestCheckInterval === 0)) { const liveIdentity = await resolveCurrentIdentity("Resolving live cancelled-run recovery tuple", true); if (liveIdentity?.obsolete) return; @@ -1328,8 +1330,6 @@ jobs: continue smokeGatePolling; } } - const cancellationDiscoveryMs = recoverableCancellation - ? refreshDiscoveryTimeoutMs : cancelledReplacementTimeoutMs; if (Date.now() - cancelledRunObservedAt >= cancellationDiscoveryMs) { if (await isCurrentPullRequestObsolete("Stopping obsolete cancelled-run smoke gate for")) { return; @@ -1346,6 +1346,27 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue; } + // A typed replacement follows the live base, even if its old event + // tuple already has a producer. Never switch the native original's + // immutable comparison; this fence applies only to the replacement. + const liveIdentity = await resolveCurrentIdentity("Fencing listed cancelled-run replacement", true); + if (liveIdentity?.obsolete) return; + if (!liveIdentity) { + if (Date.now() - cancelledRunObservedAt >= cancellationDiscoveryMs) { + core.setFailed("Cancelled runtime replacement lacks a verified live PR tuple."); + return; + } + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + const liveEventComparison = {...liveIdentity, sourceEvent: currentIdentity.sourceEvent}; + requireCurrentIdentity = true; + if (identityKey(liveEventComparison) !== identityKey(currentIdentity)) { + cancelledRecoveryMoved = true; + currentIdentity = liveIdentity; + continue smokeGatePolling; + } + currentIdentity = liveIdentity; core.info( `Exact pull_request runtime-images run ${matching.id} was cancelled; checking exact repository_dispatch replacement ${replacement.id}.` ); @@ -1595,6 +1616,7 @@ jobs: let fullSmokeJob = null; let fullSmokeStep = null; let canonicalProducerVerified = false; + let ordinaryMarkerProof = false; async function failNonTerminalSnapshot(reason) { if (await isCurrentPullRequestObsolete("Stopping obsolete stale-snapshot smoke gate for")) { return; @@ -1692,11 +1714,16 @@ jobs: const markers = (fullSmokeJob.steps ?? []).filter((step) => step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" ); + let markerProof = false; if (matching.event === "repository_dispatch" && (markers.length === 0 || (markers.length === 1 && markers[0].status !== "completed"))) { - const markerProof = await verifyKnownPlayFailure( + markerProof = await verifyKnownPlayFailure( matching, fullSmokeJob, currentIdentity, true, true); - if (["snapshot-pending", "ordinary", true].includes(markerProof)) { + if (markerProof === "ordinary") { + ordinaryMarkerProof = true; + canonicalProducerVerified = true; + } + if (markerProof === "snapshot-pending") { const snapshotKey = `marker:${matching.id}:${matching.run_attempt}:${identityKey(currentIdentity)}`; if (incompleteRefreshKey !== snapshotKey) { incompleteRefreshKey = snapshotKey; @@ -1708,11 +1735,11 @@ jobs: } } } - if (markers.length === 1 && markers[0].status === "completed" && - markers[0].conclusion === "success") { - let knownPlayVerified = false; + if (markerProof === true || (markers.length === 1 && markers[0].status === "completed" && + markers[0].conclusion === "success")) { + let knownPlayVerified = markerProof === true; try { - knownPlayVerified = await verifyKnownPlayFailure( + if (!knownPlayVerified) knownPlayVerified = await verifyKnownPlayFailure( matching, fullSmokeJob, currentIdentity, matching.event === "repository_dispatch"); } catch (error) { if (error instanceof TerminalGitHubRequestError) throw error; @@ -1801,6 +1828,10 @@ jobs: ); continue smokeGatePolling; } + if (ordinaryMarkerProof && !await isCurrentCanonicalAttempt(matching)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } return; } diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index af94cf014c..7bfd8b7651 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -853,6 +853,7 @@ async function scenario(kind, event = "pull_request") { reads += 1; return {data: {state: "open", head: {sha: head}, base: {ref: kind === "stale-final" && reads > 3 ? "other" : "develop", sha: base}, merge_commit_sha: merge}}; }}, + git: {getRef: async () => ({data: {ref: "refs/heads/develop", object: {sha: base}}})}, repos: { getCommit: async ({ref}) => ({data: {sha: ref, parents: [{sha: kind === "bad-parents" ? defaultSha : base}, {sha: head}]}}), getContent: async ({ref, path}) => { @@ -3763,6 +3764,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { if (options.originalError) throw options.originalError; const job = structuredClone(candidate); if (options.ordinaryAfterDrift) job.steps.find(s => s.name.startsWith("Known canonical")).conclusion = "skipped"; + if (options.omitGeneralMarker) job.steps = job.steps.filter(s => !s.name.startsWith("Known canonical")); return [job]; }}, "benhook1013", "FireMUD", canonicalSmokeJobName, (_label, call) => call(), async run => { if (options.directSnapshots && run.event === "repository_dispatch") { @@ -3844,7 +3846,9 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { if (options.ordinaryAfterDrift) { assert.deepEqual(failures, []); assert.deepEqual(outputs, []); assert.equal(writes, 0); } else if (options.directInvalid) { - assert.deepEqual(failures, [options.successfulSnapshots + assert.deepEqual(failures, [options.omitGeneralMarker + ? "Runtime smoke proof is missing its unambiguous transition-exception disposition." + : options.successfulSnapshots ? "Canonical PLAY transition exception could not be verified; runtime qualification remains blocked." : "Runtime images run 99 did not complete successfully: run=failure"]); assert.deepEqual(outputs, []); assert.equal(writes, 0); @@ -3892,7 +3896,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { // Exercise the exact production loop through cancellation of an old tuple and // a successful refresh of the new tuple. Only independently verified ordinary // proof is accepted; a title match and green job are insufficient. -async function movedCancellation(ordinaryProof) { +async function movedCancellation(ordinaryProof, listedOldReplacement = false) { let now = 0, typedReads = 0, proofReads = 0, finalReads = 0; const eventIdentity = {...identity, sourceEvent: "pull_request"}; const moved = {...identity, baseSha: "d".repeat(40), mergeSha: "e".repeat(40), sourceEvent: "repository_dispatch"}; @@ -3918,7 +3922,8 @@ async function movedCancellation(ordinaryProof) { {now: () => now}, 0, 100, 1, async (event, _title, selected) => { if (event === "pull_request") return old; typedReads++; - return selected.mergeSha === moved.mergeSha ? refresh : null; + return selected.mergeSha === moved.mergeSha ? refresh + : listedOldReplacement ? {...refresh, id: refresh.id - 1} : null; }, "3390", "test identity", 20, {payload: {pull_request: {head: {ref: "feature", repo: {full_name: repositoryName}}}}}, 60, 30, value => Number.isSafeInteger(value) && value > 0, async run => { @@ -4003,6 +4008,8 @@ function markerAccepted(overrides = {}) { await pendingRefreshCaller(["completed", "completed"], false, {transientFinal: true}); await movedCancellation(true); await movedCancellation(false); + await movedCancellation(true, true); + await movedCancellation(false, true); assert.equal((await recoveredFailure({original: {conclusion: "timed_out"}})).accepted, true); await pendingRefreshCaller(["queued", "completed"], false, {originalConclusion: "timed_out"}); for (const siblingStatus of ["in_progress", "queued"]) { @@ -4028,6 +4035,13 @@ function markerAccepted(overrides = {}) { snapshotExpires: directSnapshots.length === 4, directInvalid: directSnapshots[0] === "invalid", }); } + for (const state of ["complete", "invalid"]) { + await pendingRefreshCaller(["completed", "completed"], false, { + recoverDrift: true, finalIdentity: {baseSha: "d".repeat(40), mergeSha: "e".repeat(40)}, + directSnapshots: [state], successfulSnapshots: true, omitGeneralMarker: true, + directInvalid: state === "invalid", + }); + } await pendingRefreshCaller(["missing-step", "completed"]); await pendingRefreshCaller(["nonterminal-step", "completed"]); await pendingRefreshCaller(["missing-step", "missing-step", "missing-step", "completed"], false, {snapshotExpires: true}); @@ -4313,10 +4327,50 @@ assert queue_paths(runtime) == [("jobs", "dispatch-pr-base-refreshes", "concurre assert all("checkout" not in step.get("uses", "") for step in job["steps"]) assert "github.event.workflow_run.event == 'pull_request'" in job["if"] +assert publisher["on"]["workflow_run"] == { + "workflows": ["Build Runtime Images", "CI — Validation"], "types": ["completed"], +} +# Exercise the admission expressions themselves, not just the downstream JS proof. +import json +Path(sys.argv[2] + ".admission").write_text(json.dumps( + {name: publisher["jobs"][name]["if"] for name in ("source", "reconcile-failed-pr-runtime")} +)) Path(sys.argv[2]).write_text(next(step["with"]["script"] for step in job["steps"] if "github-script" in step.get("uses", ""))) PY node - "$smoke_clock_fixture.reconcile" <<'NODE' const assert = require("node:assert/strict"), fs = require("node:fs"); +const admission = JSON.parse(fs.readFileSync(process.argv[2] + ".admission", "utf8")); +const runtimePath = ".github/workflows/runtime-images.yml", validationPath = ".github/workflows/ci.yml"; +const topologyBase = "b".repeat(40), topologyHead = "a".repeat(40), topologyMerge = "c".repeat(40); +const runtimeName = `Build Runtime Images secure-pr-artifact pr-42 base-${topologyBase} head-${topologyHead} merge-${topologyMerge} mode-required`; +const validationName = `CI — Validation pr-42 base-${topologyBase} head-${topologyHead}`; +function admits(job, overrides = {}) { + const {eventName = "workflow_run", event = "pull_request", name = runtimeName, path = runtimePath, + conclusion = "success", foreign = false, action = "", branch = "main"} = overrides; + const expression = admission[job]; + assert.match(expression, /^\$\{\{ .* \}\}$/); + const evaluate = new Function("github", "contains", "fromJSON", "format", "return " + expression.slice(3, -2)); + return Boolean(evaluate({event_name: eventName, repository: "example/firemud", ref: "refs/heads/" + branch, + event: {action, repository: {default_branch: "main"}, + workflow_run: {name, display_title: name, path, event, conclusion, + head_repository: {full_name: foreign ? "fork/foreign" : "example/firemud"}}}}, + (values, value) => values.includes(value), JSON.parse, (template, arg) => template.replace("{0}", arg))); +} +const reconciler = "reconcile-failed-pr-runtime"; +const validation = {name: validationName, path: validationPath}; +for (const conclusion of ["success", "failure", "timed_out", "cancelled"]) { + assert.equal(admits("source", {...validation, conclusion}), false, conclusion); + assert.equal(admits(reconciler, {...validation, conclusion}), conclusion === "cancelled", conclusion); + assert.equal(admits("source", {conclusion}), conclusion === "success", conclusion); + assert.equal(admits(reconciler, {conclusion}), conclusion !== "success", conclusion); +} +assert.equal(admits("source", {path: ".github/workflows/untrusted.yml"}), false); +assert.equal(admits(reconciler, {...validation, path: ".github/workflows/untrusted.yml", conclusion: "cancelled"}), false); +assert.equal(admits(reconciler, {...validation, conclusion: "cancelled", event: "push"}), false); +assert.equal(admits(reconciler, {...validation, conclusion: "cancelled", foreign: true}), false); +assert.equal(admits("source", {event: "repository_dispatch"}), true); +assert.equal(admits("source", {eventName: "repository_dispatch", action: "pr-runtime-image-publication"}), true); +assert.equal(admits("source", {eventName: "repository_dispatch", action: "pr-runtime-image-publication", branch: "other"}), false); const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {${fs.readFileSync(process.argv[2], "utf8")}\n})()`); async function run(kind, shared = {visible: false, posts: 0}) { @@ -4327,11 +4381,18 @@ async function run(kind, shared = {visible: false, posts: 0}) { repository: {full_name: repository}, head_repository: {full_name: repository}, created_at: "2026-11-18T00:00:00Z"}; const ci = {...source, id: 90, workflow_id: 8, path: ".github/workflows/ci.yml", name: "CI — Validation", display_title: `CI — Validation pr-42 base-${base} head-${head}`}; + const wake = kind.startsWith("wake-"); + if (wake) kind = kind.slice("wake-".length); const cancelledCase = kind.startsWith("cancel-"); const olderCi = cancelledCase && kind !== "cancel-older-failed" ? {...ci, conclusion: "success"} : ci; const newerCancelled = {...ci, id: 91, conclusion: "cancelled"}; const refresh = {...source, id: 110, event: "repository_dispatch", head_branch: "develop", head_sha: "d".repeat(40)}; - const event = structuredClone(source); + const event = structuredClone(wake ? newerCancelled : source); + event.name = event.display_title; + if (kind === "cancel-wake-wrong-id") event.workflow_id = source.workflow_id; + if (kind === "cancel-wake-stale-head") event.head_sha = base; + if (kind === "cancel-wake-fork") event.head_repository.full_name = "fork/repo"; + if (kind === "cancel-wake-nonterminal") event.status = "in_progress"; if (kind === "typed-callback") event.event = "repository_dispatch"; if (kind === "nested-callback") event.event = "workflow_run"; if (kind === "fork") event.head_repository.full_name = "fork/repo"; @@ -4361,15 +4422,22 @@ async function run(kind, shared = {visible: false, posts: 0}) { runs = [{...ci, id: 91, ...(kind === "pending-newer" ? {status: "in_progress"} : {})}, ci]; if (kind === "new-meta-only") runs = runs.slice(0, 1); } - if (workflow_id === "ci.yml" && cancelledCase) runs = [newerCancelled, olderCi]; + if (workflow_id === "ci.yml" && cancelledCase) runs = kind === "cancel-wake-not-inventory" + ? [olderCi] : kind === "cancel-wake-newer-ci" ? [{...ci, id: 92, status: "in_progress"}, newerCancelled, olderCi] : [newerCancelled, olderCi]; if (workflow_id === "ci.yml" && ciInventoryReads > 1 && kind.startsWith("late-ci-")) { runs = kind === "late-ci-absent" ? [] : [{...ci, id: 91, ...(kind === "late-ci-pending" ? {status: "in_progress"} : {})}, ci]; } if (workflow_id === "runtime-images.yml" && runEvent === "pull_request") { - runs = kind === "newer-original" ? [{...source, id: 105, status: "in_progress"}] : [source]; + runs = ["newer-original", "cancel-wake-newer-original"].includes(kind) + ? [{...source, id: 105, status: "in_progress"}, source] : kind === "cancel-wake-no-original" ? [] : [source]; } if (workflow_id === "runtime-images.yml" && runEvent === "repository_dispatch" && shared.posts) { shared.observations = (shared.observations || 0) + 1; + if ((kind === "post-read-transient" && shared.observations === 1) || kind === "post-read-timeout") { + throw Object.assign(new Error("temporary post visibility error"), {status: 502}); + } + if (kind === "post-read-forbidden") throw Object.assign(new Error("visibility forbidden"), {status: 403}); + if (kind === "post-read-incomplete") return {data: {total_count: 1, workflow_runs: []}}; if (kind === "ambiguous-visible" && clock >= 5000) { shared.visible = true; runs = [refresh]; @@ -4462,7 +4530,8 @@ async function run(kind, shared = {visible: false, posts: 0}) { }}; await execute(github, {repo: {owner: "example", repo: "firemud"}, eventName: "workflow_run", payload: {workflow_run: event, repository: {default_branch: "develop"}}}, - {info: () => {}, setFailed: message => { shared.failure = message; }}, + {info: () => {}, warning: message => { (shared.warnings ??= []).push(message); }, + setFailed: message => { shared.failure = message; }}, class extends Date { static now() { return clock; } }, callback => {clock += 5000; callback();}); if (kind === "merge-unknown") assert.equal(tupleReads, 6, "unresolved mergeability retries are bounded"); if (kind === "merge-pending") assert.equal(tupleReads, 3, "one convergence retry plus final current tuple fence"); @@ -4471,6 +4540,15 @@ async function run(kind, shared = {visible: false, posts: 0}) { (async () => { assert.equal(await run("valid"), 1); assert.equal(await run("cancel-before-enforcement"), 1); + const delayedWake = {visible: false, posts: 0}; + assert.equal(await run("pending-newer", delayedWake), 0, "original completion cannot ignore pending CI"); + assert.equal(await run("wake-cancel-before-enforcement", delayedWake), 1, "exact cancelled CI wake restores liveness"); + assert.equal(await run("wake-cancel-before-enforcement", delayedWake), 1, "replayed wake does not redispatch"); + for (const scenario of ["cancel-wake-wrong-id", "cancel-wake-stale-head", "cancel-wake-fork", + "cancel-wake-nonterminal", "cancel-rerun", "cancel-upstream-step-failed", "cancel-older-failed", + "cancel-wake-not-inventory", "cancel-wake-newer-ci", "cancel-wake-newer-original", "cancel-wake-no-original"]) { + assert.equal(await run("wake-" + scenario), 0, scenario); + } for (const scenario of ["cancel-older-failed", "cancel-native-failure", "cancel-enforced", "cancel-missing-time", "cancel-started", "cancel-rerun", "cancel-gate-failed", "cancel-missing-step", "cancel-upstream-failure", "cancel-upstream-timeout", "cancel-upstream-action", "cancel-upstream-startup", @@ -4506,6 +4584,20 @@ async function run(kind, shared = {visible: false, posts: 0}) { await assert.rejects(run(scenario, state)); assert.equal(state.posts, ["incomplete", "at-cap"].includes(scenario) ? 0 : 1, "never retry unknown POST"); } + const readTransient = {visible: false, posts: 0}; + assert.equal(await run("post-read-transient", readTransient), 1); + assert.equal(readTransient.observations, 2); + assert.equal(readTransient.warnings.length, 1); + for (const [scenario, reason, observations] of [ + ["post-read-timeout", /accepted but visibility is unknown/, 25], + ["post-read-forbidden", /visibility forbidden/, 1], + ["post-read-incomplete", /inventory is incomplete/, 1], + ]) { + const state = {visible: false, posts: 0}; + await assert.rejects(run(scenario, state), reason); + assert.equal(state.posts, 1, "only the inventory read may retry"); + assert.equal(state.observations, observations, scenario); + } const rejectedPost = {visible: false, posts: 0}; await assert.rejects(run("rejected-post", rejectedPost), /validation rejected/); assert.equal(rejectedPost.posts, 1); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java index 60b858b516..685222f470 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -120,13 +120,13 @@ void invalidDomainRefusalIsSanitizedInternal() { } } - @Test - void typedOwnerEvidenceUnavailableKeepsItsPublicFailure() { + @ParameterizedTest + @MethodSource("ownerUnavailableFailures") + void unavailableOwnerFailureKeepsItsPublicNonOkStatus(RuntimeException failure) { var request = CapacityAdmissionTestFixture.playerRequest(); try (var guards = authenticatedCaller()) { AccountTenantCapacityOwner owner = mock(); - when(owner.commit(request, CapacityAdmissionTestFixture.PEER)) - .thenThrow(new CapacityException(Failure.ENTITLEMENT_UNAVAILABLE)); + when(owner.commit(request, CapacityAdmissionTestFixture.PEER)).thenThrow(failure); StreamObserver observer = mock(); new AccountTenantCapacityGrpcService(owner, "prod") .commitTenantCapacityAdmission( @@ -181,6 +181,18 @@ void retainedQuotaDenialCarriesTheExactAccountDecision() { } } + private static Stream ownerUnavailableFailures() { + return Stream.of( + new CapacityException(Failure.ENTITLEMENT_UNAVAILABLE), + new org.jooq.exception.DataAccessException( + "Controlled retained refusal failure", + new java.sql.SQLException("constraint", "23514")), + new org.springframework.dao.DataAccessResourceFailureException( + "Controlled storage failure"), + new org.springframework.transaction.TransactionSystemException( + "Controlled transaction failure")); + } + private static Stream ownerEvidenceFailures() { return Stream.of( new NumberFormatException("Controlled retained billing parse failure"), diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java index 2b13d1647e..e14ecd367c 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java @@ -273,24 +273,25 @@ private void cleanupAfterInitialisationFailure(Throwable failure) { closed = true; initialGeneration = publishGeneration(null, null); } - try { - retire(initialGeneration); - } catch (RuntimeException cleanupFailure) { - failure.addSuppressed(cleanupFailure); + if (markRetiredAndReadyToShutdown(initialGeneration)) { + try { + initialGeneration.channel.shutdown(); + } catch (RuntimeException cleanupFailure) { + if (cleanupFailure != failure) failure.addSuppressed(cleanupFailure); + } } } private void retire(ChannelGeneration previous) { + if (markRetiredAndReadyToShutdown(previous)) shutdownRetired(previous); + } + + private boolean markRetiredAndReadyToShutdown(ChannelGeneration previous) { synchronized (generationLock) { - if (previous == null || previous.retired) { - return; - } + if (previous == null || previous.retired) return false; previous.retired = true; - if (previous.activeCalls != 0) { - return; - } + return previous.activeCalls == 0; } - shutdownRetired(previous); } private void shutdownRetired(ChannelGeneration retired) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java index 5fe46d79f0..4a6fa0fbb8 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java @@ -6,7 +6,10 @@ import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -23,10 +26,12 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; +import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BooleanSupplier; +import java.util.function.Function; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; @@ -124,7 +129,7 @@ void replacementStubIsPublishedWhenPreviousChannelStartsShutdown() throws Except @ParameterizedTest @ValueSource(booleans = {false, true}) - void selectedChannelSurvivesReplacementOrCloseUntilTheBlockingCallReturns(boolean close) + void selectedChannelSurvivesReplacementOrCloseUntilBothBlockingCallsReturn(boolean close) throws Exception { var calls = new AtomicInteger(); var expectedResponse = PingResponse.getDefaultInstance(); @@ -152,28 +157,32 @@ public void ping(PingRequest request, StreamObserver observer) { var factory = mock(GrpcChannelFactory.class); when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) .thenReturn(previous, replacement); - var selected = new CountDownLatch(1); - var startCall = new CountDownLatch(1); + var selected = new CountDownLatch(2); + var startFirst = new CountDownLatch(1); + var startSecond = new CountDownLatch(1); try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory); - var executor = Executors.newSingleThreadExecutor()) { + var executor = Executors.newFixedThreadPool(2)) { client.initExplicit(); - var result = - executor.submit( - () -> - client.withPublishedInitializedStub( - "test client has no stub", - stub -> { - assertThat(stub.getChannel()).isSameAs(previous); - selected.countDown(); - try { - assertThat(startCall.await(5, TimeUnit.SECONDS)).isTrue(); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new AssertionError(interrupted); - } - return stub.withDeadlineAfter(5, TimeUnit.SECONDS) - .ping(PingRequest.getDefaultInstance()); - })); + Function> submitCall = + ready -> + executor.submit( + () -> + client.withPublishedInitializedStub( + "test client has no stub", + stub -> { + assertThat(stub.getChannel()).isSameAs(previous); + selected.countDown(); + try { + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError(interrupted); + } + return stub.withDeadlineAfter(5, TimeUnit.SECONDS) + .ping(PingRequest.getDefaultInstance()); + })); + var first = submitCall.apply(startFirst); + var second = submitCall.apply(startSecond); try { assertThat(selected.await(5, TimeUnit.SECONDS)).isTrue(); if (close) { @@ -186,12 +195,18 @@ public void ping(PingRequest request, StreamObserver observer) { } assertThat(previous.isShutdown()).isFalse(); assertThat(calls).hasValue(0); + startFirst.countDown(); + assertThat(first.get(5, TimeUnit.SECONDS)).isEqualTo(expectedResponse); + assertThat(calls).hasValue(1); + assertThat(previous.isShutdown()).isFalse(); + startSecond.countDown(); + assertThat(second.get(5, TimeUnit.SECONDS)).isEqualTo(expectedResponse); + assertThat(calls).hasValue(2); + assertThat(previous.isShutdown()).isTrue(); } finally { - startCall.countDown(); + startFirst.countDown(); + startSecond.countDown(); } - assertThat(result.get(5, TimeUnit.SECONDS)).isEqualTo(expectedResponse); - assertThat(calls).hasValue(1); - assertThat(previous.isShutdown()).isTrue(); } finally { replacement.shutdownNow(); } @@ -326,6 +341,37 @@ void initialisationFailurePreventsLateReloadFromCreatingAnotherChannel(@TempDir assertThat(factory.buildAttempts.get()).isEqualTo(1); } + @Test + void watcherStartFailureRetainsChannelShutdownFailure(@TempDir Path directory) throws Exception { + var grpc = new CommonGrpcClientProperties(); + grpc.setCertChain(directory.resolve("tls.crt").toString()); + grpc.setPrivateKey(directory.resolve("tls.key").toString()); + grpc.setCaCert(directory.resolve("ca.crt").toString()); + var factory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())).thenReturn(channel); + var startup = new IllegalStateException("watcher start failed"); + var shutdown = new IllegalStateException("channel shutdown failed"); + when(channel.shutdown()).thenThrow(shutdown); + + try (var policy = mockStatic(GrpcTlsReloadPolicy.class); + var watchers = + mockConstruction( + TlsCertificateWatcher.class, + (watcher, context) -> doThrow(startup).when(watcher).start()); + var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory)) { + policy.when(GrpcTlsReloadPolicy::isEnabled).thenReturn(true); + assertThatThrownBy(client::initExplicit) + .isSameAs(startup) + .satisfies(failure -> assertThat(failure.getSuppressed()).containsExactly(shutdown)); + assertThat(client.currentStub()).isNull(); + assertThatThrownBy(client::requirePublishedExplicitStub) + .isInstanceOf(IllegalStateException.class); + verify(watchers.constructed().getFirst()).close(); + verify(channel).shutdown(); + } + } + @Test void certificateChangeDuringInitialChannelBuildTriggersReload(@TempDir Path directory) throws Exception { From f6dad290d4276e3bf81246dfc092e308ebb4bad0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:30:46 +1300 Subject: [PATCH 27/96] Isolate live-base reads in retarget smoke contract --- dev-tools/tests/pr-retarget-workflow-contract.sh | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 68043e1e3b..811437e3d7 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -2938,7 +2938,7 @@ let eventMergeParents = [{ sha: baseSha }, { sha: headSha }]; let currentMergeParents = [{ sha: baseSha }, { sha: headSha }]; let availableRuns = []; let requestedCommitRefs = []; -let forbiddenCurrentBaseLookups = 0; +let currentBaseLookups = 0; let fakeNow = 1000; let onSmokeSleep = null; Date.now = () => fakeNow; @@ -3017,7 +3017,7 @@ const github = { }, git: { getRef: async () => { - forbiddenCurrentBaseLookups += 1; + currentBaseLookups += 1; return { data: { object: { sha: liveBaseSha } } }; }, }, @@ -3178,6 +3178,7 @@ checkPartialPaginationRetry().then(checkIdentityQuotaFailures).then(() => { const queryStart = workflowRunQueries.length; const jobStart = jobQueries.length; const dispatchQueryStart = repositoryDispatchQueryCount; + const currentBaseLookupStart = currentBaseLookups; availableRuns = [eventRun]; onRepositoryDispatchQuery = (queryCount) => { const replacementPoll = queryCount - dispatchQueryStart; @@ -3202,6 +3203,9 @@ checkPartialPaginationRetry().then(checkIdentityQuotaFailures).then(() => { if (jobQueries.length !== jobStart + 1 || jobQueries.at(-1).run_id !== 602) { throw new Error("Smoke Gate must wait for and validate the exact dispatch replacement smoke job"); } + if (currentBaseLookups <= currentBaseLookupStart) { + throw new Error("Smoke Gate must verify the live base before accepting a typed replacement"); + } }); }) .then(() => { @@ -3269,6 +3273,7 @@ checkPartialPaginationRetry().then(checkIdentityQuotaFailures).then(() => { eventMergeParents = [{ sha: baseSha }, { sha: headSha }]; const queryStart = workflowRunQueries.length; const jobStart = jobQueries.length; + const currentBaseLookupStart = currentBaseLookups; availableRuns = [ runtimeRun(303, runtimeTitle(currentBaseSha, headSha, currentMergeSha)), runtimeRun(304, `Build Runtime Images secure-pr-artifact pr-42 head-${headSha} mode-required`), @@ -3288,7 +3293,7 @@ checkPartialPaginationRetry().then(checkIdentityQuotaFailures).then(() => { if (jobQueries.length !== jobStart + 1 || jobQueries.at(-1).run_id !== 202) { throw new Error("Smoke Gate must select the exact successful event base/head/merge tuple"); } - if (forbiddenCurrentBaseLookups !== 0) { + if (currentBaseLookups !== currentBaseLookupStart) { throw new Error("Smoke Gate must not require the live base SHA to accept event-tuple smoke"); } }); From 6228254c262079f771c245bd2da77aebd63832d2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:02:05 +1300 Subject: [PATCH 28/96] Retain runtime refresh observation across transient inventory failures --- .github/workflows/runtime-images.yml | 14 ++++-- .github/workflows/smoke.yml | 13 ++++-- .../pr-required-gate-context-contract.sh | 46 +++++++++++++------ .../tests/pr-retarget-workflow-contract.sh | 19 ++++++++ 4 files changed, 72 insertions(+), 20 deletions(-) diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 1e54a955e4..fd3a422312 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1130,8 +1130,16 @@ jobs: } } } catch (error) { - core.setFailed(`Runtime refresh visibility is uncertain; no retry issued: ${error.message || error}`); - break; + const status = error?.status ?? error?.response?.status; + const code = error?.code ?? error?.cause?.code; + const transient = [408, 425, 429, 500, 502, 503, 504].includes(status) || + (status == null && ["ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", + "ENETUNREACH", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"].includes(code)); + if (!transient) { + core.setFailed(`Runtime refresh visibility is uncertain; no retry issued: ${error.message || error}`); + break; + } + core.warning("Runtime refresh visibility read is temporarily unavailable; keep observing without retrying any POST."); } if (pendingVisibility.length === 0) break; if (Date.now() >= visibilityDeadline) { @@ -1139,7 +1147,7 @@ jobs: core.setFailed(`Refresh dispatch ${dispatchState} but visibility is unknown for PRs ${pendingVisibility.map(item => item.tuple.prNumber).join(", ")}; no retry issued`); break; } - await new Promise(resolve => setTimeout(resolve, 5000)); + await new Promise(resolve => setTimeout(resolve, Math.min(5000, visibilityDeadline - Date.now()))); } build-base-image: diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index a5ce914160..ec3442c949 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -611,9 +611,14 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "107a7bc895f890173161ea09f707ce93d8e170093aa8c8c528fc5f98430e1bac"; - // Trusted refreshes can still execute the previous successful default-branch definition. - const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = "ea6ade0f69718573aeac4e4b5a1e9050e53e1e3cef3426b8791f182d8d49e112"; + const canonicalRuntimeWorkflowSha256 = "74f09918bb8a3ae02594264ed9a3be91d1d49e619a83e02dd0321ea1efd78800"; + // Only authenticated default-branch refreshes may use retained successful definitions. + // Keep the pre-rollout default and predecessor definitions for mixed-version runs. + const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set([ + "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b", // default at 3b81c438 + "107a7bc895f890173161ea09f707ce93d8e170093aa8c8c528fc5f98430e1bac", // immediate pre-retry definition + "ea6ade0f69718573aeac4e4b5a1e9050e53e1e3cef3426b8791f182d8d49e112", // existing trusted refresh + ]); // Retain the exact fail-red producer still executed by trusted base refreshes. const canonicalLegacyRuntimeWorkflowSha256 = "db0acb4e51630b729eb92362ea3e748f3f96b06d8ef5ca466a718ded67725804"; // Include held-admission proof, authenticated cleanup, and their executed inputs. @@ -732,7 +737,7 @@ jobs: function isSuccessfulRuntimeWorkflowDefinition(definitionHash, sourceEvent) { return definitionHash === canonicalRuntimeWorkflowSha256 || (sourceEvent === "repository_dispatch" && - definitionHash === canonicalPreviousTrustedRefreshRuntimeWorkflowSha256); + canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256.has(definitionHash)); } async function verifyCanonicalSmokeProducer(run, candidate, identity) { diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 7bfd8b7651..db306ec1dc 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3528,9 +3528,16 @@ const workflowPath = ".github/workflows/runtime-images.yml"; const repositoryName = "benhook1013/FireMUD"; const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; const canonicalRuntimeWorkflowSha256 = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); -const previousRefreshBytes = Buffer.concat([bytes, Buffer.from("\n# Previous trusted refresh definition\n")]); -const canonicalPreviousTrustedRefreshRuntimeWorkflowSha256 = require("node:crypto").createHash("sha256") - .update(previousRefreshBytes).digest("hex"); +const compatibleRefreshBytes = Array.from({length: 3}, (_, index) => + Buffer.concat([bytes, Buffer.from(`\n# Retained trusted refresh definition ${index}\n`)])); +const digest = source => require("node:crypto").createHash("sha256").update(source).digest("hex"); +const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set(compatibleRefreshBytes.map(digest)); +const checkedInCompatibility = script.match(/const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set\(\[([\s\S]*?)\]\);/)[1]; +assert.deepEqual([...checkedInCompatibility.matchAll(/"([0-9a-f]{64})"/g)].map(match => match[1]), [ + "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b", + "107a7bc895f890173161ea09f707ce93d8e170093aa8c8c528fc5f98430e1bac", + "ea6ade0f69718573aeac4e4b5a1e9050e53e1e3cef3426b8791f182d8d49e112", +]); // Separate test authority lets the same verifier exercise both immutable modes. const canonicalLegacyRuntimeWorkflowSha256 = "0".repeat(64); const canonicalPlayClassifierSha256 = JSON.parse(script.match(/const canonicalPlayClassifierSha256 = (\{[\s\S]*?\});/)[1]); @@ -3584,10 +3591,10 @@ async function verify(mutate = () => {}, event = "pull_request", knownPlay = tru }}}}; const verifier = knownPlay ? "verifyKnownPlayFailure" : "verifyCanonicalSmokeProducer"; const accepted = await new Function("github", "prNumber", "repositoryName", "canonicalSmokeJobName", "workflowPath", - "canonicalRuntimeWorkflowSha256", "canonicalPreviousTrustedRefreshRuntimeWorkflowSha256", "canonicalLegacyRuntimeWorkflowSha256", "canonicalPlayClassifierSha256", "positiveInteger", "withTransientGitHubRetry", "context", "owner", "repo", "require", "data", + "canonicalRuntimeWorkflowSha256", "canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256", "canonicalLegacyRuntimeWorkflowSha256", "canonicalPlayClassifierSha256", "positiveInteger", "withTransientGitHubRetry", "context", "owner", "repo", "require", "data", `${fn}; return ${verifier}(data.run, data.candidate, data.identity, ${allowIncompleteSteps}, ${allowOrdinary});`)( github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, - canonicalPreviousTrustedRefreshRuntimeWorkflowSha256, + canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256, data.legacyDefinition ? canonicalRuntimeWorkflowSha256 : canonicalLegacyRuntimeWorkflowSha256, canonicalPlayClassifierSha256, value => Number.isSafeInteger(value) && value > 0, (_label, call) => call(), {payload: {repository: {default_branch: "develop"}, pull_request: {head: {repo: {full_name: data.eventHeadRepository}}}}}, @@ -4228,14 +4235,27 @@ function markerAccepted(overrides = {}) { }, event), true, "exact old fail-red default-branch producer remains a diagnostic exception only"); } assert.equal(await verify(() => {}, "repository_dispatch"), true); - const usePreviousRefresh = data => Object.assign(data.definitions[workflowPath], { - content: previousRefreshBytes.toString("base64"), size: previousRefreshBytes.length, - }); - for (const knownPlay of [true, false]) { - assert.equal(await verify(usePreviousRefresh, "repository_dispatch", knownPlay), true, - "trusted refresh may retain the previous successful producer proof"); - assert.equal(await verify(usePreviousRefresh, "pull_request", knownPlay), false, - "the previous successful definition cannot attest a PR producer"); + for (const definition of compatibleRefreshBytes) { + const usePriorRefresh = data => Object.assign(data.definitions[workflowPath], { + content: definition.toString("base64"), size: definition.length, + }); + for (const knownPlay of [true, false]) { + assert.equal(await verify(usePriorRefresh, "repository_dispatch", knownPlay), true, + "authenticated default-branch refresh may use a retained successful definition"); + assert.equal(await verify(usePriorRefresh, "pull_request", knownPlay), false, + "a retained success digest cannot attest a native PR producer"); + assert.equal(await verify(data => { + usePriorRefresh(data); + data.source.head_branch = "untrusted-feature"; + }, "repository_dispatch", knownPlay), false, + "a retained success digest does not grant feature branches authority"); + } + } + const arbitraryBytes = Buffer.concat([bytes, Buffer.from("\n# Independently rehashed, not allowlisted\n")]); + for (const event of ["pull_request", "repository_dispatch"]) { + assert.equal(await verify(data => Object.assign(data.definitions[workflowPath], { + content: arbitraryBytes.toString("base64"), size: arbitraryBytes.length, + }), event), false, "an arbitrary recomputed digest is not authority"); } for (const path of Object.keys(classifierDefinitions)) { assert.equal(await verify(d => { diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 811437e3d7..2f33f95b78 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -1544,6 +1544,25 @@ async function runDispatcher({ "broad preflight still checks native producers"); assert(manyInvisible.inventoryCalls.some(request => request.event === "repository_dispatch" && request.created !== visibilityFloor), "broad preflight still checks existing dispatch producers"); + const transientTuples = [tuple, tupleFor(102, "a", "c")]; + let transientReads = 0; + const transient = await runDispatcher({tuples: transientTuples, visibilityResponse: (_request, posted) => { + if (++transientReads === 1) throw Object.assign(new Error("temporarily unavailable"), {status: 502}); + return {total_count: posted.length, workflow_runs: posted}; + }}); + assert.deepEqual(numbers(transient), ["101", "102"], "retry visibility only, never either accepted POST"); + assert.equal(transientReads, 2); + assert.equal(transient.waitedMillis, 5000); + assert.deepEqual(transient.errors, []); + for (const [failure, reason] of [ + [() => { throw Object.assign(new Error("visibility forbidden"), {status: 403}); }, "visibility forbidden"], + [() => ({total_count: 1, workflow_runs: []}), "recent run inventory is incomplete"], + ]) { + const terminal = await runDispatcher({tuples: transientTuples, visibilityResponse: failure}); + assert.deepEqual(numbers(terminal), ["101", "102"]); + assert.equal(terminal.waitedMillis, 0, "untrusted or unauthorized snapshot is terminal"); + assert(terminal.errors.some(message => message.includes(reason))); + } const multiPageObservation = await runDispatcher({tuples: [tuple], visibilityResponse: ({page}, [posted]) => ({ total_count: 101, workflow_runs: page === 1 ? Array.from({length: 100}, (_, index) => ({ From 0b0bfbe5e9a6db60ff288bf8d5eaa0fc7aea068d Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 01:15:46 +1300 Subject: [PATCH 29/96] Strengthen reloading gRPC client tests --- ...stractReloadingBlockingGrpcClientTest.java | 34 ++++++++++++++++--- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java index 82aad2568f..e11deefb88 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java @@ -97,6 +97,28 @@ void explicitLifecycleInitializesOnceAndRejectsUseAfterClose() throws Exception .hasMessage("test client is closed"); } + @Test + void publishedStubIsUnavailableToLeasedCallsUntilExplicitInitialization() throws Exception { + var grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + var beforeInit = mock(ManagedChannel.class); + var afterInit = mock(ManagedChannel.class); + var factory = mock(GrpcChannelFactory.class); + when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(beforeInit, afterInit); + try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory)) { + client.reloadChannel(); + assertThat(client.currentStub()).isNotNull(); + assertThat(client.currentStub().getChannel()).isSameAs(beforeInit); + assertThatThrownBy(client::requirePublishedExplicitStub) + .isInstanceOf(IllegalStateException.class) + .hasMessage("test client is not initialized and available"); + + client.initExplicit(); + assertThat(client.requirePublishedExplicitStub().getChannel()).isSameAs(afterInit); + } + } + @Test void replacementStubIsPublishedWhenPreviousChannelStartsShutdown() throws Exception { var grpc = new CommonGrpcClientProperties(); @@ -159,9 +181,9 @@ public void ping(PingRequest request, StreamObserver observer) { var selected = new CountDownLatch(2); var startFirst = new CountDownLatch(1); var startSecond = new CountDownLatch(1); - try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory); - var executor = Executors.newFixedThreadPool(2)) { + try (var client = new TestClient(new ServiceEndpointsProperties(), grpc, factory)) { client.initExplicit(); + var executor = Executors.newFixedThreadPool(2); Function> submitCall = ready -> executor.submit(() -> @@ -171,7 +193,7 @@ public void ping(PingRequest request, StreamObserver observer) { assertThat(stub.getChannel()).isSameAs(previous); selected.countDown(); try { - assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + ready.await(); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new AssertionError(interrupted); @@ -179,9 +201,9 @@ public void ping(PingRequest request, StreamObserver observer) { return stub.withDeadlineAfter(5, TimeUnit.SECONDS) .ping(PingRequest.getDefaultInstance()); })); - var first = submitCall.apply(startFirst); - var second = submitCall.apply(startSecond); try { + var first = submitCall.apply(startFirst); + var second = submitCall.apply(startSecond); assertThat(selected.await(5, TimeUnit.SECONDS)).isTrue(); if (close) { client.close(); @@ -204,6 +226,8 @@ public void ping(PingRequest request, StreamObserver observer) { } finally { startFirst.countDown(); startSecond.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); } } finally { replacement.shutdownNow(); From bf1c5529dc614964742f39ba7a33ae3d692dc8d8 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 13:01:47 +1300 Subject: [PATCH 30/96] Fix retained FireMUD #3451 review findings --- .github/workflows/runtime-images.yml | 85 +++-- .github/workflows/smoke.yml | 63 +++- .../account-service/runtime-and-data.md | 2 + .../pr-required-gate-context-contract.sh | 64 +++- .../tests/pr-retarget-workflow-contract.sh | 31 +- ...countCapacityOriginDecisionRepository.java | 48 ++- ..._index_retained_capacity_refusal_slots.sql | 77 +++++ ...acityMigrationPostgresIntegrationTest.java | 325 ++++++++++++++++++ 8 files changed, 623 insertions(+), 72 deletions(-) create mode 100644 services/account-service/src/main/resources/db/migration/V1040.6__index_retained_capacity_refusal_slots.sql diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index cb7928d671..1de602fdc1 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -731,29 +731,29 @@ jobs: return {...refined, absenceProven: false}; }; + const expectedWorkflowPath = ".github/workflows/runtime-images.yml"; + const workflowPathMatches = (path) => { + if (path === expectedWorkflowPath) { + return true; + } + const prefix = `${expectedWorkflowPath}@`; + if (typeof path !== "string" || !path.startsWith(prefix)) { + return false; + } + const ref = path.slice(prefix.length); + if (ref.length === 0 || ref === "@" || ref.endsWith(".") || + /[\u0000-\u0020\u007f]/.test(ref) || + ["~", "^", ":", "?", "*", "[", "\\"].some((character) => ref.includes(character)) || + ref.includes("..") || ref.includes("@{")) { + return false; + } + return ref.split("/").every((part) => + part.length > 0 && part !== "." && part !== ".." && + !part.startsWith(".") && + !part.endsWith(".lock") + ); + }; const findExactExistingProducer = (tuple, inventory) => { - const expectedWorkflowPath = ".github/workflows/runtime-images.yml"; - const workflowPathMatches = (path) => { - if (path === expectedWorkflowPath) { - return true; - } - const prefix = `${expectedWorkflowPath}@`; - if (typeof path !== "string" || !path.startsWith(prefix)) { - return false; - } - const ref = path.slice(prefix.length); - if (ref.length === 0 || ref === "@" || ref.endsWith(".") || - /[\u0000-\u0020\u007f]/.test(ref) || - ["~", "^", ":", "?", "*", "[", "\\"].some((character) => ref.includes(character)) || - ref.includes("..") || ref.includes("@{")) { - return false; - } - return ref.split("/").every((part) => - part.length > 0 && part !== "." && part !== ".." && - !part.startsWith(".") && - !part.endsWith(".lock") - ); - }; const expectedTitle = `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} ` + `base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; @@ -1115,16 +1115,49 @@ jobs: // One shared bounded observation window, not 120 seconds multiplied by the fan-out size. // The dispatcher lock remains held; no POST is retried even when visibility is uncertain. const visibilityDeadline = Date.now() + 120000; - while (pendingVisibility.length > 0) { + const expectedRepository = `${context.repo.owner}/${context.repo.repo}`; + const defaultBranch = context.payload.repository?.default_branch; + let runtimeWorkflow = null; + if (pendingVisibility.length > 0) { + try { + if (context.payload.repository?.full_name !== expectedRepository || + typeof defaultBranch !== "string" || !defaultBranch) { + throw new Error("Repository identity or default branch is unavailable"); + } + const {data: workflow} = await github.rest.actions.getWorkflow({ + ...context.repo, workflow_id: "runtime-images.yml", + }); + if (!Number.isSafeInteger(workflow?.id) || workflow.id <= 0 || + workflow.path !== expectedWorkflowPath || workflow.name !== "Build Runtime Images") { + throw new Error("Current runtime workflow identity is not trusted"); + } + runtimeWorkflow = workflow; + } catch (error) { + core.setFailed(`Runtime refresh visibility is unconfirmed because the producer workflow identity could not be trusted; no retry issued: ${error.message || error}`); + } + } + while (pendingVisibility.length > 0 && runtimeWorkflow) { try { const observed = await readInventory(visibilitySince, ["repository_dispatch"]); if (!observed.complete) throw new Error("Accepted refresh has incomplete visibility; no retry issued"); for (let index = pendingVisibility.length - 1; index >= 0; index--) { const {tuple, previousIds, dispatchSince, responseUnknown} = pendingVisibility[index]; const exactTitle = `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; - if (observed.runs.some(run => run.event === "repository_dispatch" && - run.display_title === exactTitle && !previousIds.has(run.id) && - validTimestamp(run.created_at) && Date.parse(run.created_at) >= Date.parse(dispatchSince))) { + const freshExactRuns = observed.runs.filter(run => run.event === "repository_dispatch" && + run.display_title === exactTitle && !previousIds.has(run.id) && + validTimestamp(run.created_at) && Date.parse(run.created_at) >= Date.parse(dispatchSince)); + for (const run of freshExactRuns) { + if (!Number.isSafeInteger(run.id) || run.id <= 0 || run.workflow_id !== runtimeWorkflow.id || + !workflowPathMatches(run.path) || + ![runtimeWorkflow.name, exactTitle].includes(run.name) || + run.repository?.full_name !== expectedRepository || + run.head_repository?.full_name !== expectedRepository || + run.head_branch !== defaultBranch || + typeof run.head_sha !== "string" || !/^[0-9a-f]{40}$/.test(run.head_sha)) { + throw new Error(`run ${run.id} has the exact PR tuple title but untrusted native workflow identity`); + } + } + if (freshExactRuns.length > 0) { pendingVisibility.splice(index, 1); if (responseUnknown) core.info(`Runtime refresh for PR #${tuple.prNumber} became visible after an unknown POST response.`); } diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 292112e714..d98bcd5785 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -611,7 +611,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "e37356b17221b496cdaa8e2a5a588f511d645b8806f11177e646420869b8feba"; + const canonicalRuntimeWorkflowSha256 = "27c615ce72a367a234759b3940e1345ef1eb43f67775ae4865d39e1902e1be65"; // Only authenticated default-branch refreshes may use retained successful definitions. // Keep the pre-rollout default and predecessor definitions for mixed-version runs. const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set([ @@ -917,7 +917,11 @@ jobs: // Typed refresh workflow authority is its native default-branch revision; // the executed classifier source still belongs to the verified PR merge. const workflowSha = source.event === "pull_request" ? identity.mergeSha : source.head_sha; - for (const path of [workflowPath, ...Object.keys(canonicalPlayClassifierSha256)]) { + // Only the exception relies on the historical PLAY classifier. + // An unpublished marker stays pending until its disposition is known. + const definitionPaths = ordinary || unknownDisposition + ? [workflowPath] : [workflowPath, ...Object.keys(canonicalPlayClassifierSha256)]; + for (const path of definitionPaths) { const { data: definition } = await withTransientGitHubRetry( `immutable PLAY classifier definition lookup: ${path}`, () => github.rest.repos.getContent({ @@ -1288,6 +1292,7 @@ jobs: expectedDisplayTitle, currentIdentity ); + let sameTupleCancellationDeadline = null; if ( currentIdentity.sourceEvent === "pull_request" && cancelledRunId !== null && @@ -1366,13 +1371,15 @@ jobs: continue smokeGatePolling; } const liveEventComparison = {...liveIdentity, sourceEvent: currentIdentity.sourceEvent}; - requireCurrentIdentity = true; if (identityKey(liveEventComparison) !== identityKey(currentIdentity)) { cancelledRecoveryMoved = true; + requireCurrentIdentity = true; currentIdentity = liveIdentity; continue smokeGatePolling; } - currentIdentity = liveIdentity; + // Continue polling the original event until this replacement + // supplies proof or the comparison actually moves. + sameTupleCancellationDeadline = cancelledRunObservedAt + cancellationDiscoveryMs; core.info( `Exact pull_request runtime-images run ${matching.id} was cancelled; checking exact repository_dispatch replacement ${replacement.id}.` ); @@ -1411,6 +1418,10 @@ jobs: incompleteRefreshObservedAt = Date.now(); } if (Date.now() - incompleteRefreshObservedAt >= completedSnapshotTimeoutMs) { + if (sameTupleCancellationDeadline !== null && Date.now() < sameTupleCancellationDeadline) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } core.setFailed("Terminal canonical refresh did not expose complete smoke-job proof within the snapshot convergence allowance."); return; } @@ -1562,15 +1573,28 @@ jobs: return; } } + if (sameTupleCancellationDeadline !== null && Date.now() < sameTupleCancellationDeadline) { + core.info("Cancelled-run replacement did not supply proof; checking again for the original attempt."); + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } core.setFailed( `Runtime images run ${matching.id} did not complete successfully: run=${matching.conclusion}` ); return; } - const latestIdentity = await resolveCurrentIdentity( - "Stopping stale completed smoke gate for", requireCurrentIdentity - ); + async function fenceCompletedRuntimeIdentity(label) { + const resolved = await resolveCurrentIdentity( + label, requireCurrentIdentity || matching.event === "repository_dispatch"); + if (!resolved || resolved.obsolete || sameTupleCancellationDeadline === null) return resolved; + const eventComparison = {...resolved, sourceEvent: currentIdentity.sourceEvent}; + if (identityKey(eventComparison) === identityKey(currentIdentity)) return eventComparison; + cancelledRecoveryMoved = true; + requireCurrentIdentity = true; + return resolved; + } + const latestIdentity = await fenceCompletedRuntimeIdentity("Stopping stale completed smoke gate for"); if (latestIdentity?.obsolete) { return; } @@ -1622,7 +1646,11 @@ jobs: let fullSmokeJob = null; let fullSmokeStep = null; let canonicalProducerVerified = false; - let ordinaryMarkerProof = false; + const typedRuntimeProof = matching.event === "repository_dispatch"; + if (typedRuntimeProof && !positiveInteger(matching.run_attempt)) { + core.setFailed("Typed runtime smoke producer lacks an exact attempt."); + return; + } async function failNonTerminalSnapshot(reason) { if (await isCurrentPullRequestObsolete("Stopping obsolete stale-snapshot smoke gate for")) { return; @@ -1648,11 +1676,14 @@ jobs: const jobs = await withTransientGitHubRetry( "runtime-images job lookup", () => github.paginate( - github.rest.actions.listJobsForWorkflowRun, + typedRuntimeProof + ? "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" + : github.rest.actions.listJobsForWorkflowRun, { owner, repo, run_id: matching.id, + ...(typedRuntimeProof ? {attempt_number: matching.run_attempt} : {}), per_page: 100, } ) @@ -1668,6 +1699,13 @@ jobs: return; } fullSmokeJob = producerJobs[0] ?? null; + if (typedRuntimeProof && fullSmokeJob && + (fullSmokeJob.run_id !== matching.id || + fullSmokeJob.run_attempt !== matching.run_attempt || + fullSmokeJob.head_sha !== matching.head_sha)) { + await failNonTerminalSnapshot("with a producer from a different runtime attempt"); + return; + } fullSmokeStep = fullSmokeJob?.steps?.find( (step) => step.name === "Run credential-free full-stack smoke" ) ?? null; @@ -1726,7 +1764,6 @@ jobs: markerProof = await verifyKnownPlayFailure( matching, fullSmokeJob, currentIdentity, true, true); if (markerProof === "ordinary") { - ordinaryMarkerProof = true; canonicalProducerVerified = true; } if (markerProof === "snapshot-pending") { @@ -1821,9 +1858,7 @@ jobs: ); return; } - const finalIdentity = await resolveCurrentIdentity( - "Stopping stale smoke gate before accepting full-stack proof", requireCurrentIdentity - ); + const finalIdentity = await fenceCompletedRuntimeIdentity("Stopping stale smoke gate before accepting full-stack proof"); if (finalIdentity?.obsolete) { return; } @@ -1834,7 +1869,7 @@ jobs: ); continue smokeGatePolling; } - if (ordinaryMarkerProof && !await isCurrentCanonicalAttempt(matching)) { + if (typedRuntimeProof && !await isCurrentCanonicalAttempt(matching)) { await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index c09e969038..a61b0a959d 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -90,6 +90,8 @@ Strict capacity follows the canonical [capacity-attempt proof obligations](../.. V1040.1 serializes the exact Account `ACCEPTED` and `NO_ACCEPT` origin decisions against reservation creation and rearm. A pre-V1040.1 writer cannot create a reservation after the guard applies. Upgrading a retained Account database requires independently verified [writer quiescence](../../system-architecture-database-migrations.md#version-aware-migration-checklist), including closed writer endpoints and exclusion of old writers. V1040.2 retains an exact quota denial under an explicitly installed finite tenant refusal limit. The same serializable owner transaction checks quota and chooses between a reservation and a denial. The denial carries no reservation and permanently excludes acceptance for the exact original. Exact replay returns the same decision even after capacity becomes available. An unavailable refusal budget or uncertain outcome leaves Game Session's reserve active. Account neither frees nor rearms an accepted reservation through this path. Before enabling any admission producer, the Account operator must provision every supported canonical tenant through `AccountCapacityRefusalBudgetRepository.provision` and call `requireReady` with the same explicit lifetime limit and the bounded admission cohort headroom in one writable owner transaction while producers remain quiescent. Commit only after both succeed; otherwise roll back the undersized installation so it does not permanently bind an unusable limit. Sizing is explicit: the finite lifetime limit must cover retained denials plus the planned denial cohort; it is not the gameplay capacity quota or an automatically replenished rate limit. Exact provisioning retries preserve the row and its historical evidence; a different limit conflicts. Missing, mismatched or insufficient budgets fail readiness. Readiness is a local observation, not a reservation or authority to admit, and the SQL trigger remains the runtime concurrency authority. Exhaustion requires stopping new admission and an independently designed retention-safe lifecycle, never deleting denials or resetting/increasing this immutable budget. No exhaustion detector or admission-producer stop control is implemented by these private repositories: the positive reservation path does not consult refusal headroom. Qualifying that stop, including last-slot consumption followed by available capacity, is an unmet activation prerequisite; provisioning readiness alone cannot satisfy it. These private methods do not register an endpoint, seed tenants automatically or activate the default-off capacity component. +V1040.6 backfills one immutable refusal slot per retained `NO_ACCEPT` decision. After origin identity arbitration, a fresh refusal takes the existing tenant budget lock, reads the highest slot through the tenant-slot index, and appends the next slot in the same transaction. Replay, conflict, and failed inserts leave the inventory unchanged. The migration preserves origin rows and provisioned limits. + The unregistered capacity owner requires exact retained evidence and current Account membership/issuance/scope source equality before creating a new positive player-binding reservation. Exact attempt retries replay before fresh-source or usage work; changed complete payloads conflict. The Account recovery component alone can finalize, release or rearm under its current durable claim and exact selected-owner readback; an ambiguous observation records only the bounded retry/deadline and retains the hold. No runtime readback producer or recovery client is registered. World lifecycle, authoritative prior-shape/zero-delta recovery, current selected-owner activation and complete end-to-end qualification remain held as detailed in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). The canonical gameplay LOGIN primary-credential adapter reuses Account’s password and email-OTP authority without creating a legacy token or session. Its owner transaction retains the verified challenge identity and consumes it only after new PENDING issuance; denial accounting and expiry cleanup commit under the existing owner denial path. Exact pending retry does not reverify or reconsume. Canonical-only verification pads to two KDF comparisons with non-authorizing process-local random decoy evidence using the existing Argon2 profile. The adapter participates only in the explicitly enabled protected LOGIN composition; default deployment behavior remains unchanged. Focused unit and real PostgreSQL proof and its controlled upstream/external-owner limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). Deployed authenticated issuance and timing parity remain unproved. diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 5b75472a03..810513e46e 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -629,6 +629,7 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single") { let now = 1000; const start = now; const failures = []; + let typedCurrentChecks = 0; const listRuns = async () => {}, listJobs = async () => {}; const cancelledSource = runId => ({id: runId, workflow_id: 7, run_attempt: 1, event: "pull_request", status: "completed", conclusion: "cancelled", path: ".github/workflows/runtime-images.yml", @@ -649,9 +650,16 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single") { git: {getRef: async () => ({data: {ref: "refs/heads/develop", object: {sha: base}}})}, actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs, getWorkflow: async () => ({data: {id: 7, path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images"}}), - getWorkflowRun: async ({run_id}) => ({data: {id: run_id, - run_attempt: selectionCase === "cancelled-changed-attempt" ? 2 : 1, - status: "completed", conclusion: "cancelled"}}) }, + getWorkflowRun: async ({run_id}) => { + if (run_id === 44) { + typedCurrentChecks++; + const rerunning = selectionCase === "recoverable-replacement-rerun" && typedCurrentChecks === 1; + return {data: {id: run_id, run_attempt: rerunning || selectionCase === "recoverable-replacement-rerun" ? 2 : 1, + status: rerunning ? "in_progress" : "completed", conclusion: rerunning ? null : "success"}}; + } + return {data: {id: run_id, run_attempt: selectionCase === "cancelled-changed-attempt" ? 2 : 1, + status: "completed", conclusion: "cancelled"}}; + } }, }, request: async (route, input) => { assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"); assert.equal(input.attempt_number, 1); @@ -662,16 +670,26 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single") { steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; } assert.equal(method, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); + if (input.run_id === 44) { + assert.equal(input.attempt_number, selectionCase === "recoverable-replacement-rerun" && typedCurrentChecks > 0 ? 2 : 1); + return [{id: 144, run_id: 44, run_attempt: input.attempt_number, head_sha: "d".repeat(40), + name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", + steps: [{name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]}]; + } return cancellationJobs(input.run_id); } }; github.paginate.iterator = async function* (method, input) { assert.equal(method, listRuns); assert.equal(input.workflow_id, "runtime-images.yml"); if (input.event === "repository_dispatch") { - const ready = selectionCase === "recoverable-delayed" && now - start >= 6 * 60 * 1000; - yield {data: ready ? [{id: 44, workflow_id: 7, run_attempt: 1, event: "repository_dispatch", + const originalRerun = selectionCase === "recoverable-original-rerun"; + const replacementRerun = selectionCase === "recoverable-replacement-rerun"; + const ready = originalRerun || replacementRerun || selectionCase === "recoverable-delayed" && now - start >= 6 * 60 * 1000; + const waiting = originalRerun && now === start; + yield {data: ready ? [{id: 44, workflow_id: 7, run_attempt: replacementRerun && typedCurrentChecks > 0 ? 2 : 1, event: "repository_dispatch", head_sha: "d".repeat(40), head_branch: "develop", display_title: title, - status: "completed", conclusion: "success", created_at: "2026-09-01T00:00:01Z"}] : []}; + status: waiting ? "queued" : "completed", conclusion: waiting ? null : originalRerun ? "failure" : "success", + created_at: "2026-09-01T00:00:01Z"}] : []}; return; } assert.equal(input.head_sha, head); @@ -684,6 +702,12 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single") { path: ".github/workflows/runtime-images.yml"} : {})}); const active = makeRun(42, "2026-09-01T00:00:00Z", complete ? "completed" : "in_progress", complete ? outcome : null); const cancelled = makeRun(43, "2026-09-01T00:00:00Z", "completed", "cancelled"); + if (selectionCase === "recoverable-original-rerun" || selectionCase === "recoverable-replacement-rerun") { + const originalPassing = selectionCase === "recoverable-original-rerun" && complete; + yield {data: [{...cancelled, id: 42, run_attempt: originalPassing ? 2 : 1, + conclusion: originalPassing ? "success" : "cancelled"}]}; + return; + } if (selectionCase === "duplicate" || selectionCase === "cancelled-higher-id") { yield { data: selectionCase === "duplicate" ? [ {...active, status: "completed", conclusion: "cancelled"}, {...active, id: 43}, @@ -769,6 +793,12 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single") { const delayedRecovery = await scenario("cancelled", 0, "recoverable-delayed"); assert.deepEqual(delayedRecovery.failures, []); assert.equal(delayedRecovery.minutes, 6, "Validation may dispatch an exact replacement after five minutes"); + const originalRerun = await scenario("success", 1, "recoverable-original-rerun"); + assert.deepEqual(originalRerun.failures, [], "a queued then failed same-tuple replacement cannot hide the successful original rerun"); + assert.equal(originalRerun.minutes, 1); + const replacementRerun = await scenario("cancelled", 0, "recoverable-replacement-rerun"); + assert.deepEqual(replacementRerun.failures, [], "a stale ordinary typed attempt must poll again and use the current one"); + assert.ok(replacementRerun.minutes > 0, "the first passing jobs snapshot belonged to an attempt that was no longer current"); const lateCancellation = await scenario("cancelled", 80, "recoverable-missing"); assert.equal(lateCancellation.minutes, 90, "late cancellation cannot extend global deadline"); assert.match(lateCancellation.failures[0], /Timed out waiting for the exact/); @@ -3602,7 +3632,12 @@ async function verify(mutate = () => {}, event = "pull_request", knownPlay = tru value => Number.isSafeInteger(value) && value > 0, (_label, call) => call(), {payload: {repository: {default_branch: "develop"}, pull_request: {head: {repo: {full_name: data.eventHeadRepository}}}}}, "benhook1013", "FireMUD", require, data); - if (accepted) assert.deepEqual(contentRequests, knownPlay ? [workflowPath, ...Object.keys(classifierDefinitions)] : [workflowPath]); + const pendingMarker = accepted === "snapshot-pending" && allowOrdinary && + event === "repository_dispatch" && data.source.conclusion === "success" && + !data.jobs.some(job => job.steps.some(step => step.name.startsWith("Known canonical") && step.status === "completed")); + if (accepted) assert.deepEqual(contentRequests, + knownPlay && accepted !== "ordinary" && !pendingMarker + ? [workflowPath, ...Object.keys(classifierDefinitions)] : [workflowPath]); return accepted; } // Final attempt authority remains separate from PR identity and label authority. @@ -3724,7 +3759,7 @@ async function selectedProducerFinalFence(event, moved = false) { } // Execute the failed-run branch so proof errors retain the deterministic failure diagnostic. const legacyFailedStart = script.indexOf('if (matching.conclusion !== "success")'); -const legacyFailedEnd = script.indexOf("const latestIdentity", legacyFailedStart); +const legacyFailedEnd = script.indexOf("async function fenceCompletedRuntimeIdentity", legacyFailedStart); const legacyFailedBranch = script.slice(legacyFailedStart, legacyFailedEnd); async function failedLegacyProof(stage, error, event = "pull_request") { const warnings = [], failures = [], outputs = []; @@ -3738,7 +3773,7 @@ async function failedLegacyProof(stage, error, event = "pull_request") { "canonicalSmokeJobName", "currentIdentity", "withTransientGitHubRetry", "verifyKnownPlayFailure", "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", "core", "verifyFailedPullCanonicalRefresh", "context", "resolveCurrentIdentity", "identityKey", `return (async () => { let absentRefreshKey = null, discoveredRefreshKey = null, absentRefreshObservedAt = null; - let incompleteRefreshKey = null, incompleteRefreshObservedAt = null; + let incompleteRefreshKey = null, incompleteRefreshObservedAt = null, sameTupleCancellationDeadline = null; smokeGatePolling: while (true) { ${legacyFailedBranch} break; } })();`); await execute({...source, conclusion: "failure", event}, repositoryName, github, "benhook1013", "FireMUD", canonicalSmokeJobName, identity, (_label, call) => call(), async () => {throw error;}, async () => false, @@ -4271,6 +4306,15 @@ function markerAccepted(overrides = {}) { ]) assert.equal(await verify(d => {Object.assign(d.definitions[path], change);}), false, `${path}: ${JSON.stringify(change)}`); await assert.rejects(verify(d => {delete d.definitions[path];}), /definition unavailable/); } + assert.equal(await verify(d => { + const marker = d.jobs[0].steps.find(step => step.name.startsWith("Known canonical")); + marker.conclusion = "skipped"; + d.currentPullRequest.labels = []; + const compose = d.definitions["docker/docker-compose.smoke-images.override.yml"]; + const changed = Buffer.concat([Buffer.from(compose.content, "base64"), Buffer.from("\n# changed compose\n")]); + Object.assign(compose, {content: changed.toString("base64"), size: changed.length}); + }, "repository_dispatch", true, false, true), "ordinary", + "the exact ordinary proof must not depend on exception-only classifier hashes"); for (const stackPr of [3405, 3409, 3407, 3408, 3410]) { assert.equal(await verify(d => {d.pr = String(stackPr); d.source.display_title = d.source.display_title.replace("pr-3390", `pr-${stackPr}`);}), true); } @@ -4552,7 +4596,7 @@ async function run(kind, shared = {visible: false, posts: 0}) { {name: "Enforce validation success", status: "completed", conclusion: metadata ? "skipped" : "failure"}]}]; }}; await execute(github, {repo: {owner: "example", repo: "firemud"}, eventName: "workflow_run", - payload: {workflow_run: event, repository: {default_branch: "develop"}}}, + payload: {workflow_run: event, repository: {full_name: repository, default_branch: "develop"}}}, {info: () => {}, warning: message => { (shared.warnings ??= []).push(message); }, setFailed: message => { shared.failure = message; }}, class extends Date { static now() { return clock; } }, callback => {clock += 5000; callback();}); diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 2f33f95b78..c0b30ddacd 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -865,6 +865,7 @@ const titleFor = (tuple) => `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; const producer = (tuple, event, status, conclusion = null, overrides = {}) => ({ id: Number(tuple.prNumber) * 100 + (event === "pull_request" ? 1 : 2), + workflow_id: 701, name: "Build Runtime Images", path: ".github/workflows/runtime-images.yml", event, @@ -872,6 +873,7 @@ const producer = (tuple, event, status, conclusion = null, overrides = {}) => ({ repository: { full_name: repository }, head_repository: { full_name: repository }, head_sha: event === "pull_request" ? tuple.headSha : baseSha, + head_branch: event === "pull_request" ? "feature/ci" : "develop", pull_requests: event === "pull_request" ? [{ number: Number(tuple.prNumber), head: { sha: tuple.headSha } }] : [], @@ -1016,9 +1018,9 @@ async function runDispatcher({ }, }, actions: { - getWorkflow: async () => ({ data: { - id: ciRun.workflow_id, path: ".github/workflows/ci.yml", name: "CI — Validation", ...(ciEvidence.workflow ?? {}), - } }), + getWorkflow: async ({workflow_id}) => ({ data: workflow_id === "runtime-images.yml" + ? {id: 701, path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images"} + : {id: ciRun.workflow_id, path: ".github/workflows/ci.yml", name: "CI — Validation", ...(ciEvidence.workflow ?? {})} }), getWorkflowRun: async () => { ciRunReads += 1; return { data: { ...ciRun, ...(ciEvidence.run ?? {}), ...(ciRunReads > 1 ? ciEvidence.latest ?? {} : {}) } }; @@ -1571,6 +1573,16 @@ async function runDispatcher({ })}); assert.deepEqual(multiPageObservation.inventoryCalls.filter(request => request.created === visibilityFloor).map(request => request.page), [1, 2]); assert.equal(multiPageObservation.errors.length, 0, "an exact newly visible dispatch on the second page is accepted"); + for (const invalidIdentity of [ + {head_branch: "feature/ci"}, {workflow_id: 703}, {path: ".github/workflows/ci.yml"}, + {repository: {full_name: "other/repo"}}, {head_repository: {full_name: "fork/repo"}}, + ]) { + const conflicting = await runDispatcher({tuples: [tuple], visibilityResponse: (_request, [posted]) => ({ + total_count: 1, workflow_runs: [{...posted, ...invalidIdentity}], + })}); + assert.deepEqual(numbers(conflicting), ["101"], "a conflicting native identity never retries the POST"); + assert(conflicting.errors.some(error => error.includes("untrusted native workflow identity"))); + } const shiftedObservation = await runDispatcher({tuples: [tuple], visibilityResponse: ({page}, [posted]) => ({ total_count: page === 1 ? 101 : 102, workflow_runs: page === 1 ? Array.from({length: 100}, (_, index) => ({ @@ -2993,6 +3005,8 @@ function dispatchRun(id, base, head, merge) { return { ...runtimeRun(id, runtimeTitle(base, head, merge)), event: "repository_dispatch", + run_attempt: 1, + head_sha: base, }; } @@ -3051,13 +3065,20 @@ const github = { }; }, }, - actions: { listWorkflowRuns, listJobsForWorkflowRun }, + actions: { listWorkflowRuns, listJobsForWorkflowRun, + getWorkflowRun: async ({run_id}) => ({data: availableRuns.find(run => run.id === run_id)}), + }, }, paginate: async (method, input) => { - if (method === listJobsForWorkflowRun) { + if (method === listJobsForWorkflowRun || + method === "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs") { jobQueries.push(input); + const run = availableRuns.find(row => row.id === input.run_id); return [{ name: "PR Full-Stack Smoke", + run_id: input.run_id, + run_attempt: input.attempt_number, + head_sha: run?.head_sha, status: "completed", conclusion: "success", steps: [{ diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java index 6940b02b27..147309351f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java @@ -28,14 +28,8 @@ public AccountCapacityOriginDecisionRepository(DSLContext dsl) { /** Read only. Missing row is not a refusal. */ public Record find(Request request) { transaction(); - Record row = - dsl.fetchOne( - "SELECT * FROM account_capacity_origin_decisions WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND capacity_rearm_fence = ?", - request.identity().tenantId(), - request.identity().requestId(), - request.identity().admissionId(), - request.capacityRearmFence()); - if (row != null) requireExact(request, row); + Record row = findRow(request); + if (row != null) requireExact(request, row, CapacityAdmissionDigest.preimage(request)); return row; } @@ -64,9 +58,11 @@ public UUID refuseQuota(Request request) { } private Record retain(Request request, String decision, String refusalCode) { - Record existing = find(request); + transaction(); + byte[] canonicalPayload = CapacityAdmissionDigest.preimage(request); + Record existing = find(request, canonicalPayload); if (existing != null) return requireOutcome(existing, decision, refusalCode); - requireFreshAttemptBinding(request); + requireFreshAttemptBinding(request, canonicalPayload); int inserted = 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, refusal_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", @@ -76,14 +72,14 @@ private Record retain(Request request, String decision, String refusalCode) { request.capacityRearmFence(), request.admissionAttemptId(), request.mutationDigest(), - CapacityAdmissionDigest.preimage(request), + canonicalPayload, decision, UUID.randomUUID(), refusalCode); if (inserted != 0 && inserted != 1) throw unavailable(); - Record row = find(request); + Record row = find(request, canonicalPayload); if (row == null) { - requireFreshAttemptBinding(request); + requireFreshAttemptBinding(request, canonicalPayload); throw unavailable(); } return requireOutcome(row, decision, refusalCode); @@ -91,6 +87,10 @@ private Record retain(Request request, String decision, String refusalCode) { /** SERIALIZABLE caller: include pre-origin reservations and retained rearm history. */ public void requireFreshAttemptBinding(Request request) { + requireFreshAttemptBinding(request, CapacityAdmissionDigest.preimage(request)); + } + + private void requireFreshAttemptBinding(Request request, byte[] canonicalPayload) { Record conflict = dsl.fetchOne( "SELECT 1 FROM (" @@ -104,10 +104,25 @@ public void requireFreshAttemptBinding(Request request) { request.identity().admissionId(), request.capacityRearmFence(), request.mutationDigest(), - CapacityAdmissionDigest.preimage(request)); + canonicalPayload); if (conflict != null) throw conflict(); } + private Record find(Request request, byte[] canonicalPayload) { + Record row = findRow(request); + if (row != null) requireExact(request, row, canonicalPayload); + return row; + } + + private Record findRow(Request request) { + return dsl.fetchOne( + "SELECT * FROM account_capacity_origin_decisions WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND capacity_rearm_fence = ?", + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.capacityRearmFence()); + } + private static Record requireOutcome(Record row, String decision, String refusalCode) { if (!decision.equals(row.get("decision", String.class)) || !Objects.equals(refusalCode, row.get("refusal_code", String.class))) { @@ -116,11 +131,10 @@ private static Record requireOutcome(Record row, String decision, String refusal return row; } - private static void requireExact(Request request, Record row) { + private static void requireExact(Request request, Record row, byte[] canonicalPayload) { if (!request.admissionAttemptId().equals(row.get("admission_attempt_id", UUID.class)) || !request.mutationDigest().equals(row.get("mutation_digest", String.class)) - || !Arrays.equals( - CapacityAdmissionDigest.preimage(request), row.get("canonical_payload", byte[].class)) + || !Arrays.equals(canonicalPayload, row.get("canonical_payload", byte[].class)) || row.get("decision_id", UUID.class) == null || !("ACCEPTED".equals(row.get("decision", String.class)) || "NO_ACCEPT".equals(row.get("decision", String.class)))) throw conflict(); diff --git a/services/account-service/src/main/resources/db/migration/V1040.6__index_retained_capacity_refusal_slots.sql b/services/account-service/src/main/resources/db/migration/V1040.6__index_retained_capacity_refusal_slots.sql new file mode 100644 index 0000000000..8513d288f5 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1040.6__index_retained_capacity_refusal_slots.sql @@ -0,0 +1,77 @@ +-- Keep refusal admission independent of the number of retained origin rows. +-- Serialize this backfill with origin writes and preserve every original row. +-- [jooq ignore start] +LOCK TABLE account_capacity_origin_decisions IN SHARE ROW EXCLUSIVE MODE; +-- [jooq ignore stop] + +CREATE TABLE account_capacity_origin_refusal_slots ( + tenant_uuid UUID NOT NULL, + slot BIGINT NOT NULL CHECK (slot > 0), + decision_id UUID NOT NULL UNIQUE REFERENCES account_capacity_origin_decisions(decision_id), + PRIMARY KEY (tenant_uuid, slot) +); + +-- [jooq ignore start] +INSERT INTO account_capacity_origin_refusal_slots (tenant_uuid, slot, decision_id) +SELECT tenant_uuid, row_number() OVER (PARTITION BY tenant_uuid ORDER BY decision_id), decision_id +FROM account_capacity_origin_decisions +WHERE decision = 'NO_ACCEPT'; + +CREATE FUNCTION guard_account_capacity_origin_refusal_slot_source() RETURNS TRIGGER +LANGUAGE plpgsql AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM account_capacity_origin_decisions + WHERE decision_id = NEW.decision_id AND tenant_uuid = NEW.tenant_uuid AND decision = 'NO_ACCEPT' + ) THEN + RAISE EXCEPTION 'Capacity refusal slot requires its original tenant refusal' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_capacity_origin_refusal_slot_source + BEFORE INSERT ON account_capacity_origin_refusal_slots + FOR EACH ROW EXECUTE FUNCTION guard_account_capacity_origin_refusal_slot_source(); + +CREATE TRIGGER account_capacity_origin_refusal_slot_immutable + BEFORE UPDATE OR DELETE ON account_capacity_origin_refusal_slots + FOR EACH ROW EXECUTE FUNCTION account_capacity_origin_decision_immutable(); + +CREATE TRIGGER account_capacity_origin_refusal_slots_no_truncate + BEFORE TRUNCATE ON account_capacity_origin_refusal_slots + FOR EACH STATEMENT EXECUTE FUNCTION account_capacity_origin_decision_immutable(); + +CREATE OR REPLACE FUNCTION require_account_capacity_origin_refusal_budget() RETURNS TRIGGER +LANGUAGE plpgsql AS $$ +DECLARE refusal_limit INTEGER; last_slot BIGINT; +BEGIN + IF NEW.decision <> 'NO_ACCEPT' THEN RETURN NEW; END IF; + + -- Keep the same serializable tenant guard and immutable provisioned limit. + UPDATE account_capacity_origin_refusal_budget + SET maximum_refusals = maximum_refusals + WHERE tenant_uuid = NEW.tenant_uuid + RETURNING maximum_refusals INTO refusal_limit; + IF NOT FOUND THEN + RAISE EXCEPTION 'Capacity refusal budget is unavailable' USING ERRCODE = '23514'; + END IF; + + SELECT COALESCE(( + SELECT slot + FROM account_capacity_origin_refusal_slots + WHERE tenant_uuid = NEW.tenant_uuid + ORDER BY slot DESC + LIMIT 1 + ), 0) INTO last_slot; + IF last_slot >= refusal_limit THEN + RAISE EXCEPTION 'Capacity refusal budget is exhausted' USING ERRCODE = '23514'; + END IF; + + -- The existing AFTER INSERT trigger runs only after origin identity wins. + INSERT INTO account_capacity_origin_refusal_slots (tenant_uuid, slot, decision_id) + VALUES (NEW.tenant_uuid, last_slot + 1, NEW.decision_id); + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index 2595afec31..c850888b5d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -6,6 +6,7 @@ import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.temporal.ChronoUnit; +import java.util.List; import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.accountservice.entity.Account; @@ -509,6 +510,330 @@ void refusalBudgetRunsAfterIdentityArbitrationAndCountsTheInsertedLastSlot() thr } } + @Test + void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { + String schema = "capacity_refusal_slots_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("1038") + .load() + .migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); + var historicalTenant = source(); + transaction.executeWithoutResult(status -> + new FreshTenantIdentityAssociationRepository(dsl, "prod") + .importVerified(historicalTenant)); + + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("1040.1") + .load() + .migrate(); + UUID firstHistoricalRequest = UUID.randomUUID(); + UUID firstHistoricalAdmission = UUID.randomUUID(); + UUID firstHistoricalAttempt = UUID.randomUUID(); + UUID firstHistoricalDecision = UUID.fromString("00000000-0000-0000-0000-000000001041"); + UUID secondHistoricalRequest = UUID.randomUUID(); + UUID secondHistoricalAdmission = UUID.randomUUID(); + UUID secondHistoricalAttempt = UUID.randomUUID(); + UUID secondHistoricalDecision = UUID.fromString("00000000-0000-0000-0000-000000001042"); + String historicalInsert = + "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, ?, ?, ?, 'NO_ACCEPT', ?)"; + dsl.execute( + historicalInsert, + historicalTenant.canonicalTenantId(), + firstHistoricalRequest, + firstHistoricalAdmission, + firstHistoricalAttempt, + "a".repeat(64), + new byte[] {1, 2, 3}, + firstHistoricalDecision); + dsl.execute( + historicalInsert, + historicalTenant.canonicalTenantId(), + secondHistoricalRequest, + secondHistoricalAdmission, + secondHistoricalAttempt, + "b".repeat(64), + new byte[] {4, 5, 6}, + secondHistoricalDecision); + + var acceptedTenant = source(); + var operations = new AccountTenantCreationBootstrapOperationRepository(dsl); + transaction.executeWithoutResult(status -> { + new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(acceptedTenant); + var claimed = + claimBootstrap(operations, new AccountRepository(dsl).save(creator()), acceptedTenant); + var current = operations.findForUpdate(claimed.requestId()).orElseThrow(); + assertThat(current.status()).isEqualTo("IN_PROGRESS"); + operations.complete(current.requestId(), completion(current)); + }); + + UUID acceptedRequest = UUID.randomUUID(); + UUID acceptedAdmission = UUID.randomUUID(); + UUID acceptedAttempt = UUID.randomUUID(); + UUID acceptedDecision = UUID.randomUUID(); + UUID reservationId = UUID.randomUUID(); + String acceptedDigest = "c".repeat(64); + byte[] acceptedPayload = new byte[] {7, 0, 8, 9}; + String evaluationIdentity = "sha256:" + "d".repeat(64); + String snapshotIdentity = "sha256:" + "e".repeat(64); + String callerWorkload = "controlled-capacity-fixture"; + Instant evaluatedAt = Instant.now().truncatedTo(ChronoUnit.MICROS); + Instant evaluationExpiresAt = evaluatedAt.plusSeconds(30); + Instant reservationExpiresAt = evaluatedAt.plusSeconds(60); + Instant reconcileDeadline = reservationExpiresAt.plusSeconds(60); + transaction.executeWithoutResult(status -> { + 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 (?, ?, ?, ?, 'game-session-service', ?, ?::timestamptz, ?::timestamptz)", + evaluationIdentity, + snapshotIdentity, + acceptedTenant.canonicalTenantId(), + callerWorkload, + new byte[] {10, 11, 12}, + AccountTenantCapacityRepository.at(evaluatedAt), + AccountTenantCapacityRepository.at(evaluationExpiresAt)); + assertThat( + dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = 1, usage_revision = 2 WHERE tenant_uuid = ? AND owner_service = 'game-session-service' AND held_units = 0 AND used_units = 0 AND usage_revision = 1", + acceptedTenant.canonicalTenantId())) + .isEqualTo(1); + 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', ?)", + acceptedTenant.canonicalTenantId(), + acceptedRequest, + acceptedAdmission, + acceptedAttempt, + acceptedDigest, + acceptedPayload, + acceptedDecision); + 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, reconcile_deadline, state, execution_status) VALUES (?, ?, ?, ?, 'game-session-service', ?, ?, 1, 1, ?, ?, ?, 1, ?::timestamptz, ?::timestamptz, 'RESERVED', 'OWNER_EXECUTION_PENDING')", + acceptedTenant.canonicalTenantId(), + acceptedRequest, + acceptedAdmission, + reservationId, + callerWorkload, + acceptedAttempt, + acceptedDigest, + acceptedPayload, + evaluationIdentity, + AccountTenantCapacityRepository.at(reservationExpiresAt), + AccountTenantCapacityRepository.at(reconcileDeadline)); + }); + + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("1040.5") + .load() + .migrate(); + var originalDecisions = + dsl.fetch( + "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM account_capacity_origin_decisions ORDER BY decision_id") + .intoMaps(); + assertThat(originalDecisions).hasSize(3); + + Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .target("1040.6") + .load() + .migrate(); + + assertThat( + dsl.fetch( + "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM account_capacity_origin_decisions ORDER BY decision_id") + .intoMaps()) + .isEqualTo(originalDecisions); + assertThat(refusalSlots(dsl)) + .containsExactly( + new RefusalSlot(historicalTenant.canonicalTenantId(), 1, firstHistoricalDecision), + new RefusalSlot(historicalTenant.canonicalTenantId(), 2, secondHistoricalDecision)); + assertThat( + dsl.fetchOne( + "SELECT 1 FROM account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", + historicalTenant.canonicalTenantId())) + .isNull(); + assertThat( + dsl.fetchOne( + "SELECT 1 FROM account_capacity_origin_refusal_slots WHERE decision_id = ?", + acceptedDecision)) + .isNull(); + + var expectedSlots = + List.of( + new RefusalSlot(historicalTenant.canonicalTenantId(), 1, firstHistoricalDecision), + new RefusalSlot(historicalTenant.canonicalTenantId(), 2, secondHistoricalDecision)); + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO account_capacity_origin_refusal_slots (tenant_uuid, slot, decision_id) VALUES (?, 3, ?)", + acceptedTenant.canonicalTenantId(), + acceptedDecision)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO account_capacity_origin_refusal_slots (tenant_uuid, slot, decision_id) VALUES (?, 3, ?)", + acceptedTenant.canonicalTenantId(), + firstHistoricalDecision)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + + transaction.executeWithoutResult(status -> + new AccountCapacityRefusalBudgetRepository(dsl) + .provision(historicalTenant.canonicalTenantId(), 3)); + String insertedDecision = + "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, refusal_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING"; + UUID freshRequest = UUID.randomUUID(); + UUID freshAdmission = UUID.randomUUID(); + UUID freshAttempt = UUID.randomUUID(); + UUID freshDecision = UUID.randomUUID(); + Object[] freshRefusal = { + historicalTenant.canonicalTenantId(), + freshRequest, + freshAdmission, + 1L, + freshAttempt, + "f".repeat(64), + new byte[] {13, 14}, + "NO_ACCEPT", + freshDecision, + "CAPACITY_QUOTA_EXCEEDED" + }; + transaction.executeWithoutResult(status -> { + assertThat(dsl.execute(insertedDecision, freshRefusal)).isEqualTo(1); + status.setRollbackOnly(); + }); + assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + assertThat(dsl.execute(insertedDecision, freshRefusal)).isEqualTo(1); + expectedSlots = + List.of( + new RefusalSlot(historicalTenant.canonicalTenantId(), 1, firstHistoricalDecision), + new RefusalSlot(historicalTenant.canonicalTenantId(), 2, secondHistoricalDecision), + new RefusalSlot(historicalTenant.canonicalTenantId(), 3, freshDecision)); + assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + + Object[] refusalReplay = freshRefusal.clone(); + refusalReplay[8] = UUID.randomUUID(); + assertThat(dsl.execute(insertedDecision, refusalReplay)).isZero(); + assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + assertThat( + dsl.execute( + insertedDecision, + historicalTenant.canonicalTenantId(), + UUID.randomUUID(), + UUID.randomUUID(), + 1L, + freshAttempt, + "1".repeat(64), + new byte[] {15}, + "NO_ACCEPT", + UUID.randomUUID(), + "CAPACITY_QUOTA_EXCEEDED")) + .isZero(); + assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + assertThat( + dsl.execute( + insertedDecision, + acceptedTenant.canonicalTenantId(), + acceptedRequest, + acceptedAdmission, + 1L, + acceptedAttempt, + acceptedDigest, + acceptedPayload, + "ACCEPTED", + UUID.randomUUID(), + null)) + .isZero(); + assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + + assertThatThrownBy(() -> + dsl.execute( + insertedDecision, + historicalTenant.canonicalTenantId(), + UUID.randomUUID(), + UUID.randomUUID(), + 1L, + UUID.randomUUID(), + "2".repeat(64), + new byte[] {16}, + "NO_ACCEPT", + UUID.randomUUID(), + "CAPACITY_QUOTA_EXCEEDED")) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> { + assertThat(failure.sqlState()).isEqualTo("23514"); + assertThat(failure).hasMessageContaining("Capacity refusal budget is exhausted"); + }); + assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))).isEqualTo(4); + assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + + assertThatThrownBy(() -> + dsl.execute( + "UPDATE account_capacity_origin_refusal_slots SET slot = slot + 10 WHERE tenant_uuid = ? AND slot = 1", + historicalTenant.canonicalTenantId())) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> + assertThat(failure) + .hasMessageContaining("Account capacity origin decisions are immutable")); + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM account_capacity_origin_refusal_slots WHERE tenant_uuid = ? AND slot = 1", + historicalTenant.canonicalTenantId())) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> + assertThat(failure) + .hasMessageContaining("Account capacity origin decisions are immutable")); + assertThatThrownBy(() -> dsl.execute("TRUNCATE account_capacity_origin_refusal_slots")) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> + assertThat(failure) + .hasMessageContaining("Account capacity origin decisions are immutable")); + assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private static List refusalSlots(org.jooq.DSLContext dsl) { + return dsl.fetch( + "SELECT tenant_uuid, slot, decision_id FROM account_capacity_origin_refusal_slots ORDER BY tenant_uuid, slot") + .map(row -> + new RefusalSlot( + row.get("tenant_uuid", UUID.class), + row.get("slot", Long.class), + row.get("decision_id", UUID.class))); + } + + private record RefusalSlot(UUID tenantUuid, long slot, UUID decisionId) {} + private static Account creator() { String suffix = UUID.randomUUID().toString().replace("-", ""); var account = new Account(); From 8ad33623cfc35dcd9aecdfffcfcd4b8e616f747a Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 13:28:25 +1300 Subject: [PATCH 31/96] Address FireMUD #3451 follow-up CLI review --- .../workflows/publish-pr-runtime-images.yml | 12 +- .github/workflows/runtime-images.yml | 28 ++++- .github/workflows/smoke.yml | 23 +++- .../account-service/runtime-and-data.md | 2 +- .../game-session-service/runtime-and-data.md | 2 +- ...rusted-runtime-workflow-definitions.tar.xz | Bin 0 -> 19644 bytes .../pr-required-gate-context-contract.sh | 100 ++++++++++++---- .../tests/pr-retarget-workflow-contract.sh | 40 ++++++- ...acityMigrationPostgresIntegrationTest.java | 112 ++++++++++++++---- ...titlementOwnerPostgresIntegrationTest.java | 88 ++++++++++++-- ...stractReloadingBlockingGrpcClientTest.java | 4 +- .../client/AccountTenantCapacityClient.java | 3 +- .../AccountTenantCapacityClientMtlsTest.java | 65 ++++++++-- 13 files changed, 393 insertions(+), 86 deletions(-) create mode 100644 dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.tar.xz diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 932292ccb5..24a7fe178b 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -14,7 +14,7 @@ permissions: {} jobs: reconcile-failed-pr-runtime: name: Reconcile Failed Original PR Runtime - if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && ((github.event.workflow_run.path == '.github/workflows/runtime-images.yml' && contains(fromJSON('["failure","cancelled","timed_out"]'), github.event.workflow_run.conclusion)) || (github.event.workflow_run.path == '.github/workflows/ci.yml' && github.event.workflow_run.conclusion == 'cancelled')) && github.event.workflow_run.head_repository.full_name == github.repository }} + if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && (((github.event.workflow_run.path == '.github/workflows/runtime-images.yml' || startsWith(github.event.workflow_run.path, '.github/workflows/runtime-images.yml@refs/')) && contains(fromJSON('["failure","cancelled","timed_out"]'), github.event.workflow_run.conclusion)) || ((github.event.workflow_run.path == '.github/workflows/ci.yml' || startsWith(github.event.workflow_run.path, '.github/workflows/ci.yml@refs/')) && github.event.workflow_run.conclusion == 'cancelled')) && github.event.workflow_run.head_repository.full_name == github.repository }} runs-on: ubuntu-latest timeout-minutes: 5 concurrency: @@ -113,7 +113,7 @@ jobs: if (!trusted(event) || event.event !== "pull_request" || event.status !== "completed" || !["failure", "cancelled", "timed_out"].includes(event.conclusion) || event.head_sha !== wakeHead || event.head_branch !== callback.head_branch) return; - } + } else if (!trusted(event)) return; const match = titlePattern.exec(event.display_title || ""); if (!match) return; const [ , number, base, head, merge] = match; @@ -293,6 +293,9 @@ jobs: if (!currentCi || currentCi.id !== selectedCi.id || currentCi.run_attempt !== selectedCi.run_attempt) return; const {data: finalCi} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); if (!matchesCi(finalCi) || finalCi.conclusion !== ci.conclusion || !await wakeCurrent() || !await sourceCurrent() || await originalSuperseded() || await currentTuple() !== baseRef) return; + // Repeat the complete trusted refresh preflight after all current-source fences. + // This is the final read before POST, so a late replacement owns recovery. + if (await newerRefresh()) return; const dispatchStarted = new Date(Date.now() - 1000).toISOString(); let responseUnknown = false; try { @@ -304,7 +307,7 @@ jobs: if ([401, 404, 422].includes(error?.status) && error.response?.status === error.status && !error.response.headers?.["retry-after"] && error.response.headers?.["x-ratelimit-remaining"] !== "0") throw error; responseUnknown = true; - core.setFailed(`Runtime refresh POST response is unknown; no retry issued: ${error.message || error}`); + core.warning(`Runtime refresh POST response is unknown; no retry issued: ${error.message || error}`); } // Keep the shared lock during observation even when the one POST response was lost. const deadline = Date.now() + 120000; @@ -331,7 +334,7 @@ jobs: source: name: Resolve Exact Runtime Publication Source - if: ${{ (github.event_name == 'workflow_run' && github.event.workflow_run.path == '.github/workflows/runtime-images.yml' && (github.event.workflow_run.event == 'pull_request' || github.event.workflow_run.event == 'repository_dispatch') && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_repository.full_name == github.repository) || (github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-image-publication' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) }} + if: ${{ (github.event_name == 'workflow_run' && (github.event.workflow_run.path == '.github/workflows/runtime-images.yml' || startsWith(github.event.workflow_run.path, '.github/workflows/runtime-images.yml@refs/')) && (github.event.workflow_run.event == 'pull_request' || github.event.workflow_run.event == 'repository_dispatch') && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_repository.full_name == github.repository) || (github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-image-publication' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -405,6 +408,7 @@ jobs: } if (callback) { const event = context.payload.workflow_run; + if (!isTrustedWorkflowPath(event.path)) throw new Error("publication callback path is not trusted"); for (const field of ["id", "workflow_id", "display_title", "event", "conclusion", "head_branch", "head_sha"]) { if (run[field] !== event[field]) throw new Error(`source API ${field} differs from callback`); } diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 1de602fdc1..713c582795 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -448,6 +448,9 @@ jobs: uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 with: script: | + const dispatcherStartedAt = Date.now(); + // Reserve the final two minutes for shared visibility and one minute for runner overhead. + const fanoutDeadline = dispatcherStartedAt + 12 * 60 * 1000; const workflowRun = context.payload.workflow_run; const refreshBranch = workflowRun.head_branch; const refreshSha = workflowRun.head_sha; @@ -970,7 +973,20 @@ jobs: let visibilitySince; let runtimeInventoryPromise; let runtimeInventoryError = null; - for (const resolved of refreshTargets) { + const reportFanoutCutoff = (targetIndex, stage) => { + const incompleteTargets = refreshTargets.slice(targetIndex) + .map(({tuple: targetTuple}) => `#${targetTuple.prNumber}`).join(", "); + core.setFailed( + `Runtime fan-out cutoff reached ${stage}; PR targets ${incompleteTargets} remain incomplete. ` + + "Already sent runtime handoffs will still be observed." + ); + }; + for (let targetIndex = 0; targetIndex < refreshTargets.length; targetIndex += 1) { + if (Date.now() >= fanoutDeadline) { + reportFanoutCutoff(targetIndex, "at a target boundary"); + break; + } + const resolved = refreshTargets[targetIndex]; const {tuple, pullRequest} = resolved; let runtimeChanges; try { @@ -1043,6 +1059,10 @@ jobs: core.info(`Skipping changed runtime tuple for PR #${tuple.prNumber}.`); continue; } + if (Date.now() >= fanoutDeadline) { + reportFanoutCutoff(targetIndex, `before the runtime POST for PR #${tuple.prNumber}`); + break; + } const previousIds = new Set(inventory?.runs?.map(run => run.id) || []); const dispatchSince = new Date(Date.now() - 1000).toISOString(); const pending = {tuple, previousIds, dispatchSince, responseUnknown: false}; @@ -1071,7 +1091,7 @@ jobs: break runtimeRefresh; } pending.responseUnknown = true; - core.setFailed(`Runtime refresh handoff for PR #${tuple.prNumber} is uncertain; no retry issued: ${error.message || error}`); + core.warning(`Runtime refresh handoff for PR #${tuple.prNumber} is uncertain; no retry issued: ${error.message || error}`); runtimeInventoryPromise = undefined; break runtimeRefresh; } @@ -1093,6 +1113,10 @@ jobs: core.info(`Skipping preview deploy reconciliation for #${tuple.prNumber}: target is not preview-eligible.`); continue; } + if (Date.now() >= fanoutDeadline) { + reportFanoutCutoff(targetIndex, `before the preview POST for PR #${tuple.prNumber}`); + break; + } core.info(`Dispatching preview deploy reconciliation for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); try { await github.rest.repos.createDispatchEvent({ diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index d98bcd5785..438312c36f 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -611,7 +611,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "27c615ce72a367a234759b3940e1345ef1eb43f67775ae4865d39e1902e1be65"; + const canonicalRuntimeWorkflowSha256 = "9d03a4a9085dc310dabb03091dbdc6f027bdecb468e2589f08f546c4cdcaf988"; // Only authenticated default-branch refreshes may use retained successful definitions. // Keep the pre-rollout default and predecessor definitions for mixed-version runs. const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set([ @@ -944,6 +944,10 @@ jobs: "current runtime attempt lookup", () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: source.id }) ); + if (source.event === "repository_dispatch" && latest.id === source.id && + positiveInteger(latest.run_attempt) && latest.run_attempt > source.run_attempt) { + return "attempt-superseded"; + } if (latest.id !== source.id || latest.run_attempt !== source.run_attempt || latest.status !== "completed" || latest.conclusion !== source.conclusion) return false; // The fingerprinted marker attests the PR event label or the typed @@ -1019,6 +1023,7 @@ jobs: const proofRun = {id: replacement.id, run_attempt: replacement.run_attempt, conclusion: replacement.conclusion}; const proof = await verifyKnownPlayFailure(replacement, candidate, identity, true, true); + if (proof === "attempt-superseded") return "pending"; if (proof === "ordinary") return {status: "ordinary", run: proofRun}; if (proof === "snapshot-pending") return {status: "snapshot-pending", run: proofRun}; if (proof === true) return {status: "verified", run: proofRun}; @@ -1410,6 +1415,10 @@ jobs: const directRefresh = matching.event === "repository_dispatch" && matching.conclusion === "failure"; const directProof = matching.conclusion !== "failure" ? false : (directRefresh || Boolean(candidate)) && await verifyKnownPlayFailure(matching, candidate, currentIdentity, directRefresh); + if (directProof === "attempt-superseded") { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } knownPlayVerified = directProof === true; if (directRefresh && directProof === "snapshot-pending") { const snapshotKey = `direct:${identityKey(currentIdentity)}:${matching.id}:${matching.run_attempt}`; @@ -1608,6 +1617,10 @@ jobs: if (cancelledRecoveryMoved && matching.event === "repository_dispatch") { const proof = await verifyKnownPlayFailure(matching, null, currentIdentity, true, true); + if (proof === "attempt-superseded") { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } if (proof === "snapshot-pending") { const snapshotKey = `cancelled-move:${matching.id}:${matching.run_attempt}:${identityKey(currentIdentity)}`; if (incompleteRefreshKey !== snapshotKey) { @@ -1763,6 +1776,10 @@ jobs: (markers.length === 0 || (markers.length === 1 && markers[0].status !== "completed"))) { markerProof = await verifyKnownPlayFailure( matching, fullSmokeJob, currentIdentity, true, true); + if (markerProof === "attempt-superseded") { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } if (markerProof === "ordinary") { canonicalProducerVerified = true; } @@ -1788,6 +1805,10 @@ jobs: if (error instanceof TerminalGitHubRequestError) throw error; core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); } + if (knownPlayVerified === "attempt-superseded") { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } if (knownPlayVerified === "snapshot-pending") { const snapshotKey = `successful:${matching.id}:${matching.run_attempt}:${identityKey(currentIdentity)}`; if (incompleteRefreshKey !== snapshotKey) { diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index a61b0a959d..7cf51b2666 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -88,7 +88,7 @@ Current public bootstrap, direct-scope, JOIN, connect-token and numeric entitlem Strict capacity follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). The prepared V1040 storage records immutable exact Account evaluation bytes, one stable outer request/reservation identity, the current attempt/digest and monotonic rearm/reservation fences, prior-attempt evidence, recovery claims, and durable held/used units. Deferred PostgreSQL constraints compare the complete reservation inventory with usage; eligibility reads and issuer-local counters cannot initialize or replace it. Zero usage is established only when the existing creator bootstrap commits against a genuinely new fresh-tenant association born in that same Account transaction, with the exact creation tuple and nonadmitting sequence-zero baseline. Earlier tenants are not backfilled. The actual player evaluator retains its complete bundle inside its final source transaction, so failed source commit exposes neither a capacity evaluation nor an entitlement result. Reservations use conservative microsecond expiry bounds without extending the evidence lifetime. The same prepared recovery schema retains its immutable read history and `capacity-recovery/1` retry budget. Deadline or budget exhaustion quarantines the original complete hold; it does not expire, release or replace it. No live recovery source/scheduler or quarantine-resolution authority is registered. -V1040.1 serializes the exact Account `ACCEPTED` and `NO_ACCEPT` origin decisions against reservation creation and rearm. A pre-V1040.1 writer cannot create a reservation after the guard applies. Upgrading a retained Account database requires independently verified [writer quiescence](../../system-architecture-database-migrations.md#version-aware-migration-checklist), including closed writer endpoints and exclusion of old writers. V1040.2 retains an exact quota denial under an explicitly installed finite tenant refusal limit. The same serializable owner transaction checks quota and chooses between a reservation and a denial. The denial carries no reservation and permanently excludes acceptance for the exact original. Exact replay returns the same decision even after capacity becomes available. An unavailable refusal budget or uncertain outcome leaves Game Session's reserve active. Account neither frees nor rearms an accepted reservation through this path. Before enabling any admission producer, the Account operator must provision every supported canonical tenant through `AccountCapacityRefusalBudgetRepository.provision` and call `requireReady` with the same explicit lifetime limit and the bounded admission cohort headroom in one writable owner transaction while producers remain quiescent. Commit only after both succeed; otherwise roll back the undersized installation so it does not permanently bind an unusable limit. Sizing is explicit: the finite lifetime limit must cover retained denials plus the planned denial cohort; it is not the gameplay capacity quota or an automatically replenished rate limit. Exact provisioning retries preserve the row and its historical evidence; a different limit conflicts. Missing, mismatched or insufficient budgets fail readiness. Readiness is a local observation, not a reservation or authority to admit, and the SQL trigger remains the runtime concurrency authority. Exhaustion requires stopping new admission and an independently designed retention-safe lifecycle, never deleting denials or resetting/increasing this immutable budget. No exhaustion detector or admission-producer stop control is implemented by these private repositories: the positive reservation path does not consult refusal headroom. Qualifying that stop, including last-slot consumption followed by available capacity, is an unmet activation prerequisite; provisioning readiness alone cannot satisfy it. These private methods do not register an endpoint, seed tenants automatically or activate the default-off capacity component. +V1040.1 serializes the exact Account `ACCEPTED` and `NO_ACCEPT` origin decisions against reservation creation and rearm. A pre-V1040.1 writer cannot create a reservation after the guard applies. The [database migration compatibility and writer-quiescence policy](../../system-architecture-database-migrations.md#version-aware-migration-checklist) governs deployment. A reset must preserve results for still-eligible retries and may proceed only once external-action outcomes are known and any receipts to be discarded have passed their retry and reconciliation window. V1040.2 retains an exact quota denial under an explicitly installed finite tenant refusal limit. The same serializable owner transaction checks quota and chooses between a reservation and a denial. The denial carries no reservation and permanently excludes acceptance for the exact original. Exact replay returns the same decision even after capacity becomes available. An unavailable refusal budget or uncertain outcome leaves Game Session's reserve active. Account neither frees nor rearms an accepted reservation through this path. Before enabling any admission producer, the Account operator must provision every supported canonical tenant through `AccountCapacityRefusalBudgetRepository.provision` and call `requireReady` with the same explicit lifetime limit and the bounded admission cohort headroom in one writable owner transaction while producers remain quiescent. Commit only after both succeed; otherwise roll back the undersized installation so it does not permanently bind an unusable limit. Sizing is explicit: the finite lifetime limit must cover retained denials plus the planned denial cohort; it is not the gameplay capacity quota or an automatically replenished rate limit. Exact provisioning retries preserve the row and its historical evidence; a different limit conflicts. Missing, mismatched or insufficient budgets fail readiness. Readiness is a local observation, not a reservation or authority to admit, and the SQL trigger remains the runtime concurrency authority. Exhaustion requires stopping new admission and an independently designed retention-safe lifecycle, never deleting denials or resetting/increasing this immutable budget. No exhaustion detector or admission-producer stop control is implemented by these private repositories: the positive reservation path does not consult refusal headroom. Qualifying that stop, including last-slot consumption followed by available capacity, is an unmet activation prerequisite; provisioning readiness alone cannot satisfy it. These private methods do not register an endpoint, seed tenants automatically or activate the default-off capacity component. V1040.6 backfills one immutable refusal slot per retained `NO_ACCEPT` decision. After origin identity arbitration, a fresh refusal takes the existing tenant budget lock, reads the highest slot through the tenant-slot index, and appends the next slot in the same transaction. Replay, conflict, and failed inserts leave the inventory unchanged. The migration preserves origin rows and provisioned limits. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index e6225b0e8e..610648fe81 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -14,7 +14,7 @@ The exact current Game Session owner establishes irreversible closure of serving The target Game Session owner persists the teardown identity and progress in its own PostgreSQL storage, then retains the immutable terminal evidence under that same identity. A replacement worker reads the persisted progress and exact receipt rather than reconstructing either from Redis, an in-memory job or the current binding alone. The receipt binds the original admission, FINAL evidence, binding lineage and exact Account reservation; conflicting identities or stale owner fences must be refused. -Qualification must prove restart before send, Account commit followed by response loss and worker restart, and exact receipt replay without a second decrement. Account—not Game Session—atomically retains the retirement receipt and decrements used capacity. Wrong identity or fence must fail closed, and no failure or retry may reopen serving or resume. These are acceptance requirements, not claims that the target path or its restart proof exists today. +Qualification must prove a restart after irreversible closure or settlement but before the terminal receipt exists, then verify the replacement completes that same teardown from durable progress with serving and resume still closed. Separately prove restart before send, Account commit followed by response loss and worker restart, and exact receipt replay without a second decrement. Account—not Game Session—atomically retains the retirement receipt and decrements used capacity. Wrong identity or fence must fail closed, and no failure or retry may reopen serving or resume. These are acceptance requirements, not claims that the target path or its restart proof exists today. ## Implementation Status diff --git a/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.tar.xz b/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.tar.xz new file mode 100644 index 0000000000000000000000000000000000000000..013546a1ed982248afcc8586f2f2de88e9a67a3a GIT binary patch literal 19644 zcmV(jK=!}=H+ooF000E$*0e?f03iV!0000G&sfapAOB2wT>u!FNM<8K&2tu3Iggb= z&qcT-I9Z0B2j%BQD&EV9wr_F9H;XHqYWUKHJG1(7Ly@kx3$)=Ys7At%rF{_rXQ@X3 z>nC6C29kyU!2naK>T8ffd`S%+GSW|yBZTMZ*Kxh-tPGFOzrj6eO&s0-jyKU&d#WO7$+zrCS#9d?T z9nsdEw;kJ%-1gc$zeLS`ALGRV-gkHPh?spRtXYGvT>GK0z)=1neP_L|)S>UXdkyH% z{1h1N>h%|alV_q__Eb>I3%pmDtSCRpco$HcTpBKUsH>jv#Uz^K!9Pubzo&dP~7<4++F&m^T6ex!(UfG!)aauX8>~UKInD4l|f>cO$;~aZErU(bXHKK&Vs*$aP zA62r}E%7X33q66I>iQXdB?yG2UYU`JD3kOAQ;9|kp>8qEkRTXRRzJPx3V3!XA_?}T zgK*aG>^+-bqSlw*Pow9KYH{Yt6ux;|ec7;c@u?=xR1 zK5*%;I{y!#=z1a9d{%@FVCZb_5pW~zf?N#(j+GI~;6m`wp7;og*jEh>MJ(nQ!oj)^ z=RAydnvVn-vci;<0r!x4vD9!Hoc}NGco4d&;zMpp1tsy6y>TG!8JNPR0!9ri0ekvGdO9@a~hXV!d0s^nUN@Jtqc?VML4$V5s)A)EiAo4 zaatSmbKG&%esFvMiCLDovYp0V$K-Q}=A}dsgeUVH$9C%jxC-c&J`B!GTe}9)&f8s` zaE)Wa^_#)3(4$6l5r6JZbNRk=(+c;)33x`JZYR-ovr>87ll?N-K=F{|@`+VxAuIa< zM@5&d0FIy1{d-7xYs@2?ykL>2H4-jtj`bmu+K%nKEodtcP0t9Dhh~kvT3O6-hTdZN zo~ldpvqyB*fcG|LwE-Z%PyRd;K_K?@;dN)bJbl5UI{>9u@efybCII2F;eRU*zezom zl!QP=5Do|;cCgkuNt~g@*FCGdtRfZ(FU(hgSZwVykd+2{+E#1`e?JmA`J(&H_ShRC z)YtH1N!;sa1tGVA{8-@h((=LDxzY2=e|A;LI&%h5ifaUfO&TRjp@K($OpdNK`yxxl zv=DKbBNxlWle6HYfE4NvE+9aDj^bsmluX&f>Wu;;HgZXs|5IuIqEET9Mdut+8b+rr z=bg8beCf&1Hs^S9JQ!05)yCD zOB*UiPmR;FBjR409~#r<5a(291WWeJTc%MW&ppiIU`DtcOg7C!YJr#O43_|hMh@AE zgy{_23Fk*yfk@87y{w|$SUJMxkOHCCX}9ja5-|+RqQm`U?7@mbeD@9&Or@*XPlLuU zfYD6VsohVj7*6$&v5BPdYRzV zgcLTuXu)|$!`Ig0Fon&iMk02cA3|e*OzEi=gK29C{Dia|A6q^?AiNk|^s{cVEMw08 zsV)JHOW|s=x>K|(P@(uSjzoUHnh=i?i7(FC?ET2wJyM5`E^phSiV!jPRJ0`1GoJ8q zvKLzCz^z$0Q~-c*#;5)ilDF0(-%0i&@~Xe$3pIG8k|^d<)1zoFuYb@Uf;{&*QEhWh zY{86e&tpF+J z?NF$5jX65f3#e55#2z=~+eS-kFWPB52P&{ztrgOMKJJGb8 zLITS|V9e8NAYOo?V|$CiPHEk2L`PDTDfs!$d4c7n_O+4O2nZQ%hywuA3A73gQklmz zO8&o4pgB+k6y{-|gs4s8@BlQ-Klj?q%3fxDuLsd9<=7!;j+buJYOH1Ovd5yV@~5WO zWKN7HuiRDb`l2%}|J&#skUX`AS&=}1p|}bOsd06Ctg~^j9KS_ObE;pOmhan6XVj&f z!-yzA_;D1=4W}`N2DxQc`hS@TrPLvbZ6Rvm|z zR=J6rP)F}itpfOO*0ynLlL02xufuXxsTfHabBo1#4D0xJi=xAH-168cbs(Rj$Si1khs*?z=95PYqsvb^)NU zDF1Yb-vlSLwB@N$pLPJ-h51>0>Ipvi&K4i66=GiHPcviYBi+*3-r`6{J5IElVD;-Cv{V zjB2(#Nnx29PH-wHjYV0~>eoq&qC1jK26M|b8)Nb2mSwSqQ*0OS@+IIaH`Jm8U!dET zFZyWD_>uv4k0}WPaToDG6+t42@54FXa%2tTVLGUSN~gamI;M96wu!k^I6^9a!x*mN zR6B^#%@=J*rSWWPt+>P21cW;eYwgIG~2@$W5xVyQD=K0pp9H z71*koOc@PQvPc8k>(L8jm2%;sL+9(1G0`dUjl6>Q!nnVOT6!AX--Q0vgcO&mKBG$B z2I4iYQ9U_Y_e;=UM=Y)>#1L>y$jsPWkmjV3o)H0iM`=}$7D&5E$%AHf=YgV@{j{Gq zZja?(g60@?$rIJjbst@9bl3=s$Zkc0u51<0eX#0liTJ}HD+$e48ou~@t1LHMgHmfP zBeu=^suh>vpRCIKUbg)v>j#0Aqp%s&S$FL4K17?<2(b!g`$%Aa+x_fZWL!NGv~5>E zyrpmSuqSug^c*B(C4kH%I@CL%aL_Vody1V`Zm8!X<1ob~aF?D!n5?6xkJaZHS%>;+ zU0dyUiMl@%76N^ujP!P>*TxpI!iUzSAivstV>T%M)I`6(;bnS0QrS~mz2!`ACMl_; z9E{ELnTc$t+9i$Y=Z0@;j!Cb@w+P_g4&LU!P^(izSN>;EA&1rXxXe5#r}!dK!R&vTF?1wsSHMdpuVE9vSvl^8 zZu|?juf3K}+kL31k}+FhcVq07hxiIQ9I(Uel_@-;6@pt-mxdtsEcSuBugHfKumTo0 z>Qte$x@|W3UF1Q1rKOhENFh1`@QRz$(32np!!GJWldNy8j{j9{GU7qR9UDEqxyJKA zpE>OvaTKa2^_C-Qo1X@~IjW@duh|8ct-8hCuVfuhUHS7$xi5UG%(>i^Mfu7wl3XN*ZwGrWLe^H3)x6eN+Jg&kMEGWD53cn~^|ns~4r&G6Q$N zzmJ1}qWc2!cDw@V{9vAz6A1qLKKf^CnNm1RuOe%SG{dhNQ-5v~j6|a%GoR%h$NlGA zX!!cGPfgs^*K0LNaEeGLLRs2+y?KO3=jG}=BsHG4|6M*19tda%jH6x80fhfvBoZSs z+?VEfHNqI%HWiZV(|M0K3aOvGXaa9^qA`6e4U1?f^U6WJM)ifW27wB6rXan0vz}5@ z|7?6+MMj3ixTzmvgrm?MewC{`_<5Udvcpk8&fQPF*DRE8C?g9v^bi6P2&&0DzhV$R zGym=Yh&*aV%3Gry%jMLh0}g>3hN`jO%k*tF63QdVp_Elp=@L5A(VW4pjVICEWCa1g zH{wCg?;nBK=!c;+vp&UiYQ&tXzZd#Dr>eDnCMDfgbLKh@IJI0XkrCojIp#F;rGn4` ztanMqkL;I(uULv|Gsm{;Go{UB^F_bv6EMc>sPosG_NDZ8O5Y!ZEHVMYsxjp_ZZP?b zX{MQ@+lDlE!$2e@z!V@<(w4WRLi&||Nebuf))RK5U%PZq)6D#VDTn5@0+mt|I@+8hH_VW5#3md^rjfwdxeASaWMg)|s1S1Ll$XB64mll~4qaNDG{J4Ip&G8eV zr?<}VsTpq4yYcvBrp?UG>|4ddA&C)4=E23RCr-s*VluS=q&Elx%UPjk$BDIkz&+e=_B(+t6PnoEIB zbs$43z=3CIyOqz8*--s`U3`!05s3m8d<~2kQmf;$b+F0S!BGVKeS+ z?v_CoCfmu|cC}PNA3%o3^jGvcVy66Lrh{ybbA;}0I$qkHMS)qoms^|`22|Ne(a+-1 z#vkyn1qz>`=dc-idv=Yfh0_L>`y}?TPUYxKCvr+(FJY!IYhvUc;^=C86|^q1%gpos zeeOO=a^KQQ(8Kho!19bUrpZp-;0Kr!nbr2boT)!BxM-`xmk%?Grhrhj&fR=I?i0W* z=&k=`26UL~0Zvh#A%sd*{6S~awd=^w6i2c^8*hWoAOKm@x}Wy9v1;p9$n1V`V1Mug zm@L`VuO?bp&qga+XQDnX7zM8V+<_dnodD6jwi;4Muk-g)`p#E12I{0+<_Gvd00p z_kf}&IfFv3)aDX~p@+I>6}&sik*8G{;ze~DpEjwi%aYf~!gzzav;DV-g6I$aI5Erl z$v37{^!jSqs#x?#n*v_uLhma8PEsy=-xC+1d7N5s-tWF&~$7U>kr7+g9^m)+DJheH2qVXy1(V(w2_P6%= zH8#$|i4m4ro{>n*!M$J6$sPC7AhfR62~WM{DwFt*Q)M-LsoEJ09{i%{NP zjvvjyG4T#6dxaa|yXPvHB@@@PKx-^Vr*PRJSsj$)gF2nV><>_x%7P^Mq~Byh1U2_< z_BBGmw-{^OrW~&E0NY`qcS)Iqr0+X*h~Hp<&Jv(VVVvkRCFb`=5C)ooXD_Ikz)pK)KGIT~bq|+J?Zi z@TA%fV%&<-8+WY;tjkBMTuJi^K@L27>QG+QH3aS}Tn|HZLNBoVI!OK(zDFJ)3+V+b zdyqw&QLwyIsZ=t_tb9Q>myB3$9?EL4sG73GR*{pM)o`Pp7^=z60)5)Cn%EaOBhxVH z%G4J8X~`R6#B={;CZuV%#$Wj+K@u2E1IU1)a);)%lDMiGm{>avHe|Q^rgziTN0xHd zS8Vfe`#tKsvC&`^(r3dY<>FaxcC-iMJRhV-uG~#km$LeQ53^KJ=LB!BV;Hbkg+fCp z_^)%h!}Y%#bAK-bo;fF-EZdhYl?IPem*KL#`q~%!yE;Rb3?X@K61ZYu@F0$CJ_}`- z#qTn*x^J~WdM!AL1icc15TE>oFC1YF%IFZ=jrDTWoNdP$@n(=D$BgVI4x_4VNRF_t zVl6jLDfzhzf&DU~n@W9rCQ3MC{J92cN67%Mj}RO1Ejerc)lE@P?+)-(rgSku zlSxv06e8v0^Dp$Q^A-G0WV1BV^g1`78^7^lK-F;_iyRg4x8?EP=zv@-jrKT{{EC(k zw^s5`q0TN*EwfI*rcO1^&KVL*R| z)W~P1|FZjVw_#K(vCwsW*!$WhVR2!T@5FE0<}`5G_O_5s*=KxzPx#i2_BeBix9VPt zON5n3x1Nf0fB!eet?~={!EjwzGX!cWeCU;jtivZqnT81QW}E&MB)>nl>PG6pRk6w< zVNrDCNrvB+^T63>iR)~1A<>{q$(mfLGqWkO5n2*bzgs(DS#l{i837Y*j81pw4LKvh zVU=tLZ}sY^f#-rBMW(&EJT9D_0HUT^;mFTuBl-R8GkbpMwt4t9hg$vZjI`H|Pd;AN zquH|nQo#^5O{=;?G-di*qEeVcSgb0x#tj=c5*nSJEIz#;NAM;dSZmSrq{?F%B_y;} zG<(Q2lH2~fw?zxTe+*Z*;?eC6=$wk?h-C>uYnp^RRWR9q6Q1uBin+ZuRtg5+)~e@6 z=~qv|S8LeWyK>n^txvbCmdnu-oL`jfTZn5KmBdDk_8I+6h|~R^KiBc#yH)SVodAY>R&jHmQ1~V`jJPXxm9Q{~Aj(CKh>ug{yfkt1)DnJBQp+hH zt!NZ}+UQ5LZW3GAQX`|qEc}w}LtD5QnIUDHhBHp#)awD+8tlU+ty`B>dX|Ux=v8nT z(uQMeH~Z+WZfVGl&g;_>Km`$_{zOU7k02vVoG(>CQw|Fz2gI!0zi-Ty$9{N2O%_wc z*lvrG#?Z_UQOPTrFy+in3W=UP=7Vcc&)&4EUuQ7?;uBA5h0^2QF8B8H$d#Ki-u+v8 z$?a#!0^z(%{ti%8ZAJp;%8=cV*wv`B2Lfs3>%6XG%{Ila!!2qd9FHmSD|sntcqx#Q3)w-+^=VFBPB zYg*KMK8w@LK0WGxnW)z0WGrJ{ZuBbKQJ^NCiW`B*p$u@GEckm`@<%m!il8f7Yy4mn{paZZq5T^f`5Jc(K#oa5S{;W%TjWJhpMBPj7Uh3D zvjN^ZSEEvUq$&xFh2NP5Quyl1*3&ueq4s)_e$4OfNm8l+|FN!ASPDdJXTOo# z@d>^mU$=}1odMhz+$A8P55hTlR*k=4rQQC6-OsR55%xZbjjqX+x6x9ue#4||33M{9 zj<6z^A4~@kdhPQ_+8~7cBWIT1i+rMS`T9&ru8?SdnpYd@RBpmmIy)h>DeT`cbAM85 z)%F~_Rr6Nl1ybrj?5sQXl!x;=s>p%ghJc#$1{-hU-=~9){sSN9aNOUMVSyVfYYL~g zsBXd(_d=1|14PP$t-}jXu&`w2=VnJlDgV7-KwzktYAfC^vxNgKcq3T$wkI~ zhHBow3JGM$4dkiaL(vmkBi@xec7Nn1A{Tq6@rQjc5?zw58!NeogQQ{p2 zu#};V6dy>zuXU~685Fb}kgXVjwF;qIgreoxK4ObVF~*+4qx64Df)P;6XZ(a)&UC$< z!o}ANwr^1T#Ee_wo>?Bfb%#0h8ws!)A=|R~vzH`6?F@n%lNBnj*7@G`%o|?8N!xU* z$qs#pQySDak6%W({)G>K@|M6XSLXc2J*=}Hsch1QILx7))0M+NgnQC7Op(SlwsG~s zzg4Tytpo9lj;Dc!1pBe6JqtE-A-5Uuv>z!QL!}0(>-<; zy827on{`VUP*=i>(XyjKR)^F8TitC?aOj;X8~4JQFu6*cjO(sI{SCfRof|G zux^?Kad_!e8O5|AI99>pu$?x7=6_7+w*lhGa!r?_)Gnc$J-sEb|BD4vVKC?_xzI%Z z@#+*xgMG~zlk{5kEz_s7d9xm?Zby`7?(G63YIkbmjEZ&37`7O4>`~e*xmq1v<~1oC z$kZoV>5*O*XR-q~2*T)PxhCsvQ6l|lD0d#ukSpLv3TX?r$c^o_w(i07eH0;Ys!^+t z97e==EqVDee5t{n6M)g&T&LAH2c63ya>(WpoR&bdmi0~|=a5=rSX0W~<%+;w>299h z@1A#GexTc`;h>NS1f>Fq<9q7WuK~Y9SbnewfiZDaJZg{dr=4a37_Q4(+k0&`#OKRH z2^WMI(XPvO1A52;uxM@oSQ_Gx7{w56<$TUo(ehEjkN}p(dg9 zgN7}(4~}S*7f!R(ojrqsbq7KUKq83uhbJsOoHAe}!jYS90C?kkTtU#A7cD6BPtM>m zE+U^WY}%$8m8w-gnEQ>4Gr__5%dj}o-&y3z==(sNdtNhDk&-yeSAHMYzc#QA>lX)?Oj=WWrANI5VE00(0}E|{yR1~ zUK_pf!}7Cy+5YcIqdIE!(8cmXJv;+{dpycCy#DT=NXoL%$<+*k2<@IyCxjZb?GLh^2!c-zB;DmTs^XG zh3}_Y%Vp%yvFyUZO$@@-KJNic7`V(*!-%Z#pW!` z{BrQMOy9uoox$v-0*14Fa^p*TTw z&$%)J>z1}%Ly6Gr`H2lkS>6|npf(le=Ojmgt{Th~Hegpj>+sWPE%LSPVTeq-M{k5x zQ`^Z1?~Vi?h8G$ep}8ab|0rC(c{9A5%Z-e%)@%U}WyS?eBmZ+}XX7`f)6u3RJ)-V*uH8p)2|6&|45+{Ol^socn1MI&9QkT7SsFWxa8@JBvYX z!EeMIYJ!T-GIt{A{bje26E9?3-*o>4vdWE@Xso5d_m=xG;)6}%!2?|s(ZP-PQGRq? zH_W3kApsgwS5F#3cQ6p+peN#RUz~pp0(IL=f`UZdTNf5q7lOAllli&fUEVTpD@a;c z9)Z8PE~?UL$G@VO&Km)d9P&Aj5QSq4@66%^9*ZW&7z0I+QPSyQLd9+;B*5Y~1)@qA zI+?qk-DTEvBGE|C$iaN>R_+o41QhdJV6iTc-YKQk;})^2OO{k`vwHcZ-^O0O2%C7f zxjAKj)EsC}j8I6`L6J$KlO=E2vXTfsJ^IO{OU;PiOZ)q1@!Jy6bqit&hLHE&#c5~$ z_&2S*{G95~hy99}oz2lbDv1(Gz}_9|NHqtPriSCYY)agY=`Lhyax0 z!py`vH-N+cw(sP#)b-90ry36NUkAYp(C?5e{$)+md*omI(5dGfw_uj|H_@#AwvHS zxe>EaZ>|^aEhhl0&@K5mA}(HYiDE*uWIxuPUhRj-TitO8XI~S&st^^SF1XfrGwxQW z#EPN+Mu3CpMb;P)>vdzj1S!8R88>n36M|p0w~pYIchC103XR{OQm4a$nX%?nx(I;Y|y4_`h(_gByDrmIrmJlg|nQ1`jkt=!7hdP}e6<~iKG z;!Fv*Z9#{^P`9>K|60-Eh6)h}dDZVi6|M_ZLmAke6v!`5rSy<~LPYLYe*-%g`U z41IP@+rZ$Fc0^ZjXa*-bJ|*`s6IFK z!{Dv_A0{=#*Z(%P1cK|-FJx_@1GfOD5*G82HH|7Ph?Ktpb0LC?ut$B!9(6;!By_Ff zl1sd$!Omo#P3fErp#U!=(6tQ#8HYXy5#J`(W1l$M_cyaM!^>j{f|IjXgdH(9!u7@$ zuV;#INW~1em}!gnUX#I&A|q!{q41#LL)CMuvX|1-K=onK)mnN>i9m9j?a&`o9OQ@M zY$I2PP`Dj0FrQ9pQ+ZGA9AvcUep0K)L*qN@?;;eS&?y5y05|dgs5Xdp=NUe1^^J9^ zD=;@kUfF9-PR3-7BX7A{zRoXp-D$tx`z~v~f-CHv_U!`}BnsV*vki$&dn^KAiL1_s z-CS~g%i>Qxj!l7~W;x0FYE0ub`7kFKJf-D;(U(*FPREF5fJswjAO+Vzh>)BOH%s&6 z2&BwCD$k+@D+)HH9`)%i*MWzHBF%-q8mI%Nb^Nyq(`-}!DVA`IAv$g;CdQMNJ zB(h;iRXeVgLe5;a&5sT4O4q`MRkCb!$NnzBiKf+|PG30h(|4uEt(9{4wK2+n#|a=x zzDNzoE2g9mfwXuVQ>~eo_qk+M;8~I+=>gpy9tiW^If}$CdX0>a)iZ{eDmJ+2F7h4) zXq>SgQmMSN8Hi!%&-5{FfN{g>^%V{=NcdgMUzthT5bCt6P$Byt^HIhc8L#=67h@&b z_mqLutNbm+~>;|hr$bdcut3mdU2R@_eXQ9_=PuH~Jl+u`xqbduFmj1wrq zu&lnU2QbsG5-MHzTl+|Qba_5{BdUvGoj&!i|3I~;pPoH(_yuCpF=(__HN6%(Tpar& z;cXP=X`+imW5yH;ki5l6(kc0*19@(cRF?-oQ09Li@ps<9dvprq68o2pzscr3BQ&ju zwJjx41V>gs>>DvWe~^a)Sgnfw7Z7nrP?ID%|{s$3ONAkS* zLCM9i#;jcOy~QvW&8fYIu#>JZZrDO5;x<9Cy>$LJw3ih*Axzsn3MEOcqKkR+c~n!O z7khrhkGe!8MY8AfW_rI7F9Q8k3P~m+EAAC}z}WCaNT2=~iT{c63hMmjX`~%mAMmz- z*w{f^nDf&P3S~zT9lkj;U8j`@Fq5BeUbx@l-1|sHjsvs>9#R-=M%3|X8!Q(&azqJB zuKD9M@?^3s=5tU8OAUfwVFv*mi>gYjG>KZY0$X3Ihc6}lYhR4*0Y~KL3mfkfB$g~+ zA{_=WCg=5qDV5Jr%1w`NMsMQGzRU6JRvlN~&YGAO!{VFJW2M(AKJH-cytJyCykClA z`*9C3tT^2uHn2KD>qKK;HS_Dvc$(tJ$~1jiT5-^;H&FcvJ!GH7T@B#z-h&ANCChks z?!~h_%n+Zfh^ZWd2v<9wl*JP)8HeFPqd7#@0+J>NE;lmH(}^))3K~=MmT|N2&lZDD zam7wfkvgmQpdm>h8v_Cu*@r0ewMlEK)kyG2Z7yQa;Vzd2MVG+0&f-a^hG=A7Uk@ft~091E~z< z7`|wrd_Aqau-jA8V2K{9Fc&laynH#8nYm^*=-oY0q-u`8FVLmHbY;JK%I(l}499N@ zC;d<#ak~Y5jI_Q*A!BdmVI4@Z3lR@vOdwTDZh@!{8cK+g_ILzIQj;vB!+H>vNR9m{ zy`W0mC&3Y_S-;C0_5UcVi+&$RVmX%8cI<3lk@O#9L6GNX30fq9v~6;@-p%Gn0u}4` zwQdadJU&Z%>pIB1=svO~M!f-3cUQ5_kf!S4l?BoyTJr;(%%2FB%msn~IBBLGoeL7L zBWrxUg<{Fx4ErrY;%r9(EeF)hY&RtEoBN@gaV*G>IYBzsZa|3w1GB8jYA0C{`G#z_U8G3T1gc&D?i56`?5eq0OpvuTi&NJUl=#3N;6k&3kfIQ`Dexos;j&^PcqQM;!1aF_FnWX5elcockS^Ti?maSgAG;|La2J?3%ZSn}e>`N*gQ$I(P!~s(=?C86C)s zL+t0wYgsSdHshy(x5}l$gyNHB5#Lg6X?LSplLPsY-EkAk65+iq3V;S>rH13wpBt&0W!dxA8HLX~eGmP?={VihA>_kMOMZ#)sb%qgOfl znr3x;xXeowy2ZI?gqaNszbZRo&~6A*dA% zvq}Lio>Zlul8%lV@-JG~sreqv(q=R!(#&yal1#+)c4G4-H7ghb4$a}?B6oZ&e7k(a z4Wp7=$oa_ov&Q2NLH85AM)P%v_*?;1Um+Lb^X#}ij1m8c`^*nbyga^aj(A$w7YMsv zjt#RzSXf?UyYMHWEGq%d(d(9&%qz}7`Ya5w?}c5q-J3x4luv&@5X%m;I^~B|>nu&7 zGO5FI=*?Y$(aRo0qXSy+_8X$T7+vvt*qaz>yrCI-F>)@;iz(>K)OiGuJvb%rQa6Pd z2oi7UWcpXull~2*n8w?MXRdBkd3P)FhN^DRTT+4YDNks~y|q=BDI}BA4y8 zQvz?q4`80NK?_2IJOFYyYU_s!^N4=^^)p+vajvC}(yU=UzLORfR}fYKLX<_kOWMBx z4MF@+1W)wgP~SM_Xwur@#G1TysqGM)x7{O6k{)E}czZI&#C~+_=EE;enU;HuEUThV zT4F5#k$W`Rl{s-1B260<9aMaiqL{-5(t4>c$+>*nVS?5m^}AdTz5jJZiA*3y!XS)6 z=FA-2i($NgV_!eK?qU2|784aBVFRe^DLTB{FhTRs891HFrYXba{G|i^YOj@cao=i_ zd|ULmSjA8VQ@~JK;=@XRw%*2+Y{E4~C6e)~bR-jU=kSP(cgLxYOQI?l>19aq=Ui`h z{54dyfA!iBbn^Ham^)lkB9?Wac*(MjmCRx^S(hGM|Lyrp{|Qr{@&~d1pA!64C_Wa_ z_WlQ$b&O82tZ#+(1UR|W4&S5Oj(J8|hQTXNi-s~B4Ny$ASZ7ZS|5Cy7kO$?XWq$X~ z5Ej|_l>IB#@&Wc*LO0E=k@0u6|`lq%}w>xSIXr z!XO;Z+Sd_?Q7j_ae^bR)M=$;VT-a3+lfA+YFQozJLvF#|RzdLKfl&OP5;%Eh7f33Ki9OgLNo=uawQYX#e*Giq?IyFxz+ zeJ3sUF@0VhaNumT@U9KYco{iI6Gto(NWh`@cL0#{BO}{fi2ehCHjYU5!`LJ%b=JD* z#(lHZK75D2b4rZnVv|7Z5g-@0y-Nh47-5oo2IEivy;M(S+bK*{k>W^aP>sa{+Hp&| z-J~^@1*-x9X9Dpy=DucS7%wT_uAZE*Oqyc2i%!Uod3Aey%uLeK$Rd@TLnQp#;%IW{mRyDT+6%?lf2Kiv~;?;vo9h+H`^kvv{ zdXgVkANSM&yG;zTqF(%~sR}H2a{uXK$Q*z7Q?mwMAdB%XMaWpWF<%S{D!NXTu3b8m71o1niUc7RXfvmgPZUqqF!95-f8D(`CK@CYVwSmtYdMY%1 zSuUyyzTW``@wQVPWgfPb(M$Y8u|0wr3t=TOxh?i`Cuy1STrA`M;IE_poy-H0eJcdH z@nOG^-<;yk|5D4`w3|yQJ2w;k6Co)^xjBc8L^}028qnD5ceetp?mWxje^@pq6(y3- zn?4X-C@3Q$>2S%F9L???Sz~uZc$yq|to;QiJ6?@=ZLn)#u#DTwbKw_m%rRmjK=A@; zIp&7z3pi(5bY4*yerv0jCXb-~B6^VF>oJSfE>r)t!z;q*!oERB^>FPBcV{hll@{fo zAxeL=nc@A^vZ8jPteMD;`GU*tC56JSN0yPWyN91+8s@mXu+MBKLI5MK_vCJ&cp}S} z=*WvPriiu?hd_+ljSFq(quMPVL9E8}p<@|AfRrI!(O1A1Yd@tIPUpT$SKZGrodIv^ zdx&2Re)2s~Es^GzME7mT;42IpVK-P^oNn*MVZ6H2%}vGcxyw%>;y(j&l6J8ns+x!K z0G7Px-n6<~jyA*frwgX-gyxEA$G1htZ-f;eiaUSOA1?mH+;PT)La~n+t)!cV9X~cz z>XTcub&M772Ds;JlDASMo*r`tBft;&BEQEbhrG-{SAWc%_Pis}#buice zR4ro`OmSx$ZE>n=`Bb3X-k^HbmLgziJlDFs#|_#*TtKmq2jrHZ#&C=_b?Ksl$th{% zsy4-NjIt2{)3j7bQS0)!b8_@aP_mUMNI7fbzpb}9&qgr9_H3B($c8Won&^jUnG$Bz zcz|b+V5_PB*N|Q&_7M}2d7hgXHei7Y$B{90{}=Tt)7REP!}rXqKW`i{~9 zP$bbHsO~ghr8l)TZ6w8bGm)%2(c43oZ)riy!O|=nxEox{Wr2UM8I{f@B#x1RiYC`w zEq^?~x_n6j50m?K3grwsykX)cN>wewNgB31tGaPeUU%ur DX5aq1zAWKs2&wi(V zZTnmNXr@4Gd)F}e_k9RO2?VCXhF|0|TaiDfL0QU4uPW1C2YD{1jhUBVqN~25%4>I; z;mUm?LT>6qyZ?4>YW`zT-m!)&LLEo}|9*(sgXoho8|@qxya;I!Z0{3{uXRn*vS$a+ zpluLKmebZa5Ey5#ikw6|(a5ihW|>Vm{@S*Pel?Vvt1#R-%v+(TQg-u?#_<0uXQ{_% zgaCQ|W2LIdy%0pY^J&hfi|JA0BdonaJYBY8cbUsdBmHRjPsFuAB@wD<{FViKtbb@L z)J;jDc!1(6g<0^@Yn#3171_;G-dQtSDAov*k6%;0YtG9!8T%xVMlj`wf|rSX*IXsA z1X>`vyF!LW;ViP&UtU@bZg*y z2HQ~s+XL>H<=Hi_a)ESR$p3xPnCP7|BcfwLsNerxjY?v-p>`CYa>$Kg?(aKahPt?e zpcMTi*=Hd%(&x&z%_G?QE6=pYRLRlN0b=^Awx0;NLl^~*5ZjZp+h-*EkVtZFH3LK_ z8LrF2AFgvgNT#%r|6HD|v@xtv3jo1Cds<97=EWvm=oj>4wJ&zW7sN#3@_z9C<=l&V z`gtvY14+8xzGJC~4^MLPPC*7ruRuLeM9))LD}f$AMIj7Yhdn+{`C7f__-l4z;C7#_EzFp-@x%B;%E=7VddEuv9 zCfcmB<*?XO6ikASXv^49RF^G6Z|^N5Cn)_0#s;tgB&rK4qDnxi|GcFC!V5ZGc~+UF zC5W!z_;{J|Q!l8-Zh3C26ipcvGyM(19xJ~}&8;0OUqj{dLi3-d3 zfMUPdi#vDtSw zdN3%!wV0lMJdu~fs)IiM6>d@Z#gPnnOy1y`@DhXq#Ue0(=uMePO>`BUP}(u_QUavu zC(*Bx{Rz$$oSu{Wqd||}C9>lLq7Kox4_d|+0bEc^ggM(%d@dm)JpsC7SA&{Kfc!Wo zERDla7~lu-mBNZY7;&rLl}zT5aBSRC?1~&6VW!haJBM%u+{}DUxV4VMV4eypy-NY zbsnyDKRq!8&-$*=MtXyR>4JB}UYBx_6g3JvgrIw(5D!$>Ks-6@Rfyp%)Q9Z{X}MB# z*7c|VR^>PDTEDlPG=V7iKT`jW=pF9)?P~CR#KRZzF=k&QmA;^M`ARYV22EXtCgJr^ z28TEW0s1V3dyd+QnV|$|pV>ypqKo|h=>o5QNa6%>RWKir82D^M#gRLtIEvof5NUVH zB8dJHRZw^yCQwI2LE5QFTg8U*_jT9kSs(0@0YWMY$_qhs+C6}ms_o!8!>#t7fsmhl zBs+?z39q|SEEi*?wF3=!Hc2#5gV2P@?<-gJS)l=RFLQT^TK;Gw&^|j{C){ z*5k^r;<{TcCOtRzZ*YYa#?#Jn-u+A5FD+W_pwW^tiljvmcgK)E!Mk>QT+lR4mm)iY zXA9?c2Bwxs`Vf`H0{I8W1v*XD0kaHD^TPI~WU1dxIJK%p;^a|+a97WzRD8!byl7%; zL4Uvoqg1g-By{gN>R+Xjk7-V1q#->e43WFQSK~sGffQyzJB471j%AqA9Uakbz+2`7 zN*uM@cK@A$~VpNE}gLh@Q>_fsAL8mS)BWe<$z$vz}{_}-!iJQ z1^6O=0H!vV!Gs=Ew#5$#zOPwg_BHG zqpMuqg&P_UD0_^(_sNqn)JyI~UbmC*8XEF;g%G$q8wFF({(dIZmS(}{ zB&;=Rj+$Nuya)fE@ux4{3Xt2LlYm5#Lp%Vhuf(5$*+|e~#d0(puW+)x;lQyoSmH;A z<^c+|m^x-xseo)<{AMo^&nr4OMN5Z`ec@D~ghwrStzfQV8-dVi;Q?Z8qWIkyVZqSR z9wX|wha?H$DkNX_TTtQVX;tIAR(+z>oJ-BN>KWKo4hsNxe!;C^vrjc12kKz}b(K{G z8sN2y=ZCDyI~2pNQmtkJOBlDB;N+fscEvz*jd0Yc5hMS(KuHp8Eg)TjDO`WoV<|MF zER~v{z-^DT)-+!nAmqpzhWG})Pae(`ma)?dn$!mYZX4wF^iKIzY%x!#?JD&quQE&) z2GW3Y?%c`;_)cR+)XANaDC|}R(Kt-DYZ(?FEt1F^Mrsl#N8pAy<1n8X zK7wnks;2ui|G$30eMHmKRA)S9EiK^v#QQV_% zC1%S>524-!P+F!~${f|Geo+BInPWI}A~%o9X}D7iuU9x~-VmJ55UvM_+CYBBJeg!U z)mF!ei4KBiec&|SnYJom{G%>e1$<|2O)PRCcBvYq{0Ptc&ZACQhuV`5eANnx-nE6n5nn{(J}x3p@UFOr3M8`^XihLk0f zEniLiV{?!33a$K6)_QwO6}3x_0?;epco2Yy8fXpdF1`w~vY({$>ZYwb_;F97B8%e7 zY@d?`0^$$AN)cNt{IC~hS}&P#D7SB7EAuJ7s)nsD}EM1kzak69$% zMHr#Wz(2jq254S_jm2#vXvS0`AZ9=r){EVVbb2|cs#ucNjFD-|8=w*?UdHFSqfjL^ z5j&n_Sc|htMgi?9r^|6>5Iz?B3ginuothZg3obWoSDQq`azcIEVuh9|6w!&vr6XtT z{Fq2+0x{_~r7tYaQ>-Z)uFma*SDPB&*7D`yQU#}-Hyx;CZS$wk3(fAEp^7)wNJ|%S zbA_P_71A}A_DyMXS&9+~9~Th=baJ^Aj1y)Xhv!@LLf{bQ3qb%x)%-@>0G(w;a!F(p z-CbI&y~9l}8N2y_OK?WxEe=*)ieCidH}kz`aE9O&gOLnq#jff~ZpXi>!a#5HVo6Hr z4TtIEIf*aVdan=>iCr~R4t3-{08JA?Z7zc-1EDB@3u=Mq@jal$0c!w4z-HSSmijn; zI42$OJ!TrgY<8rf^_}na^W))%UqCWpuYxHk7`#&l#gY?$={(lR%VyUEvxyjO?1zix z>7sihR`@ptwr=*Itp+nEU9%$8&T1P+^(&$ax_ypD|6{@DTt4x4hTLN4EBTEJnZw${ zhG`j2R>|FASya~6NY~=>Pby)Zb%r8SRK)YUuXc&%c{vujNQI_wIon@0u){8Im`B$DS@NAH+M@#4@^fA`Fq)P=^yvs%<+__1sQhr|rE51v_-{0W zTFOD9uW@-F&YV+iFzaLrg{pGL>Zu5je-(|QtKc^{v0%G{0MY$-NIJ%TNNJ_`%lIPO z84T7rEWBHUi|C|YfZ+OK4(h&2KHC~K6&|E#ZL(kbxwZ|L(o#rWOiFNsu5$PC-9_`b zXv^^(y)ha3Qe}}>X=ZxDbPnee@!cBHm?CVbycQi&^`cAN$ZMxAd682bZA|e%qKCpO zRkGmI@OWcQTXoW5;_sYNUwkD;GOGdo{@)l`ehmcb>Sir4aib2QZx!Y!K7H0XF5SIu zP322wJz6}H;M2EF0Dj3<$3?buM$ym?Lyg^&WJl(dj}boog*^3*X|xl`O2Vd^SIe2X zg+fCP5O)?ex~J`_4cQm$je?+qnD7e7fz2hdx@x6YBS$`InZTDwAx)-1=H4zss&u5_ zVcUE@A$>vrS-3G8dbA^59iCDNP^V{PD@xaNAb3J#N7ALmc~d2=_&8^K_%>DS1d!)6 zGA@l1yK0`~2_xONEih-NS@%7`?qc%DIG)Bs{a7&j=Su1JHJT2N@(Xq^eC^!htFB`b z<@c;_gYy9Uq+r)ge(x`lbS5vgtPdRtuE)#{P2NsnlV%d$(i2ZYz;_@;SG93Zt9vE} zO3&nNH$UJ?!+885WdRI!?J1liAQd8OqEaMInPL&Fpw!7>;E?xXZx{MLO}gy*ODzhC z)n(+WtMHa?%J5Cp_{jw@cxYn)a7l^)VPu~3w+9`OwOp~wWRwq(Fq`U_Sea%}X?!is zS$-CGL>MiYr=U9;fRyd!eBgVSAI*G9-y`=`*XcRCiy)8 zvCJMC@mB#@hIhb43v&V`g*lx^@xtF?3Wg@IGxdRnxf;f~Aennf6XTze4Q7|?azLB0b8)H4cre$o)|bebUwo$1VnO2^IQ9uenZGpx z$O-STSe%q@^ZJDQEj4wkN~D9vt#5T3`T)QC=E4=VhFy2RK1#|u%GyCw1!)GakMSs$ zff2|*e5OciZ?CK)&L`6_#`1``A#*lwsuh>FO|7@XlB93c1W~AD|>Bc^K@LZj$>WY{LO>^DJ}+V)3KV1UO=|E*O$VSl@<77gzn zg|5}Oz`y>Vnto8wJUhj-p@nTXR%(^P(3SFjq9Vy_dm(Qo2xw!tD)Ya?_OwP4|6ezx zzwjhy+#;o)91($slYb}A?ELElgh9Eil!K~rT>{t;H;Ws}D^5~`UBU1Kn-5um93wdUbMCsS*XL*U>Rrot zVy$T1+r(x;X&n<=w4_c5o;NtvLrHl zsV<^fVjw8=0m`4AS2|9)sh9j0Ugp&P9DnqFAH~#inA1x6?V`z3_$tLH(s^sU@!91~ z%X3^4RG^q8X78xQt8D1QXyNiEyf!ja@yTsvc~{dE3ucnv58<$>T5XNaIhR8io7@v3 z%|$`zILz#05tUn?HAiD#L3^FHm!fUad>jCx6%@SRL}A3}e&*!KwM~ zQf8(gtL^&Aq{kPp9<|0x#QcQ1s+~$BgQM?q#bFc>Bs1+-IbrQqzBcTXN~%a(FrD${ zg2fukE`@Av#~zB!wK&QE0000066byYge|7p00EVm0f4|DFP-)KvBYQl0ssI200dcD Dv-DaD literal 0 HcmV?d00001 diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 810513e46e..f662581e3b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -500,6 +500,7 @@ import hashlib import json import re import sys +import tarfile import yaml root = Path(sys.argv[1]) @@ -607,6 +608,23 @@ for clause in ( raise SystemExit(f"Temporary PLAY marker lacks fail-closed clause: {clause}") Path(sys.argv[2] + ".marker").write_text(marker["if"]) Path(sys.argv[2] + ".producer").write_bytes((root / ".github/workflows/runtime-images.yml").read_bytes()) +# These are verbatim runtime-images.yml blobs at the named Git commits. Bundle +# the bytes so the contract is deterministic even in a shallow CI checkout. +retained_refs = ( + "1eca914a699e08c7c47791b80b89ceba2a5104f5", + "3b81c438ddf473c94ad0424ad9a979d7070091e4", + "6b4c33d57a6c44c44258bdbfdae6aa3f59b31ecf", + "3f19ad85ad2fa867b978ec009b078eb950ae1b97", + "2c5bfc6129723cff130081a66a25986cf18555bc", +) +with tarfile.open(root / "dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.tar.xz", "r:xz") as archive: + retained_definitions = [] + for ref in retained_refs: + entry = archive.getmember(f"{ref}.yml") + if not entry.isfile(): + raise SystemExit(f"Historical runtime workflow bytes are absent for {ref}") + retained_definitions.append(base64.b64encode(archive.extractfile(entry).read()).decode("ascii")) +Path(sys.argv[2] + ".retained-producers.json").write_text(json.dumps(retained_definitions)) Path(sys.argv[2]).write_text(script) PY @@ -3558,21 +3576,19 @@ const workflowPath = ".github/workflows/runtime-images.yml"; const repositoryName = "benhook1013/FireMUD"; const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; const canonicalRuntimeWorkflowSha256 = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); -const expectedCompatibleRefreshDigests = [ - "2a769961890119fc91a83b2987537122704f6624035d1572b446569d5f9d11a1", - "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b", - "107a7bc895f890173161ea09f707ce93d8e170093aa8c8c528fc5f98430e1bac", - "ea6ade0f69718573aeac4e4b5a1e9050e53e1e3cef3426b8791f182d8d49e112", -]; +const retainedRefreshDefinitions = JSON.parse(fs.readFileSync(process.argv[2] + ".retained-producers.json", "utf8")); +const [legacyDefinition] = retainedRefreshDefinitions.splice(-1); +const compatibleRefreshBytes = retainedRefreshDefinitions.map(value => Buffer.from(value, "base64")); +const legacyRefreshBytes = Buffer.from(legacyDefinition, "base64"); const checkedInCompatibility = script.match(/const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set\(\[([\s\S]*?)\]\);/)[1]; const checkedInCompatibilityDigests = [...checkedInCompatibility.matchAll(/"([0-9a-f]{64})"/g)].map(match => match[1]); -assert.deepEqual(checkedInCompatibilityDigests, expectedCompatibleRefreshDigests); -const compatibleRefreshBytes = Array.from({length: checkedInCompatibilityDigests.length}, (_, index) => - Buffer.concat([bytes, Buffer.from(`\n# Retained trusted refresh definition ${index}\n`)])); const digest = source => require("node:crypto").createHash("sha256").update(source).digest("hex"); -const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set(compatibleRefreshBytes.map(digest)); -// Separate test authority lets the same verifier exercise both immutable modes. -const canonicalLegacyRuntimeWorkflowSha256 = "0".repeat(64); +assert.deepEqual(checkedInCompatibilityDigests, compatibleRefreshBytes.map(digest), + "only byte-exact historical trusted refresh definitions remain eligible"); +const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set(checkedInCompatibilityDigests); +const legacyDigest = script.match(/const canonicalLegacyRuntimeWorkflowSha256 = "([0-9a-f]{64})";/)[1]; +assert.equal(legacyDigest, digest(legacyRefreshBytes), "the fail-red digest must match the executed historical workflow"); +const canonicalLegacyRuntimeWorkflowSha256 = legacyDigest; const canonicalPlayClassifierSha256 = JSON.parse(script.match(/const canonicalPlayClassifierSha256 = (\{[\s\S]*?\});/)[1]); const classifierDefinitions = JSON.parse(fs.readFileSync(process.argv[2] + ".classifiers.json", "utf8")); const headSha = "a".repeat(40), baseSha = "b".repeat(40), mergeSha = "c".repeat(40); @@ -3609,6 +3625,10 @@ async function verify(mutate = () => {}, event = "pull_request", knownPlay = tru "Known canonical transition PLAY failure with successful authenticated cleanup").conclusion = "skipped"; } mutate(data); + if (data.legacyDefinition) { + data.definitions[workflowPath].content = legacyRefreshBytes.toString("base64"); + data.definitions[workflowPath].size = legacyRefreshBytes.length; + } const contentRequests = []; const github = {request: async () => ({data: data.source}), paginate: async () => data.jobs, rest: {actions: {getWorkflow: async () => ({data: {id: 7, path: workflowPath, name: "Build Runtime Images"}}), @@ -3628,7 +3648,7 @@ async function verify(mutate = () => {}, event = "pull_request", knownPlay = tru `${fn}; return ${verifier}(data.run, data.candidate, data.identity, ${allowIncompleteSteps}, ${allowOrdinary});`)( github, data.pr, data.consumerRepository, canonicalSmokeJobName, workflowPath, canonicalRuntimeWorkflowSha256, canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256, - data.legacyDefinition ? canonicalRuntimeWorkflowSha256 : canonicalLegacyRuntimeWorkflowSha256, canonicalPlayClassifierSha256, + canonicalLegacyRuntimeWorkflowSha256, canonicalPlayClassifierSha256, value => Number.isSafeInteger(value) && value > 0, (_label, call) => call(), {payload: {repository: {default_branch: "develop"}, pull_request: {head: {repo: {full_name: data.eventHeadRepository}}}}}, "benhook1013", "FireMUD", require, data); @@ -3735,24 +3755,28 @@ async function failedProof(error, event = "pull_request") { assert.match(warnings[0], /^Canonical PLAY transition exception proof is unavailable:/); assert.deepEqual(outputs, []); } -async function selectedProducerFinalFence(event, moved = false) { +async function selectedProducerFinalFence(event, moved = false, superseded = false) { const outputs = [], failures = [], required = []; + let proofs = 0, sleeps = 0; const core = {warning: () => {}, setFailed: x => failures.push(x), setOutput: (...x) => outputs.push(x)}; core.summary = {addHeading() {return this;}, addRaw() {return this;}, async write() {}}; const execute = new Function("fullSmokeJob", "matching", "canonicalSmokeJobName", "currentIdentity", "verifyKnownPlayFailure", "TerminalGitHubRequestError", "core", "resolveCurrentIdentity", "identityKey", "isCurrentCanonicalAttempt", "setTimeout", "sleepMs", `return (async () => { let requireCurrentIdentity = false, iterations = 0; - smokeGatePolling: while (iterations++ < 1) { ${failedBranch} break; } })();`); - await execute(candidate, {...source, event}, canonicalSmokeJobName, identity, async () => true, + smokeGatePolling: while (iterations++ < ${superseded ? 2 : 1}) { ${failedBranch} break; } })();`); + await execute(candidate, {...source, event}, canonicalSmokeJobName, identity, async () => + ++proofs === 1 && superseded ? "attempt-superseded" : true, TerminalGitHubRequestError, core, async (_label, current) => { required.push(current); return {...identity, canonicalPlayEligible: true, ...(current ? {sourceEvent: "repository_dispatch"} : {}), ...(current && moved ? {baseSha: "e".repeat(40), mergeSha: "f".repeat(40)} : {})}; }, selected => { const {canonicalPlayEligible, ...tuple} = selected; return JSON.stringify(tuple); }, - async () => true, resolve => resolve(), 0); - assert.deepEqual(required, [event === "repository_dispatch"]); + async () => true, resolve => {sleeps++; resolve();}, 0); + assert.equal(proofs, superseded ? 2 : 1); + assert.equal(sleeps, superseded ? 1 : 0); + assert.deepEqual(required, Array(proofs - (superseded ? 1 : 0)).fill(event === "repository_dispatch")); assert.deepEqual(failures, []); assert.equal(outputs.length, event === "repository_dispatch" && moved ? 0 : 1, "selected typed producer must reject base movement after proof, original retains immutable event semantics"); @@ -4187,7 +4211,7 @@ function markerAccepted(overrides = {}) { data => {data.currentPullRequest.labels = [];}, data => {data.currentPullRequest.head.sha = "e".repeat(40);}, data => {data.currentBase.object.sha = "e".repeat(40);}, - data => {data.latest.run_attempt++;}, + data => {data.latest.id++;}, data => {data.definitions[workflowPath].size++;}, ]) { assert.equal(await verify(data => {change(data); invalidate(data);}, "repository_dispatch", true, true), false, @@ -4208,6 +4232,7 @@ function markerAccepted(overrides = {}) { await selectedProducerFinalFence(event); await selectedProducerFinalFence(event, true); } + await selectedProducerFinalFence("repository_dispatch", false, true); await pendingRefreshCaller(["completed"], true, {finalIdentity: {baseSha: "d".repeat(40)}}); await pendingRefreshCaller(["completed"], true, {finalIdentity: {mergeSha: "e".repeat(40)}}); await pendingRefreshCaller(["completed", "completed"], false, { @@ -4236,7 +4261,7 @@ function markerAccepted(overrides = {}) { d => {d.identity.headSha = "e".repeat(40);}, d => {d.source.head_repository.full_name = "attacker/FireMUD";}, d => {d.source.head_branch = "other";}, - d => {d.latest.run_attempt++;}, + d => {d.latest.id++;}, d => {d.candidate.steps.find(s => s.name === "Stop smoke stack").conclusion = "failure";}, d => {d.candidate.steps.find(s => s.name === "Export fixed-tag preview image artifact").conclusion = "success";}, d => {d.definitions[workflowPath].content = Buffer.from("untrusted workflow").toString("base64");}, @@ -4335,7 +4360,8 @@ function markerAccepted(overrides = {}) { d => {d.run.event = "workflow_dispatch";}, d => {d.source.event = "workflow_run";}, d => {d.source.run_attempt = 1;}, - d => {d.latest.run_attempt = 3; assert.equal(d.source.run_attempt, 2);}, + d => {d.latest.id = 123;}, + d => {d.latest.run_attempt = 1;}, d => {d.latest.conclusion = "failure"; assert.equal(d.source.conclusion, "success");}, d => {d.source.path = ".github/workflows/spoof.yml";}, d => {d.source.repository.full_name = "attacker/FireMUD";}, @@ -4359,6 +4385,8 @@ function markerAccepted(overrides = {}) { assert.equal(await verify(mutate, event), false, `${event}: ${mutate.toString()}`); } } + assert.equal(await verify(d => {d.latest.run_attempt = 3;}, "pull_request"), false); + assert.equal(await verify(d => {d.latest.run_attempt = 3;}, "repository_dispatch"), "attempt-superseded"); for (const mutate of [ d => {d.source.head_branch = "feature/untrusted";}, d => {d.source.head_sha = "invalid";}, @@ -4416,12 +4444,13 @@ function admits(job, overrides = {}) { conclusion = "success", foreign = false, action = "", branch = "main"} = overrides; const expression = admission[job]; assert.match(expression, /^\$\{\{ .* \}\}$/); - const evaluate = new Function("github", "contains", "fromJSON", "format", "return " + expression.slice(3, -2)); + const evaluate = new Function("github", "contains", "fromJSON", "format", "startsWith", "return " + expression.slice(3, -2)); return Boolean(evaluate({event_name: eventName, repository: "example/firemud", ref: "refs/heads/" + branch, event: {action, repository: {default_branch: "main"}, workflow_run: {name, display_title: name, path, event, conclusion, head_repository: {full_name: foreign ? "fork/foreign" : "example/firemud"}}}}, - (values, value) => values.includes(value), JSON.parse, (template, arg) => template.replace("{0}", arg))); + (values, value) => values.includes(value), JSON.parse, (template, arg) => template.replace("{0}", arg), + (value, prefix) => value.toLowerCase().startsWith(prefix.toLowerCase()))); } const reconciler = "reconcile-failed-pr-runtime"; const validation = {name: validationName, path: validationPath}; @@ -4431,6 +4460,10 @@ for (const conclusion of ["success", "failure", "timed_out", "cancelled"]) { assert.equal(admits("source", {conclusion}), conclusion === "success", conclusion); assert.equal(admits(reconciler, {conclusion}), conclusion !== "success", conclusion); } +const qualified = path => `${path}@refs/heads/develop`; +assert.equal(admits("source", {path: qualified(runtimePath)}), true); +assert.equal(admits(reconciler, {path: qualified(runtimePath), conclusion: "failure"}), true); +assert.equal(admits(reconciler, {...validation, path: qualified(validationPath), conclusion: "cancelled"}), true); assert.equal(admits("source", {path: ".github/workflows/untrusted.yml"}), false); assert.equal(admits(reconciler, {...validation, path: ".github/workflows/untrusted.yml", conclusion: "cancelled"}), false); assert.equal(admits(reconciler, {...validation, conclusion: "cancelled", event: "push"}), false); @@ -4456,6 +4489,8 @@ async function run(kind, shared = {visible: false, posts: 0}) { const refresh = {...source, id: 110, event: "repository_dispatch", head_branch: "develop", head_sha: "d".repeat(40)}; const event = structuredClone(wake ? newerCancelled : source); event.name = event.display_title; + if (["qualified-runtime", "cancel-qualified"].includes(kind)) event.path = qualified(event.path); + if (kind === "malformed-callback-path") event.path += "@refs/heads/a..b"; if (kind === "cancel-wake-wrong-id") event.workflow_id = source.workflow_id; if (kind === "cancel-wake-stale-head") event.head_sha = base; if (kind === "cancel-wake-fork") event.head_repository.full_name = "fork/repo"; @@ -4464,7 +4499,7 @@ async function run(kind, shared = {visible: false, posts: 0}) { if (kind === "nested-callback") event.event = "workflow_run"; if (kind === "fork") event.head_repository.full_name = "fork/repo"; if (kind === "success") event.conclusion = "success"; - let clock = 0, tupleReads = 0, sourceReads = 0, metadataReads = 0, ciInventoryReads = 0; + let clock = 0, tupleReads = 0, sourceReads = 0, metadataReads = 0, ciInventoryReads = 0, refreshInventoryReads = 0; const github = {rest: { actions: { getWorkflow: async ({workflow_id}) => ({data: workflow_id === "ci.yml" @@ -4498,6 +4533,13 @@ async function run(kind, shared = {visible: false, posts: 0}) { runs = ["newer-original", "cancel-wake-newer-original"].includes(kind) ? [{...source, id: 105, status: "in_progress"}, source] : kind === "cancel-wake-no-original" ? [] : [source]; } + if (workflow_id === "runtime-images.yml" && runEvent === "repository_dispatch") { + refreshInventoryReads++; + if (refreshInventoryReads === 2 && !shared.posts) { + if (kind === "late-refresh") runs = [refresh]; + if (kind === "late-refresh-incomplete") return {data: {total_count: 1, workflow_runs: []}}; + } + } if (workflow_id === "runtime-images.yml" && runEvent === "repository_dispatch" && shared.posts) { shared.observations = (shared.observations || 0) + 1; if ((kind === "post-read-transient" && shared.observations === 1) || kind === "post-read-timeout") { @@ -4607,6 +4649,13 @@ async function run(kind, shared = {visible: false, posts: 0}) { (async () => { assert.equal(await run("valid"), 1); assert.equal(await run("cancel-before-enforcement"), 1); + assert.equal(await run("qualified-runtime"), 1); + assert.equal(await run("wake-cancel-qualified"), 1); + assert.equal(await run("malformed-callback-path"), 0); + assert.equal(await run("late-refresh"), 0, "a trusted late replacement suppresses dispatch"); + const lateIncomplete = {visible: false, posts: 0}; + await assert.rejects(run("late-refresh-incomplete", lateIncomplete), /inventory is incomplete/); + assert.equal(lateIncomplete.posts, 0, "unverifiable final inventory cannot authorize a POST"); const delayedWake = {visible: false, posts: 0}; assert.equal(await run("pending-newer", delayedWake), 0, "original completion cannot ignore pending CI"); assert.equal(await run("wake-cancel-before-enforcement", delayedWake), 1, "exact cancelled CI wake restores liveness"); @@ -4676,7 +4725,8 @@ async function run(kind, shared = {visible: false, posts: 0}) { const ambiguousVisible = {visible: false, posts: 0}; assert.equal(await run("ambiguous-visible", ambiguousVisible), 1); assert.equal(ambiguousVisible.observations, 2, "observe an exact late handoff after losing the POST response"); - assert.match(ambiguousVisible.failure, /response is unknown; no retry issued/); + assert.equal(ambiguousVisible.failure, undefined); + assert.match(ambiguousVisible.warnings[0], /response is unknown; no retry issued/); await run("valid", ambiguousVisible); assert.equal(ambiguousVisible.posts, 1, "the next serialized callback sees the exact handoff and does not retry"); // Under the shared job mutex, a CI-first visible refresh suppresses completion recovery. diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index c0b30ddacd..2cc9cc1832 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -897,6 +897,7 @@ async function runDispatcher({ branchHeads = {}, branchErrors = {}, pullOverrides = {}, mergeParents = {}, ciEvidence = {}, hideDispatchVisibility = false, filesByPr = {}, postFailurePr = null, previewFailurePr = null, visibilityResponse = null, filesFailurePr = null, postFailureVisible = false, postFailureStatus = null, + fanoutCutoffAfterInventory = false, fanoutCutoffAfterPreviewPr = null, }) { const dispatches = []; const postedRuns = []; @@ -1015,6 +1016,9 @@ async function runDispatcher({ if (postFailureStatus) Object.assign(error, {status: postFailureStatus, response: {status: postFailureStatus}}); throw error; } + if (request.event_type === "preview-deploy" && request.client_payload.pr_number === fanoutCutoffAfterPreviewPr) { + fakeNow += 12 * 60 * 1000; + } }, }, actions: { @@ -1062,7 +1066,11 @@ async function runDispatcher({ : refinement ? inventory.refinedTotalCount ?? filteredRuns.length : inventory.initialPageTotals?.[request.page] ?? inventory.initialTotalCount ?? inventory.total_count ?? filteredRuns.length; - return { data: { total_count: filteredTotalCount, workflow_runs: filteredRuns.slice((request.page - 1) * 100, request.page * 100) } }; + const response = { data: { total_count: filteredTotalCount, workflow_runs: filteredRuns.slice((request.page - 1) * 100, request.page * 100) } }; + if (fanoutCutoffAfterInventory && request.event === "repository_dispatch") { + fakeNow += 12 * 60 * 1000; + } + return response; }, }, }, @@ -1403,7 +1411,10 @@ async function runDispatcher({ assert.deepEqual(numbers(skippedFirst), ["102"], "non-runtime first PR must not starve second"); const failedPost = await runDispatcher({ tuples: [tuple, sibling], postFailurePr: "101" }); assert.deepEqual(numbers(failedPost), ["101", "102"], "ambiguous first POST must not retry or starve second"); - assert(failedPost.errors.some(message => message.includes("ambiguous POST timeout"))); + assert(failedPost.warnings.some(message => message.includes("ambiguous POST timeout")), + "transport uncertainty is a warning while strict visibility observation continues"); + assert(!failedPost.errors.some(message => message.includes("ambiguous POST timeout")), + "an uncertain POST response alone must not fail a handoff that can still become visible"); assert.equal(failedPost.waitedMillis, 120000, "observe unknown handoff through the same bounded shared window"); assert(failedPost.errors.some(message => message.includes("attempted but visibility is unknown for PRs 101"))); const deniedPost = await runDispatcher({tuples: [tuple, sibling], postFailurePr: "101", postFailureStatus: 422}); @@ -1416,9 +1427,29 @@ async function runDispatcher({ assert.deepEqual(numbers(observedAmbiguousPost), ["101", "102"], "visible ambiguous handoff must not retransmit"); assert(previewDispatches(observedAmbiguousPost).some(item => item.client_payload.pr_number === "101")); assert(observedAmbiguousPost.infos.some(message => message.includes("became visible after an unknown POST response"))); - assert(observedAmbiguousPost.errors.some(message => message.includes("ambiguous POST timeout")), - "visibility does not conceal the transport failure"); + assert(observedAmbiguousPost.warnings.some(message => message.includes("ambiguous POST timeout")), + "the unknown transport result remains visible as a warning"); + assert.deepEqual(observedAmbiguousPost.errors, [], + "strict native visibility resolves an uncertain handoff without failing the job"); assert(!observedAmbiguousPost.errors.some(message => message.includes("visibility is unknown"))); + const cutoffBeforePost = await runDispatcher({tuples: [tuple], fanoutCutoffAfterInventory: true}); + assert.deepEqual(numbers(cutoffBeforePost), [], "the twelve-minute reservation cutoff prevents a new runtime POST"); + assert(cutoffBeforePost.errors.some(message => message.includes("fan-out cutoff") && + message.includes("before the runtime POST for PR #101") && message.includes("#101 remain incomplete")), + "a necessary target stopped before its POST is explicitly reported incomplete"); + const cutoffAtBoundary = await runDispatcher({ + tuples: [{...tuple, labels: [{name: "preview:priority"}]}, sibling], + fanoutCutoffAfterPreviewPr: "101", + }); + assert.deepEqual(numbers(cutoffAtBoundary), ["101"], "the cutoff stops subsequent runtime fan-out at the next target boundary"); + assert.equal(previewDispatches(cutoffAtBoundary).filter(item => item.client_payload.pr_number === "101").length, 1, + "preview dispatch remains independent for the target processed before cutoff"); + assert(cutoffAtBoundary.errors.some(message => message.includes("fan-out cutoff") && + message.includes("at a target boundary") && message.includes("#102 remain incomplete"))); + assert(cutoffAtBoundary.inventoryCalls.some((request, index) => + request.created === "2026-01-07T23:59:59.000Z..*" && cutoffAtBoundary.observationPostCounts[index] === 1), + "runtime handoffs sent before cutoff are still observed"); + assert(!cutoffAtBoundary.errors.some(message => message.includes("visibility is unknown"))); const transientFirst = await runDispatcher({ tuples: [tuple, sibling], apiFailure: (_request, count) => count === 1, }); @@ -2040,6 +2071,7 @@ require_contains "$pr_image_publisher_path" 'GitHub displays this run in the def require_contains "$pr_image_publisher_path" 'markdown_code(os.environ[' require_contains "$pr_image_publisher_path" 'from html import escape' require_contains "$pr_image_publisher_path" '{markdown_code(os.environ[' + assert_job_contains publish-pr-runtime-images.yml publish 'contents: read' # shellcheck disable=SC2016 # These are literal GitHub expression and shell source contracts. require_contains "$pr_image_publisher_path" 'pr-runtime-images-{image_tag}' diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index c850888b5d..a5822a2b12 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -462,49 +462,119 @@ void refusalBudgetRunsAfterIdentityArbitrationAndCountsTheInsertedLastSlot() thr new AccountCapacityRefusalBudgetRepository(dsl) .provision(concurrentTenant.canonicalTenantId(), 1); }); - UUID concurrentAttempt = UUID.randomUUID(); + UUID winningRequest = UUID.randomUUID(); + UUID winningAdmission = UUID.randomUUID(); + UUID winningAttempt = UUID.randomUUID(); + UUID winningDecision = UUID.randomUUID(); + UUID losingRequest = UUID.randomUUID(); + UUID losingAdmission = UUID.randomUUID(); + UUID losingAttempt = UUID.randomUUID(); + UUID losingDecision = UUID.randomUUID(); + UUID freshRequest = UUID.randomUUID(); + UUID freshAdmission = UUID.randomUUID(); + UUID freshAttempt = UUID.randomUUID(); + UUID freshDecision = UUID.randomUUID(); + assertThat(List.of(winningRequest, losingRequest, freshRequest)).doesNotHaveDuplicates(); + assertThat(List.of(winningAdmission, losingAdmission, freshAdmission)) + .doesNotHaveDuplicates(); + assertThat(List.of(winningAttempt, losingAttempt, freshAttempt)).doesNotHaveDuplicates(); + String concurrentRefusalInsert = + "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, refusal_code) " + + "VALUES (?, ?, ?, 1, ?, ?, ?, 'NO_ACCEPT', ?, 'CAPACITY_QUOTA_EXCEEDED') " + + "ON CONFLICT DO NOTHING"; try (var stale = data.getConnection(); var winner = data.getConnection()) { stale.setTransactionIsolation(java.sql.Connection.TRANSACTION_SERIALIZABLE); stale.setAutoCommit(false); + winner.setAutoCommit(true); var staleDsl = DSL.using(stale, SQLDialect.POSTGRES); - // Establish the serializable snapshot before the winning global identity is committed. - assertThat(staleDsl.fetchCount(DSL.table("account_capacity_origin_decisions"))) - .isEqualTo(1); + // Both origins are distinct and belong to one tenant with exactly one refusal slot. + // Establish the losing transaction's snapshot before the winner commits its last slot. + assertThat( + staleDsl.fetch( + "SELECT slot FROM account_capacity_origin_refusal_slots WHERE tenant_uuid = ?", + concurrentTenant.canonicalTenantId())) + .isEmpty(); assertThat( DSL.using(winner, SQLDialect.POSTGRES) .execute( - insert, + concurrentRefusalInsert, concurrentTenant.canonicalTenantId(), - UUID.randomUUID(), - UUID.randomUUID(), - concurrentAttempt, + winningRequest, + winningAdmission, + winningAttempt, "c".repeat(64), new byte[] {3}, - UUID.randomUUID())) + winningDecision)) .isEqualTo(1); assertThatThrownBy(() -> staleDsl.execute( - insert, - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - concurrentAttempt, + concurrentRefusalInsert, + concurrentTenant.canonicalTenantId(), + losingRequest, + losingAdmission, + losingAttempt, "d".repeat(64), new byte[] {4}, - UUID.randomUUID())) + losingDecision)) .isInstanceOfSatisfying( org.jooq.exception.DataAccessException.class, failure -> assertThat(failure.sqlState()).isEqualTo("40001")); stale.rollback(); } - assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))).isEqualTo(2); + + var winningOrigin = + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_decisions " + + "WHERE tenant_uuid = ?", + concurrentTenant.canonicalTenantId()) + .intoMap(); + assertThat(winningOrigin) + .containsEntry("request_id", winningRequest) + .containsEntry("admission_id", winningAdmission) + .containsEntry("admission_attempt_id", winningAttempt) + .containsEntry("decision", "NO_ACCEPT") + .containsEntry("decision_id", winningDecision) + .containsEntry("refusal_code", "CAPACITY_QUOTA_EXCEEDED"); + assertThatThrownBy(() -> + dsl.execute( + concurrentRefusalInsert, + concurrentTenant.canonicalTenantId(), + freshRequest, + freshAdmission, + freshAttempt, + "e".repeat(64), + new byte[] {5}, + freshDecision)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> { + assertThat(failure.sqlState()).isEqualTo("23514"); + assertThat(failure).hasMessageContaining("Capacity refusal budget is exhausted"); + }); assertThat( - dsl.fetchSingle( - "SELECT decision FROM account_capacity_origin_decisions WHERE admission_attempt_id = ?", - concurrentAttempt) - .get("decision")) - .isEqualTo("NO_ACCEPT"); + dsl.fetch( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_decisions " + + "WHERE tenant_uuid = ?", + concurrentTenant.canonicalTenantId()) + .intoMaps()) + .usingRecursiveComparison() + .isEqualTo(List.of(winningOrigin)); + assertThat( + dsl.fetch( + "SELECT tenant_uuid, slot, decision_id " + + "FROM account_capacity_origin_refusal_slots WHERE tenant_uuid = ?", + concurrentTenant.canonicalTenantId()) + .map(row -> + new RefusalSlot( + row.get("tenant_uuid", UUID.class), + row.get("slot", Long.class), + row.get("decision_id", UUID.class)))) + .containsExactly( + new RefusalSlot(concurrentTenant.canonicalTenantId(), 1, winningDecision)); } finally { new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index 7e1dfe02c5..dc1cc902e6 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -17,6 +17,7 @@ import java.sql.SQLException; import java.time.Clock; import java.time.Instant; +import java.time.ZoneId; import java.time.ZoneOffset; import java.time.temporal.ChronoUnit; import java.util.HexFormat; @@ -27,6 +28,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; @@ -372,7 +374,7 @@ void actualFirstJoinRetainsItsPositiveMembershipAndExactScopeBinding() { } @Test - void exactCapacityRefusalCommitsAndReplaysAfterHeadroomReturns() { + void exactCapacityRefusalReplaysAfterHeadroomReturnsAndEvaluationExpires() { Fixture f = fixture(true, true); var request = capacityRequest(f); long quota = request.evidence().quota(); @@ -433,7 +435,7 @@ void exactCapacityRefusalCommitsAndReplaysAfterHeadroomReturns() { 7, "sha256:" + "e".repeat(64), "controlled-owner-no-execution".getBytes(StandardCharsets.US_ASCII)), - Clock.fixed(f.now, ZoneOffset.UTC)); + f.clock); assertThat( recovery .reconcile( @@ -443,6 +445,26 @@ void exactCapacityRefusalCommitsAndReplaysAfterHeadroomReturns() { .isEqualTo(TenantCapacityAdmission.State.RELEASED); assertThat(f.dsl.fetchSingle(readHeld, f.tenantId).get("held_units", Long.class)) .isEqualTo(quota - 1); + // The exact durable refusal must win over both returned quota headroom and expired evidence. + Instant evaluationExpiresAt = request.evidence().expiresAt(); + assertThat(f.clock.instant()).isBefore(evaluationExpiresAt); + f.clock.setInstant(evaluationExpiresAt.plus(1, ChronoUnit.MICROS)); + assertThat(f.clock.instant()).isAfter(evaluationExpiresAt); + var retainedReservations = + f.dsl + .fetch( + "SELECT *, xmin::text AS row_version FROM account_tenant_capacity_reservations " + + "ORDER BY reservation_id") + .intoMaps(); + var retainedSlots = + f.dsl + .fetch( + "SELECT tenant_uuid, slot, decision_id " + + "FROM account_capacity_origin_refusal_slots WHERE tenant_uuid = ?", + f.tenantId) + .intoMaps(); + assertThat(retainedSlots).hasSize(1); + assertThat(retainedSlots.get(0)).containsEntry("decision_id", decision.get()); assertThatThrownBy(() -> f.capacityOwner.commit(request, PEER)) .isInstanceOfSatisfying( CapacityException.class, @@ -453,6 +475,22 @@ void exactCapacityRefusalCommitsAndReplaysAfterHeadroomReturns() { assertThat(f.dsl.fetchSingle(readDenial, identity).intoMap()) .usingRecursiveComparison() .isEqualTo(retained); + assertThat( + f.dsl + .fetch( + "SELECT *, xmin::text AS row_version FROM account_tenant_capacity_reservations " + + "ORDER BY reservation_id") + .intoMaps()) + .usingRecursiveComparison() + .isEqualTo(retainedReservations); + assertThat( + f.dsl + .fetch( + "SELECT tenant_uuid, slot, decision_id " + + "FROM account_capacity_origin_refusal_slots WHERE tenant_uuid = ?", + f.tenantId) + .intoMaps()) + .isEqualTo(retainedSlots); assertThat(f.dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))) .isEqualTo(Math.toIntExact(quota + 1)); assertThat(f.dsl.fetchSingle(countDeniedReservations, identity).get("n", Long.class)).isZero(); @@ -672,6 +710,7 @@ private static final class Fixture { private final DriverManagerDataSource dataSource; private final DSLContext dsl; private final Instant now; + private final MutableClock clock; private final TransactionTemplate transaction; private final AccountRepository accounts; private final AccountTenantMembershipRepository memberships; @@ -685,6 +724,7 @@ private static final class Fixture { private Fixture(DriverManagerDataSource dataSource, boolean join, boolean initializeCapacity) { this.dataSource = dataSource; now = initializeCapacity ? Instant.now().truncatedTo(ChronoUnit.MICROS) : NOW; + clock = new MutableClock(now, ZoneOffset.UTC); dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); var transactions = new DataSourceTransactionManager(dataSource); transaction = new TransactionTemplate(transactions); @@ -872,14 +912,7 @@ private Fixture(DriverManagerDataSource dataSource, boolean join, boolean initia }); capacityOwner = new AccountTenantCapacityOwner( - dsl, - accounts, - snapshots, - issuances, - scopes, - transactions, - Clock.fixed(now, ZoneOffset.UTC), - NAMESPACE); + dsl, accounts, snapshots, issuances, scopes, transactions, clock, NAMESPACE); var targets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); controlledTarget(targets); owner = @@ -896,7 +929,7 @@ private Fixture(DriverManagerDataSource dataSource, boolean join, boolean initia tenantEvents, targets, transactions, - Clock.fixed(now, ZoneOffset.UTC), + clock, NAMESPACE); } @@ -921,6 +954,39 @@ private Request request() { } } + private static final class MutableClock extends Clock { + private final AtomicReference current; + private final ZoneId zone; + + private MutableClock(Instant instant, ZoneId zone) { + this(new AtomicReference<>(instant), zone); + } + + private MutableClock(AtomicReference current, ZoneId zone) { + this.current = current; + this.zone = zone; + } + + @Override + public ZoneId getZone() { + return zone; + } + + @Override + public Clock withZone(ZoneId newZone) { + return zone.equals(newZone) ? this : new MutableClock(current, newZone); + } + + @Override + public Instant instant() { + return current.get(); + } + + private void setInstant(Instant instant) { + current.set(instant); + } + } + private static StoredOperation claimBootstrap( AccountTenantCreationBootstrapOperationRepository operations, Account creator, diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java index e11deefb88..beb5dfd8f9 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java @@ -193,7 +193,9 @@ public void ping(PingRequest request, StreamObserver observer) { assertThat(stub.getChannel()).isSameAs(previous); selected.countDown(); try { - ready.await(); + assertThat(ready.await(5, TimeUnit.SECONDS)) + .as("the selected call must be released before its bounded wait") + .isTrue(); } catch (InterruptedException interrupted) { Thread.currentThread().interrupt(); throw new AssertionError(interrupted); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java index 77da188f4b..debd777ddc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java @@ -74,7 +74,7 @@ public Result commit(Request request, long absoluteDeadlineMillis) { // during sampling can only shorten the bound; it must never extend the caller budget. Deadline sampledAt = Deadline.after(0, TimeUnit.NANOSECONDS); Instant sampledInstant = clock.instant(); - request.requireStructurallyValid(); + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); if (request.context().owner() != TenantCapacityAdmission.Owner.GAME_SESSION || !namespace.equals(request.targetNamespace())) throw new IllegalArgumentException("Exact Game Session context required"); @@ -85,7 +85,6 @@ public Result commit(Request request, long absoluteDeadlineMillis) { Context.current().getDeadline(), absoluteDeadlineMillis, sampledInstant); - var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); CommitTenantCapacityAdmissionResponse response; try { response = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index 5e194ae237..2663f96d3b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -283,7 +283,7 @@ void successfulRpcPropagatesMinimumOfExplicitIncomingAndMaximumDeadline( } @ParameterizedTest - @CsvSource({"3000, 60000, 3000", "60000, 3000, 3000", "60000, 60000, 5000"}) + @CsvSource({"1000, 60000, 1000", "3000, 60000, 3000", "60000, 3000, 3000", "60000, 60000, 5000"}) void deadlineSelectionKeepsTheWholeChosenBudget( long explicitMillis, long incomingMillis, long expectedMillis) { var nanos = new AtomicLong(); @@ -380,20 +380,24 @@ void explicitRemainingBudgetBoundsAStalledAccountCall() throws Exception { AtomicInteger calls = new AtomicInteger(); AtomicBoolean respond = new AtomicBoolean(true); AtomicLong observedNanos = new AtomicLong(); - Server server = server("account", calls, false, observedNanos, respond); + var measuredSecondInvocationEntered = new CountDownLatch(1); + Server server = + server("account", calls, false, observedNanos, respond, measuredSecondInvocationEntered); try (var client = client(server)) { client.init(); var request = CapacityAdmissionTestFixture.playerRequest(); client.commit(request, deadline()); respond.set(false); - assertThatThrownBy(() -> - client.commit(request, CapacityAdmissionTestFixture.NOW.toEpochMilli() + 1_000L)) + // Leave dispatch headroom while still bounding this attempt below the client's five seconds. + long explicitDeadline = CapacityAdmissionTestFixture.NOW.toEpochMilli() + 3_000L; + assertThatThrownBy(() -> client.commit(request, explicitDeadline)) .isInstanceOf(StatusRuntimeException.class) .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()) .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(measuredSecondInvocationEntered.await(5, TimeUnit.SECONDS)).isTrue(); assertThat(calls).hasValue(2); // The timed-out invocation reached the nonresponding handler. - assertThat(observedNanos.get()).isLessThanOrEqualTo(TimeUnit.SECONDS.toNanos(1)); + assertThat(observedNanos.get()).isLessThanOrEqualTo(TimeUnit.SECONDS.toNanos(3)); } finally { stop(server); } @@ -408,9 +412,12 @@ void commitReachesItsTransportDeadlineWhileTlsReloadIsBlocked() throws Exception try { var calls = new AtomicInteger(); var respond = new AtomicBoolean(true); + var measuredSecondInvocationEntered = new CountDownLatch(1); var tls = pki.clientProperties(directory, pki.identity("client")); var factory = new BlockingReloadChannelFactory(); - server = server("account", calls, false, new AtomicLong(), respond); + server = + server( + "account", calls, false, new AtomicLong(), respond, measuredSecondInvocationEntered); try (var client = client(server, tls, factory); var executor = Executors.newSingleThreadExecutor()) { client.init(); @@ -420,7 +427,7 @@ void commitReachesItsTransportDeadlineWhileTlsReloadIsBlocked() throws Exception try { Files.writeString(Path.of(tls.getCertChain()), "\n", StandardOpenOption.APPEND); assertThat(factory.reloadStarted.await(5, TimeUnit.SECONDS)).isTrue(); - long explicitDeadline = CapacityAdmissionTestFixture.NOW.toEpochMilli() + 1_000L; + long explicitDeadline = CapacityAdmissionTestFixture.NOW.toEpochMilli() + 3_000L; var timedOut = executor.submit(() -> assertThatThrownBy(() -> client.commit(request, explicitDeadline)) @@ -429,7 +436,9 @@ void commitReachesItsTransportDeadlineWhileTlsReloadIsBlocked() throws Exception failure -> assertThat(failure.getStatus().getCode()) .isEqualTo(Status.Code.DEADLINE_EXCEEDED))); - timedOut.get(3, TimeUnit.SECONDS); + assertThat(measuredSecondInvocationEntered.await(4, TimeUnit.SECONDS)).isTrue(); + timedOut.get(4, TimeUnit.SECONDS); + assertThat(factory.releaseReload.getCount()).isEqualTo(1); assertThat(calls).hasValue(2); } finally { factory.releaseReload.countDown(); @@ -453,7 +462,9 @@ void incomingDeadlineBoundsAStalledAccountCall() throws Exception { AtomicInteger calls = new AtomicInteger(); AtomicBoolean respond = new AtomicBoolean(true); AtomicLong observedNanos = new AtomicLong(); - Server server = server("account", calls, false, observedNanos, respond); + var measuredSecondInvocationEntered = new CountDownLatch(1); + Server server = + server("account", calls, false, observedNanos, respond, measuredSecondInvocationEntered); var scheduler = Executors.newSingleThreadScheduledExecutor(); try (var client = client(server)) { client.init(); @@ -462,14 +473,15 @@ void incomingDeadlineBoundsAStalledAccountCall() throws Exception { respond.set(false); assertThatThrownBy(() -> Context.current() - .withDeadlineAfter(1_000, TimeUnit.MILLISECONDS, scheduler) + .withDeadlineAfter(3_000, TimeUnit.MILLISECONDS, scheduler) .call(() -> client.commit(request, deadline()))) .isInstanceOf(StatusRuntimeException.class) .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()) .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(measuredSecondInvocationEntered.await(5, TimeUnit.SECONDS)).isTrue(); assertThat(calls).hasValue(2); // The incoming deadline bounded an actual in-flight call. - assertThat(observedNanos.get()).isLessThanOrEqualTo(TimeUnit.SECONDS.toNanos(1)); + assertThat(observedNanos.get()).isLessThanOrEqualTo(TimeUnit.SECONDS.toNanos(3)); } finally { scheduler.shutdownNow(); stop(server); @@ -539,7 +551,19 @@ private static Server server( AtomicLong observedNanos, AtomicBoolean respond) throws Exception { - return server(identity, calls, wrongFence, observedNanos, respond, null); + return server(identity, calls, wrongFence, observedNanos, respond, null, null); + } + + private static Server server( + String identity, + AtomicInteger calls, + boolean wrongFence, + AtomicLong observedNanos, + AtomicBoolean respond, + CountDownLatch measuredSecondInvocationEntered) + throws Exception { + return server( + identity, calls, wrongFence, observedNanos, respond, null, measuredSecondInvocationEntered); } private static Server server( @@ -550,6 +574,18 @@ private static Server server( AtomicBoolean respond, AtomicReference serverFailure) throws Exception { + return server(identity, calls, wrongFence, observedNanos, respond, serverFailure, null); + } + + private static Server server( + String identity, + AtomicInteger calls, + boolean wrongFence, + AtomicLong observedNanos, + AtomicBoolean respond, + AtomicReference serverFailure, + CountDownLatch measuredSecondInvocationEntered) + throws Exception { UUID reservationId = UUID.randomUUID(); var service = new AccountServiceGrpc.AccountServiceImplBase() { @@ -560,7 +596,10 @@ public void commitTenantCapacityAdmission( observedNanos.set( Objects.requireNonNull(Context.current().getDeadline()) .timeRemaining(TimeUnit.NANOSECONDS)); - calls.incrementAndGet(); + int invocation = calls.incrementAndGet(); + if (invocation == 2 && measuredSecondInvocationEntered != null) { + measuredSecondInvocationEntered.countDown(); + } if (!respond.get()) return; assertServerSide( serverFailure, From 7af9b836e3f47e0f2fb60446cfff57a23b7182fe Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 14:35:06 +1300 Subject: [PATCH 32/96] Settle retained FireMUD #3451 review findings --- .../workflows/publish-pr-runtime-images.yml | 273 ++++++++++---- .github/workflows/runtime-images.yml | 192 ++++++---- .github/workflows/smoke.yml | 151 +++++++- .../account-service/api-contracts.md | 2 + .../game-session-service/runtime-and-data.md | 2 +- ...rusted-runtime-workflow-definitions.tar.xz | Bin 19644 -> 0 bytes .../trusted-runtime-workflow-definitions.txt | 345 ++++++++++++++++++ .../pr-required-gate-context-contract.sh | 241 +++++++++--- .../tests/pr-retarget-workflow-contract.sh | 190 ++++++++-- .../pr-runtime-image-publication-contract.sh | 264 +++++++++++++- ...acityMigrationPostgresIntegrationTest.java | 264 +++++++++++++- ...stractReloadingBlockingGrpcClientTest.java | 2 +- 12 files changed, 1686 insertions(+), 240 deletions(-) delete mode 100644 dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.tar.xz create mode 100644 dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.txt diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 24a7fe178b..092e427b9e 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -14,7 +14,7 @@ permissions: {} jobs: reconcile-failed-pr-runtime: name: Reconcile Failed Original PR Runtime - if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && (((github.event.workflow_run.path == '.github/workflows/runtime-images.yml' || startsWith(github.event.workflow_run.path, '.github/workflows/runtime-images.yml@refs/')) && contains(fromJSON('["failure","cancelled","timed_out"]'), github.event.workflow_run.conclusion)) || ((github.event.workflow_run.path == '.github/workflows/ci.yml' || startsWith(github.event.workflow_run.path, '.github/workflows/ci.yml@refs/')) && github.event.workflow_run.conclusion == 'cancelled')) && github.event.workflow_run.head_repository.full_name == github.repository }} + if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && (((github.event.workflow_run.path == '.github/workflows/runtime-images.yml' || startsWith(github.event.workflow_run.path, '.github/workflows/runtime-images.yml@')) && contains(fromJSON('["failure","cancelled","timed_out"]'), github.event.workflow_run.conclusion)) || ((github.event.workflow_run.path == '.github/workflows/ci.yml' || startsWith(github.event.workflow_run.path, '.github/workflows/ci.yml@')) && github.event.workflow_run.conclusion == 'cancelled')) && github.event.workflow_run.head_repository.full_name == github.repository }} runs-on: ubuntu-latest timeout-minutes: 5 concurrency: @@ -34,6 +34,23 @@ jobs: with: script: | const repository = `${context.repo.owner}/${context.repo.repo}`; + const prePostDeadline = Date.now() + 2 * 60 * 1000; + const withRequestDeadline = (options, deadline, phase) => { + const remainingMs = deadline - Date.now(); + if (remainingMs <= 0) { + const error = new Error(`${phase} deadline reached; request not issued`); + error.code = "REQUEST_DEADLINE_EXPIRED"; + throw error; + } + return { + ...options, + request: { + ...options.request, + signal: AbortSignal.timeout(remainingMs), + }, + }; + }; + const prePostOptions = options => withRequestDeadline(options, prePostDeadline, "Pre-dispatch"); const callback = context.payload.workflow_run; let event = callback; const positive = value => Number.isSafeInteger(value) && value > 0; @@ -43,23 +60,38 @@ jobs: event.status !== "completed" || !["failure", "cancelled", "timed_out"].includes(event.conclusion) || event.repository?.full_name !== repository || event.head_repository?.full_name !== repository || !positive(event.id) || !positive(event.run_attempt)) return; - const {data: workflow} = await github.rest.actions.getWorkflow({...context.repo, workflow_id: "runtime-images.yml"}); + const {data: workflow} = await github.rest.actions.getWorkflow(prePostOptions({...context.repo, workflow_id: "runtime-images.yml"})); if (!positive(workflow.id) || workflow.path !== ".github/workflows/runtime-images.yml" || workflow.name !== "Build Runtime Images") throw new Error("Untrusted runtime workflow identity"); - const matchesPath = (path, expected) => path === expected || - (typeof path === "string" && path.startsWith(`${expected}@refs/`) && - !/[\s~^:?*[\\]/.test(path.slice(expected.length + 1)) && !path.includes("..") && !path.includes("@{")); + const validWorkflowRef = ref => { + if (typeof ref !== "string" || ref.length === 0 || ref === "@" || + ref.includes("..") || ref.includes("@{") || ref.includes("//") || + ref.startsWith("/") || ref.endsWith("/") || ref.endsWith(".")) return false; + const forbidden = new Set(["~", "^", ":", "?", "*", "[", "\\"]); + if ([...ref].some(character => { + const code = character.charCodeAt(0); + return code <= 32 || code === 127 || forbidden.has(character); + })) return false; + return ref.split("/").every(part => part.length > 0 && !part.startsWith(".") && + !part.endsWith(".") && !part.endsWith(".lock")); + }; + const matchesPath = (path, expected) => { + if (path === expected) return true; + const prefix = `${expected}@`; + return typeof path === "string" && path.startsWith(prefix) && + validWorkflowRef(path.slice(prefix.length)); + }; const trusted = run => run?.workflow_id === workflow.id && matchesPath(run.path, workflow.path) && run.repository?.full_name === repository && run.head_repository?.full_name === repository && [workflow.name, run.display_title].includes(run.name) && positive(run.id) && positive(run.run_attempt); // Inventory incompleteness is unknown, never permission to dispatch duplicates. - const inventory = async (workflowId, filter) => { + const inventory = async (workflowId, filter, deadline = prePostDeadline, phase = "Pre-dispatch") => { const runs = [], ids = new Set(); let total; for (let page = 1; page <= 10; page++) { - const {data} = await github.rest.actions.listWorkflowRuns({ + const {data} = await github.rest.actions.listWorkflowRuns(withRequestDeadline({ ...context.repo, workflow_id: workflowId, per_page: 100, page, ...filter, - }); + }, deadline, phase)); total ??= data?.total_count; if (!Number.isInteger(total) || total < 0 || total >= 1000 || data?.total_count !== total || !Array.isArray(data.workflow_runs) || data.workflow_runs.length !== Math.min(100, total - runs.length)) { @@ -82,7 +114,7 @@ jobs: if (callback.conclusion !== "cancelled" || callback.head_sha !== wakeHead || typeof callback.head_branch !== "string" || !callback.head_branch || !positive(Number(wakeNumber))) return; - ({data: ciWorkflow} = await github.rest.actions.getWorkflow({...context.repo, workflow_id: "ci.yml"})); + ({data: ciWorkflow} = await github.rest.actions.getWorkflow(prePostOptions({...context.repo, workflow_id: "ci.yml"}))); if (!positive(ciWorkflow.id) || ciWorkflow.path !== ".github/workflows/ci.yml" || ciWorkflow.name !== "CI — Validation") throw new Error("Untrusted CI workflow identity"); const matchesWake = run => run?.id === callback.id && run.run_attempt === callback.run_attempt && @@ -90,16 +122,17 @@ jobs: run.event === "pull_request" && run.status === "completed" && run.conclusion === "cancelled" && run.repository?.full_name === repository && run.head_repository?.full_name === repository && run.head_sha === wakeHead && run.head_branch === callback.head_branch && - run.display_title === callback.display_title && [ciWorkflow.name, callback.display_title].includes(run.name); + run.display_title === callback.display_title && run.path === callback.path && + [ciWorkflow.name, callback.display_title].includes(run.name); if (!matchesWake(callback)) return; wakeCurrent = async () => { - const {data: current} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: callback.id}); + const {data: current} = await github.rest.actions.getWorkflowRun(prePostOptions({...context.repo, run_id: callback.id})); return matchesWake(current); }; if (!await wakeCurrent()) return; let pr; for (let attempt = 0; attempt < 6; attempt++) { - ({data: pr} = await github.rest.pulls.get({...context.repo, pull_number: Number(wakeNumber)})); + ({data: pr} = await github.rest.pulls.get(prePostOptions({...context.repo, pull_number: Number(wakeNumber)}))); if (pr.state !== "open" || pr.head?.sha !== wakeHead || pr.mergeable !== null || attempt === 5) break; await new Promise(resolve => setTimeout(resolve, 2000)); @@ -118,16 +151,17 @@ jobs: if (!match) return; const [ , number, base, head, merge] = match; const sourceCurrent = async () => { - const {data: run} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: event.id}); + const {data: run} = await github.rest.actions.getWorkflowRun(prePostOptions({...context.repo, run_id: event.id})); return trusted(run) && run.id === event.id && run.run_attempt === event.run_attempt && run.event === "pull_request" && run.status === "completed" && run.conclusion === event.conclusion && - run.head_sha === head && run.display_title === event.display_title && run.head_branch === event.head_branch; + run.head_sha === head && run.display_title === event.display_title && run.head_branch === event.head_branch && + run.path === event.path; }; if (!await sourceCurrent()) return; const currentTuple = async () => { let pr; for (let attempt = 0; attempt < 6; attempt++) { - ({data: pr} = await github.rest.pulls.get({...context.repo, pull_number: Number(number)})); + ({data: pr} = await github.rest.pulls.get(prePostOptions({...context.repo, pull_number: Number(number)}))); if (pr.state !== "open" || pr.head?.sha !== head || pr.mergeable !== null || attempt === 5) break; await new Promise(resolve => setTimeout(resolve, 2000)); @@ -135,8 +169,8 @@ jobs: if (pr.state !== "open" || pr.head?.repo?.full_name !== repository || pr.base?.repo?.full_name !== repository || pr.head?.sha !== head || pr.head?.ref !== event.head_branch || typeof pr.base?.ref !== "string" || !pr.base.ref || pr.mergeable !== true || pr.merge_commit_sha !== merge) return null; - const {data: ref} = await github.rest.git.getRef({...context.repo, ref: `heads/${pr.base.ref}`}); - const {data: commit} = await github.rest.repos.getCommit({...context.repo, ref: merge}); + const {data: ref} = await github.rest.git.getRef(prePostOptions({...context.repo, ref: `heads/${pr.base.ref}`})); + const {data: commit} = await github.rest.repos.getCommit(prePostOptions({...context.repo, ref: merge})); if (ref.ref !== `refs/heads/${pr.base.ref}` || ref.object?.sha !== base || commit.sha !== merge || commit.parents?.length !== 2 || commit.parents[0]?.sha !== base || commit.parents[1]?.sha !== head) return null; return pr.base.ref; @@ -148,18 +182,20 @@ jobs: return runs.some(run => run.display_title === event.display_title && run.id > event.id); }; if (await originalSuperseded()) return; - if (!ciWorkflow) ({data: ciWorkflow} = await github.rest.actions.getWorkflow({...context.repo, workflow_id: "ci.yml"})); + if (!ciWorkflow) ({data: ciWorkflow} = await github.rest.actions.getWorkflow(prePostOptions({...context.repo, workflow_id: "ci.yml"}))); if (!positive(ciWorkflow.id) || ciWorkflow.path !== ".github/workflows/ci.yml" || ciWorkflow.name !== "CI — Validation") { throw new Error("Untrusted CI workflow identity"); } const ciTitle = `CI — Validation pr-${number} base-${base} head-${head}`; let ci; - const matchesCi = run => run && run.id === ci?.id && run.run_attempt === ci?.run_attempt && positive(run.run_attempt) && + const matchesCiIdentity = (run, expected) => run && run.id === expected?.id && + run.run_attempt === expected?.run_attempt && positive(run.run_attempt) && run.workflow_id === ciWorkflow.id && matchesPath(run.path, ciWorkflow.path) && - run.event === "pull_request" && run.status === "completed" && + run.event === "pull_request" && run.repository?.full_name === repository && run.head_repository?.full_name === repository && run.head_sha === head && run.head_branch === event.head_branch && run.display_title === ciTitle && [ciWorkflow.name, ciTitle].includes(run.name); + const matchesCi = run => matchesCiIdentity(run, ci) && run.status === "completed"; const selectCi = async () => { ci = null; const ciRuns = (await inventory("ci.yml", {event: "pull_request", head_sha: head})) @@ -169,12 +205,34 @@ jobs: // Metadata-only completions cannot conceal an earlier substantive attempt for this exact tuple. for (const candidate of ciRuns) { ci = candidate; - if (!positive(ci.id) || !matchesCi(ci)) return null; // Unfinished/new unclassified CI owns its later callback. - const {data: ciNative} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); - if (!matchesCi(ciNative)) return null; - const jobs = await github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", - {...context.repo, run_id: ci.id, attempt_number: ci.run_attempt, per_page: 100}); - if (!Array.isArray(jobs) || jobs.some(job => !job || typeof job.name !== "string" || !job.name.trim())) return null; + if (!positive(ci.id) || !positive(ci.run_attempt) || !matchesCiIdentity(ci, candidate)) return null; + let skippedCandidate = false; + for (let classificationAttempt = 1; classificationAttempt <= 3; classificationAttempt++) { + const {data: ciNative} = await github.rest.actions.getWorkflowRun( + prePostOptions({...context.repo, run_id: candidate.id}) + ); + if (!matchesCiIdentity(ciNative, candidate)) return null; + if (ciNative.status !== "completed" || typeof ciNative.conclusion !== "string" || !ciNative.conclusion) { + if (classificationAttempt < 3) { + await new Promise(resolve => setTimeout(resolve, 2000)); + continue; + } + return null; + } + ci = ciNative; + const jobs = await github.paginate( + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + prePostOptions({...context.repo, run_id: ci.id, attempt_number: ci.run_attempt, per_page: 100}) + ); + const retryClassification = async () => { + if (classificationAttempt >= 3) return false; + await new Promise(resolve => setTimeout(resolve, 2000)); + return true; + }; + if (!Array.isArray(jobs) || jobs.some(job => !job || typeof job.name !== "string" || !job.name.trim())) { + if (await retryClassification()) continue; + return null; + } const metadataName = "PR Metadata Edit (Validation Gate)"; const metadataExpression = "github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Validation Gate)' || 'Validation Gate'"; const normalizedName = name => { @@ -192,17 +250,25 @@ jobs: typeof job.check_run_url === "string" && job.check_run_url.startsWith(checkPrefix) && /^[1-9][0-9]*$/.test(job.check_run_url.slice(checkPrefix.length)); const gates = jobs.filter(job => job.name === "Validation Gate"); - if (metadata.length) { - // Only one positively skipped native metadata job can be ignored. - // Unknown/mixed identities must never reveal an older CI result. - if (metadata.length !== 1 || jobs.length !== 1 || gates.length || !nativeJob(metadata[0]) || - metadata[0].conclusion !== "skipped") return null; - const {data: latestMetadata} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); - if (!matchesCi(latestMetadata) || latestMetadata.conclusion !== ci.conclusion || - ciNative.conclusion !== ci.conclusion) return null; - ci = null; - continue; - } + if (metadata.length) { + // Only one positively skipped native metadata job can be ignored. + // Unknown/mixed identities must never reveal an older CI result. + if (metadata.length !== 1 || jobs.length !== 1 || gates.length || !nativeJob(metadata[0]) || + metadata[0].conclusion !== "skipped") { + if (await retryClassification()) continue; + return null; + } + const {data: latestMetadata} = await github.rest.actions.getWorkflowRun( + prePostOptions({...context.repo, run_id: ci.id}) + ); + if (!matchesCi(latestMetadata) || latestMetadata.conclusion !== ci.conclusion) { + if (await retryClassification()) continue; + return null; + } + ci = null; + skippedCandidate = true; + break; + } const gate = gates.length === 1 ? gates[0] : null; const preservation = gate?.steps?.filter(step => step.name === "Preserve successful required gate on metadata-only edit") || []; const enforcement = gate?.steps?.filter(step => step.name === "Enforce validation success") || []; @@ -219,28 +285,49 @@ jobs: // inventory without failures or unexplained work may reveal older proof. const seenJobIds = new Set(); const seenChecks = new Set(); + let coherentCancellation = true; for (const job of jobs) { if (!nativeJob(job) || seenJobIds.has(job.id) || seenChecks.has(job.check_run_url) || - !["success", "skipped", "cancelled"].includes(job.conclusion) || !Array.isArray(job.steps)) return null; + !["success", "skipped", "cancelled"].includes(job.conclusion) || !Array.isArray(job.steps)) { + coherentCancellation = false; + break; + } seenJobIds.add(job.id); seenChecks.add(job.check_run_url); for (const step of job.steps) { if (!step || typeof step.name !== "string" || !step.name.trim() || step.status !== "completed" || !["success", "skipped", "cancelled"].includes(step.conclusion) || - (step.conclusion === "cancelled" && step.started_at !== null)) return null; + (step.conclusion === "cancelled" && step.started_at !== null)) { + coherentCancellation = false; + break; + } } + if (!coherentCancellation) break; + } + if (!coherentCancellation) { + if (await retryClassification()) continue; + return null; + } + const {data: latestCancelled} = await github.rest.actions.getWorkflowRun( + prePostOptions({...context.repo, run_id: ci.id}) + ); + if (!matchesCi(latestCancelled) || latestCancelled.conclusion !== "cancelled") { + if (await retryClassification()) continue; + return null; } - const {data: latestCancelled} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); - if (!matchesCi(latestCancelled) || latestCancelled.conclusion !== "cancelled") return null; skippedPreEnforcementCancellation = true; if (validationWake && !skippedExactWake) { if (ci.id !== callback.id || ci.run_attempt !== callback.run_attempt) return null; skippedExactWake = true; } ci = null; - continue; + skippedCandidate = true; + break; + } + if (ci.conclusion === "cancelled" || ciNative.conclusion === "cancelled") { + if (await retryClassification()) continue; + return null; } - if (ci.conclusion === "cancelled" || ciNative.conclusion === "cancelled") return null; if (!gate || !positive(gate.id) || gate.run_id !== ci.id || gate.run_attempt !== ci.run_attempt || gate.head_sha !== head || ![ciWorkflow.name, ciTitle].includes(gate.workflow_name) || gate.status !== "completed" || typeof gate.check_run_url !== "string" || !gate.check_run_url.startsWith(checkPrefix) || @@ -255,33 +342,64 @@ jobs: gate.check_run_url.startsWith(checkPrefix) && /^[1-9][0-9]*$/.test(gate.check_run_url.slice(checkPrefix.length)) && preservation.length === 1 && preservation[0].status === "completed" && preservation[0].conclusion === "success" && enforcement.length === 1 && enforcement[0].status === "completed" && enforcement[0].conclusion === "skipped") { - const {data: latestMetadata} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); - if (!matchesCi(latestMetadata)) return null; + const {data: latestMetadata} = await github.rest.actions.getWorkflowRun( + prePostOptions({...context.repo, run_id: ci.id}) + ); + if (!matchesCi(latestMetadata) || latestMetadata.conclusion !== ci.conclusion) { + if (await retryClassification()) continue; + return null; + } ci = null; - continue; + skippedCandidate = true; + break; } + if (await retryClassification()) continue; return null; } if (skippedPreEnforcementCancellation && (ci.conclusion !== "success" || ciNative.conclusion !== "success" || - gate.conclusion !== "success" || enforcement[0].conclusion !== "success")) return null; + gate.conclusion !== "success" || enforcement[0].conclusion !== "success")) { + if (await retryClassification()) continue; + return null; + } break; + } + if (skippedCandidate) continue; + if (ci) break; } return validationWake && !skippedExactWake ? null : ci; }; ci = await selectCi(); if (!ci) return; - const newerRefresh = async (createdSince = event.created_at) => { - const runs = await inventory("runtime-images.yml", {event: "repository_dispatch", created: `${createdSince}..*`}); + const newerRefresh = async ( + createdSince = event.created_at, + deadline = prePostDeadline, + strictlyAfter = null + ) => { + const phase = deadline === prePostDeadline ? "Pre-dispatch" : "Refresh visibility"; + const runs = await inventory( + "runtime-images.yml", + {event: "repository_dispatch", created: `${createdSince}..*`}, + deadline, + phase + ); const exact = runs.filter(run => run.display_title === event.display_title && run.id > event.id); for (const run of exact) { if (!trusted(run) || run.event !== "repository_dispatch" || run.head_branch !== context.payload.repository.default_branch || !sha(run.head_sha)) { throw new Error("Exact refresh has conflicting native provenance"); } + if (strictlyAfter !== null && + (typeof run.created_at !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(run.created_at) || + !Number.isFinite(Date.parse(run.created_at)))) { + throw new Error("Exact refresh has an invalid creation timestamp"); + } } // Completed refresh also owns this recovery; never retry a refresh from its completion callback. - return exact.length > 0; + // Run timestamps can have second precision, so equality is not post-dispatch visibility proof. + return strictlyAfter === null ? exact.length > 0 : exact.some(run => + Date.parse(run.created_at) > Date.parse(strictlyAfter) + ); }; if (typeof event.created_at !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(event.created_at) || !Number.isFinite(Date.parse(event.created_at))) throw new Error("Invalid original run creation timestamp"); @@ -291,18 +409,29 @@ jobs: const selectedCi = ci; const currentCi = await selectCi(); if (!currentCi || currentCi.id !== selectedCi.id || currentCi.run_attempt !== selectedCi.run_attempt) return; - const {data: finalCi} = await github.rest.actions.getWorkflowRun({...context.repo, run_id: ci.id}); + const {data: finalCi} = await github.rest.actions.getWorkflowRun(prePostOptions({...context.repo, run_id: ci.id})); if (!matchesCi(finalCi) || finalCi.conclusion !== ci.conclusion || !await wakeCurrent() || !await sourceCurrent() || await originalSuperseded() || await currentTuple() !== baseRef) return; // Repeat the complete trusted refresh preflight after all current-source fences. // This is the final read before POST, so a late replacement owns recovery. if (await newerRefresh()) return; - const dispatchStarted = new Date(Date.now() - 1000).toISOString(); + if (Date.now() >= prePostDeadline) { + throw new Error("Pre-dispatch deadline reached; no refresh POST issued and visibility reserve retained"); + } + const dispatchStarted = new Date().toISOString(); let responseUnknown = false; try { - await github.rest.repos.createDispatchEvent({...context.repo, event_type: "pr-runtime-base-refresh", client_payload: { - pr_number: number, base_ref: baseRef, base_sha: base, head_sha: head, merge_sha: merge, - }}); + await github.rest.repos.createDispatchEvent(prePostOptions({ + ...context.repo, + event_type: "pr-runtime-base-refresh", + client_payload: { + pr_number: number, base_ref: baseRef, base_sha: base, head_sha: head, merge_sha: merge, + }, + request: {retries: 0}, + })); } catch (error) { + if (error?.code === "REQUEST_DEADLINE_EXPIRED") { + throw new Error("Pre-dispatch deadline reached; refresh POST was not issued and visibility reserve remains unused"); + } // A documented repository-dispatch 404/422 or authentication 401 is not a lost response. if ([401, 404, 422].includes(error?.status) && error.response?.status === error.status && !error.response.headers?.["retry-after"] && error.response.headers?.["x-ratelimit-remaining"] !== "0") throw error; @@ -313,13 +442,14 @@ jobs: const deadline = Date.now() + 120000; for (;;) { try { - if (await newerRefresh(dispatchStarted)) break; + if (await newerRefresh(dispatchStarted, deadline, dispatchStarted)) break; } catch (error) { const status = error?.status ?? error?.response?.status; const code = error?.code ?? error?.cause?.code; const transient = [408, 425, 429, 500, 502, 503, 504].includes(status) || - (status == null && ["ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", - "ENETUNREACH", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"].includes(code)); + (status == null && (["ABORT_ERR", "ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", + "ENETUNREACH", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"].includes(code) || + ["AbortError", "TimeoutError"].includes(error?.name))); if (!transient) throw error; core.warning("Exact refresh visibility read is temporarily unavailable; keep observing without retrying the POST."); } @@ -334,7 +464,7 @@ jobs: source: name: Resolve Exact Runtime Publication Source - if: ${{ (github.event_name == 'workflow_run' && (github.event.workflow_run.path == '.github/workflows/runtime-images.yml' || startsWith(github.event.workflow_run.path, '.github/workflows/runtime-images.yml@refs/')) && (github.event.workflow_run.event == 'pull_request' || github.event.workflow_run.event == 'repository_dispatch') && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_repository.full_name == github.repository) || (github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-image-publication' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) }} + if: ${{ (github.event_name == 'workflow_run' && (github.event.workflow_run.path == '.github/workflows/runtime-images.yml' || startsWith(github.event.workflow_run.path, '.github/workflows/runtime-images.yml@')) && (github.event.workflow_run.event == 'pull_request' || github.event.workflow_run.event == 'repository_dispatch') && github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_repository.full_name == github.repository) || (github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-image-publication' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -381,12 +511,13 @@ jobs: const prefix = `${workflow.path}@`; if (typeof value !== "string" || value.slice(0, prefix.length) !== prefix) return false; const ref = value.slice(prefix.length); - if (!ref || ref === "@" || ref.endsWith(".") || ref.includes("..") || - ref.includes("@{") || ref.includes("//") || [...ref].some(character => + if (!ref || ref === "@" || ref.startsWith("/") || ref.endsWith("/") || + ref.endsWith(".") || ref.includes("..") || ref.includes("@{") || ref.includes("//") || + [...ref].some(character => character.charCodeAt(0) <= 32 || character.charCodeAt(0) === 127 || "~^:?*[\\".includes(character))) return false; return ref.split("/").every(part => part && part !== "." && part !== ".." && - !part.startsWith(".") && !part.endsWith(".lock")); + !part.startsWith(".") && !part.endsWith(".") && !part.endsWith(".lock")); } const titlePattern = /^Build Runtime Images secure-pr-artifact pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40}) merge-([0-9a-f]{40}) mode-required$/; const deadline = Date.now() + 120000; @@ -408,8 +539,10 @@ jobs: } if (callback) { const event = context.payload.workflow_run; - if (!isTrustedWorkflowPath(event.path)) throw new Error("publication callback path is not trusted"); - for (const field of ["id", "workflow_id", "display_title", "event", "conclusion", "head_branch", "head_sha"]) { + if (!Number.isSafeInteger(event.id) || event.id !== sourceId || + !Number.isSafeInteger(event.run_attempt) || event.run_attempt <= 0 || + !isTrustedWorkflowPath(event.path)) throw new Error("publication callback path or run identity is not trusted"); + for (const field of ["id", "workflow_id", "run_attempt", "path", "display_title", "event", "conclusion", "head_branch", "head_sha"]) { if (run[field] !== event[field]) throw new Error(`source API ${field} differs from callback`); } for (const field of ["repository", "head_repository"]) { @@ -552,15 +685,19 @@ jobs: if not isinstance(value, str) or not value.startswith(prefix): return False ref = value[len(prefix):] - if not ref or ref == "@" or ref.endswith(".") or ".." in ref or "@{" in ref or "//" in ref or any( - ord(character) <= 32 or ord(character) == 127 or - character in "~^:?*[\\" - for character in ref + if ( + not ref or ref == "@" or ref.startswith("/") or ref.endswith("/") or + ref.endswith(".") or ".." in ref or "@{" in ref or "//" in ref or any( + ord(character) <= 32 or ord(character) == 127 or + character in "~^:?*[\\" + for character in ref + ) ): return False return all( part and part not in {".", ".."} and not part.startswith(".") and + not part.endswith(".") and not part.endswith(".lock") for part in ref.split("/") ) diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 713c582795..b6caebff94 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -431,7 +431,7 @@ jobs: concurrency: group: runtime-pr-refresh-dispatch queue: max - if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.status == 'completed' && (github.event.workflow_run.event == 'pull_request' || (github.event.workflow_run.event == 'push' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop'))) && github.event.workflow_run.head_repository.full_name == github.repository }} + if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.status == 'completed' && (github.event.workflow_run.path == '.github/workflows/ci.yml' || startsWith(github.event.workflow_run.path, '.github/workflows/ci.yml@')) && (github.event.workflow_run.event == 'pull_request' || (github.event.workflow_run.event == 'push' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop'))) && github.event.workflow_run.head_repository.full_name == github.repository }} runs-on: ubuntu-latest timeout-minutes: 15 permissions: @@ -451,6 +451,22 @@ jobs: const dispatcherStartedAt = Date.now(); // Reserve the final two minutes for shared visibility and one minute for runner overhead. const fanoutDeadline = dispatcherStartedAt + 12 * 60 * 1000; + const withRequestDeadline = (options, deadline, phase) => { + const remainingMs = deadline - Date.now(); + if (remainingMs <= 0) { + const error = new Error(`${phase} deadline reached; request not issued`); + error.code = "REQUEST_DEADLINE_EXPIRED"; + throw error; + } + return { + ...options, + request: { + ...options.request, + signal: AbortSignal.timeout(remainingMs), + }, + }; + }; + const fanoutOptions = options => withRequestDeadline(options, fanoutDeadline, "Runtime fan-out"); const workflowRun = context.payload.workflow_run; const refreshBranch = workflowRun.head_branch; const refreshSha = workflowRun.head_sha; @@ -501,17 +517,19 @@ jobs: const runtimeRunLookbackMilliseconds = 7 * 24 * 60 * 60 * 1000; const waitForMergeRefresh = async () => { - await new Promise((resolve) => setTimeout(resolve, 2000)); + const remainingMs = fanoutDeadline - Date.now(); + if (remainingMs <= 0) throw new Error("Runtime fan-out deadline reached during merge refresh"); + await new Promise((resolve) => setTimeout(resolve, Math.min(2000, remainingMs))); }; const hasRuntimeChange = async (pullRequest) => { const files = await github.paginate( github.rest.pulls.listFiles, - { + fanoutOptions({ ...context.repo, pull_number: pullRequest.number, per_page: 100, - }, + }), (response) => response.data ); const expectedFileCount = pullRequest.changed_files; @@ -555,10 +573,10 @@ jobs: const resolveExactMerge = async (number, baseBranch = refreshBranch, baseSha = refreshSha, expectedHeadSha = null) => { for (let attempt = 1; attempt <= 5; attempt += 1) { - const response = await github.rest.pulls.get({ + const response = await github.rest.pulls.get(fanoutOptions({ ...context.repo, pull_number: number, - }); + })); const pullRequest = response.data; const currentHeadSha = pullRequest.head?.sha; const currentBaseRef = pullRequest.base?.ref; @@ -606,10 +624,10 @@ jobs: } try { - const commit = await github.rest.repos.getCommit({ + const commit = await github.rest.repos.getCommit(fanoutOptions({ ...context.repo, ref: mergeSha, - }); + })); const parents = commit.data.parents?.map((parent) => parent.sha) || []; if (commit.data.sha !== mergeSha || parents.length !== 2 || @@ -623,6 +641,7 @@ jobs: return null; } } catch (error) { + if (Date.now() >= fanoutDeadline) throw error; if (attempt < 5) { await waitForMergeRefresh(); continue; @@ -649,7 +668,7 @@ jobs: /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(value) && Number.isFinite(Date.parse(value)); - const readInventory = async (createdSince, events = runtimeRunEvents) => { + const readInventory = async (createdSince, events = runtimeRunEvents, deadline = fanoutDeadline, phase = "Runtime fan-out") => { const inventory = []; let complete = true; let incompleteReason = null; @@ -657,10 +676,10 @@ jobs: let total; const eventRuns = [], ids = new Set(); for (let page = 1; page <= 10; page += 1) { - const response = await github.rest.actions.listWorkflowRuns({ + const response = await github.rest.actions.listWorkflowRuns(withRequestDeadline({ ...context.repo, workflow_id: "runtime-images.yml", event, created: `${createdSince}..*`, per_page: runtimeRunPageSize, page, - }); + }, deadline, phase)); const payload = response?.data; total ??= payload?.total_count; if (!Number.isInteger(total) || total < 0 || !Array.isArray(payload?.workflow_runs) || @@ -692,7 +711,7 @@ jobs: const loadExistingRuntimeRuns = async () => { const createdSince = new Date(Date.now() - runtimeRunLookbackMilliseconds).toISOString(); - const initial = await readInventory(createdSince); + const initial = await readInventory(createdSince, runtimeRunEvents, fanoutDeadline, "Runtime fan-out"); if (initial.complete) { return initial; } @@ -716,7 +735,7 @@ jobs: const refinementSince = [...inFlightRuns.map(run => run.created_at), ciCompletedAt] .sort((a, b) => Date.parse(a) - Date.parse(b))[0]; // Refinement can confirm a producer, but cannot prove absence outside its narrower range. - const refined = await readInventory(refinementSince); + const refined = await readInventory(refinementSince, runtimeRunEvents, fanoutDeadline, "Runtime fan-out"); if (!refined.complete) { return { ...refined, @@ -735,26 +754,28 @@ jobs: }; const expectedWorkflowPath = ".github/workflows/runtime-images.yml"; - const workflowPathMatches = (path) => { - if (path === expectedWorkflowPath) { + const validWorkflowRef = ref => { + if (typeof ref !== "string" || ref.length === 0 || ref === "@" || + ref.includes("..") || ref.includes("@{") || ref.includes("//") || + ref.startsWith("/") || ref.endsWith("/") || ref.endsWith(".")) return false; + const forbidden = new Set(["~", "^", ":", "?", "*", "[", "\\"]); + if ([...ref].some(character => { + const code = character.charCodeAt(0); + return code <= 32 || code === 127 || forbidden.has(character); + })) return false; + return ref.split("/").every(part => part.length > 0 && !part.startsWith(".") && + !part.endsWith(".") && !part.endsWith(".lock")); + }; + const workflowPathMatches = (path, expected = expectedWorkflowPath) => { + if (path === expected) { return true; } - const prefix = `${expectedWorkflowPath}@`; + const prefix = `${expected}@`; if (typeof path !== "string" || !path.startsWith(prefix)) { return false; } const ref = path.slice(prefix.length); - if (ref.length === 0 || ref === "@" || ref.endsWith(".") || - /[\u0000-\u0020\u007f]/.test(ref) || - ["~", "^", ":", "?", "*", "[", "\\"].some((character) => ref.includes(character)) || - ref.includes("..") || ref.includes("@{")) { - return false; - } - return ref.split("/").every((part) => - part.length > 0 && part !== "." && part !== ".." && - !part.startsWith(".") && - !part.endsWith(".lock") - ); + return validWorkflowRef(ref); }; const findExactExistingProducer = (tuple, inventory) => { const expectedTitle = @@ -792,8 +813,8 @@ jobs: } } } - ordered.sort((left, right) => right.created_at.localeCompare(left.created_at)); - if (ordered.length > 1 && ordered[0].created_at === ordered[1].created_at) { + ordered.sort((left, right) => Date.parse(right.created_at) - Date.parse(left.created_at)); + if (ordered.length > 1 && Date.parse(ordered[0].created_at) === Date.parse(ordered[1].created_at)) { throw new Error("newest exact runtime producer has an ambiguous created_at timestamp"); } const newest = ordered[0]; @@ -811,7 +832,7 @@ jobs: // A later substantive CI signal may still recover publication from an older producer. const ciCompleted = Date.parse(workflowRun.updated_at || ""); if (newest.event === "repository_dispatch" && Number.isFinite(ciCompleted) && - Date.parse(newest.created_at) >= ciCompleted) return [newest]; + Date.parse(newest.created_at) > ciCompleted) return [newest]; return []; } throw new Error(`run ${newest.id} has an unknown status and cannot be classified`); @@ -841,18 +862,17 @@ jobs: run.head_branch === refreshBranch && run.head_sha === refreshSha && run.display_title === workflowRun.display_title && [ciName, workflowRun.display_title].includes(run.name) && - (run.path === ciPath || (typeof run.path === "string" && - run.path.startsWith(`${ciPath}@`) && run.path.length > ciPath.length + 1)); + workflowPathMatches(run.path, ciPath) && run.path === workflowRun.path; if (!titleMatch || titleMatch[3] !== refreshSha) { core.warning("Skipping PR runtime reconciliation: callback lacks exact CI PR/base/head title metadata."); return; } - const {data: ciWorkflow} = await github.rest.actions.getWorkflow({ + const {data: ciWorkflow} = await github.rest.actions.getWorkflow(fanoutOptions({ ...context.repo, workflow_id: "ci.yml", - }); - const {data: source} = await github.rest.actions.getWorkflowRun({ + })); + const {data: source} = await github.rest.actions.getWorkflowRun(fanoutOptions({ ...context.repo, run_id: workflowRun.id, - }); + })); if (ciWorkflow.id !== workflowRun.workflow_id || ciWorkflow.path !== ciPath || ciWorkflow.name !== ciName || !matchesSource(source)) { core.warning("Skipping PR runtime reconciliation: current CI workflow/run identity differs from callback."); @@ -860,7 +880,7 @@ jobs: } const jobs = await github.paginate( "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", - {...context.repo, run_id: source.id, attempt_number: source.run_attempt, per_page: 100} + fanoutOptions({...context.repo, run_id: source.id, attempt_number: source.run_attempt, per_page: 100}) ); const gates = jobs.filter((job) => job.name === "Validation Gate"); const gate = gates.length === 1 ? gates[0] : null; @@ -879,9 +899,9 @@ jobs: core.info("Skipping PR runtime reconciliation: exact CI attempt is metadata-only or lacks substantive native gate evidence."); return; } - const {data: latest} = await github.rest.actions.getWorkflowRun({ + const {data: latest} = await github.rest.actions.getWorkflowRun(fanoutOptions({ ...context.repo, run_id: source.id, - }); + })); if (!matchesSource(latest)) { core.warning("Skipping PR runtime reconciliation: CI attempt was superseded during classification."); return; @@ -890,10 +910,10 @@ jobs: } let currentBranch; try { - currentBranch = await github.rest.git.getRef({ + currentBranch = await github.rest.git.getRef(fanoutOptions({ ...context.repo, ref: `heads/${refreshBranch}`, - }); + })); } catch (error) { if (error.status !== 404) throw error; core.info(`Skipping obsolete CI callback: branch ${refreshBranch} no longer exists.`); @@ -910,12 +930,12 @@ jobs: ["main", "develop"].includes(refreshBranch); const pullRequests = protectedPrHead ? [] : await github.paginate( github.rest.pulls.list, - { + fanoutOptions({ ...context.repo, state: "open", base: refreshBranch, per_page: 100, - }, + }), (response) => response.data ); const refreshTargets = []; @@ -936,12 +956,12 @@ jobs: // is only a reconcile signal: re-read its source's current exact tuple. const sourcePullRequests = await github.paginate( github.rest.pulls.list, - { + fanoutOptions({ ...context.repo, state: "open", head: `${context.repo.owner}:${refreshBranch}`, per_page: 100, - }, + }), (response) => response.data ); for (const source of sourcePullRequests) { @@ -954,10 +974,10 @@ jobs: source.base.ref.length === 0) { continue; } - const sourceBase = await github.rest.git.getRef({ + const sourceBase = await github.rest.git.getRef(fanoutOptions({ ...context.repo, ref: `heads/${source.base.ref}`, - }); + })); const sourceBaseSha = sourceBase.data.object?.sha; if (!shaPattern.test(sourceBaseSha || "")) { core.warning(`Skipping source PR #${source.number}: current base ref SHA is invalid.`); @@ -992,6 +1012,10 @@ jobs: try { runtimeChanges = await hasRuntimeChange(pullRequest); } catch (error) { + if (Date.now() >= fanoutDeadline) { + reportFanoutCutoff(targetIndex, "during changed-file proof"); + break; + } core.setFailed(`Cannot verify runtime changed files for PR #${tuple.prNumber}; no dispatch issued: ${error.message || error}`); } runtimeRefresh: if (runtimeChanges) { @@ -1024,6 +1048,10 @@ jobs: } } if (fallbackReason) { + if (Date.now() >= fanoutDeadline) { + reportFanoutCutoff(targetIndex, "during runtime inventory"); + break; + } core.setFailed(`Cannot verify exact runtime producer inventory for PR #${tuple.prNumber}; no dispatch issued: ${fallbackReason}`); runtimeInventoryPromise = undefined; runtimeInventoryError = null; @@ -1041,6 +1069,10 @@ jobs: try { current = await resolveExactMerge(tuple.prNumber, tuple.baseRef, tuple.baseSha, tuple.headSha); } catch (error) { + if (Date.now() >= fanoutDeadline) { + reportFanoutCutoff(targetIndex, "during runtime tuple proof"); + break; + } core.setFailed(`Cannot verify runtime tuple for PR #${tuple.prNumber}; no dispatch issued: ${error.message || error}`); break runtimeRefresh; } @@ -1050,8 +1082,14 @@ jobs: } let currentBase; try { - ({data: currentBase} = await github.rest.git.getRef({...context.repo, ref: `heads/${tuple.baseRef}`})); + ({data: currentBase} = await github.rest.git.getRef(fanoutOptions({ + ...context.repo, ref: `heads/${tuple.baseRef}`, + }))); } catch (error) { + if (Date.now() >= fanoutDeadline) { + reportFanoutCutoff(targetIndex, "during runtime base proof"); + break; + } core.setFailed(`Cannot read current base for PR #${tuple.prNumber}: ${error.message || error}`); break runtimeRefresh; } @@ -1064,12 +1102,12 @@ jobs: break; } const previousIds = new Set(inventory?.runs?.map(run => run.id) || []); - const dispatchSince = new Date(Date.now() - 1000).toISOString(); + const dispatchSince = new Date().toISOString(); const pending = {tuple, previousIds, dispatchSince, responseUnknown: false}; visibilitySince ??= dispatchSince; pendingVisibility.push(pending); try { - await github.rest.repos.createDispatchEvent({ + await github.rest.repos.createDispatchEvent(fanoutOptions({ ...context.repo, event_type: "pr-runtime-base-refresh", client_payload: { @@ -1079,10 +1117,17 @@ jobs: head_sha: tuple.headSha, merge_sha: tuple.mergeSha, }, - }); + request: {retries: 0}, + })); } catch (error) { // Repository dispatch documents 404 and 422 as rejected requests; 401 is invalid authentication. // A transport error or retryable response is not proof of rejection. + if (error?.code === "REQUEST_DEADLINE_EXPIRED") { + pendingVisibility.pop(); + if (!pendingVisibility.length) visibilitySince = undefined; + core.setFailed(`Runtime refresh POST cutoff for PR #${tuple.prNumber}; request was not issued.`); + break runtimeRefresh; + } if ([401, 404, 422].includes(error?.status) && error.response?.status === error.status && !error.response.headers?.["retry-after"] && error.response.headers?.["x-ratelimit-remaining"] !== "0") { pendingVisibility.pop(); @@ -1105,6 +1150,10 @@ jobs: try { previewCurrent = await resolveExactMerge(tuple.prNumber, tuple.baseRef, tuple.baseSha, tuple.headSha); } catch (error) { + if (Date.now() >= fanoutDeadline) { + reportFanoutCutoff(targetIndex, "during preview tuple proof"); + break; + } core.setFailed(`Cannot verify preview tuple for PR #${tuple.prNumber}; no dispatch issued: ${error.message || error}`); continue; } @@ -1119,7 +1168,7 @@ jobs: } core.info(`Dispatching preview deploy reconciliation for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); try { - await github.rest.repos.createDispatchEvent({ + await github.rest.repos.createDispatchEvent(fanoutOptions({ ...context.repo, event_type: "preview-deploy", client_payload: { @@ -1131,8 +1180,13 @@ jobs: merge_sha: tuple.mergeSha, preview_domain: "preview.firedevops.net", }, - }); + request: {retries: 0}, + })); } catch (error) { + if (error?.code === "REQUEST_DEADLINE_EXPIRED") { + core.setFailed(`Preview handoff cutoff for PR #${tuple.prNumber}; request was not issued.`); + continue; + } core.setFailed(`Preview reconciliation handoff for PR #${tuple.prNumber} is uncertain; no retry issued: ${error.message || error}`); } } @@ -1148,9 +1202,9 @@ jobs: typeof defaultBranch !== "string" || !defaultBranch) { throw new Error("Repository identity or default branch is unavailable"); } - const {data: workflow} = await github.rest.actions.getWorkflow({ + const {data: workflow} = await github.rest.actions.getWorkflow(withRequestDeadline({ ...context.repo, workflow_id: "runtime-images.yml", - }); + }, visibilityDeadline, "Runtime visibility observation")); if (!Number.isSafeInteger(workflow?.id) || workflow.id <= 0 || workflow.path !== expectedWorkflowPath || workflow.name !== "Build Runtime Images") { throw new Error("Current runtime workflow identity is not trusted"); @@ -1161,15 +1215,26 @@ jobs: } } while (pendingVisibility.length > 0 && runtimeWorkflow) { + if (Date.now() >= visibilityDeadline) { + const dispatchState = pendingVisibility.some(item => item.responseUnknown) ? "attempted" : "accepted"; + core.setFailed(`Refresh dispatch ${dispatchState} but visibility is unknown for PRs ${pendingVisibility.map(item => item.tuple.prNumber).join(", ")}; no retry issued`); + break; + } try { - const observed = await readInventory(visibilitySince, ["repository_dispatch"]); + const observed = await readInventory( + visibilitySince, + ["repository_dispatch"], + visibilityDeadline, + "Runtime visibility observation" + ); if (!observed.complete) throw new Error("Accepted refresh has incomplete visibility; no retry issued"); for (let index = pendingVisibility.length - 1; index >= 0; index--) { const {tuple, previousIds, dispatchSince, responseUnknown} = pendingVisibility[index]; const exactTitle = `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; + // Equal second-granularity timestamps cannot prove the run followed this POST. const freshExactRuns = observed.runs.filter(run => run.event === "repository_dispatch" && run.display_title === exactTitle && !previousIds.has(run.id) && - validTimestamp(run.created_at) && Date.parse(run.created_at) >= Date.parse(dispatchSince)); + validTimestamp(run.created_at) && Date.parse(run.created_at) > Date.parse(dispatchSince)); for (const run of freshExactRuns) { if (!Number.isSafeInteger(run.id) || run.id <= 0 || run.workflow_id !== runtimeWorkflow.id || !workflowPathMatches(run.path) || @@ -1190,8 +1255,9 @@ jobs: const status = error?.status ?? error?.response?.status; const code = error?.code ?? error?.cause?.code; const transient = [408, 425, 429, 500, 502, 503, 504].includes(status) || - (status == null && ["ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", - "ENETUNREACH", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"].includes(code)); + (status == null && (["ABORT_ERR", "ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", + "ENETUNREACH", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"].includes(code) || + ["AbortError", "TimeoutError"].includes(error?.name))); if (!transient) { core.setFailed(`Runtime refresh visibility is uncertain; no retry issued: ${error.message || error}`); break; @@ -1199,12 +1265,8 @@ jobs: core.warning("Runtime refresh visibility read is temporarily unavailable; keep observing without retrying any POST."); } if (pendingVisibility.length === 0) break; - if (Date.now() >= visibilityDeadline) { - const dispatchState = pendingVisibility.some(item => item.responseUnknown) ? "attempted" : "accepted"; - core.setFailed(`Refresh dispatch ${dispatchState} but visibility is unknown for PRs ${pendingVisibility.map(item => item.tuple.prNumber).join(", ")}; no retry issued`); - break; - } - await new Promise(resolve => setTimeout(resolve, Math.min(5000, visibilityDeadline - Date.now()))); + const remaining = visibilityDeadline - Date.now(); + if (remaining > 0) await new Promise(resolve => setTimeout(resolve, Math.min(5000, remaining))); } build-base-image: diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 438312c36f..a01ec45799 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -569,12 +569,33 @@ jobs: const refreshDiscoveryTimeoutMs = prerequisiteAndQueueAllowanceMinutes * 60 * 1000; const completedSnapshotTimeoutMs = 8 * snapshotSleepMs; const pullRequestCheckInterval = 2; - const retryableStatuses = new Set([408, 425, 429, 500, 502, 503, 504]); + const retryableStatuses = new Set([408, 425, 429]); + const transientTransportCodes = new Set([ + "ECONNABORTED", "ECONNREFUSED", "ECONNRESET", "EAI_AGAIN", "EHOSTUNREACH", + "ENETUNREACH", "EPIPE", "ETIMEDOUT", "ERR_SOCKET_TIMEOUT", "UND_ERR_CONNECT_TIMEOUT", + "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_SOCKET", + ]); let pollIteration = 0; let identityDiagnostic = "current PR identity has not been resolved"; class TerminalGitHubRequestError extends Error {} + function isRetryableGitHubStatus(status) { + return retryableStatuses.has(status) || + (Number.isInteger(status) && status >= 500 && status <= 599); + } + + function isTransientGitHubFailure(error) { + if (error instanceof TerminalGitHubRequestError) return false; + const status = error?.status ?? error?.response?.status; + if (status != null) return isRetryableGitHubStatus(status); + let cause = error; + for (let depth = 0; cause && depth < 4; depth += 1, cause = cause.cause) { + if (transientTransportCodes.has(cause.code)) return true; + } + return false; + } + async function withTransientGitHubRetry(label, operation) { const maxAttempts = 4; let retryDelayMs = 1000; @@ -593,7 +614,7 @@ jobs: ? Math.max(1000, resetSeconds * 1000 - Date.now() + 1000) : retryDelayMs; const remainingMs = timeoutMs - (Date.now() - started); - const retryable = quotaExhausted || status == null || retryableStatuses.has(status); + const retryable = quotaExhausted || status == null || isRetryableGitHubStatus(status); if (!retryable || attempt === maxAttempts || delayMs >= remainingMs) { if (status === 403) { throw new TerminalGitHubRequestError(`${label}: ${error.message ?? "GitHub refused the request"}`, { cause: error }); @@ -611,7 +632,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "9d03a4a9085dc310dabb03091dbdc6f027bdecb468e2589f08f546c4cdcaf988"; + const canonicalRuntimeWorkflowSha256 = "71b6f3cf41d6cc5369b84a8ae1c8b026e201709b634ea6ba53aa28a29343c0d8"; // Only authenticated default-branch refreshes may use retained successful definitions. // Keep the pre-rollout default and predecessor definitions for mixed-version runs. const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set([ @@ -735,13 +756,25 @@ jobs: } } + function isRuntimeSourceWorkflowPath(value) { + if (value === workflowPath) return true; + const prefix = workflowPath + "@"; + if (typeof value !== "string" || !value.startsWith(prefix)) return false; + const rawRef = value.slice(prefix.length); + const ref = rawRef.startsWith("refs/heads/") ? rawRef.slice("refs/heads/".length) : rawRef; + return (!rawRef.startsWith("refs/") || rawRef.startsWith("refs/heads/")) && + /^[A-Za-z0-9_][A-Za-z0-9_.\/-]{0,254}$/.test(ref) && + !ref.includes("..") && !ref.endsWith(".") && + ref.split("/").every(part => part && !part.startsWith(".") && !part.endsWith(".lock")); + } + function isSuccessfulRuntimeWorkflowDefinition(definitionHash, sourceEvent) { return definitionHash === canonicalRuntimeWorkflowSha256 || (sourceEvent === "repository_dispatch" && canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256.has(definitionHash)); } - async function verifyCanonicalSmokeProducer(run, candidate, identity) { + async function verifyCanonicalSmokeProducer(run, candidate, identity, requireTerminalSmokeProof = false) { if (!positiveInteger(run.id) || !positiveInteger(run.run_attempt)) return false; const { data: source } = await withTransientGitHubRetry( "exact runtime workflow attempt lookup", @@ -754,7 +787,7 @@ jobs: if ( source.id !== run.id || source.run_attempt !== run.run_attempt || source.status !== "completed" || source.conclusion !== "success" || - source.path !== workflowPath || source.repository?.full_name !== repositoryName || + !isRuntimeSourceWorkflowPath(source.path) || source.repository?.full_name !== repositoryName || !positiveInteger(source.workflow_id) || source.display_title !== expectedTitle || source.event !== run.event || !["pull_request", "repository_dispatch"].includes(source.event) ) return false; @@ -781,11 +814,12 @@ jobs: { owner, repo, run_id: source.id, attempt_number: source.run_attempt, per_page: 100 } ) ); + if (!Array.isArray(jobs)) return false; const producers = jobs.filter((job) => job.name === canonicalSmokeJobName); if (producers.length !== 1) return false; const job = producers[0]; if ( - !positiveInteger(job.id) || job.id !== candidate.id || + !positiveInteger(job.id) || (candidate && job.id !== candidate.id) || job.run_id !== source.id || job.run_attempt !== source.run_attempt || job.head_sha !== source.head_sha || job.status !== "completed" || job.conclusion !== "success" || job.check_run_url !== `https://api.github.com/repos/${repositoryName}/check-runs/${job.id}` @@ -809,6 +843,29 @@ jobs: if (markers.length !== 1 || markers[0].status !== "completed" || markers[0].conclusion !== "skipped") return false; } else if (definitionHash !== canonicalLegacyRuntimeWorkflowSha256) return false; + if (requireTerminalSmokeProof) { + if (source.workflow_id !== run.workflow_id || run.repository?.full_name !== repositoryName || + run.head_sha !== source.head_sha || + run.status !== "completed" || run.conclusion !== "success") return false; + if (markers.length !== 1 || markers[0].status !== "completed" || + markers[0].conclusion !== "skipped") return false; + if (!Array.isArray(job.steps)) return false; + const smokeSteps = job.steps.filter((step) => + step.name === "Run credential-free full-stack smoke" + ); + if (smokeSteps.length > 1 || (smokeSteps.length === 1 && + (smokeSteps[0].status !== "completed" || smokeSteps[0].conclusion !== "success"))) return false; + for (const name of [ + "Stop smoke stack", + "Require successful runtime smoke and authenticated cleanup", + ]) { + const matches = job.steps.filter((step) => step.name === name); + if (matches.length !== 1 || matches[0].status !== "completed" || + matches[0].conclusion !== "success") return false; + } + if (job.steps.some((step) => step.status !== "completed" || + !["success", "skipped"].includes(step.conclusion))) return false; + } const { data: latest } = await withTransientGitHubRetry( "current runtime attempt lookup", () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: source.id }) @@ -833,7 +890,7 @@ jobs: if ( source.id !== run.id || source.run_attempt !== run.run_attempt || source.status !== "completed" || source.conclusion !== run.conclusion || !["success", "failure"].includes(source.conclusion) || - source.path !== workflowPath || source.repository?.full_name !== repositoryName || + !isRuntimeSourceWorkflowPath(source.path) || source.repository?.full_name !== repositoryName || !positiveInteger(source.workflow_id) || source.display_title !== expectedTitle || source.event !== run.event ) return false; @@ -988,8 +1045,7 @@ jobs: latest.status === "completed" && latest.conclusion === run.conclusion; } catch (error) { if (error instanceof TerminalGitHubRequestError) throw error; - const status = error?.status ?? error?.response?.status; - if (status != null && !retryableStatuses.has(status)) throw error; + if (!isTransientGitHubFailure(error)) throw error; core.warning("Final canonical attempt is temporarily unavailable; retaining bounded polling without accepting proof."); return false; } @@ -1022,9 +1078,16 @@ jobs: const candidate = jobs.find((job) => job.name === canonicalSmokeJobName); const proofRun = {id: replacement.id, run_attempt: replacement.run_attempt, conclusion: replacement.conclusion}; + if (replacement.conclusion === "success" && + await verifyCanonicalSmokeProducer(replacement, candidate, identity, true)) { + return {status: "ordinary", run: proofRun}; + } const proof = await verifyKnownPlayFailure(replacement, candidate, identity, true, true); if (proof === "attempt-superseded") return "pending"; - if (proof === "ordinary") return {status: "ordinary", run: proofRun}; + if (proof === "ordinary") { + if (!await verifyCanonicalSmokeProducer(replacement, candidate, identity, true)) return false; + return {status: "ordinary", run: proofRun}; + } if (proof === "snapshot-pending") return {status: "snapshot-pending", run: proofRun}; if (proof === true) return {status: "verified", run: proofRun}; // A new attempt can start between list/proof reads. Invalid current proof @@ -1327,7 +1390,7 @@ jobs: const recoverableCancellation = matching.event === "pull_request" && matching.repository?.full_name === repositoryName && matching.head_repository?.full_name === repositoryName && - matching.path === workflowPath && positiveInteger(matching.workflow_id) && + isRuntimeSourceWorkflowPath(matching.path) && positiveInteger(matching.workflow_id) && positiveInteger(matching.id) && positiveInteger(matching.run_attempt) && matching.head_sha === currentIdentity.headSha && matching.display_title === expectedDisplayTitle && typeof matching.head_branch === "string" && matching.head_branch.length > 0 && @@ -1616,7 +1679,25 @@ jobs: } if (cancelledRecoveryMoved && matching.event === "repository_dispatch") { - const proof = await verifyKnownPlayFailure(matching, null, currentIdentity, true, true); + let proof; + try { + const ordinaryProducerVerified = matching.conclusion === "success" && + await verifyCanonicalSmokeProducer(matching, null, currentIdentity, true); + proof = ordinaryProducerVerified ? "ordinary" : + await verifyKnownPlayFailure(matching, null, currentIdentity, true, true); + if (proof === "ordinary" && !ordinaryProducerVerified && + !await verifyCanonicalSmokeProducer(matching, null, currentIdentity, true)) { + proof = false; + } + } catch (error) { + if (error instanceof TerminalGitHubRequestError) throw error; + if (!isTransientGitHubFailure(error)) throw error; + core.warning( + `Moved cancelled-run smoke proof is temporarily unavailable; retaining bounded polling: ${error.message ?? String(error)}` + ); + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } if (proof === "attempt-superseded") { await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; @@ -1705,7 +1786,8 @@ jobs: return; } const producerJobs = jobs.filter((job) => - job.name === "PR Full-Stack Smoke" || job.name === canonicalSmokeJobName + job.name === canonicalSmokeJobName || + (!typedRuntimeProof && job.name === "PR Full-Stack Smoke") ); if (producerJobs.length > 1) { await failNonTerminalSnapshot("with ambiguous producer jobs"); @@ -1723,11 +1805,29 @@ jobs: (step) => step.name === "Run credential-free full-stack smoke" ) ?? null; if (fullSmokeJob?.status === "completed") { - // Known terminal smoke failure/skipping cannot be replaced by job success. - if (fullSmokeStep?.status === "completed") { + // Typed success is ordinary proof only through the complete canonical producer. + if (typedRuntimeProof && fullSmokeJob.name === canonicalSmokeJobName && + fullSmokeJob.conclusion === "success") { + try { + canonicalProducerVerified = await verifyCanonicalSmokeProducer( + matching, fullSmokeJob, currentIdentity, true + ); + } catch (error) { + if (error instanceof TerminalGitHubRequestError) throw error; + core.warning(`Canonical smoke producer proof is unavailable: ${error.message}`); + } + if (canonicalProducerVerified) break; + const markers = (fullSmokeJob.steps ?? []).filter((step) => + step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" + ); + const markerPending = markers.length === 0 || + (markers.length === 1 && markers[0].status !== "completed"); + if (!markerPending && fullSmokeStep?.status === "completed") break; + } else if (fullSmokeStep?.status === "completed") { + // The native pull_request path keeps its existing step-proof behavior. break; } - if (fullSmokeJob.name === canonicalSmokeJobName && + if (!typedRuntimeProof && fullSmokeJob.name === canonicalSmokeJobName && fullSmokeJob.conclusion === "success") { try { canonicalProducerVerified = await verifyCanonicalSmokeProducer( @@ -1781,7 +1881,14 @@ jobs: continue smokeGatePolling; } if (markerProof === "ordinary") { - canonicalProducerVerified = true; + try { + canonicalProducerVerified = await verifyCanonicalSmokeProducer( + matching, fullSmokeJob, currentIdentity, true + ); + } catch (error) { + if (error instanceof TerminalGitHubRequestError) throw error; + core.warning(`Canonical ordinary smoke proof is unavailable: ${error?.message ?? String(error)}`); + } } if (markerProof === "snapshot-pending") { const snapshotKey = `marker:${matching.id}:${matching.run_attempt}:${identityKey(currentIdentity)}`; @@ -1857,6 +1964,16 @@ jobs: core.setFailed("Runtime smoke proof is missing its unambiguous transition-exception disposition."); return; } + if (typedRuntimeProof && !canonicalProducerVerified) { + if (!await isCurrentCanonicalAttempt(matching)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + core.setFailed( + "Typed ordinary runtime smoke lacks canonical native job, authenticated cleanup, or terminal-guard proof." + ); + return; + } } if (fullSmokeJob?.conclusion !== "success") { diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 55ee2236fc..d7243e2afb 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -236,6 +236,8 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns the typed `TENANT_BILLING_BLOCKED` response. This billing refusal does not consume the quota-refusal budget or create a durable decision receipt; it remains available when no refusal-budget row exists. Fresh creation-eligible evidence with checked insufficient capacity returns the typed `CAPACITY_QUOTA_EXCEEDED` response only after the exact durable `NO_ACCEPT` decision commits. If its refusal budget is missing or exhausted, Account returns non-OK `ENTITLEMENT_UNAVAILABLE` instead; no quota receipt or settlement authority is issued. Each refusal is bound to the exact original attempt, mutation digest, snapshot and evaluation. A quota refusal includes the immutable Account decision UUID only after an exact durable `NO_ACCEPT` commits. A matching exact retry returns the retained receipt. A quota refusal without that receipt grants no evidence settlement authority. The response contains exactly one commitment or one typed refusal. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a changed exact retry. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact attempt-and-fence retries replay; a changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. +Exact replay is guaranteed only for outcomes Account durably retained. A billing or non-creating entitlement refusal that did not retain a decision receipt is not a replayable outcome; a later retry rechecks current evidence freshness before deciding and cannot treat the earlier refusal as a retained result. + The shared [capacity-admission/v1 schema](../../../../services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json) declares the exact ADR 0047 seven-field mapping and bounds. Its `accountEvidence` member is canonical padded base64 of the complete existing Account bundle bytes, validated by the closed variant codec with canonical re-encoding equality before hashing. This binds every evidence field and cutoff/checkpoint byte, not a digest or reconstructed subset. `capacity_delta` is `optional int64`; missing presence is invalid and a present zero remains distinct. The Game Session and World alternatives retain distinct typed contexts. The ordinary registered Account receiver does not expose this private composition, and no route is enabled by adding the proto. - `ExportTenantData` – tenant-wide billing-safe export for one tenant, available to the caller's live `tenantAdmin` membership while gameplay is billing-blocked and limited to tenant-owned exportable records plus minimum stable subject references. The target request is tenant-only. The legacy account-targeted gRPC handler returns `FAILED_PRECONDITION` before parsing selectors or reading Account data because no authorized internal caller is configured; the target tenant-only transport and authorization remain unimplemented. This containment does not change the separately authorized REST/service export path. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 610648fe81..c9024fc349 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -12,7 +12,7 @@ This is a target-only contract, not an enabled or runtime-qualified retirement p The exact current Game Session owner establishes irreversible closure of serving and resume for the admitted binding and retains settlement of applicable effects and indexes. Game Session supplies an authenticated terminal receipt linked to the original admission, FINAL evidence, binding lineage and Account reservation. [Account owns retirement of the corresponding used capacity](../account-service/runtime-and-data.md#finalized-capacity-usage-retirement). Before irreversible closure or settlement can discard the original work state, Game Session must durably retain the exact teardown identity and progress evidence needed for a replacement owner to finish the same terminal receipt. A crash between closure/settlement and receipt retention resumes that original teardown without reopening the binding or inventing a new receipt identity. The terminal receipt remains durable and exactly readable after binding closure and worker replacement. A replacement owner recovers and redelivers that same receipt until Account's exact retirement acknowledgement is known; this recovery never reopens serving or resume. -The target Game Session owner persists the teardown identity and progress in its own PostgreSQL storage, then retains the immutable terminal evidence under that same identity. A replacement worker reads the persisted progress and exact receipt rather than reconstructing either from Redis, an in-memory job or the current binding alone. The receipt binds the original admission, FINAL evidence, binding lineage and exact Account reservation; conflicting identities or stale owner fences must be refused. +The target Game Session owner persists the teardown identity and progress in its own PostgreSQL storage, then retains the immutable terminal evidence under that same identity. A replacement worker reads the persisted progress and exact receipt rather than reconstructing either from Redis, an in-memory job or the current binding alone. The receipt binds the original admission, FINAL evidence, binding lineage and exact Account reservation; conflicting identities or stale owner fences must be refused. After a lost or ambiguous Account response, that retained receipt and its original fence remain historical immutable evidence, not present sender authority: redelivery is performed only by the currently authenticated replacement owner under its current owner authority, without replacing or advancing the original teardown identity or receipt fence. Qualification must prove a restart after irreversible closure or settlement but before the terminal receipt exists, then verify the replacement completes that same teardown from durable progress with serving and resume still closed. Separately prove restart before send, Account commit followed by response loss and worker restart, and exact receipt replay without a second decrement. Account—not Game Session—atomically retains the retirement receipt and decrements used capacity. Wrong identity or fence must fail closed, and no failure or retry may reopen serving or resume. These are acceptance requirements, not claims that the target path or its restart proof exists today. diff --git a/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.tar.xz b/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.tar.xz deleted file mode 100644 index 013546a1ed982248afcc8586f2f2de88e9a67a3a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 19644 zcmV(jK=!}=H+ooF000E$*0e?f03iV!0000G&sfapAOB2wT>u!FNM<8K&2tu3Iggb= z&qcT-I9Z0B2j%BQD&EV9wr_F9H;XHqYWUKHJG1(7Ly@kx3$)=Ys7At%rF{_rXQ@X3 z>nC6C29kyU!2naK>T8ffd`S%+GSW|yBZTMZ*Kxh-tPGFOzrj6eO&s0-jyKU&d#WO7$+zrCS#9d?T z9nsdEw;kJ%-1gc$zeLS`ALGRV-gkHPh?spRtXYGvT>GK0z)=1neP_L|)S>UXdkyH% z{1h1N>h%|alV_q__Eb>I3%pmDtSCRpco$HcTpBKUsH>jv#Uz^K!9Pubzo&dP~7<4++F&m^T6ex!(UfG!)aauX8>~UKInD4l|f>cO$;~aZErU(bXHKK&Vs*$aP zA62r}E%7X33q66I>iQXdB?yG2UYU`JD3kOAQ;9|kp>8qEkRTXRRzJPx3V3!XA_?}T zgK*aG>^+-bqSlw*Pow9KYH{Yt6ux;|ec7;c@u?=xR1 zK5*%;I{y!#=z1a9d{%@FVCZb_5pW~zf?N#(j+GI~;6m`wp7;og*jEh>MJ(nQ!oj)^ z=RAydnvVn-vci;<0r!x4vD9!Hoc}NGco4d&;zMpp1tsy6y>TG!8JNPR0!9ri0ekvGdO9@a~hXV!d0s^nUN@Jtqc?VML4$V5s)A)EiAo4 zaatSmbKG&%esFvMiCLDovYp0V$K-Q}=A}dsgeUVH$9C%jxC-c&J`B!GTe}9)&f8s` zaE)Wa^_#)3(4$6l5r6JZbNRk=(+c;)33x`JZYR-ovr>87ll?N-K=F{|@`+VxAuIa< zM@5&d0FIy1{d-7xYs@2?ykL>2H4-jtj`bmu+K%nKEodtcP0t9Dhh~kvT3O6-hTdZN zo~ldpvqyB*fcG|LwE-Z%PyRd;K_K?@;dN)bJbl5UI{>9u@efybCII2F;eRU*zezom zl!QP=5Do|;cCgkuNt~g@*FCGdtRfZ(FU(hgSZwVykd+2{+E#1`e?JmA`J(&H_ShRC z)YtH1N!;sa1tGVA{8-@h((=LDxzY2=e|A;LI&%h5ifaUfO&TRjp@K($OpdNK`yxxl zv=DKbBNxlWle6HYfE4NvE+9aDj^bsmluX&f>Wu;;HgZXs|5IuIqEET9Mdut+8b+rr z=bg8beCf&1Hs^S9JQ!05)yCD zOB*UiPmR;FBjR409~#r<5a(291WWeJTc%MW&ppiIU`DtcOg7C!YJr#O43_|hMh@AE zgy{_23Fk*yfk@87y{w|$SUJMxkOHCCX}9ja5-|+RqQm`U?7@mbeD@9&Or@*XPlLuU zfYD6VsohVj7*6$&v5BPdYRzV zgcLTuXu)|$!`Ig0Fon&iMk02cA3|e*OzEi=gK29C{Dia|A6q^?AiNk|^s{cVEMw08 zsV)JHOW|s=x>K|(P@(uSjzoUHnh=i?i7(FC?ET2wJyM5`E^phSiV!jPRJ0`1GoJ8q zvKLzCz^z$0Q~-c*#;5)ilDF0(-%0i&@~Xe$3pIG8k|^d<)1zoFuYb@Uf;{&*QEhWh zY{86e&tpF+J z?NF$5jX65f3#e55#2z=~+eS-kFWPB52P&{ztrgOMKJJGb8 zLITS|V9e8NAYOo?V|$CiPHEk2L`PDTDfs!$d4c7n_O+4O2nZQ%hywuA3A73gQklmz zO8&o4pgB+k6y{-|gs4s8@BlQ-Klj?q%3fxDuLsd9<=7!;j+buJYOH1Ovd5yV@~5WO zWKN7HuiRDb`l2%}|J&#skUX`AS&=}1p|}bOsd06Ctg~^j9KS_ObE;pOmhan6XVj&f z!-yzA_;D1=4W}`N2DxQc`hS@TrPLvbZ6Rvm|z zR=J6rP)F}itpfOO*0ynLlL02xufuXxsTfHabBo1#4D0xJi=xAH-168cbs(Rj$Si1khs*?z=95PYqsvb^)NU zDF1Yb-vlSLwB@N$pLPJ-h51>0>Ipvi&K4i66=GiHPcviYBi+*3-r`6{J5IElVD;-Cv{V zjB2(#Nnx29PH-wHjYV0~>eoq&qC1jK26M|b8)Nb2mSwSqQ*0OS@+IIaH`Jm8U!dET zFZyWD_>uv4k0}WPaToDG6+t42@54FXa%2tTVLGUSN~gamI;M96wu!k^I6^9a!x*mN zR6B^#%@=J*rSWWPt+>P21cW;eYwgIG~2@$W5xVyQD=K0pp9H z71*koOc@PQvPc8k>(L8jm2%;sL+9(1G0`dUjl6>Q!nnVOT6!AX--Q0vgcO&mKBG$B z2I4iYQ9U_Y_e;=UM=Y)>#1L>y$jsPWkmjV3o)H0iM`=}$7D&5E$%AHf=YgV@{j{Gq zZja?(g60@?$rIJjbst@9bl3=s$Zkc0u51<0eX#0liTJ}HD+$e48ou~@t1LHMgHmfP zBeu=^suh>vpRCIKUbg)v>j#0Aqp%s&S$FL4K17?<2(b!g`$%Aa+x_fZWL!NGv~5>E zyrpmSuqSug^c*B(C4kH%I@CL%aL_Vody1V`Zm8!X<1ob~aF?D!n5?6xkJaZHS%>;+ zU0dyUiMl@%76N^ujP!P>*TxpI!iUzSAivstV>T%M)I`6(;bnS0QrS~mz2!`ACMl_; z9E{ELnTc$t+9i$Y=Z0@;j!Cb@w+P_g4&LU!P^(izSN>;EA&1rXxXe5#r}!dK!R&vTF?1wsSHMdpuVE9vSvl^8 zZu|?juf3K}+kL31k}+FhcVq07hxiIQ9I(Uel_@-;6@pt-mxdtsEcSuBugHfKumTo0 z>Qte$x@|W3UF1Q1rKOhENFh1`@QRz$(32np!!GJWldNy8j{j9{GU7qR9UDEqxyJKA zpE>OvaTKa2^_C-Qo1X@~IjW@duh|8ct-8hCuVfuhUHS7$xi5UG%(>i^Mfu7wl3XN*ZwGrWLe^H3)x6eN+Jg&kMEGWD53cn~^|ns~4r&G6Q$N zzmJ1}qWc2!cDw@V{9vAz6A1qLKKf^CnNm1RuOe%SG{dhNQ-5v~j6|a%GoR%h$NlGA zX!!cGPfgs^*K0LNaEeGLLRs2+y?KO3=jG}=BsHG4|6M*19tda%jH6x80fhfvBoZSs z+?VEfHNqI%HWiZV(|M0K3aOvGXaa9^qA`6e4U1?f^U6WJM)ifW27wB6rXan0vz}5@ z|7?6+MMj3ixTzmvgrm?MewC{`_<5Udvcpk8&fQPF*DRE8C?g9v^bi6P2&&0DzhV$R zGym=Yh&*aV%3Gry%jMLh0}g>3hN`jO%k*tF63QdVp_Elp=@L5A(VW4pjVICEWCa1g zH{wCg?;nBK=!c;+vp&UiYQ&tXzZd#Dr>eDnCMDfgbLKh@IJI0XkrCojIp#F;rGn4` ztanMqkL;I(uULv|Gsm{;Go{UB^F_bv6EMc>sPosG_NDZ8O5Y!ZEHVMYsxjp_ZZP?b zX{MQ@+lDlE!$2e@z!V@<(w4WRLi&||Nebuf))RK5U%PZq)6D#VDTn5@0+mt|I@+8hH_VW5#3md^rjfwdxeASaWMg)|s1S1Ll$XB64mll~4qaNDG{J4Ip&G8eV zr?<}VsTpq4yYcvBrp?UG>|4ddA&C)4=E23RCr-s*VluS=q&Elx%UPjk$BDIkz&+e=_B(+t6PnoEIB zbs$43z=3CIyOqz8*--s`U3`!05s3m8d<~2kQmf;$b+F0S!BGVKeS+ z?v_CoCfmu|cC}PNA3%o3^jGvcVy66Lrh{ybbA;}0I$qkHMS)qoms^|`22|Ne(a+-1 z#vkyn1qz>`=dc-idv=Yfh0_L>`y}?TPUYxKCvr+(FJY!IYhvUc;^=C86|^q1%gpos zeeOO=a^KQQ(8Kho!19bUrpZp-;0Kr!nbr2boT)!BxM-`xmk%?Grhrhj&fR=I?i0W* z=&k=`26UL~0Zvh#A%sd*{6S~awd=^w6i2c^8*hWoAOKm@x}Wy9v1;p9$n1V`V1Mug zm@L`VuO?bp&qga+XQDnX7zM8V+<_dnodD6jwi;4Muk-g)`p#E12I{0+<_Gvd00p z_kf}&IfFv3)aDX~p@+I>6}&sik*8G{;ze~DpEjwi%aYf~!gzzav;DV-g6I$aI5Erl z$v37{^!jSqs#x?#n*v_uLhma8PEsy=-xC+1d7N5s-tWF&~$7U>kr7+g9^m)+DJheH2qVXy1(V(w2_P6%= zH8#$|i4m4ro{>n*!M$J6$sPC7AhfR62~WM{DwFt*Q)M-LsoEJ09{i%{NP zjvvjyG4T#6dxaa|yXPvHB@@@PKx-^Vr*PRJSsj$)gF2nV><>_x%7P^Mq~Byh1U2_< z_BBGmw-{^OrW~&E0NY`qcS)Iqr0+X*h~Hp<&Jv(VVVvkRCFb`=5C)ooXD_Ikz)pK)KGIT~bq|+J?Zi z@TA%fV%&<-8+WY;tjkBMTuJi^K@L27>QG+QH3aS}Tn|HZLNBoVI!OK(zDFJ)3+V+b zdyqw&QLwyIsZ=t_tb9Q>myB3$9?EL4sG73GR*{pM)o`Pp7^=z60)5)Cn%EaOBhxVH z%G4J8X~`R6#B={;CZuV%#$Wj+K@u2E1IU1)a);)%lDMiGm{>avHe|Q^rgziTN0xHd zS8Vfe`#tKsvC&`^(r3dY<>FaxcC-iMJRhV-uG~#km$LeQ53^KJ=LB!BV;Hbkg+fCp z_^)%h!}Y%#bAK-bo;fF-EZdhYl?IPem*KL#`q~%!yE;Rb3?X@K61ZYu@F0$CJ_}`- z#qTn*x^J~WdM!AL1icc15TE>oFC1YF%IFZ=jrDTWoNdP$@n(=D$BgVI4x_4VNRF_t zVl6jLDfzhzf&DU~n@W9rCQ3MC{J92cN67%Mj}RO1Ejerc)lE@P?+)-(rgSku zlSxv06e8v0^Dp$Q^A-G0WV1BV^g1`78^7^lK-F;_iyRg4x8?EP=zv@-jrKT{{EC(k zw^s5`q0TN*EwfI*rcO1^&KVL*R| z)W~P1|FZjVw_#K(vCwsW*!$WhVR2!T@5FE0<}`5G_O_5s*=KxzPx#i2_BeBix9VPt zON5n3x1Nf0fB!eet?~={!EjwzGX!cWeCU;jtivZqnT81QW}E&MB)>nl>PG6pRk6w< zVNrDCNrvB+^T63>iR)~1A<>{q$(mfLGqWkO5n2*bzgs(DS#l{i837Y*j81pw4LKvh zVU=tLZ}sY^f#-rBMW(&EJT9D_0HUT^;mFTuBl-R8GkbpMwt4t9hg$vZjI`H|Pd;AN zquH|nQo#^5O{=;?G-di*qEeVcSgb0x#tj=c5*nSJEIz#;NAM;dSZmSrq{?F%B_y;} zG<(Q2lH2~fw?zxTe+*Z*;?eC6=$wk?h-C>uYnp^RRWR9q6Q1uBin+ZuRtg5+)~e@6 z=~qv|S8LeWyK>n^txvbCmdnu-oL`jfTZn5KmBdDk_8I+6h|~R^KiBc#yH)SVodAY>R&jHmQ1~V`jJPXxm9Q{~Aj(CKh>ug{yfkt1)DnJBQp+hH zt!NZ}+UQ5LZW3GAQX`|qEc}w}LtD5QnIUDHhBHp#)awD+8tlU+ty`B>dX|Ux=v8nT z(uQMeH~Z+WZfVGl&g;_>Km`$_{zOU7k02vVoG(>CQw|Fz2gI!0zi-Ty$9{N2O%_wc z*lvrG#?Z_UQOPTrFy+in3W=UP=7Vcc&)&4EUuQ7?;uBA5h0^2QF8B8H$d#Ki-u+v8 z$?a#!0^z(%{ti%8ZAJp;%8=cV*wv`B2Lfs3>%6XG%{Ila!!2qd9FHmSD|sntcqx#Q3)w-+^=VFBPB zYg*KMK8w@LK0WGxnW)z0WGrJ{ZuBbKQJ^NCiW`B*p$u@GEckm`@<%m!il8f7Yy4mn{paZZq5T^f`5Jc(K#oa5S{;W%TjWJhpMBPj7Uh3D zvjN^ZSEEvUq$&xFh2NP5Quyl1*3&ueq4s)_e$4OfNm8l+|FN!ASPDdJXTOo# z@d>^mU$=}1odMhz+$A8P55hTlR*k=4rQQC6-OsR55%xZbjjqX+x6x9ue#4||33M{9 zj<6z^A4~@kdhPQ_+8~7cBWIT1i+rMS`T9&ru8?SdnpYd@RBpmmIy)h>DeT`cbAM85 z)%F~_Rr6Nl1ybrj?5sQXl!x;=s>p%ghJc#$1{-hU-=~9){sSN9aNOUMVSyVfYYL~g zsBXd(_d=1|14PP$t-}jXu&`w2=VnJlDgV7-KwzktYAfC^vxNgKcq3T$wkI~ zhHBow3JGM$4dkiaL(vmkBi@xec7Nn1A{Tq6@rQjc5?zw58!NeogQQ{p2 zu#};V6dy>zuXU~685Fb}kgXVjwF;qIgreoxK4ObVF~*+4qx64Df)P;6XZ(a)&UC$< z!o}ANwr^1T#Ee_wo>?Bfb%#0h8ws!)A=|R~vzH`6?F@n%lNBnj*7@G`%o|?8N!xU* z$qs#pQySDak6%W({)G>K@|M6XSLXc2J*=}Hsch1QILx7))0M+NgnQC7Op(SlwsG~s zzg4Tytpo9lj;Dc!1pBe6JqtE-A-5Uuv>z!QL!}0(>-<; zy827on{`VUP*=i>(XyjKR)^F8TitC?aOj;X8~4JQFu6*cjO(sI{SCfRof|G zux^?Kad_!e8O5|AI99>pu$?x7=6_7+w*lhGa!r?_)Gnc$J-sEb|BD4vVKC?_xzI%Z z@#+*xgMG~zlk{5kEz_s7d9xm?Zby`7?(G63YIkbmjEZ&37`7O4>`~e*xmq1v<~1oC z$kZoV>5*O*XR-q~2*T)PxhCsvQ6l|lD0d#ukSpLv3TX?r$c^o_w(i07eH0;Ys!^+t z97e==EqVDee5t{n6M)g&T&LAH2c63ya>(WpoR&bdmi0~|=a5=rSX0W~<%+;w>299h z@1A#GexTc`;h>NS1f>Fq<9q7WuK~Y9SbnewfiZDaJZg{dr=4a37_Q4(+k0&`#OKRH z2^WMI(XPvO1A52;uxM@oSQ_Gx7{w56<$TUo(ehEjkN}p(dg9 zgN7}(4~}S*7f!R(ojrqsbq7KUKq83uhbJsOoHAe}!jYS90C?kkTtU#A7cD6BPtM>m zE+U^WY}%$8m8w-gnEQ>4Gr__5%dj}o-&y3z==(sNdtNhDk&-yeSAHMYzc#QA>lX)?Oj=WWrANI5VE00(0}E|{yR1~ zUK_pf!}7Cy+5YcIqdIE!(8cmXJv;+{dpycCy#DT=NXoL%$<+*k2<@IyCxjZb?GLh^2!c-zB;DmTs^XG zh3}_Y%Vp%yvFyUZO$@@-KJNic7`V(*!-%Z#pW!` z{BrQMOy9uoox$v-0*14Fa^p*TTw z&$%)J>z1}%Ly6Gr`H2lkS>6|npf(le=Ojmgt{Th~Hegpj>+sWPE%LSPVTeq-M{k5x zQ`^Z1?~Vi?h8G$ep}8ab|0rC(c{9A5%Z-e%)@%U}WyS?eBmZ+}XX7`f)6u3RJ)-V*uH8p)2|6&|45+{Ol^socn1MI&9QkT7SsFWxa8@JBvYX z!EeMIYJ!T-GIt{A{bje26E9?3-*o>4vdWE@Xso5d_m=xG;)6}%!2?|s(ZP-PQGRq? zH_W3kApsgwS5F#3cQ6p+peN#RUz~pp0(IL=f`UZdTNf5q7lOAllli&fUEVTpD@a;c z9)Z8PE~?UL$G@VO&Km)d9P&Aj5QSq4@66%^9*ZW&7z0I+QPSyQLd9+;B*5Y~1)@qA zI+?qk-DTEvBGE|C$iaN>R_+o41QhdJV6iTc-YKQk;})^2OO{k`vwHcZ-^O0O2%C7f zxjAKj)EsC}j8I6`L6J$KlO=E2vXTfsJ^IO{OU;PiOZ)q1@!Jy6bqit&hLHE&#c5~$ z_&2S*{G95~hy99}oz2lbDv1(Gz}_9|NHqtPriSCYY)agY=`Lhyax0 z!py`vH-N+cw(sP#)b-90ry36NUkAYp(C?5e{$)+md*omI(5dGfw_uj|H_@#AwvHS zxe>EaZ>|^aEhhl0&@K5mA}(HYiDE*uWIxuPUhRj-TitO8XI~S&st^^SF1XfrGwxQW z#EPN+Mu3CpMb;P)>vdzj1S!8R88>n36M|p0w~pYIchC103XR{OQm4a$nX%?nx(I;Y|y4_`h(_gByDrmIrmJlg|nQ1`jkt=!7hdP}e6<~iKG z;!Fv*Z9#{^P`9>K|60-Eh6)h}dDZVi6|M_ZLmAke6v!`5rSy<~LPYLYe*-%g`U z41IP@+rZ$Fc0^ZjXa*-bJ|*`s6IFK z!{Dv_A0{=#*Z(%P1cK|-FJx_@1GfOD5*G82HH|7Ph?Ktpb0LC?ut$B!9(6;!By_Ff zl1sd$!Omo#P3fErp#U!=(6tQ#8HYXy5#J`(W1l$M_cyaM!^>j{f|IjXgdH(9!u7@$ zuV;#INW~1em}!gnUX#I&A|q!{q41#LL)CMuvX|1-K=onK)mnN>i9m9j?a&`o9OQ@M zY$I2PP`Dj0FrQ9pQ+ZGA9AvcUep0K)L*qN@?;;eS&?y5y05|dgs5Xdp=NUe1^^J9^ zD=;@kUfF9-PR3-7BX7A{zRoXp-D$tx`z~v~f-CHv_U!`}BnsV*vki$&dn^KAiL1_s z-CS~g%i>Qxj!l7~W;x0FYE0ub`7kFKJf-D;(U(*FPREF5fJswjAO+Vzh>)BOH%s&6 z2&BwCD$k+@D+)HH9`)%i*MWzHBF%-q8mI%Nb^Nyq(`-}!DVA`IAv$g;CdQMNJ zB(h;iRXeVgLe5;a&5sT4O4q`MRkCb!$NnzBiKf+|PG30h(|4uEt(9{4wK2+n#|a=x zzDNzoE2g9mfwXuVQ>~eo_qk+M;8~I+=>gpy9tiW^If}$CdX0>a)iZ{eDmJ+2F7h4) zXq>SgQmMSN8Hi!%&-5{FfN{g>^%V{=NcdgMUzthT5bCt6P$Byt^HIhc8L#=67h@&b z_mqLutNbm+~>;|hr$bdcut3mdU2R@_eXQ9_=PuH~Jl+u`xqbduFmj1wrq zu&lnU2QbsG5-MHzTl+|Qba_5{BdUvGoj&!i|3I~;pPoH(_yuCpF=(__HN6%(Tpar& z;cXP=X`+imW5yH;ki5l6(kc0*19@(cRF?-oQ09Li@ps<9dvprq68o2pzscr3BQ&ju zwJjx41V>gs>>DvWe~^a)Sgnfw7Z7nrP?ID%|{s$3ONAkS* zLCM9i#;jcOy~QvW&8fYIu#>JZZrDO5;x<9Cy>$LJw3ih*Axzsn3MEOcqKkR+c~n!O z7khrhkGe!8MY8AfW_rI7F9Q8k3P~m+EAAC}z}WCaNT2=~iT{c63hMmjX`~%mAMmz- z*w{f^nDf&P3S~zT9lkj;U8j`@Fq5BeUbx@l-1|sHjsvs>9#R-=M%3|X8!Q(&azqJB zuKD9M@?^3s=5tU8OAUfwVFv*mi>gYjG>KZY0$X3Ihc6}lYhR4*0Y~KL3mfkfB$g~+ zA{_=WCg=5qDV5Jr%1w`NMsMQGzRU6JRvlN~&YGAO!{VFJW2M(AKJH-cytJyCykClA z`*9C3tT^2uHn2KD>qKK;HS_Dvc$(tJ$~1jiT5-^;H&FcvJ!GH7T@B#z-h&ANCChks z?!~h_%n+Zfh^ZWd2v<9wl*JP)8HeFPqd7#@0+J>NE;lmH(}^))3K~=MmT|N2&lZDD zam7wfkvgmQpdm>h8v_Cu*@r0ewMlEK)kyG2Z7yQa;Vzd2MVG+0&f-a^hG=A7Uk@ft~091E~z< z7`|wrd_Aqau-jA8V2K{9Fc&laynH#8nYm^*=-oY0q-u`8FVLmHbY;JK%I(l}499N@ zC;d<#ak~Y5jI_Q*A!BdmVI4@Z3lR@vOdwTDZh@!{8cK+g_ILzIQj;vB!+H>vNR9m{ zy`W0mC&3Y_S-;C0_5UcVi+&$RVmX%8cI<3lk@O#9L6GNX30fq9v~6;@-p%Gn0u}4` zwQdadJU&Z%>pIB1=svO~M!f-3cUQ5_kf!S4l?BoyTJr;(%%2FB%msn~IBBLGoeL7L zBWrxUg<{Fx4ErrY;%r9(EeF)hY&RtEoBN@gaV*G>IYBzsZa|3w1GB8jYA0C{`G#z_U8G3T1gc&D?i56`?5eq0OpvuTi&NJUl=#3N;6k&3kfIQ`Dexos;j&^PcqQM;!1aF_FnWX5elcockS^Ti?maSgAG;|La2J?3%ZSn}e>`N*gQ$I(P!~s(=?C86C)s zL+t0wYgsSdHshy(x5}l$gyNHB5#Lg6X?LSplLPsY-EkAk65+iq3V;S>rH13wpBt&0W!dxA8HLX~eGmP?={VihA>_kMOMZ#)sb%qgOfl znr3x;xXeowy2ZI?gqaNszbZRo&~6A*dA% zvq}Lio>Zlul8%lV@-JG~sreqv(q=R!(#&yal1#+)c4G4-H7ghb4$a}?B6oZ&e7k(a z4Wp7=$oa_ov&Q2NLH85AM)P%v_*?;1Um+Lb^X#}ij1m8c`^*nbyga^aj(A$w7YMsv zjt#RzSXf?UyYMHWEGq%d(d(9&%qz}7`Ya5w?}c5q-J3x4luv&@5X%m;I^~B|>nu&7 zGO5FI=*?Y$(aRo0qXSy+_8X$T7+vvt*qaz>yrCI-F>)@;iz(>K)OiGuJvb%rQa6Pd z2oi7UWcpXull~2*n8w?MXRdBkd3P)FhN^DRTT+4YDNks~y|q=BDI}BA4y8 zQvz?q4`80NK?_2IJOFYyYU_s!^N4=^^)p+vajvC}(yU=UzLORfR}fYKLX<_kOWMBx z4MF@+1W)wgP~SM_Xwur@#G1TysqGM)x7{O6k{)E}czZI&#C~+_=EE;enU;HuEUThV zT4F5#k$W`Rl{s-1B260<9aMaiqL{-5(t4>c$+>*nVS?5m^}AdTz5jJZiA*3y!XS)6 z=FA-2i($NgV_!eK?qU2|784aBVFRe^DLTB{FhTRs891HFrYXba{G|i^YOj@cao=i_ zd|ULmSjA8VQ@~JK;=@XRw%*2+Y{E4~C6e)~bR-jU=kSP(cgLxYOQI?l>19aq=Ui`h z{54dyfA!iBbn^Ham^)lkB9?Wac*(MjmCRx^S(hGM|Lyrp{|Qr{@&~d1pA!64C_Wa_ z_WlQ$b&O82tZ#+(1UR|W4&S5Oj(J8|hQTXNi-s~B4Ny$ASZ7ZS|5Cy7kO$?XWq$X~ z5Ej|_l>IB#@&Wc*LO0E=k@0u6|`lq%}w>xSIXr z!XO;Z+Sd_?Q7j_ae^bR)M=$;VT-a3+lfA+YFQozJLvF#|RzdLKfl&OP5;%Eh7f33Ki9OgLNo=uawQYX#e*Giq?IyFxz+ zeJ3sUF@0VhaNumT@U9KYco{iI6Gto(NWh`@cL0#{BO}{fi2ehCHjYU5!`LJ%b=JD* z#(lHZK75D2b4rZnVv|7Z5g-@0y-Nh47-5oo2IEivy;M(S+bK*{k>W^aP>sa{+Hp&| z-J~^@1*-x9X9Dpy=DucS7%wT_uAZE*Oqyc2i%!Uod3Aey%uLeK$Rd@TLnQp#;%IW{mRyDT+6%?lf2Kiv~;?;vo9h+H`^kvv{ zdXgVkANSM&yG;zTqF(%~sR}H2a{uXK$Q*z7Q?mwMAdB%XMaWpWF<%S{D!NXTu3b8m71o1niUc7RXfvmgPZUqqF!95-f8D(`CK@CYVwSmtYdMY%1 zSuUyyzTW``@wQVPWgfPb(M$Y8u|0wr3t=TOxh?i`Cuy1STrA`M;IE_poy-H0eJcdH z@nOG^-<;yk|5D4`w3|yQJ2w;k6Co)^xjBc8L^}028qnD5ceetp?mWxje^@pq6(y3- zn?4X-C@3Q$>2S%F9L???Sz~uZc$yq|to;QiJ6?@=ZLn)#u#DTwbKw_m%rRmjK=A@; zIp&7z3pi(5bY4*yerv0jCXb-~B6^VF>oJSfE>r)t!z;q*!oERB^>FPBcV{hll@{fo zAxeL=nc@A^vZ8jPteMD;`GU*tC56JSN0yPWyN91+8s@mXu+MBKLI5MK_vCJ&cp}S} z=*WvPriiu?hd_+ljSFq(quMPVL9E8}p<@|AfRrI!(O1A1Yd@tIPUpT$SKZGrodIv^ zdx&2Re)2s~Es^GzME7mT;42IpVK-P^oNn*MVZ6H2%}vGcxyw%>;y(j&l6J8ns+x!K z0G7Px-n6<~jyA*frwgX-gyxEA$G1htZ-f;eiaUSOA1?mH+;PT)La~n+t)!cV9X~cz z>XTcub&M772Ds;JlDASMo*r`tBft;&BEQEbhrG-{SAWc%_Pis}#buice zR4ro`OmSx$ZE>n=`Bb3X-k^HbmLgziJlDFs#|_#*TtKmq2jrHZ#&C=_b?Ksl$th{% zsy4-NjIt2{)3j7bQS0)!b8_@aP_mUMNI7fbzpb}9&qgr9_H3B($c8Won&^jUnG$Bz zcz|b+V5_PB*N|Q&_7M}2d7hgXHei7Y$B{90{}=Tt)7REP!}rXqKW`i{~9 zP$bbHsO~ghr8l)TZ6w8bGm)%2(c43oZ)riy!O|=nxEox{Wr2UM8I{f@B#x1RiYC`w zEq^?~x_n6j50m?K3grwsykX)cN>wewNgB31tGaPeUU%ur DX5aq1zAWKs2&wi(V zZTnmNXr@4Gd)F}e_k9RO2?VCXhF|0|TaiDfL0QU4uPW1C2YD{1jhUBVqN~25%4>I; z;mUm?LT>6qyZ?4>YW`zT-m!)&LLEo}|9*(sgXoho8|@qxya;I!Z0{3{uXRn*vS$a+ zpluLKmebZa5Ey5#ikw6|(a5ihW|>Vm{@S*Pel?Vvt1#R-%v+(TQg-u?#_<0uXQ{_% zgaCQ|W2LIdy%0pY^J&hfi|JA0BdonaJYBY8cbUsdBmHRjPsFuAB@wD<{FViKtbb@L z)J;jDc!1(6g<0^@Yn#3171_;G-dQtSDAov*k6%;0YtG9!8T%xVMlj`wf|rSX*IXsA z1X>`vyF!LW;ViP&UtU@bZg*y z2HQ~s+XL>H<=Hi_a)ESR$p3xPnCP7|BcfwLsNerxjY?v-p>`CYa>$Kg?(aKahPt?e zpcMTi*=Hd%(&x&z%_G?QE6=pYRLRlN0b=^Awx0;NLl^~*5ZjZp+h-*EkVtZFH3LK_ z8LrF2AFgvgNT#%r|6HD|v@xtv3jo1Cds<97=EWvm=oj>4wJ&zW7sN#3@_z9C<=l&V z`gtvY14+8xzGJC~4^MLPPC*7ruRuLeM9))LD}f$AMIj7Yhdn+{`C7f__-l4z;C7#_EzFp-@x%B;%E=7VddEuv9 zCfcmB<*?XO6ikASXv^49RF^G6Z|^N5Cn)_0#s;tgB&rK4qDnxi|GcFC!V5ZGc~+UF zC5W!z_;{J|Q!l8-Zh3C26ipcvGyM(19xJ~}&8;0OUqj{dLi3-d3 zfMUPdi#vDtSw zdN3%!wV0lMJdu~fs)IiM6>d@Z#gPnnOy1y`@DhXq#Ue0(=uMePO>`BUP}(u_QUavu zC(*Bx{Rz$$oSu{Wqd||}C9>lLq7Kox4_d|+0bEc^ggM(%d@dm)JpsC7SA&{Kfc!Wo zERDla7~lu-mBNZY7;&rLl}zT5aBSRC?1~&6VW!haJBM%u+{}DUxV4VMV4eypy-NY zbsnyDKRq!8&-$*=MtXyR>4JB}UYBx_6g3JvgrIw(5D!$>Ks-6@Rfyp%)Q9Z{X}MB# z*7c|VR^>PDTEDlPG=V7iKT`jW=pF9)?P~CR#KRZzF=k&QmA;^M`ARYV22EXtCgJr^ z28TEW0s1V3dyd+QnV|$|pV>ypqKo|h=>o5QNa6%>RWKir82D^M#gRLtIEvof5NUVH zB8dJHRZw^yCQwI2LE5QFTg8U*_jT9kSs(0@0YWMY$_qhs+C6}ms_o!8!>#t7fsmhl zBs+?z39q|SEEi*?wF3=!Hc2#5gV2P@?<-gJS)l=RFLQT^TK;Gw&^|j{C){ z*5k^r;<{TcCOtRzZ*YYa#?#Jn-u+A5FD+W_pwW^tiljvmcgK)E!Mk>QT+lR4mm)iY zXA9?c2Bwxs`Vf`H0{I8W1v*XD0kaHD^TPI~WU1dxIJK%p;^a|+a97WzRD8!byl7%; zL4Uvoqg1g-By{gN>R+Xjk7-V1q#->e43WFQSK~sGffQyzJB471j%AqA9Uakbz+2`7 zN*uM@cK@A$~VpNE}gLh@Q>_fsAL8mS)BWe<$z$vz}{_}-!iJQ z1^6O=0H!vV!Gs=Ew#5$#zOPwg_BHG zqpMuqg&P_UD0_^(_sNqn)JyI~UbmC*8XEF;g%G$q8wFF({(dIZmS(}{ zB&;=Rj+$Nuya)fE@ux4{3Xt2LlYm5#Lp%Vhuf(5$*+|e~#d0(puW+)x;lQyoSmH;A z<^c+|m^x-xseo)<{AMo^&nr4OMN5Z`ec@D~ghwrStzfQV8-dVi;Q?Z8qWIkyVZqSR z9wX|wha?H$DkNX_TTtQVX;tIAR(+z>oJ-BN>KWKo4hsNxe!;C^vrjc12kKz}b(K{G z8sN2y=ZCDyI~2pNQmtkJOBlDB;N+fscEvz*jd0Yc5hMS(KuHp8Eg)TjDO`WoV<|MF zER~v{z-^DT)-+!nAmqpzhWG})Pae(`ma)?dn$!mYZX4wF^iKIzY%x!#?JD&quQE&) z2GW3Y?%c`;_)cR+)XANaDC|}R(Kt-DYZ(?FEt1F^Mrsl#N8pAy<1n8X zK7wnks;2ui|G$30eMHmKRA)S9EiK^v#QQV_% zC1%S>524-!P+F!~${f|Geo+BInPWI}A~%o9X}D7iuU9x~-VmJ55UvM_+CYBBJeg!U z)mF!ei4KBiec&|SnYJom{G%>e1$<|2O)PRCcBvYq{0Ptc&ZACQhuV`5eANnx-nE6n5nn{(J}x3p@UFOr3M8`^XihLk0f zEniLiV{?!33a$K6)_QwO6}3x_0?;epco2Yy8fXpdF1`w~vY({$>ZYwb_;F97B8%e7 zY@d?`0^$$AN)cNt{IC~hS}&P#D7SB7EAuJ7s)nsD}EM1kzak69$% zMHr#Wz(2jq254S_jm2#vXvS0`AZ9=r){EVVbb2|cs#ucNjFD-|8=w*?UdHFSqfjL^ z5j&n_Sc|htMgi?9r^|6>5Iz?B3ginuothZg3obWoSDQq`azcIEVuh9|6w!&vr6XtT z{Fq2+0x{_~r7tYaQ>-Z)uFma*SDPB&*7D`yQU#}-Hyx;CZS$wk3(fAEp^7)wNJ|%S zbA_P_71A}A_DyMXS&9+~9~Th=baJ^Aj1y)Xhv!@LLf{bQ3qb%x)%-@>0G(w;a!F(p z-CbI&y~9l}8N2y_OK?WxEe=*)ieCidH}kz`aE9O&gOLnq#jff~ZpXi>!a#5HVo6Hr z4TtIEIf*aVdan=>iCr~R4t3-{08JA?Z7zc-1EDB@3u=Mq@jal$0c!w4z-HSSmijn; zI42$OJ!TrgY<8rf^_}na^W))%UqCWpuYxHk7`#&l#gY?$={(lR%VyUEvxyjO?1zix z>7sihR`@ptwr=*Itp+nEU9%$8&T1P+^(&$ax_ypD|6{@DTt4x4hTLN4EBTEJnZw${ zhG`j2R>|FASya~6NY~=>Pby)Zb%r8SRK)YUuXc&%c{vujNQI_wIon@0u){8Im`B$DS@NAH+M@#4@^fA`Fq)P=^yvs%<+__1sQhr|rE51v_-{0W zTFOD9uW@-F&YV+iFzaLrg{pGL>Zu5je-(|QtKc^{v0%G{0MY$-NIJ%TNNJ_`%lIPO z84T7rEWBHUi|C|YfZ+OK4(h&2KHC~K6&|E#ZL(kbxwZ|L(o#rWOiFNsu5$PC-9_`b zXv^^(y)ha3Qe}}>X=ZxDbPnee@!cBHm?CVbycQi&^`cAN$ZMxAd682bZA|e%qKCpO zRkGmI@OWcQTXoW5;_sYNUwkD;GOGdo{@)l`ehmcb>Sir4aib2QZx!Y!K7H0XF5SIu zP322wJz6}H;M2EF0Dj3<$3?buM$ym?Lyg^&WJl(dj}boog*^3*X|xl`O2Vd^SIe2X zg+fCP5O)?ex~J`_4cQm$je?+qnD7e7fz2hdx@x6YBS$`InZTDwAx)-1=H4zss&u5_ zVcUE@A$>vrS-3G8dbA^59iCDNP^V{PD@xaNAb3J#N7ALmc~d2=_&8^K_%>DS1d!)6 zGA@l1yK0`~2_xONEih-NS@%7`?qc%DIG)Bs{a7&j=Su1JHJT2N@(Xq^eC^!htFB`b z<@c;_gYy9Uq+r)ge(x`lbS5vgtPdRtuE)#{P2NsnlV%d$(i2ZYz;_@;SG93Zt9vE} zO3&nNH$UJ?!+885WdRI!?J1liAQd8OqEaMInPL&Fpw!7>;E?xXZx{MLO}gy*ODzhC z)n(+WtMHa?%J5Cp_{jw@cxYn)a7l^)VPu~3w+9`OwOp~wWRwq(Fq`U_Sea%}X?!is zS$-CGL>MiYr=U9;fRyd!eBgVSAI*G9-y`=`*XcRCiy)8 zvCJMC@mB#@hIhb43v&V`g*lx^@xtF?3Wg@IGxdRnxf;f~Aennf6XTze4Q7|?azLB0b8)H4cre$o)|bebUwo$1VnO2^IQ9uenZGpx z$O-STSe%q@^ZJDQEj4wkN~D9vt#5T3`T)QC=E4=VhFy2RK1#|u%GyCw1!)GakMSs$ zff2|*e5OciZ?CK)&L`6_#`1``A#*lwsuh>FO|7@XlB93c1W~AD|>Bc^K@LZj$>WY{LO>^DJ}+V)3KV1UO=|E*O$VSl@<77gzn zg|5}Oz`y>Vnto8wJUhj-p@nTXR%(^P(3SFjq9Vy_dm(Qo2xw!tD)Ya?_OwP4|6ezx zzwjhy+#;o)91($slYb}A?ELElgh9Eil!K~rT>{t;H;Ws}D^5~`UBU1Kn-5um93wdUbMCsS*XL*U>Rrot zVy$T1+r(x;X&n<=w4_c5o;NtvLrHl zsV<^fVjw8=0m`4AS2|9)sh9j0Ugp&P9DnqFAH~#inA1x6?V`z3_$tLH(s^sU@!91~ z%X3^4RG^q8X78xQt8D1QXyNiEyf!ja@yTsvc~{dE3ucnv58<$>T5XNaIhR8io7@v3 z%|$`zILz#05tUn?HAiD#L3^FHm!fUad>jCx6%@SRL}A3}e&*!KwM~ zQf8(gtL^&Aq{kPp9<|0x#QcQ1s+~$BgQM?q#bFc>Bs1+-IbrQqzBcTXN~%a(FrD${ zg2fukE`@Av#~zB!wK&QE0000066byYge|7p00EVm0f4|DFP-)KvBYQl0ssI200dcD Dv-DaD diff --git a/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.txt b/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.txt new file mode 100644 index 0000000000..934ab25a8f --- /dev/null +++ b/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.txt @@ -0,0 +1,345 @@ +/Td6WFoAAATm1rRGAgAhARwAAAAQz1jM6B//THldABiZSGYjQs1zFlY5j5VBz0W4JDhZhp0H5edF +Kt7LibZvccY3iyubavjShTuz+nJDka63C7ThK6hGwo+lfREBZ6lHAOsnX+4GkoX/wQBTqeprkEJ8 +SQ0hRrnXMWiFEUjkmMK7a6vI+wb9jlrpHGAijy0PlqE1fdkdKO5Aik1m+DFEFy5YU381bfhd1kBo +E9BOYJOlpo3fBM9UU2C7bei/xTMtGtwNwsTEXWPsHdHWnbcd25Dc9to8v0TNfh/jxQHed3f1iJh9 +J6xZg69c+6GwwFD+IX1nva/Uoe+6ew3oz/wUGO3q9ReBk2eiXPZUUMsLvFeYrCg/yXgXUJtcGi55 +qKue8MUkmuTDlVPzHPEoXJ4Ee8Yh4FOpGHQ61DEbpCwUKIcqXtmZHXFaOa3scVsDmO+4u4JUSHbj +HHs9pggHwDWihMKqka2EH1Wy1i3xLGILPYGd6voZfSUIhKVemZGJKJP0BFOJRguhbjHMkCAYUlY/ +vecKeHYoIgn2pYVgDe9GDCsXN89Lwlc4Am+AMG8hKteE7gZ1/Ly1Hie15UhfNtLg0JHhWeHVK2wm +S527D2CGFeodeJrxwndctfBT6lRRXv9tndgC+c7cacG+lGOCDbTMpj79Sqnwuj5fIxhunb7vM18p +PnDprzr/D6DoeiHZfFaEDWDobO4RcCPtglwNAo6VEcngQvDQnvgIithXDQ5FLOYXwsG6D+c8jHaa +jwQZssKUlAH3kHqx1HAanP8v7ngQuqniQ25JBSXxlL1xIO4ZmNKq26M8/4xb4jvLaQw05oMBgiv7 +p0pHX2sOPNp76CLZOmPRwoihNT+YWhX9ms7TYTLoHlXS04Y1sRcloghimnuBifi9IIM0l2YeJiA+ +UaQTA7moz+uGa0pZNJZ4sVVav7Fh0dmQ7ftyRnfm0NEHtj8w3i4SBC6gVdvltLNYrVQI16uI60bT +MzhpzXMal0/CVas1mZEoaq0ME/xFOLbqEZAgLS0svUJxWhvzc9xx1H5wfACJWZa4sp3GXcfkc4jm +pUQQhCfzHMd26wO4CuiWPgzOTFu7BtHO212dcI1jwvWbwa/Qo0Z0EX/uTnP5vnPTCvfDCXhGoG4n +0XWzUnnck/0y2EDxkOTyiVVpISv7AUdFl60Ajp/S/XtIeWvMI5u8YJGoNRIubI71IZLaju28LWgr +EE3PCJKHZo29WlnMcYbeYvmeqkvzs0d01YD3Nma1ASC/T/48E0Eg9vThdWe7PH3BojsApVfxD1d3 +JgDhseF/Kw6/ST2UlIRARhAOCCJ2sNY6SZyhxdc9q7usIhYJL8xXgVhs7TSQlQZ62lZsCH8/Ejn5 +ovvN9tgbIdTX8GNJ3OtnBSG3gfxY4PTS8sHaudHzyn92Vck6cwZRimsEhE0aJUuhgkd/TI6uNfsi +S8W0EHGZIxfLxJOz4KSAFOoPLiBAfo7iZa6UTNnD6o0CIzZySZn/U2n/ok+5skXnHFIaRqct5523 +knzpydA253hyPBhTCNXG1daFIth7Vo4tY4FvQRQIYun/BpJO1jLFHQbwcqv2fyjia0sbKkZPjdOz +I+Jemx8a0+YQ51RnBEv2zFumUSLPPcziYEa4HEw2zUNqgZfpDJcAh0YO2YqE6QzcCedHWYFIzsO9 +rKLdWDnC5pACoddpt+6+EjEMy6LD/WTswYpBfPcOFUylq9hPg8YvgNFM1andT6sYTvWQsYmk8WrN +dH35Ls+p9I4ZJtj8wxvVuD8c+NylpPSQ2j3uNOOSWsTvZYQUNr5owXlHw9fW4jCFzahGInacH0Jj +gEzpqRWDaWsJ/IS0HB9bPj4gvBhd9LNusixjzv6pLgGNS+FqsrpTtCtQofgxjkR+v5oQjxKJL87Z +7P3I2z1Sh44ub9uiihAx91S0JNMznvBxshda58CtWThUAIBwxqf+FJK31iLfSfYi8qq/4gs1eKSS +KOZS06NoL69/0B6CPPc5UW1zTmzBjI5pPGduvhRlNlXAHI/J8iRIdwAmfTvOYq7x0zedwRWOKEY6 +wyGMtX9laUfWCo1tuWkMQZ3Q1HjYJmGMAXXtDQHpRxEfa6VX150vycMc/t7mWqfdQvRfCcx9ytjR +MeUkLrStACnm7VCoc405OtILqFT8xB435NtGS2sv37V9wZjMNgP+kc+RSzJb6kZdHlA8cOSmc7hB +O9G0m0ICy0JgzNNrIF6AomN7i8FOad1sREdSlCn4+c55geWl9rWR2QgIGW2IAwDTCbQKDVKZxzRK +/r9QoDlQBBTmYaCEqE3i8AA0zD/32szKXmZ9rwfRK+XYIWiOl27Taqxl8LLHoqzyp6bWZE6MJ6/c +Ve36ojMt/9voHJA8tYdZkUCAobgKCalxdXuss3GwHL9FTHOqX5qW79tOZ9SlnMOIKED4cRTLDacx +hga5ZVb6f5k1ZmROK01SnVxaA3mJSFpeFvz0Kt6OSRXeUjvtF5drJltQMwL7oHWVj2o2/ewU/KES +WzzAygNkDCsNcmqqAJWqvnX5pYFxwQhyE2gFxHRlmvJw+v4x0muJN9XS6dmXZejjAWAZrS9S2ggT +kzHqObUZ8YyK9fuO5S3ZsWDuOVgBTfuDCGuMarzo2QNFJQTekxqCEHOoyCpKMDruWcQg+H8qJgi0 +MEuX1eTFj2agWAr0Uk4MF6GpQ3ElLFYdh5dWuYmbUEfvT60C+G/WtnFrkwEm1a/DclWpGEkZc4vF +egzr+HfknXHqmwju1XYLZ555U2iNZeEtxlTeZ6XbIAApScRCVxy9LJQexGxBH8RQ0RpMYyRVrsYM +BNBjDe67LoFPDV5+dgGgsCj/dIjfBCe0tOWpUZ92ANuF+Vl85CmXaNzycVTh6dXoF+kYRhjc8CNn +NRNCIIVcogdk86U6MG9fTVgM9u2y3gr2rPNm4U/jTef9nJOJwdnQOeWVOD5ktVjm2Sm0mMZsYYya +JzIqaOnT/XxK7fbQfmPY//SAfpPwwOVlppCrTLgLSaS+S9+qau6KJq871tPGNBWkPxktSx6x3V+j +6IxqtjxJYZkaTnAqKI1FWdLq10mLojuSTgZzyzUbY/HmlmWxhlNsF+/yJeArN9SiBF+g25Yv+mjP ++JIBd48pCQJxF/FAFUEiie/DOd5yZA3jYTqogkqnvyk6pncDtom5VDhCKn/DGK7hVDuI0c0XbUil +8XoJ9jb3ilCXe15vvhpMbHlWRb+9mT/cgcoF895e2DUrXrFqt5RTNqNC/nO7ksY+GledDCX47AFD +RPmHC2mev/VsKWSBAw1N29wa4X/5zjighu3ITaqzu6RFGQHji6AV2KqZTBkNUrJIA9rr0QtklXLh +oUPn65Qx0SnxjbyC98K4v4daehrc34T+1YQUl6o+o0reBuI1rlE9OVr3S9BfRyyuKcQQcEzIzNhc +kOakkZ4RAXtHaVWPFki7ScmDZnXngaKW/bSfN26P5V+C5hh1yRPVz3UfXWx02AiLyG5Fg65sFc99 +sOprifjDICsJzVcavvh7qyw3XINSay0jts37qhWX4Z+syvxetv0m6weBlaOwGdRZd+zwPkSb1Qix +Cmb7SGB/2/3sXGRcPRK0bVc/vKVv9LAnd9r0HCRjJYDMJDrUO6Fw0DJpe4qdV26o5yLjMMUlcJee +Qpiso6eP1ecZWYf6al1b7XeJuj8TFgJ9ooz0dqjXxhaywofWpSC/2nxjNij+1ES/v+Flej5S2VNb +veVMbyYpqaQcjM3zmYlsp9oljennhm9qjkmvxbcI4N4O3ua/UKtTQ1f+Z8mG9+sZUVwNoq0oIYlr +dJnWubVntiuRXIRxqFhN7/nTykyoXY4qLwFAVShy/XI0nzu9OKxJhSBUTwGUJc1AmhviXS5D7clI +wkSoC3/VJgpQdqPlQD+BpmDaIYfV97jMPCin+CJRwex/mTF0JGxXwEslr2ETv1k57oZu/Au2r72W +T9t9qKmSMVthd2PslIf4CjocsMPslSk8ohWCW1SXhiD3LPaBu6/IhxSwAhY36lShtLptNvld5EF9 +paWW1kghOgLwipvT0JMgBMMu6kOTrG+tjwKB21UUmike+YEFltlG/foieFQ5wvxuQiFp4wN8E/+h +zE6lAKm0wDS0zD1iOpwz5pNrmFfcqWyXzLPkBMS1QmB+IY+AmyBVpkerHiMFGUmNVQsWlg1cdT2r +IbCC69YyZPqUXHn+XpvZM/qF/AXAx8fjQR8u++T5nBNx8GjiggtLjG+1oQ8Bd/XiVrNUexIsJ447 +ZnSywrkFjfhQn1+QcG+lypAdGz2+ucbzQJ857R1xFKon9ZYjapufBr05qqTzr9kFl626xd2vZB1P +XfnzU4IDTUMDsiQ22RLyC9OzcuTruSrfXfS8kYvENV0X7FIgShpw5aYVtIg1CH9JfVQBAs8LtdRk +CvZrm5FAbqsXpdkyA3e/v4+DgKL7AvJ2vALp/GCelhMI/vo++mdrmVI4TK8ia4k0w68aU39uE4xE +oyIzn+Udx/3nXGj4+rNPTdzU12s1SXCKSCdCWdp6vXmER+fl6jwkNZ62/10+EB4IaAiMo13PAYT/ +XiQSIzLcl+Z4NcIY2zYVkuvTeY83CqmfvGgCb3SiMX0sDYtoKPPKQb1G9YWzBoEKdKYgvXuznlJT +/2x8XUVGhsS4qR9ihKPQHX6Vqzv4eZtussNRQM7dT73XLJRvKCMLOPQQAhIIqsk7v2IQPjP/7gCI +PGpFylujHcvl1KQDDoEbhqqx38v0bTYSyiPJoZRVUukSOtPRnMGtjSfR3GQFAb834kHO7x+B2OiH +oTSzPsV0asScqr8X+junqrV+JiXdVnPmOg44tVwskRHiUjnmNPOlgtACrHdJxo/sl4SvWIpqM8e2 +6zOlzWTzRb/qEzDG66jz15v2pfR2St8fhCwyAcKqMeU4bjD5jGmmmaPbhjR3w0AkJcAUIFTSlrek +QvqVf0kK5+3WE3akX7t0T9PM/IEph+a1ApVSEzrasZ5Ue+jqPCV4sNCnMJ41/3QYH4ZBFVEQsedG +p0n4E5/enSCzSqSy/nRlUHdwHHcMqdItkxxGGA/qKxiHYGb28vpaCxvBTY2J+Sp81ZM6RgSUrAQj +Cf7IV6FClxaZEqMe2sj8uH6pzfEToae3zvCpGW7Su/H4ZKbNzQctKWnAaYy4iMWTjIePLlw6bsFU +uLomt/uQSA4/KwPmVwnYzARhsibStza8Ug3j2SIn0/jEBlgkXd7qeOyvS6KkLU5GB09zzHspIJBo +20tgLtMMwXeaS4FOdSBDKsCBZ2i7ldO4g+ojE4bMuZO+HkjMqvT3Y8DoweyVqD3YB+sF2+JhOJIB +DTtxYTPube6WQRYm28nbdrVUQR9Ahsf0V/Q6Yqb8ZKaDbI5zhO5uOl7anUWBWbyXW5wWBlTZSdHP +4tHGH/CvBQqfoeewGXp7do2phdMGlvsk9rBO5ehMJ3JKXy9hpjBrYuQe4uhqfBW0LrPLzPP+fe4+ +SnLf0krQw/SowPKMM6bJTt3gB5gTmdX2vpypPzC4aKvDlw8zi6aAULXO3Xw+7hPALeit/2QGdJjr +AU5RniGESlX8QWfTtevIzxRHskAbb4POIABZ07qf9rexautWyOx+cWB/8ASYLNnVryZaWM9GK1pn +qNJm7+JT2D1u/q7hkfuTTuP2Sc1pBqBtK4jq4KXWKLbfarvbG9QYCXhJyAlX8TgHezib8vlJ1pmr +fFQaDnRdeyjydhRXP50NRncnhTPe/CuY31gCmBtasscBt/eAoic5g0Ku1OYShqGHumcVvDvJkadV +GOJFdRqfNqmsy5LXyMJ4g7qz/beIgugP/jgxy/nJN6ZU9Ppq2apY9EebAl7mQu8rAE5SLnq60qnS +uKMbt9rsS6GHESLFUHsfpJecdkf3W4p+hSX+cIZKiq7BH1sLuAq/+Rafx3SsTh08x2YsfqUw1rH0 +edDNPLU5gaLxKe3RoK819rf2+TU2zsKJEZZZnpFIzMG9X9HkgoZ9mvGYEU46MXGAju2sZGexEjC2 +z41HDx2+LEFQk4tQ3l6OH83AMfEOKnuFG+C75yqYJRPXs0BrLEencNkhWR2U44M6ncPsD1CZyoIk ++aTfZEIENfdt9jVCwbcYa9ymHK7xANthoXdJmYSk7zt1iN9ggM4SoEhhnPFHR4e09eWgAfK9Foc7 +JWelW7NenhAP/rcHipooINkTCRnvi2ogLtS1kpAeMpn7n3kvnWoc1Tm3M2RAuc6eXVJTpNqGwLTw +pNoOYtyK0ht3rQisy0erXEnzCkEOPHvqUF7VNQTuK1wPQ3RCL7D8Okj+F75HHiAL6QUre5BFm1Gw +vFOpVDLJrHxBNpeMWG4eymqwqJqyxFaRk5rVcKOeGKrJzgJ92rGa2Bc4I9Mw6crUFvxpyRtixHP/ +ZSakabfGX/kmQRIYTQPIgKJyh+a1kriqGphYOw02ZLf7pnfT1UeWctZXbPNw+z3qvLHRYBXSZ8Mk +5eJZbna0B+M8H6RHrtxNVZey+n8Ps1RR5wRvr2MYsFeFQkMo+K9zucP1vxtzfy8DnjknnSzbly2V +Bo9Sl+GyvfraF/u7OkOWDCF5bRK4YmDwII5sPgtlmMXvMrK6b7VAei04igS9EoIQn/yFLxxhDcro +ENuN9XLUnG3HGfFmkCTHjOwmDqOqbUiOsK9iLTdOKfm5C4ID0e7BWNjaE3TQHmYBQB2mUvccOvYP +Hpwoiaa7g+ON2qX8x1wnePPnoNS9QUro0BkeZmDA6hV20a6tdaPb1H/0DBy/+esfx6ogQnxXCCLs +dAXEcwzOihszO97tdFdSM5M0TP8j4MVxNgbcyROSuJXANbean6ZKeTZwnRhIadN4fBG6dSy4i8aw +aJOEFZ7zk5zw45iiFGktpvG1pXDBXdK9w+YfpJhd7tYUWwFlDxTl3uxzp12BynwPrNxUtiPpkkI3 +eFKz6jj8IpMEQlFKWKqnD8ZoVZEbZiYzg71o/zUjV2HBKnk3NGyhhb3+Oty5RgQs+kMqwZUOKH0P +T05epqFodQYZ0pL06bYBwashQ1GHk+ZTkYe0nESth1hEqhZ2Y8Eb/9KbBQ6V0vs7H3OUqiSAhouL +Uz2v5RaBuaU3hieEu3Kz24DWfL1CMQVMEJ8+JmaQzcurgPh8t3Mn7NqEjAsFgkhtuX0YZiroihUm +WTxH6P6jyJtKfXwmSjhj/LkGaUfJAK+PEBvwLTlr/tVNUU/vDvBUpnQxQZNJUnsUIuXj8y/0rPMV +/E9kszTS9Do3oBu/8WJA1XEdixwV8bfl8d7ogFwsjfY4lPyKlhC3VvJP5GjWG05KlGpft3wWRmVu +iPbXJfI2lGv1NTx0Ey0Fou0qTUQTAMulUbIv7yqF4qutKpBFRPNtP23/SVoAOwcFIpBSsi8tEzfm +kShmpnypDXSdquw87Yl1alR47m+aTlfi9rDz5idMHb8WE+m3VDjhsUJcY4Y7BuksOXSd2vzMF+Y7 +RXCkHrURxVsaL5WAQZofSr5+4WFAf4bUyGem/7L7cLdhVCux0HV92PvaJmFxYZPvxG/b5jRw2fa2 +kE3ZZ3x/T/jWjfY4c4m36l6LS4SVSLeeinR//zfGrfIL+sFwXVgzBGopfOiVh6zDJ0eZhgjxZpv+ +FSS/P7bqRurBVbHKImFRdORJht+W88DZZ4nrbHQh0aBLyZpcqTOzKbIRWhJSv1s7YVlyKTcZARNt +jE535w05I8FhlWwHb/XqqIHngh9Fpr25PC6cnQCiplrhyM9oI/n97DN7fui2efg1h1r97Yy0145P +Pl7Vo9mzAFLBEDZNq7pDNGX6W6JSmENYrCq2xg0bNxIanZ4sPr0gR/AmHlhr0fSkymMZJSS0VTR7 +yDSS2/67t0ULv38MV7fi0e0O6JyK5ohlCUFrmoQ7VTDZfxOe7xSKub02VgoG39aq50fpV0/BV2vY +2bty2UatT7eslsvRE5xflO1biGsalcRGjfYZ/U2I0/2eP9fx6sLaXXosgpPrUP00iOLu43dfQaMr +kb4uQiw+7eKP8r3mvG8/hg98BxX8KfX9NYs498RTizTo1sW+Yn+YU7+PSBva1i5fu1XvyJ0AhnxW +cXOfUPgmNoy4K3WVsDCIIMpFjoiPU+W8NHHz1BJ+UFLLKR+taBR+2uhHtG4SW9hSI6PFLPyS7ENb +uBiZIWWbhjNO4dTrAdka7MMmrVuXVXqWh/foVXAZ0oZjazf76K5uaciOzuvTEkAFEaP+REnPjyAj +TJwvVUBTDgsmB8Ss3L9vzJXHfnhDTRZTxNhui5LG0MwPUckrmTDlzE4KiZ485oNrUM/etKpfZzD/ +4hNPaoXS490u9/bzyJWbMt79W3rJ7WfJAuG8S/4OUFVtRgLnypDCokcHUAn9p/atu6fpfdpoY7iN +IPJ4MpeXEaNFWg6gQfYUwEkR8W2VxNcbcOXAISUfsJ61BkskfmdasQalO+EbrWtaS17hghRCEh4D +xugzPV/ELBv6GaMuE7gqUUpA14AngbdcaaZ1ayNh5yLSDfzB/lwrmkOv/H5XMa076yPQ26cszO3h +FxDz2nLgRSAb2EzBiNESSYghuqJYCIdTK//NvNEY1sgjwiIDKI2MDtdNgZOqPE3PlYyB2bu37bjp +ifF1PoM12mLnpfRitEhsq4GLtCoT4jIpOb3OzQgkoUE2qbcQqdVFxLnj0Cu3FzWbYQHgHWta1Hs+ +i9PMPj3qf5mo1uZkLGNdbvQq21GgJp6KG4HIoQxwnCz4e1rySA3CRjUqbnJ2yv6a3b9NKeNT4nL6 +VnY+b9+RlJAS1Z8fe0D7E5XiBtMacmeiDw4KAJgZvO5tBhV4xzmak5sNkn5iCvSSiuE62DiFLhMA +1d0KN0WiRRVjp1j2K4DYkps9tDJsx1qhKx/dz4PDwqfKaEKja+f6O4uvZKBNCtH27jvEFwpZhKiQ +EwwFOH49NynOefvTUIKJcRbxh7M30uwj7fyYiX0OxPQWu6QXg74eMj3j4zmKoCtba/xgE/3n6P6h +/RsZ+Rp3DUCOSUJaHYdCW+RFUJ991o4W5X88swHeOlejUnukKgmMhd+ZBlL46srW0znuofZ6kX7M +7+1JWdAqgzKznxhwB+ilmkZ0ZoC49s1nef1Glep4msc1725nDV06FxzgN0mfeWYHOjpvDOgvGqKV +1LJbSTev+wz7k8VqOHSbRGu3RQPtzEhzgV6N42jl87pxcoZ8UqFmcVRPg0DwqfCNsFmUiHryU6pV +/7GuVFgKRGxnv5Hb8Qm+IV+3jAidAdwX3CUgoQ/COXlWjb9gpd3+g93PsFER9j6Jja7JlbfRUrF+ +w6RrCXQyro6wIpcfTAcReu3zSNoghPsjZ5bfi3yicfn6TEmukGh/mlcb6lRuwlU6OyG0KezfMHN/ +UmrV9hy7VfNW5AVS6kDsrDv2lIfzOqrIgd+GgJrzBhtv4t+ng47+Ax/ncNzfk2GBGytrCqe3qG7C +FPdCkdsDRMqDrcMLT+R4bySm++DpflyTTUFA0gbXJmtolmmc8NBORZBiQWSvhVtBREjTSxFPun3b +L67fKS/niB7JuPlCep0lUvdNNhFdQ7783aqw9KxgRWT0zRmjP6QxsslFxn6Gat6/CglkyA3kqd1D +0RNbI96VO3Z/5CblIvhSO3Xrwv0berml4B9f7rlpoMHEI9VR4h0GsJShjRQfSMGvda3dGRS0HJCt +GIG1CqFbhKLl2D5ii0gxxp7Co/R/SoIRUMxn/IRbznS9ncLF1wy2b1D7xIxb4p5ZHr11hzn0Gwmw +GiHbsvmzlyRB7QyCGpMVKq/W+d71zBtewUnbdKvJDn2IUxrUN49fRrj+hQ+A8pbALFfm/MY9rLMe +qWzShjjMoZ3TlcM/hHvSNEyRxjW2cfXCv1Wr0K0D8YyOp4GGBPuxqT0LNnMhtxnwtB8pHUOlBqnr +/FgIQ08RGGpoQ/sIs5jdhGcE8RUzVMfM4nGiKyVciWx+pXrCl0QnltaJDIW7L/Fq3DfSp96D77ZB +rQyvj+DH2wkQmOOQ4dp/h9AmutIAC7fdnKEfTA8Uu3kPRi7c1BsIoll447LlHoLYnlpfXR49HMQd +RIqVQaVGbIDCuvpL25t1SxdQV8KL0bKjQVaH52pEyrneEmod9c64fkpp+9rsNi1V0Z60tVuJ0miV +E5UuZbD1c+AYFL6MF1BTdZV/6C14DH8huyz6B3ZiF/5VhLkzmygq3W01e+rOQWSoC179PBTz1Pr+ +s/GXQ067WTONyXTu1Xe4w4e8gbmwT6oZ+NJ87ctycWcBVlRReDiYd+QdvDr7d9BV2ylgsG6aBXF4 +6VQZxbQhOFbB4rCdNoLmf0zotwHiyXJNl6LULqGbPb0lr/+LBVNhMOgqudBE/vHqFEqDfc0Zk/Ra +9S3Tp7N5sx6rbkeUZ+7tAiRqd2rjjIp1yxi2GHLsUdosuVodXeY1KRzI1Cda6ZFeFmeyAzcIwuhl +uSbrbVEi/Wgodx7PkCvgRwppC7bIje21tu7B9H0UIW+qUauPHEbEeC15+TJ8qcGeE4DR3Fyn1TcH +ncshcsjmEZyWQLOW9U4i55BaYlhTyt3lisBe6W6e3u+ed19+oNuq4aCQCQSlAojje+rVrwG/Q1h+ +sAiBMXFVPGqP8KedZgIYrstb23ttNsTny0MJF4QY0a7LdgN6yAKwaG4AWBrikBjFEG3lfM5W0fJR +wZHPuu/yHzU7O3YRq7TAHHPnuGFbvamFM0FhThR6q31tmBIS7nNpPY2tt3qKsm1zn2ANgQK1U301 +ZLjRcIFeunoq/AS4DN3dxjBLfmcLzDjSui4SxS4pPset/LzATv2o+CkWuIhrBs0iXMdW/ZTTnGRY +5O4308j2WVJ0/6Bj1cOh4LeoyaNNPVESx21RV+fQrCwDMSkkW7U3tsw5jPpMDEJbqR/L+4b/PMTt +2nChJqH0g4Yttg+OaJQXTrPUnT2DgnUHQgpAIoj3hycsPZwyYCTCkZtuAHjjfFxB0JsXLSjzT87g +MS4inzBs2qYalapVP5j7jYwzwcH4y7A40t9Z5Mno+0Cce14zVZGSOMtXfh/XwH4nEkwKrjrZJGA2 +9oBtMFR8zbBN4jmI3bD9VU5RD9OIjV6lIeE4Ce1dWXtlgl8gELKhRtB/5cb+OzY5Xhu98cPys3zZ +/u9Jozpq9dDF8kI9PAN/ezzKcVnFsBH8xyq3ak+UaBOitACtAtdj5SbnQtfMwG88V+LzsyLUprLv +7xh6ueTeVWNlZcRxDzbsqiSLQMvVSJJ9IJAuKBUstNT5Mbc/N8Wz1FO4i3O29Bb+BJjy8LrOta6+ +3nPc/LxuPmgQ3lwk6yePbk3lJ9ojLZqjfIeEQD6ZTkCxxat6Zvb9lgU6CwUWfLvzzINr7MTnGZZ9 +zJ2P9Y86u4y7JhzPdekmpfLKDnu+OqblXD2yboXvp1rLZeTQtAfz/2QL8+VeVVNac7CB88d7kjrV +KKyv9XD4vm3OMondpleleO0QQAtbR43g/rQ/JYF2CfbfjN42F79YpVBOvPDbgNtaL1vztyvJPk6Q +9EUh/rNx6aVUtNj8qqLF5izM/rb7KZlsrmhISgzgoa4aedzFYGulTGXOWka9hdcuiHyl3ZHRHhMC +CMk/IxkDQ7P+oThBdM+5MgLrlrZdQ4nQ7PmJDUhZ3heMoDYV5uckR4GuGswUNmBXP+vw02gt8rXt +YYhMu0dvhFVT28kI744EH4YXGhuhuSP7/yhcvnkzvJvLjYyw1mwBD2XGBUwkA5yf+brUEYHKhI4j +R5MSgZlUouzwzgGxCqv7rYv2VQhQm9BhKL4vKF2fBV8S/e1Lse1MqZ2fJcT4JK58FZCcSk1vdZXv +JjxV6SoHAGzIulzMA0TRgXhruQV4tpG9W7ErSRP7Rj3MJcUTeUKvezyn+FLjkuUHtji8WDDd3Nm9 +kvpxLJ8KVMAoYwDZdaEr+enQWxBf/OwqzJz7aRQ6bNRdWn/IwWW9cbg7i0FuwW/EHGqCis8ydyLo +/WW3kRMvZFzfdP8FssqNl2ispcH3lvsw4oNN4sEDXRTRwY33UX50XTfMozEhARpTV08aQncwEOOg +J+JwX5x/DQJ120yCgkTdWxcWVheCtzOT+bnhXd4ybytIWlgegb+5LqrSace/opjOGwGRHPI5jxCF +YwvvzOIEHosmxxgDRZBR0ulhQsVuJyTA4jcFokoYOpm7nt1l1nQi0UjPyMF87lbuEgIEFPNcYLEu +kN4ppdXjFrGrS5ZUb7N6+aXfxl69CJt4t7k5ZX/UHGhPjFBI1UGRSaKTJW/ZspIIPj36yaRLzYjf +S/v7aPHbEtB1C2IKhpD33cVpZ/74N63AbBjIsBkqnSbr6mkeEqaOwR8QCHWTmJaT0RN+lh8DoRus +EK2xJpiqEIP0o6OIAJTiwszEOjeAw/+27+Sz1PXOEacaDvFfB8EL0O+QLP5lTdN75F/80KnnHLdg +oDCw21cdFZoGqHveW/Ot/HHdlEckWLcvpChgFTuV3rK8mUkb5vb12fDmretaI8cBLODTdq40/8qd +1iFC/w65EbNQb64X7i0nAKvQLfk4Ii5ec4liQrRkP9aeXu2HyFvdcQhnXxO9qhAVoS641ncz7lan +xIqh/0aAg+hF1hgQ63VjvQQpvy4ZN3HrE4JftbeO4JV3z/cWCo3foFKnw4KZseZU5K2880IowJ3t +IexMF57u2LDCljk6p+IiD18+QfdXz+2mq1LgPNsDa1D3udat3MrVekuv5eY53L3iTAm3bUGHwlC3 +tlX/WtHhiHjduWqN8f4HUF/H9P8uvJ+2GlhpsB6pfyoGd9FaQ3B+fu7Wcky6GkjfYshbKlptVUFx +8jEpRvE8Hwx0xagvCpzgkrcIl0zPA/vhZci5wkwoDEFF1G2K7M43UGKwqhqg4LPhh07v+0T+niCc +F2pUsMGW0E0f/znt1wE3u7gxu+U4XOeo2REH6p5miRBBaXgX3spSf1exHvfiW6cIbFw3qYe1xrz1 +RNOuTsJK2Wa4GectjhB8iIZsUzDP+Lk6etUei/2enk/kqOHYZ2lKfty9cEhLPO5XbHRyPK+KfuRH +YONApcrGaiG5PIW0HyuOsHp9/RzYQjR2sgFJCOZvxpsKvNUWMutUhn8B1S9kTm4NfwJHW5VNINCo +n8PWa8C9ZHTXapI2Et9Oo0wMfXZN28DgkXZEV3BoBic6PiX3MBNVdxRbDfqWRN6NWtlEqRdIiEmg +a8HxwAiroM4tP9Zdw+Ct/B8mNcTX/za1BILr1C9kbaEDtwCnEhbzkDWNKiyIlL8BcyGCirBHfcge +dUO8JHSt4pJLvKXBzmSfTemcDKEALyTQtQ0BGYc+CBHfJtZjnzja9zezM8PLYwmCk7NXhB0xNsL1 +xhavZ4pwSMUMuJhpi/hek8GOIiNnT6HwoOFD1XOrspfS1ED1YdHVWnpLiUBym+3QH1Qc5IfibCNX +h1C4HS8wn05qU3lP7RxktOh+UqvHQ+M76u8iFKDQKQM/ADfyAKg2iHbnGT5s9Y11qiswN0Ze2WtO +TsZkjSNvuVq+zi923Wm/3vsua76CK+ye9u0DFiQK3Y6zDYlNeywCYImrzofdXHJ9y+JPPY5NgaFm +Ocn6akzjNfkwJxg8peWA0ZdT/E7HiGaASVNlIAXXQIiQnA03S/PkCKTMPSrPogYrCjalHvXpS6Nm +OVdFpgQbMRTFp5YIwBvzjqQc+4wGKWDanoWztf/3ek5PpSSyYUlVO66VQs5cts2PDe5K18KGVbJs +dMf+LsCJptWhTl8479N3pcetlXL4tTHKf8cJIEq+SA3IK6akD4G0eBtTrZmX97lkVeBZkiTpAd0e +Hgjz3jmKxC56jYyP1TOGmCo2uOgu8h4FaJyxHlKpvLMZiGHoz/QxboBxw+r1FQ4xSPhdzF+ZSdoQ +6rSrUCH7H/NRxhoZr/mYF2Ml2veW21YSLN2EopX8N3TozcrjCokedJDm9QsbsSpW3E70UUKeka7l +nafb4fHZdJLVU4wTKMGwrL6sBzDTrxIqXfhb+0h6dHk+eiOqi2GdPvWv/0C1p5+ePXL4BWLSMWi0 +VjW9FjpcHPsj4W0U5mmii0NjxhQKkLzFSNIp+aQDeW6QVJcHP1DmfyDxd97Ae3QK5BL7l42/yeY9 +IzStiLUtJVEER1Y/7BsxPH+QhwJYrYr+FxBxR+TBEAl6gdrPn4ON5nFXm0Pi7mGiSP348+PFODC+ +yGNWvZB/yp3F0g0EH4gsAHaEQwOAsGPMW80IYDJnR/BOM5FTMHrkUK0iEyYz4ouceTb5qF0l6tJp +Y/M+IGc/vocUXue/u9xSFkxis6ZvPX1gk3e8R78YWtrDde0hlgL+BxFWR/K8+EHJxbDGrFzyvcUw +F82pvYewk64wbthCJuI2QbG9dP43tJcVOSFM2z0KJUmtoot583lUU6EXe37Ej7pEJEWy5/Nmer8R +LwL9VApJJiIr7hV5wNjwREif/hiJ/4nyCur85WmkHVof8LaA2NhBW5jz0w4KZUcRHb45M12nlQgw +k59vXrjf4tz7SEWOA7QFHlIYbEbU8WkbLBc5ckQJS6754zTyZLIs5nNQCEsNgl9hBwEci6pKrDSJ +WrQCW1+qhy8l/WtfjO0BR+TnCxvvEySWLF8iHQYwJuf1hSmVz1HKTY9vRm/izL7L8etWHVfezpqY +FsPim9BjpdcpPu5g7by0qpq8X4pj+3EPMaw43SA2sDpB60RjXzXz6854muLHyjR9Wlpx0Ks3UP0J +PWSfxV0N4PHegwkBJct4d+7FszzMEJ+siKkcgwhXO5+UxRMsGYfhQaM5RNYCkiYHLjcyztOJMWAK +GlPzlnGz8M8Wg05xxU5OkTqr96AhSSAbAwIY2YdBHOze4HGQw8AQjm3xnVyi5SnUdjGgCiWMeJ29 +FrSZlnpB5WLPoXOB48+WgOzQ9HWGGVnnb6jhPudVbgz1ETse44iz9ii2lrVvChN7YoIhM5fwqHRB +TJAYW7TYsG72XSZz/gF9QW8sUjrYMd7nRFI+zd55bWwS2dOc/HLiWEcfYiWmgZ3oAQOpDOUYvmig +fD2tvLDbU9JgiR6rMBcz/rx8OZWZuWY26N09UaRqjr8v0KXAdGW/esrt0HQMx28KJ/1QH3G7BX2M +tL5FIWNv5mEdSLELEQ9jTCBVS26BqA4aSoiS9ngESVKTLKPDehCVSI39KL2gStwnwRGqWb/LG/X/ +KKuLfh9HYjmW1XbsbF+R9B9jQZDnZwlaJIG0bXK43s3mSAIV6/e1bgz2PD5Le+s6yLzoPrIlRr0B +U3dXsc6QpurhlQXSJFrzA5zMnwiWzAWCADhpph2dCxKvI2t8vYViyd4M+y1C4mxHAi0H1MxsNyTw +m/uhm3Es20lt4nlL9blRukyslmTavj3nYj8rcv888SKoSK3ioZofucMAmw98Oa0iadk126L/7UJB +nZOcpuLAZC/q5wB5hFhUv7ayBCDyrKVecWilpgrAG6YMqtC+Rj6QFrMjQxd++bs5QTrWbkCJAgOz +rMlqJ1kR+YZst12kSNIErjCGqko00YUKq5XN3Hc4FaEo8+Vvlx+WNoVI3TBZS9GKILnpB8inHTub +psWeCjtfUhhjv44WyRRUwrG4Sxa/8Y2D4QEWoTQJOhbboRV1d0MtTnINJqOehMO3YxhHDTeR2Upd +rUF3rqptJCRNdvOIidTSJQmX9Yi2tZ8XgKUjRWVYOqtWne2JeLcog+KRtS1RPu8Z0/07XzvJOew4 +r9QisbaWr7M95O81nAUq/u3t5vPv/HyOKl4b+BxlxeJK94u422wQ+dPdDnV3ygzByR38OISobFin +VHb+I2bZ60IwKrNpkJRIRVYRxCNlY5GKtQI4/c7NuW0rMNA38DtRu6b35RrpDxvK7uknD+kjYoGs +y2jP+NwnMJuquRrTsuiWprZilZwUrAfYgFCrpCw+sbWbZ/+ACpeqemzhNqhYrEhJi5XV3jBO4sDm +IEdIaVurnfGy/Ccty51SFn8vMxoTWh9mA9iSagNz/8t7sG+PqlXkhm9cJmiQuFpWsEmfRK6WtXIX +px9cIoeepP/hipQ06wQi+f9LmZ9L8zGoduhrJFMx2X1uobXNuxorMZHJPmbgbhuc+x2YW9/JyVip +NhD/60Lk7Jq3h5uDrtdKGywEOngC9KqAFx8ZHciMQ+znzGtZL90246eBt8qlwoTik2UR31JtaXej +WZMD+ZHdcRPLEuG9LQqAK4eZHJGOOpgGYKrV+WO2LCAHz0Xz7zjGt67I8IkShhqSN2MiAjtV0WSb +HvgS6LDoRNrzF8Z/1guWNJapsUkVuECVO3B+gk38VYF2frKMh3UljdAOgtjRs3snNKNL6q4rhoUs +UecvDpdSTD0QmZp41ApObSj0+aEdeeeXMwfLWeMwPgt6sv7NXdF/t/Exj2nErv1QmWcjinrzq4/w +rPXGh98To1c5+ppmdXy4zEsUvV7+mKAWk2gYsOY8qCGtQ8zNBxLn1UCWEGOtECwXBX/Mja3i9unU +JJ3EYguD5Z7ly+0SD+za2XXzKgFZi7nPlM6x1+Nut3iKuUrUQFfrkk06zjWQSZC35lXd65EhqBUN +s0oBLZ5UpZ+Sjo4a8i9a16n5HszSZjQm0sxxaJJMxPV2YvMlNSsYAg7N4eMid3wsfLt8xA2jklzI ++cj7s8bjDkH3E71G83WJ+FwBVV8hF+Lz7Lg9jBH/iPvMD028PL5sjnha2BcIu16ODbNDWFheZLvw +J6EsKwHO0euWmMwrzkD6LAyx74Vdtt2bQPSUT38/EMsOszrlh1XrLE2hMqnDcujNXYHRyx5EowNa +7/Ybor0YXfF62JsYabyhGXoxci7Liynoy9R5BJA9OCXvUjeFGAgSb+lk+lfWk/4NpZjG24Vnrm5U +eXcr8oaqbtBbUoHy5MXfq3LC7wmrHdvk5qbkiyKX7bVTAm/ED2Ces0ELQoM8AHI4auuHC/OIfv31 +M1u0ca6ljdKsYT2+kxYWVxBWAUKURbxL2r8ADUH8UARP9OFQ3zjmaNLa4cSavHWp7RCct90jTZIe +ZOh4ezLGxH507ObDL06ZlnuMLKuiT1piLQCRezTZlTlxFiJNGxQdVHyTopjDBtJ6qS/JuXzbYYLW +IPW7XA+9/3VFiUwgRsIgjEHmzBzci2G8gGNfP7zuYfxaFhMVImEDqOspOrzbMEHz0Bk4ncqmKcPl +/KUD/WqvlXZx32qTfFv0uFjFUAZTwFBa4sNKf7bexpRswjVFJZLxqnQkE3Ln8IiMd8epjkuiKhfp +ZUjx51xvd/w1VLV/9doQdPL4GZg7XFMilnWgeMmyjZXMYjRZlx5c/+35S/8JU5/yB7H/nxL8VSg+ +FtL2/geYdYxOsaxvhfYEOLnUDt+j2455RlmGwStOi4YyHA1QTLVYZ08N/1LB8pAH5aNlfvfNEBbZ ++ZT9K9byAfZaQjfNreRcnTaJ/+7EWpCojLhqjYs5RJZxPeHUYa5+ZUekNUgpuJr948IgHM7a1xGI +USwi2X9TxVZHL/3/XNhVEZO9wg4vpQHnQ27B3la01YTt5riH0uRP3hJkxdRsbGPExnmg3v4kgRcU +g9PReh9CqM4931zKxaH2CXPt80w4W/zoTypiawXbozNqcK67Qj8JfSct9jF9Xh5w4Gy08K4NyngZ +OUcTRywSSMCh93cAkPMjI9tciP4DgTaOSPfD2CQrdda66MZ9s9U+fIe/c0qM5mKTQOwRIBe3vUsE +oRhhknsG40//vVRPZdspTFWR4khnUI3FA9pxS7rdpDWVBasCAWcC8TbmvmZlGC8p3q6enLBMmmK4 +i07Ij3l1e3zMUodcp5q7bRT1W2Q8ovjr8BAzGnNx9Tz27wdzkrvP6iHV2BRfG6E91NBF0eGhbV8s +0+FzK6bx218Nh6AJracx0QySSmLZ2fr1zQ1HMwF5LVh78Ox3gbwEIJjBuG/ZN3KCMT8psLCskffJ +XUORGuxUEcNINUVDf0cfR34RQtABXHws/d9Sym1hOTYwJrssNT7M6wXM7T5M9E5ojqg3uLoIypvA +jEvSfpzvBH9BlObRbux91J8u0oizHtBSO3dqfpOBGdJsgj76ReTomuEYScb6ujZSlDZVQTxLynvg +A43YF9OdeOpg0ceUViivBlEbfPhzgafl84L8h8WQ+0nSvSGW2xC99gb5YPPi1YNLHZtZk/Rl2HN6 +kh9XH/fUAbtNDLKiXvyrqQosd3L/6WLIHH/3U7MGXiCL8S5FyFi5MVldhFQdZlNKCQhcps2Qm+WG +IdTBw1dbCrE4EwTxO6VevHKTgay72W4FEODBPR4MGWV1GEENSTK1gc8beio0fVkuqgq+3wEG8bZT +HWUetpXRS/xDsT2CGQthJTG5LfZyJ2mZ8Vws4/7gr6P+ncwDkn0rBLnxYb+Q35zizv9Sy9y0m0sp +OzcT/RMhKUa5OYeNRDr1OBrQ2Ot3twKs7jzL4H9YNiYVJZLPmz4QXSgoIyLpcMmVHM3uHlljd0R4 +mhx4rP0FJztejXhtsGtgsIzby3PhF27MMWIiQPECaTnmhusLOGdadF5RGH5rq5cmj6D9InqQ4esx +i9UuU/+1wyvC6MK+QUj1cO0Md2cteJUW5aAhSn+0meH91LKidqKsmciO+YLL7iWFwq5HlpGwu4ef +YxrmuLywz2wnQgAjrvfkbqF4IsuX6MiLMaaIthGHQIzajQtt56PaLR5BrMbzoWMZQYCUIV3RV8AX +az+lF07nvktX3c8wnQFv6nuIXw1+8j1QLZHml0T3bcjgKwwbYTdYXZxu78VhvLrTzU3F77nLTyHi +PwNyknaxIaqah/EAlrzn3rS6W442w/WnC6bthOaKace3RcdvhBUfijt/0h8u/sTcccaEQrGPGK2k +m4YdPzZV6pNbs3WMFe8GuOdskrdSJJ4ecwcjwA/55VGG8F4UKm4shH1SpYVWRSBNUuRPa1XZdTDX +/1QtYxZMcWcbbXGqa/lUoNzeoHrVliJgaDzXurzHDdpAXECxkAfklqDGcIw2demigskpaeSqNsVw +jLIRAdO0VEhR6/K4c3L0SVCylShIOWviv623Oc9GMML2bJjxyIYwCJroh2iZEmbVeIBnkGCrqf/X +kF4m9hETkXwIvv2RTjR0/GBRqvwju/0OBFAKFLDjUH1mRO6IH2bB/ZRlWpaAUGqebHFm7ReMVaYW +xDeajZx6YzAXJkV2h3/BgPRdXEc01qW+gJCLhG+1QjqVjKJMg8K0uOhR8LtJC8dJeXCdSj/v2t+Q +gEUOyBtoPJYmMm7ZsjWU8mJHdgxX5w30JfXGwgMizEuuw5mVVwdx7y96kkP6F18/Bn4R3X0lONVW +M3aAfeF96Mvpr1Fo51RC3VSIBhumIneK+o7SAlAk0SCo7jRfpTe1NW0kxXgzkaw70dtDlm9pQczB +0iwbuBtcy2WBf68Zlc4lJI6RgYom11wtfzzAunxJAg+T+3UK5Qw6vGHiJUpVLcJJGrY8q7pxUF53 +6crPqZRoEOWs7yBLUu7Pfqd+bftb/GimQGt71zD5930IRQkEpsKGX+QyW5E/p0FZykmvKtNeB3ku +p42Zl2Ciq76iymt3muHKfSJCbupDu/92bmr+Y1DesYYrQh1IAf9+iNmD6JMyG+0cFrwIaRBs7xOM +r3VN0rJnB8+gbRBLltPWOBAYZ6+KnEQ80civi2aZTTj+2raIfjWUm6sw3DnMW6GoUnbzj8bw/ytn +qcdohAB5/mOlqsi9EES682nOp4vpUeMjrL1BPF22YneZy0oj/Wj4T8S1QCURqmj8lgV7rH9oK9RN +SaF4gOIqhVnw0mubveYV2c1T3lkzWyjWCJOPX1O9a87LOBn7JJBGMOWIgpeJfddcJbAEWiC6u0KG +RuEsstbjmHQykmH6BfcU93lDqNv5v0t6j0SE8NtYm0+St/Whn/sMJim1Doz/X4BgD/IMkwGlLzXh +C6Q2EzYUCkvB6yHuoK4QyipdZm9iw2MaiyeC8PQpnJwXCTSmzrb9oWYmys4MByVkbM6xZezH2XSc +7ogWw3apXcRGHvup2/JGGv94dH4IWY8bj/WY6noaI3Rr4HsG21ED2wPumOXZNa9ygXRdyP990pjo +nTMjomNBqN//XY1KYrehdhSgcsiNYe7vO1+GuriDoBT9JNlnITTS58q3zSPY+ivPtMdUydHRAWL6 +q7afCLhDGAWPENuTs9tnJPuQSHJuNQNEKBmuy8MfrnM+SKa0kf9cnqy0MaxRCwDBP3taTDrmxSZd +6Bf0ZLUvdsQXxETi8n7w/uXci3v6eS2AA0m63r5jqYgPT3LyTkEGSq9APVBEz1NYK4EeP0UhDFqH +PT5GrUaebQRo5U7kcKBziep8mLig/mfG9dPvtO1NWtPAT5Y6O/PmJZxwct6hwAclnt0Xvl3lS7n0 +/ZQuRYIxeeGnWybarLLlsNhTFEyCjmjL2FFUly1Cb+8tIyco/QjGBrACJKoLKqJKQKn/vKT/wgs6 +XXlWmaUliK7g+HiZ8VMvqMZueW6rFE0ZFDP9DcIeK79Kza1CfwkOYPHx72/c6/2amaN5nq6JCsv4 +gGK/2Ys7d/jkLtIhpcfmnehPAZBWneUKNWtn4UwQNNewDA7tF5o2iyLGf0nh+olq38jHZ9eujw3z +A/Y/UyZvKTz9w4AwMI7Ek8Ud9VkiHtrm+E0DjbTrgk/Slgk4VV17G5PlHt0zKlpYUIA4aIlfNvzf +YGBfoJFbqdX/X6zNCPFwFDWDa1zh+WbmIgG20yoSdDfY04OqXQwizIhsm82+iadHqZqLBFuPdstl +2dqSiYqfhtfAIoQerzcp6xpMTAQ0hVtl6YT8gxE4hNmcoY6uGRXY0gkSJcl29jynO64FL/ZqjB1k +NmRY7XhNeVhIjABasUegTbHOx/PIikFbK+Clzx+tAhxxw9ODTBPYyB4lLcxHCZGKkX7uExJCJTzP +tb4gPWmITI2WVGtwKRpR52vp3JCU6mRj0V88I03A1Xopv99hcqy/mLQnjcVzCDTf3uY4BCSuX82I +rpnyL0b7f31gmWPczU8XKDtFMcnotD9eWTwsmHFYuFi+zGd3ZgMZqDXPzMKQQNC9XvN0S9ynHuVT +MNXpInEZzyWYeKxWr1nnfE4qbit/SOasQrFY5BM+O1O8v4F7zY/muHnhSfjJrL6LeTJKl5NNh2FR +S/eSpEmNyJHQbEqyejAowLWYnn48kZfDqoM+/hVuUfjFkQx4TN7gmfAShALFIjCA6E2ZSU10FZxQ +2jHyUgKk6SfRr5L9Cc4VnJ6T+6NBj94lsuMEog7RuA9axhYBXFBLhDnbUnwuISM9AbpjV4OaSYD8 +OCcsjcNRGOAH8ZXCij8YcavflUzmkXBs3FLsihwdYabTSDuHcAXczHxNuLWOw2CeCiq9YfLbp9+L +vXFIop4rW+NYtc1sm+doUS2cKsYHrA9JxQQe5PXUvZkt+sBV7Gx98vFc8F/nYB43wXUernU/PTEF +z/qu0EZ6g4HpgnfEXpdykRQ1CjuEoHuiEA9U10A8OexViOEs1IftB2m5UnTW9af/VuU37lq/t5w0 +gSj4P1L/jugd7vntavB8xMMX8jFmXyOVvqB2+Uox/gZNXYYm4fVQBoc4BQH6LIV7jtqKmaEEaJ/Z +Rsiii/z/6QKvfkjiBHFVMB+QGPhsQ8WRO6Q4it7cEGl3yiKI/hJVUHgeJlBHREHaqUlbxYby93XX +6Fkf7JIBQioKygtBdNo9gJeq7eA5w632noGQn30kO4qoCa+7UiwXY6W1Aw14Nkk0UYPQhMnvK1f1 +WaEBdC9zd4la/mgj0D47XCfbf+Y7d+3MipjFPndH2/YxoOTol9toO7bjPlWQxmE5nsb82QdLr8ov +/GpkJlQMZhvl+AjvW5cjtVMXhtbjyq/iulstJj03929whRTG085y3v1L3C8tWu2g0ZIyiqRFEXfH +kD7Bu3Z7XNA0TZciO4JnC+d2BqaWSPoQlcUC+QfHBTpN1cL2pmSp3004tapF4uRRgnBXz6VUfMc3 +vGhia0F/wAajVLFIJHTvOepfpZKPaU5kpCE9JQyRu8BX40KSgRRmQTuFYIqOZZjSHR3RbsBb5gRK +HLXbeO276SfyzI3jJcd2hKxDbWLdLKJg97B4i14tvCxWDATwDz6EvFw+CuPPsilVt6pSpUywWm9z +tYbMAOEclZHZQfVxi2zKN83xLp2xA/CP7GaoZAYdWZz7i+WAYMfA3m2b3zKqsgX4In8ApjaXwYQe +VLbFDwnAes2lDKEAsnG5zsmtSg+NoqxoD5QhrO1VaIH51lS8UoWTTFWjq1zdhSBYwGOcWuwewlWS +KHuMvffJkzHUS+5FXreT8Boa8naFELg7GwVTz/5+JtSWZsHnJKw1ao6aXga8B/+f8acv3QqQ256T +gESRQzwAq6/En4HZSNBhxXI0HK9wsr3hwLEzWOJHh+YBCrWYOmZXqYBsXfxmLxHPKzo4RUuHjX3h +VKCERy14rWCuYhuB0GnhAWJtovjdGGHB0NEeI+q4hyQJ4CokX/ZbUOHmaVXjvFZ9otScS8226hnY +VQ4LAHd+wa1gs081HgfqYQB1lVUFGuC1i+eHrMo7FMOuUq1mAksYt5rg5J58dsVAc41w1KgRI/+5 +QEkSbC0gXYIpXH/XYyk0oyyVmp/AbY+01jRfHCDkyBqG+Aa+Tx7OFJax0wua1AcBbhvk9fRO+VVs +MU+n7Sr1Jq8yTBYG0oBz7tzKB/hOY0bUyZ2SKOxWBdE4TLbkYwX7fnaZZ2sZFh8tksgbRmoSJ0fg +hjjjMJ8YPoJrrKqm+zT/v37BfUTT01RnPGYtM6SUgkf2NtafOMf8s9/NW3wyUnfBHSzqHvbpUdyj +byVmy0kPod4EUFqmWMoc1ah+UQFBmWM4cyI3j8ppuFMMr1c4at4QnM4QrgeJ2kB+xjyZZDnVVseJ +iQ6CZ33gNN6Ztipg/KMuWQV8Z25NLHIgdqkapPwIz/vQCA4YtpY488IOQX1ic7Mr5Yel1drFS2gW +PE8ExTeQQB+Qjk9jYlXuSWGwKyvM4/+bc9hrt7RqnC+ShXkb2nQXhpQlky1fTfxjc4/xCq38UdZ6 +e0sVtUuOAtAr33gQgIgaaA3sLr4KsrKfpPPqpq07+HFPoiKL4stsn5MGAuIPwEoRWyv8sBdmWi+Z +cSi3b2Ir8ym+qolJc7VxHaxipsQomnD2YUSB7MaPWSTeRRihy8A/vcsGaF6CjcVtI2jGVCIgZkAZ +1ovdiXR6OaiqWJLWjJFpyhugEilexue5o1AlNRE7nmRYi7NKRgHtKafLcWYQPhb7CuQLPp2aGNkL +LjdsV5tEw3JCfdtihZYpFNGJyaUjZ+z8mEhoAjHpN6UvLM1TrCkbrs7thFebGt/W8uXhUgWnnTcd +qGRt86fPC83um6GKN9ZISxdxc4WhChXSNZf2TWlzWYoSCR8XEQN0crkUjBNmG4fnW/RC4BDmC0EA +RNX8RtwAnWVFcklkE91dWqy9w00vGbv5gEtwRuMtDlZdil8E4zfzvWdwhuAVg5EMaMWu6kpux7+q +wkBv82JJSukNh+nkOYkv13qvEBGJXTVUDnXkPgBNE0FtLoMoA6EogAtqgefxPaDFAWsAQsBm2xmW ++jh+OCcd8D1mGsFsdqSh9Z3v9fPj4YdfQDJhr4IpKBi8UwfFkhN/6TzWyMtm1wSziRht7IeL5emi +eyNW+DcGtm72oK0GMyddsyLUzmobR/Urogu6fY5G/2PB51w+8XeG3GLoK/mNC5nD2sOGaRlOVsnd +YVlU1tZI1+LyTyphnXWGIlNUxPO7r3aJ5nk5FrlIi65YLQX8ZVZvXcMeMyZp0b47/k5ewFi2VPvj +3jlOg8XTSIxd3/JrbvP8wQnicr4h+5vGTdHqC/gNP0SIYdQqU2dCzEQXyGs52182sMMub5hH1wBZ +8p0n2qMC2PJzXjYwmpY+9OkIWuW6mxqo/HDmpWs3RvhvNINaykGir3F5H86cU20w62QKhapyx+qp +CJB/FY2iq+A3OLFgu4MA0f13SDrGfkhppfjL+CLbGQzWOSy8W4SL6KRegOD6Yg7qvko+2xo1FR6k +Z22yX/q5tg2X0lJIXUxKcISucvfy3UXzuGjL8R29MRn6UmWRV2lmesJ0DucT8d0a0ZgibKi8Fh1S +9aJL3chrpy55kVMcbUzxQKKHwitVsuDT8HhjTVt10mHi75xSX3wlRzKrAf3+3xhZfg0E6upmLTBx +ow6hbxXmKD591jku3b1uTeVLZj1aPJLg07dNAH7JVsdFtnRG0dAOQ43dk2RH5pSPET79hTz1jWm0 +E8lKwqaaV8uZuYVCQw4QdxY1uqftqQ3ZF+yNgqCDmPAKyIHNJbK6aqVXI0c+aZnAl0ghTaZB5t4u +Qqp0pOBh23w+IX1B/1m4MRp6tCNdHZ5SCVCnZ2QrStd0IHhCZEfSpcV5UyWt+Dhne/g2VewEkOc0 +Mi6NE7tqnuQJI923LTBnp1n3PcHuYvLIOJ7GQ/1YMPvnSun2NZoOjvILdi987dzjq65jEuX3rG+D +8wD7pGDXTX7vL5F0Ji+1rA8dCa7HzA5N3k5hk2YS3tITT0LAdyBFV7VxT6t7JgZKz+RtNz/gSsN4 +/CFlAQx27SmcIyAVImuiUiROmWIRrKDUyWHgkPdibxf6Pk267PpLLQqJ1WXkqqvwlm7K8E3U+MkF +MHhoYwBwSYoAYWSe87cHHZG1XLHLZJQPkDCb6phYmWZQaXwtzVl+FndEGC2Yp6A7GoCU7eV84HuY +H818SuSZ9ybWc3nL4D+T8zCdK1YH8h96CaE1ZzNMY27zN/gEP5tyhu6gWThxrWHNwsWAZvY+RMGQ +t644eK6k/quQsdHh5MDzvDfYaa0e/kVbXMJbjwAAQsTbPfpe38OCk7AC5xsx8T/UEB1PFT1OQ962 +hkSEKQeSnQNuPev668z7c71DJvk9ALHMHhrxVwFYhnfMShvd4rFA3gkw6OIro73W4M5yv0o5F2MR +nyfcDfymCtJNdVVS0ipiqap+nVdgF9bGHsd+eZYnk+ext/twiz+/SpjcOyxAfSVdxYc2WPL0bfoc +4/INme2G2naNv7KNwpswnuF226MFf0+Hre+siTDOJpyC7gL1ZQpeocgJ5dXnDN02jDu0gmEFX1i6 +bEa7JXBMDi315gwKbOJJlP9BgrPHiiTYbsyOuZe6TGUirDG6QCNkoSZfz5SNIcaiFf8fswKg2D8F +1ETZcuj7uRrGuSCZe0kT45+RDWaX63JAm7FzcanKeDDXsdaXyJhffKbTYkHjHDj2CUWZvzUCyAnv +sFiclG7z+oT7LTV1q0qkg8atb3Ub+gC/++bCFbWGXXe/PkrKOsraQVMFaQavj/EoloERyD98pkhr +b6+sI84n0zDG8oi4IXM2b6oVl7dNrbfDkqRv1ARRqKAjfHwKe+midxMOqxxLeDbE4Qmx/dNdU2EW +JjmLgWNM5pvXt0NGACKD0ll7MPTPLz2LUTTixq5QFvlNqwrfu4gK9gAUVZwVT259SCjaC0D6P4rD +D5byloovjTHm6lJLXkksRrlNO70KZ6QrHHoDAW+UI0SU2Euhk3knLiIHaIa4JMOBktkS44cS4vNS +uI7DrPYjpmsYQqPrR6vmOEVtUxRd7vioqZivis6Ze2ygzNGM2ZEma6FZWiglnLHsWeu55zpk2Ca0 +7DdBmNr2R1BggMdM/61VPWF/u6wWDe8eha7VuMC//p+aflDQPDvFtKGFbTdWapXC0JXyfqIiyWt7 +IW8mCGhjuCrzv8P2tEYS/183pL/wJGfcIqWfHBGBh5N/J8/s/Osea+g6kXUjnSBJdEJ2P5649nG+ +DFQpvXUUGnzFtOzRbrxyVBqsjWIceIRBuayUg6pyXQLYEDeLG8orTlKEXcHwBJsPWYEcIzj7c+66 +qdfnZ/bqXct4Yq1o3dvEZkFpHRNbtKRZukq3H4xyXAGbtJe49Q+KCp1ymJyWDY6lkyR2aSIRaxmh +siQye6kuolliICj0Acqfnlc6Trmpl/wXXubU/hx/9H4fxdRymNNK+e2iyVP4KsUo0nlru/HZ5U3L +c1wTVKCYJWbvqMWrbOjDaOHyJrw2MlTxyW1leVfTFAtmkt8P4bCpWm2NzjmXQxib3BMizUVB6DjM +7Kxvadc4De8byelbf1mbP3eEKsNrSi9Qc4terUvVJ3/YI1gd8qEMY9QBwan57lJmpiCr7frKpMcX +rx61xkvE/IS6qp1KI4Oj73LFYRQQJDPtVzlh7Va+NuyUSqpIWzCd8eaCxRrLLoVsbsceis21OMoA +AAAAABLnff+ELabaAAGVmQGAwCAvnfX7scRn+wIAAAAABFla diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index f662581e3b..176e222d6d 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -497,6 +497,7 @@ python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' from pathlib import Path import base64 import hashlib +import io import json import re import sys @@ -617,7 +618,9 @@ retained_refs = ( "3f19ad85ad2fa867b978ec009b078eb950ae1b97", "2c5bfc6129723cff130081a66a25986cf18555bc", ) -with tarfile.open(root / "dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.tar.xz", "r:xz") as archive: +fixture = root / "dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.txt" +retained_archive = io.BytesIO(base64.b64decode(fixture.read_bytes())) +with tarfile.open(fileobj=retained_archive, mode="r:xz") as archive: retained_definitions = [] for ref in retained_refs: entry = archive.getmember(f"{ref}.yml") @@ -639,11 +642,12 @@ const canonicalCancellationInventory = JSON.parse(require("node:fs").readFileSyn assert.equal(cancellationInventory.length, 13); assert.deepEqual([...cancellationInventory].sort(), canonicalCancellationInventory.sort(), "bounded cancellation inventory must match all canonical runtime workflow job names"); -const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, - payload: { pull_request: { number: 42, head: { sha: head, ref: "feature", repo: {full_name: "example/firemud"}}, - base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; + const context = { repo: { owner: "example", repo: "firemud" }, sha: merge, + payload: { repository: {default_branch: "develop"}, + pull_request: { number: 42, head: { sha: head, ref: "feature", repo: {full_name: "example/firemud"}}, + base: { ref: "develop", sha: base }, created_at: "2026-09-01T00:00:00Z" } } }; const execute = new Function("github", "context", "core", "Date", "setTimeout", `return (async () => {\n${script}\n})()`); -async function scenario(outcome, completedAtMinutes, selectionCase = "single") { +async function scenario(outcome, completedAtMinutes, selectionCase = "single", typedSmokeConclusion = "success") { let now = 1000; const start = now; const failures = []; @@ -651,20 +655,97 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single") { const listRuns = async () => {}, listJobs = async () => {}; const cancelledSource = runId => ({id: runId, workflow_id: 7, run_attempt: 1, event: "pull_request", status: "completed", conclusion: "cancelled", path: ".github/workflows/runtime-images.yml", + name: "Build Runtime Images", repository: {full_name: "example/firemud"}, + head_repository: {full_name: "example/firemud"}, head_sha: head, head_branch: "feature", + display_title: title, created_at: "2026-09-01T00:00:00Z", + pull_requests: [{number: 42, base: {ref: "develop", sha: base}, head: {sha: head}}]}); + const currentPullRun = (runId, runAttempt, status, conclusion) => ({ + ...cancelledSource(runId), run_attempt: runAttempt, status, conclusion, + }); + const originalRerunComplete = () => selectionCase === "recoverable-original-rerun" && + now - start >= completedAtMinutes * 60 * 1000; + const refreshSource = (runAttempt, status = "completed", conclusion = "success") => ({ + id: 44, workflow_id: 7, run_attempt: runAttempt, event: "repository_dispatch", + status, conclusion, path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images", repository: {full_name: "example/firemud"}, head_repository: {full_name: "example/firemud"}, - head_sha: head, display_title: title}); + head_sha: "d".repeat(40), head_branch: "develop", display_title: title, + created_at: "2026-09-01T00:00:01Z", run_started_at: "2026-09-01T00:00:02Z", + updated_at: status === "completed" ? "2026-09-01T00:30:02Z" : "2026-09-01T00:05:00Z", + pull_requests: [], + }); + const smokeJob = (runId, runAttempt, smokeConclusion) => { + const jobId = runId === 44 ? 144 : runId * 100 + 1; + return {id: jobId, run_id: runId, run_attempt: runAttempt, + head_sha: runId === 44 ? "d".repeat(40) : head, + workflow_name: "Build Runtime Images", name: "PR Full-Stack Smoke (runtime-required=true)", + status: "completed", conclusion: smokeConclusion === "success" ? "success" : "failure", + created_at: "2026-09-01T00:00:01Z", started_at: "2026-09-01T00:00:02Z", + completed_at: "2026-09-01T00:30:02Z", + url: `https://api.github.com/repos/example/firemud/actions/jobs/${jobId}`, + html_url: `https://github.com/example/firemud/actions/runs/${runId}/job/${jobId}`, + check_run_url: `https://api.github.com/repos/example/firemud/check-runs/${jobId}`, + steps: [ + {name: "Set up job", number: 1, status: "completed", conclusion: "success", + started_at: "2026-09-01T00:00:02Z", completed_at: "2026-09-01T00:00:03Z"}, + {name: "Run credential-free full-stack smoke", number: 2, status: "completed", + conclusion: smokeConclusion, started_at: "2026-09-01T00:05:00Z", completed_at: "2026-09-01T00:25:00Z"}, + {name: "Stop smoke stack", number: 3, status: "completed", conclusion: "success", + started_at: "2026-09-01T00:25:00Z", completed_at: "2026-09-01T00:29:00Z"}, + {name: "Known canonical transition PLAY failure with successful authenticated cleanup", number: 4, + status: "completed", conclusion: "skipped", started_at: null, completed_at: null}, + {name: "Export fixed-tag preview image artifact", number: 5, status: "completed", + conclusion: smokeConclusion === "success" ? "success" : "skipped", + started_at: smokeConclusion === "success" ? "2026-09-01T00:29:00Z" : null, + completed_at: smokeConclusion === "success" ? "2026-09-01T00:29:30Z" : null}, + {name: "Upload preview image artifact", number: 6, status: "completed", + conclusion: smokeConclusion === "success" ? "success" : "skipped", + started_at: smokeConclusion === "success" ? "2026-09-01T00:29:30Z" : null, + completed_at: smokeConclusion === "success" ? "2026-09-01T00:29:45Z" : null}, + {name: "Summarize secure PR runtime artifact", number: 7, status: "completed", + conclusion: smokeConclusion === "success" ? "success" : "skipped", + started_at: smokeConclusion === "success" ? "2026-09-01T00:29:45Z" : null, + completed_at: smokeConclusion === "success" ? "2026-09-01T00:29:55Z" : null}, + {name: "Require successful runtime smoke and authenticated cleanup", number: 8, + status: "completed", conclusion: smokeConclusion === "success" ? "success" : "failure", + started_at: "2026-09-01T00:30:00Z", completed_at: "2026-09-01T00:30:01Z"}, + ]}; + }; + const isPreExecutionCancelledRun = runId => { + if (selectionCase === "duplicate") return runId === 42; + if (["cancelled-higher-id", "cancelled-older-success", "cancelled-executed", "cancelled-partial-inventory", + "cancelled-empty-inventory", "cancelled-unknown-outcome", "cancelled-changed-attempt"].includes(selectionCase)) return runId === 43; + if (selectionCase === "recoverable-original-rerun") return runId === 42 && !originalRerunComplete(); + if (selectionCase.startsWith("recoverable-")) return runId === 42; + return runId === 42 && outcome === "cancelled"; + }; const cancellationJobs = runId => { if (selectionCase === "cancelled-empty-inventory") return []; const names = selectionCase === "cancelled-partial-inventory" ? cancellationInventory.slice(1) : cancellationInventory; - return names.map((name, index) => ({id: runId * 100 + index + 1, run_id: runId, - name, - status: "completed", conclusion: selectionCase === "cancelled-unknown-outcome" && index === 0 + return names.map((name, index) => { + const id = runId * 100 + index + 1; + return {id, run_id: runId, run_attempt: 1, head_sha: head, workflow_name: "Build Runtime Images", + name, status: "completed", conclusion: selectionCase === "cancelled-unknown-outcome" && index === 0 ? "failure" : index % 2 === 0 ? "cancelled" : "skipped", - steps: selectionCase === "cancelled-executed" && index === 0 ? [{name: "executed"}] : []})); + created_at: "2026-09-01T00:00:00Z", started_at: null, completed_at: "2026-09-01T00:00:10Z", + html_url: `https://github.com/example/firemud/actions/runs/${runId}/job/${id}`, + check_run_url: `https://api.github.com/repos/example/firemud/check-runs/${id}`, + steps: selectionCase === "cancelled-executed" && index === 0 + ? [{name: "Set up job", number: 1, status: "completed", conclusion: "success", + started_at: "2026-09-01T00:00:02Z", completed_at: "2026-09-01T00:00:03Z"}] + : []}; + }); }; const github = { rest: { pulls: { get: async () => ({ data: { state: "open", head: { sha: head }, base: { ref: "develop", sha: base }, merge_commit_sha: merge } }) }, - repos: { getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }) }, + repos: { + getCommit: async () => ({ data: { sha: merge, parents: [{ sha: base }, { sha: head }] } }), + getContent: async ({path, ref}) => { + assert.equal(path, ".github/workflows/runtime-images.yml"); + assert.ok([merge, "d".repeat(40)].includes(ref), ref); + const bytes = require("node:fs").readFileSync(process.argv[2] + ".producer"); + return {data: {type: "file", path, encoding: "base64", content: bytes.toString("base64"), size: bytes.length}}; + }, + }, git: {getRef: async () => ({data: {ref: "refs/heads/develop", object: {sha: base}}})}, actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs, getWorkflow: async () => ({data: {id: 7, path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images"}}), @@ -672,27 +753,41 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single") { if (run_id === 44) { typedCurrentChecks++; const rerunning = selectionCase === "recoverable-replacement-rerun" && typedCurrentChecks === 1; - return {data: {id: run_id, run_attempt: rerunning || selectionCase === "recoverable-replacement-rerun" ? 2 : 1, - status: rerunning ? "in_progress" : "completed", conclusion: rerunning ? null : "success"}}; + const attempt = rerunning || selectionCase === "recoverable-replacement-rerun" ? 2 : 1; + return {data: refreshSource(attempt, rerunning ? "in_progress" : "completed", + rerunning ? null : typedSmokeConclusion)}; } - return {data: {id: run_id, run_attempt: selectionCase === "cancelled-changed-attempt" ? 2 : 1, - status: "completed", conclusion: "cancelled"}}; + if (run_id === 42 && originalRerunComplete()) { + return {data: currentPullRun(42, 2, "completed", "success")}; + } + return {data: {...cancelledSource(run_id), + run_attempt: selectionCase === "cancelled-changed-attempt" ? 2 : 1}}; } }, }, request: async (route, input) => { assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"); - assert.equal(input.attempt_number, 1); - return {data: cancelledSource(input.run_id)}; + if (input.run_id === 44) { + const attempt = selectionCase === "recoverable-replacement-rerun" && typedCurrentChecks > 0 ? 2 : 1; + assert.equal(input.attempt_number, attempt); + return {data: refreshSource(attempt, "completed", typedSmokeConclusion)}; + } + if (input.run_id === 42 && originalRerunComplete()) { + assert.equal(input.attempt_number, 2); + return {data: currentPullRun(42, 2, "completed", "success")}; + } + assert.equal(input.attempt_number, 1); + return {data: cancelledSource(input.run_id)}; }, paginate: async (method, input) => { if (method === listJobs) { - return [{ id: input.run_id + 100, run_id: input.run_id, name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", - steps: [{ name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success" }] }]; + if (input.run_id === 44) return [smokeJob(44, + selectionCase === "recoverable-replacement-rerun" && typedCurrentChecks > 0 ? 2 : 1, typedSmokeConclusion)]; + if (isPreExecutionCancelledRun(input.run_id)) return cancellationJobs(input.run_id); + const runConclusion = selectionCase === "newer-failure-over-success" && input.run_id === 43 ? "failure" : outcome; + return [smokeJob(input.run_id, originalRerunComplete() && input.run_id === 42 ? 2 : 1, runConclusion)]; } assert.equal(method, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); if (input.run_id === 44) { assert.equal(input.attempt_number, selectionCase === "recoverable-replacement-rerun" && typedCurrentChecks > 0 ? 2 : 1); - return [{id: 144, run_id: 44, run_attempt: input.attempt_number, head_sha: "d".repeat(40), - name: "PR Full-Stack Smoke", status: "completed", conclusion: "success", - steps: [{name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]}]; + return [smokeJob(44, input.attempt_number, typedSmokeConclusion)]; } return cancellationJobs(input.run_id); } }; @@ -704,10 +799,8 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single") { const replacementRerun = selectionCase === "recoverable-replacement-rerun"; const ready = originalRerun || replacementRerun || selectionCase === "recoverable-delayed" && now - start >= 6 * 60 * 1000; const waiting = originalRerun && now === start; - yield {data: ready ? [{id: 44, workflow_id: 7, run_attempt: replacementRerun && typedCurrentChecks > 0 ? 2 : 1, event: "repository_dispatch", - head_sha: "d".repeat(40), head_branch: "develop", display_title: title, - status: waiting ? "queued" : "completed", conclusion: waiting ? null : originalRerun ? "failure" : "success", - created_at: "2026-09-01T00:00:01Z"}] : []}; + yield {data: ready ? [refreshSource(replacementRerun && typedCurrentChecks > 0 ? 2 : 1, + waiting ? "queued" : "completed", waiting ? null : originalRerun ? "failure" : typedSmokeConclusion)] : []}; return; } assert.equal(input.head_sha, head); @@ -817,6 +910,10 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single") { const replacementRerun = await scenario("cancelled", 0, "recoverable-replacement-rerun"); assert.deepEqual(replacementRerun.failures, [], "a stale ordinary typed attempt must poll again and use the current one"); assert.ok(replacementRerun.minutes > 0, "the first passing jobs snapshot belonged to an attempt that was no longer current"); + const failedCurrentTypedSmoke = await scenario("cancelled", 0, "recoverable-replacement-rerun", "failure"); + assert.equal(failedCurrentTypedSmoke.failures.length, 1, + "a current typed refresh with a failed full-stack smoke step must not be accepted as ordinary proof"); + assert.match(failedCurrentTypedSmoke.failures[0], /did not complete successfully|did not expose a terminal PR Full-Stack Smoke job and smoke step/); const lateCancellation = await scenario("cancelled", 80, "recoverable-missing"); assert.equal(lateCancellation.minutes, 90, "late cancellation cannot extend global deadline"); assert.match(lateCancellation.failures[0], /Timed out waiting for the exact/); @@ -873,20 +970,49 @@ async function scenario(kind, event = "pull_request") { base: {ref: "develop", sha: base}, created_at: "2026-09-01T00:00:00Z"}, }}; const source = {id: 42, workflow_id: 7, run_attempt: 1, repository: {full_name: repository}, - created_at: "2026-09-01T00:00:00Z", + created_at: "2026-09-01T00:00:00Z", run_started_at: "2026-09-01T00:00:01Z", + updated_at: "2026-09-01T00:30:01Z", head_repository: {full_name: repository}, path: ".github/workflows/runtime-images.yml", - event, head_sha: event === "pull_request" ? head : defaultSha, head_branch: "develop", display_title: title, - status: "completed", conclusion: "success", pull_requests: []}; + name: "Build Runtime Images", event, head_sha: event === "pull_request" ? head : defaultSha, + head_branch: event === "pull_request" ? "feature" : "develop", display_title: title, + status: "completed", conclusion: "success", + pull_requests: event === "pull_request" ? [{number: 42, base: {ref: "develop", sha: base}, head: {sha: head}}] : []}; const job = {id: 100, run_id: 42, run_attempt: 1, head_sha: source.head_sha, + workflow_name: "Build Runtime Images", created_at: "2026-09-01T00:00:00Z", + started_at: "2026-09-01T00:00:01Z", completed_at: "2026-09-01T00:30:01Z", + url: `https://api.github.com/repos/${repository}/actions/jobs/100`, + html_url: `https://github.com/${repository}/actions/runs/42/job/100`, check_run_url: `https://api.github.com/repos/${repository}/check-runs/100`, name: "PR Full-Stack Smoke (runtime-required=true)", status: "completed", conclusion: "success", - steps: [{name: "Known canonical transition PLAY failure with successful authenticated cleanup", status: "completed", conclusion: "skipped"}]}; + steps: [ + {name: "Known canonical transition PLAY failure with successful authenticated cleanup", number: 1, + status: "completed", conclusion: "skipped", started_at: null, completed_at: null}, + {name: "Run credential-free full-stack smoke", number: 2, status: "completed", conclusion: "success", + started_at: "2026-09-01T00:05:00Z", completed_at: "2026-09-01T00:25:00Z"}, + {name: "Stop smoke stack", number: 3, status: "completed", conclusion: "success", + started_at: "2026-09-01T00:25:00Z", completed_at: "2026-09-01T00:29:00Z"}, + {name: "Export fixed-tag preview image artifact", number: 4, status: "completed", conclusion: "success", + started_at: "2026-09-01T00:29:00Z", completed_at: "2026-09-01T00:29:30Z"}, + {name: "Upload preview image artifact", number: 5, status: "completed", conclusion: "success", + started_at: "2026-09-01T00:29:30Z", completed_at: "2026-09-01T00:29:45Z"}, + {name: "Summarize secure PR runtime artifact", number: 6, status: "completed", conclusion: "success", + started_at: "2026-09-01T00:29:45Z", completed_at: "2026-09-01T00:29:55Z"}, + {name: "Require successful runtime smoke and authenticated cleanup", number: 7, status: "completed", + conclusion: "success", started_at: "2026-09-01T00:30:00Z", completed_at: "2026-09-01T00:30:01Z"}, + ]}; if (kind === "marker-missing") job.steps = []; if (kind === "marker-success") job.steps[0].conclusion = "success"; if (kind.startsWith("legacy")) job.name = "PR Full-Stack Smoke"; + if (kind === "legacy-missing") job.steps = []; if (kind === "not-required") job.name = "PR Full-Stack Smoke (runtime-required=false)"; if (kind === "step-skipped") job.steps = [{name: "Run credential-free full-stack smoke", status: "completed", conclusion: "skipped"}]; if (kind === "legacy-positive") job.steps = [{name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]; + if (kind === "failed-smoke-step") { + source.conclusion = job.conclusion = job.steps[1].conclusion = "failure"; + job.steps[1].conclusion = "failure"; + job.steps[3].conclusion = job.steps[4].conclusion = job.steps[5].conclusion = "skipped"; + job.steps[6].conclusion = "failure"; + } const sourceMutations = { "wrong-repository": {repository: {full_name: "other/repo"}}, "wrong-workflow": {workflow_id: 8}, "wrong-path": {path: ".github/workflows/fake.yml"}, @@ -927,10 +1053,11 @@ async function scenario(kind, event = "pull_request") { assert.equal(input.run_id, 42); assert.equal(input.attempt_number, 1); const mutations = { "wrong-job": {id: 101}, "wrong-job-run": {run_id: 43}, "wrong-job-attempt": {run_attempt: 2}, - "wrong-job-head": {head_sha: defaultSha}, "wrong-check-url": {check_run_url: "https://example.com/check"}, + "wrong-job-head": {head_sha: "e".repeat(40)}, "wrong-check-url": {check_run_url: "https://example.com/check"}, "failed-job": {conclusion: "failure"}, "pending-job": {status: "in_progress", conclusion: null}, }; - return kind === "duplicate-attempt-jobs" ? [job, {...job, id: 101}] : [{...job, ...(mutations[kind] || {})}]; + return ["duplicate-jobs", "duplicate-attempt-jobs"].includes(kind) + ? [job, {...job, id: 101}] : [{...job, ...(mutations[kind] || {})}]; }}; github.paginate.iterator = async function* (method, input) { assert.equal(method, listRuns); @@ -948,14 +1075,16 @@ async function scenario(kind, event = "pull_request") { for (const event of ["pull_request", "repository_dispatch"]) { const success = await scenario("success", event); assert.deepEqual(success.failures, []); - assert.deepEqual(success.refs, [event === "pull_request" ? merge : defaultSha], "immutable definition must come from actual source event revision"); + assert.deepEqual(success.refs, event === "pull_request" ? [] : [defaultSha], + "typed refresh definition must come from its current source revision; native PR proof remains step-based"); } assert.deepEqual((await scenario("legacy-positive")).failures, []); for (const kind of ["marker-missing", "marker-success", "legacy-missing", "not-required", "step-skipped", "wrong-repository", "wrong-workflow", - "wrong-path", "wrong-event", "wrong-head", "wrong-head-repository", "wrong-title", "wrong-source-attempt", - "changed-definition", "unavailable-definition", "wrong-job", "wrong-job-run", "wrong-job-attempt", "wrong-job-head", - "wrong-check-url", "failed-job", "pending-job", "duplicate-jobs", "duplicate-attempt-jobs", "newer-attempt", "bad-parents"]) { - assert.equal((await scenario(kind)).failures.length, 1, `${kind} must not supply successful proof`); + "wrong-path", "wrong-event", "wrong-head", "wrong-head-repository", "wrong-title", "wrong-source-attempt", "failed-smoke-step", + "changed-definition", "unavailable-definition", "wrong-job", "wrong-job-run", "wrong-job-attempt", "wrong-job-head", + "wrong-check-url", "failed-job", "pending-job", "duplicate-jobs", "duplicate-attempt-jobs", "newer-attempt", "bad-parents"]) { + assert.equal((await scenario(kind, "repository_dispatch")).failures.length, 1, + `${kind} must not supply successful current typed refresh proof`); } assert.equal((await scenario("wrong-dispatch-branch", "repository_dispatch")).failures.length, 1); const stale = await scenario("stale-final"); @@ -3569,7 +3698,7 @@ for (const [declaration] of icons) { assert.equal(statusIcon("skipped"), "⏭️"); } const bytes = fs.readFileSync(process.argv[2] + ".producer"); -const start = script.indexOf("function isSuccessfulRuntimeWorkflowDefinition("); +const start = script.indexOf("function isRuntimeSourceWorkflowPath("); const end = script.indexOf("// Commit objects", start); const fn = script.slice(start, end); const workflowPath = ".github/workflows/runtime-images.yml"; @@ -3661,16 +3790,25 @@ async function verify(mutate = () => {}, event = "pull_request", knownPlay = tru return accepted; } // Final attempt authority remains separate from PR identity and label authority. +class TerminalGitHubRequestError extends Error {} +const retryHelpersStart = script.indexOf("function isRetryableGitHubStatus("); +const retryHelpersEnd = script.indexOf("async function withTransientGitHubRetry(", retryHelpersStart); +const transientCodeList = script.match(/const transientTransportCodes = new Set\(\[([\s\S]*?)\]\);/); +assert.ok(retryHelpersStart >= 0 && retryHelpersEnd > retryHelpersStart && transientCodeList); +const transientTransportCodes = [...transientCodeList[1].matchAll(/"([^"]+)"/g)].map(match => match[1]); +const isTransientGitHubFailure = new Function("TerminalGitHubRequestError", "retryableStatuses", "transientTransportCodes", + `${script.slice(retryHelpersStart, retryHelpersEnd)}; return isTransientGitHubFailure;`)( + TerminalGitHubRequestError, new Set([408, 425, 429]), new Set(transientTransportCodes)); async function finalAttemptCheck(latest, error = null) { const start = script.indexOf("async function isCurrentCanonicalAttempt("); const end = script.indexOf("async function verifyFailedPullCanonicalRefresh(", start); const check = new Function("github", "withTransientGitHubRetry", "owner", "repo", - "TerminalGitHubRequestError", "retryableStatuses", "core", + "TerminalGitHubRequestError", "retryableStatuses", "isTransientGitHubFailure", "core", `${script.slice(start, end)}; return isCurrentCanonicalAttempt;`)( {rest: {actions: {getWorkflowRun: async ({run_id}) => { assert.equal(run_id, 99); if (error) throw error; return {data: latest}; }}}}, (_label, call) => call(), "benhook1013", "FireMUD", TerminalGitHubRequestError, - new Set([408, 425, 429, 500, 502, 503, 504]), {warning: () => {}}); + new Set([408, 425, 429]), isTransientGitHubFailure, {warning: () => {}}); return check({id: 99, run_attempt: 2, conclusion: "success"}); } assert.ok(script.includes("const refreshDiscoveryTimeoutMs = prerequisiteAndQueueAllowanceMinutes * 60 * 1000;")); @@ -3740,7 +3878,6 @@ async function recoveredFailure(options = {}, selectedRun = null, selectedIdenti const failedStart = script.indexOf('// A continued probe'); const failedEnd = script.indexOf('if (fullSmokeJob?.conclusion !== "success")', failedStart); const failedBranch = script.slice(failedStart, failedEnd); -class TerminalGitHubRequestError extends Error {} async function failedProof(error, event = "pull_request") { const warnings = [], failures = [], outputs = []; const core = {warning: value => warnings.push(value), setFailed: value => failures.push(value), @@ -4069,7 +4206,7 @@ function markerAccepted(overrides = {}) { const currentAttempt = {id: 99, run_attempt: 2, status: "completed", conclusion: "success"}; assert.equal(await finalAttemptCheck(currentAttempt), true); assert.equal(await finalAttemptCheck(null, Object.assign(new Error("temporary"), {status: 502})), false); - assert.equal(await finalAttemptCheck(null, new Error("network")), false); + assert.equal(await finalAttemptCheck(null, Object.assign(new Error("network"), {code: "ECONNRESET"})), false); const denied = new TerminalGitHubRequestError("denied"); await assert.rejects(finalAttemptCheck(null, denied), error => error === denied); const missing = Object.assign(new Error("missing"), {status: 404}); @@ -4184,6 +4321,12 @@ function markerAccepted(overrides = {}) { data.definitions[workflowPath].content = Buffer.from("wrong immutable producer").toString("base64"); data.definitions[workflowPath].size = Buffer.byteLength("wrong immutable producer"); }})).accepted, false, "an untrusted typed run must fail before waiting for omitted jobs"); + for (const suffix of ["@develop", "@refs/heads/develop"]) { + assert.equal(await verify(data => { data.source.path = workflowPath + suffix; }, "repository_dispatch", false), true); + } + for (const path of [workflowPath + "@refs/heads/a..b", workflowPath + "@refs/tags/develop", ".github/workflows/other.yml@develop"]) { + assert.equal(await verify(data => { data.source.path = path; }, "repository_dispatch", false), false); + } const marker = "Known canonical transition PLAY failure with successful authenticated cleanup"; const ordinary = candidate.steps.map(step => step.name === marker ? {...step, conclusion: "skipped"} : {...step}); @@ -4499,7 +4642,8 @@ async function run(kind, shared = {visible: false, posts: 0}) { if (kind === "nested-callback") event.event = "workflow_run"; if (kind === "fork") event.head_repository.full_name = "fork/repo"; if (kind === "success") event.conclusion = "success"; - let clock = 0, tupleReads = 0, sourceReads = 0, metadataReads = 0, ciInventoryReads = 0, refreshInventoryReads = 0; + const startClock = Date.parse(source.created_at); + let clock = startClock, tupleReads = 0, sourceReads = 0, metadataReads = 0, ciInventoryReads = 0, refreshInventoryReads = 0; const github = {rest: { actions: { getWorkflow: async ({workflow_id}) => ({data: workflow_id === "ci.yml" @@ -4516,7 +4660,7 @@ async function run(kind, shared = {visible: false, posts: 0}) { sourceReads++; return {data: {...source, ...((kind === "stale-attempt" || kind === "late-rerun" && sourceReads > 1) ? {run_attempt: 2} : {})}}; }, - listWorkflowRuns: async ({workflow_id, page, event: runEvent}) => { + listWorkflowRuns: async ({workflow_id, page, event: runEvent, created}) => { if (workflow_id === "ci.yml") ciInventoryReads++; let runs = workflow_id === "ci.yml" ? [{...ci, ...(kind === "ci-pending" ? {status: "in_progress"} : {})}] : shared.visible ? [refresh] : []; @@ -4547,7 +4691,7 @@ async function run(kind, shared = {visible: false, posts: 0}) { } if (kind === "post-read-forbidden") throw Object.assign(new Error("visibility forbidden"), {status: 403}); if (kind === "post-read-incomplete") return {data: {total_count: 1, workflow_runs: []}}; - if (kind === "ambiguous-visible" && clock >= 5000) { + if (kind === "ambiguous-visible" && clock - startClock >= 5000) { shared.visible = true; runs = [refresh]; } @@ -4555,6 +4699,12 @@ async function run(kind, shared = {visible: false, posts: 0}) { if (workflow_id === "runtime-images.yml" && runEvent === "repository_dispatch" && kind === "second-page") { runs = Array.from({length: 100}, (_, i) => ({...refresh, id: 1000 + i, display_title: "unrelated"})).concat(refresh); } + if (created !== undefined) { + assert.match(created, /^>=/); + const floor = Date.parse(created.slice(2)); + assert(Number.isFinite(floor)); + runs = runs.filter(run => Date.parse(run.created_at) >= floor); + } return {data: {total_count: kind === "incomplete" ? 1001 : kind === "at-cap" ? 1000 : runs.length, workflow_runs: runs.slice((page - 1) * 100, page * 100)}}; }, }, @@ -4570,6 +4720,7 @@ async function run(kind, shared = {visible: false, posts: 0}) { assert.deepEqual(request, {owner: "example", repo: "firemud", event_type: "pr-runtime-base-refresh", client_payload: {pr_number: "42", base_ref: "develop", base_sha: base, head_sha: head, merge_sha: merge}}); shared.posts++; + refresh.created_at = new Date(clock).toISOString(); if (["ambiguous-post", "ambiguous-visible"].includes(kind)) throw new Error("unknown POST outcome"); if (kind === "rejected-post") throw Object.assign(new Error("validation rejected"), {status: 422, response: {status: 422}}); if (kind !== "invisible") shared.visible = true; diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 2cc9cc1832..81098068f0 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -897,7 +897,7 @@ async function runDispatcher({ branchHeads = {}, branchErrors = {}, pullOverrides = {}, mergeParents = {}, ciEvidence = {}, hideDispatchVisibility = false, filesByPr = {}, postFailurePr = null, previewFailurePr = null, visibilityResponse = null, filesFailurePr = null, postFailureVisible = false, postFailureStatus = null, - fanoutCutoffAfterInventory = false, fanoutCutoffAfterPreviewPr = null, + fanoutCutoffAfterInventory = false, fanoutCutoffAfterPreviewPr = null, expireAfterFirstApiRequest = false, }) { const dispatches = []; const postedRuns = []; @@ -908,7 +908,11 @@ async function runDispatcher({ const inventoryCalls = []; const observationPostCounts = []; const timerPostCounts = []; + const deadlineSignals = []; + const apiRequestRecords = []; let waitedMillis = 0; + let fakeNow = Date.parse("2026-01-08T00:00:00Z"); + let expireOnFirstRequest = expireAfterFirstApiRequest; const currentBaseSha = tuples[0]?.baseSha ?? baseSha; const allTuples = [...tuples, ...sourceTuples]; const tupleByNumber = new Map(allTuples.map((tuple) => [tuple.prNumber, tuple])); @@ -953,10 +957,32 @@ async function runDispatcher({ error: (message) => errors.push(message), setFailed: (message) => errors.push(message), }; + const recordApiRequest = (name, options, oneShot = false) => { + assert(options && typeof options === "object", `${name} must receive request options`); + assert(options.request && typeof options.request === "object", `${name} must receive a deadline request signal`); + assert.deepEqual(Object.keys(options.request).sort(), oneShot ? ["retries", "signal"] : ["signal"], + `${name} must preserve the exact normal/request option shape`); + if (oneShot) assert.equal(options.request.retries, 0, `${name} must disable transport retries`); + assert(deadlineSignals.includes(options.request.signal), `${name} must use the actual extracted deadline helper`); + assert(Number.isSafeInteger(options.request.signal.timeoutMs) && options.request.signal.timeoutMs > 0, + `${name} must receive a positive remaining wall-clock deadline`); + apiRequestRecords.push({name, options, abortedAtIssue: options.request.signal.aborted}); + if (expireOnFirstRequest) { + expireOnFirstRequest = false; + fakeNow += options.request.signal.timeoutMs; + assert.equal(options.request.signal.aborted, true, `${name} mock must observe its wall-clock AbortSignal deadline`); + const error = new Error("mock request aborted at its wall-clock deadline"); + error.name = "TimeoutError"; + throw error; + } + return options.request.signal; + }; const github = { rest: { git: { - getRef: async ({ ref }) => { + getRef: async (request) => { + recordApiRequest("git.getRef", request); + const {ref} = request; refRequests.push(ref); const branchError = typeof branchErrors[ref] === "function" ? branchErrors[ref](refRequests.length) : branchErrors[ref]; if (branchError) throw Object.assign(new Error("fixture branch lookup failed"), { status: branchError }); @@ -968,12 +994,15 @@ async function runDispatcher({ }, pulls: { list: async (request) => { + recordApiRequest("pulls.list", request); pullListRequests.push(request); return { data: (request.head ? sourceTuples : tuples) .filter((tuple) => request.head || tuple.baseRef === request.base) .map(pullRequestFor) }; }, - get: async ({ pull_number }) => { + get: async (request) => { + recordApiRequest("pulls.get", request); + const {pull_number} = request; const number = String(pull_number); const reads = (pullReads.get(number) ?? 0) + 1; pullReads.set(number, reads); @@ -983,18 +1012,23 @@ async function runDispatcher({ ...(typeof override === "function" ? override(reads) : override ?? {}), } }; }, - listFiles: async ({ pull_number }) => { + listFiles: async (request) => { + recordApiRequest("pulls.listFiles", request); + const {pull_number} = request; if (String(pull_number) === filesFailurePr) throw new Error("fixture changed-files lookup failed"); return { data: filesByPr[String(pull_number)] ?? [{ filename: "services/example/src/Main.java" }] }; }, }, repos: { - getCommit: async ({ ref }) => { + getCommit: async (request) => { + recordApiRequest("repos.getCommit", request); + const {ref} = request; const tuple = allTuples.find((candidate) => candidate.mergeSha === ref); return { data: { sha: ref, parents: (mergeParents[ref] ?? [tuple.baseSha, tuple.headSha]) .map((parent) => ({ sha: parent })) } }; }, createDispatchEvent: async (request) => { + recordApiRequest("repos.createDispatchEvent", request, true); dispatches.push(request); if (request.event_type === "preview-deploy" && request.client_payload.pr_number === previewFailurePr) { throw new Error("ambiguous preview POST timeout"); @@ -1008,7 +1042,8 @@ async function runDispatcher({ prNumber: payload.pr_number, baseSha: payload.base_sha, headSha: payload.head_sha, mergeSha: payload.merge_sha, }, "repository_dispatch", "queued", null, { - id: 900000 + postedRuns.length, created_at: "2026-01-08T00:00:00Z", + id: 900000 + postedRuns.length, + created_at: new FakeDate(fakeNow + 1000).toISOString(), })); } if (ambiguousRuntimePost) { @@ -1022,17 +1057,23 @@ async function runDispatcher({ }, }, actions: { - getWorkflow: async ({workflow_id}) => ({ data: workflow_id === "runtime-images.yml" - ? {id: 701, path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images"} - : {id: ciRun.workflow_id, path: ".github/workflows/ci.yml", name: "CI — Validation", ...(ciEvidence.workflow ?? {})} }), - getWorkflowRun: async () => { + getWorkflow: async (request) => { + recordApiRequest("actions.getWorkflow", request); + const {workflow_id} = request; + return { data: workflow_id === "runtime-images.yml" + ? {id: 701, path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images"} + : {id: ciRun.workflow_id, path: ".github/workflows/ci.yml", name: "CI — Validation", ...(ciEvidence.workflow ?? {})} }; + }, + getWorkflowRun: async (request) => { + recordApiRequest("actions.getWorkflowRun", request); ciRunReads += 1; return { data: { ...ciRun, ...(ciEvidence.run ?? {}), ...(ciRunReads > 1 ? ciEvidence.latest ?? {} : {}) } }; }, listWorkflowRuns: async (request) => { + recordApiRequest("actions.listWorkflowRuns", request); inventoryCalls.push(request); observationPostCounts.push(dispatches.filter(item => item.event_type === "pr-runtime-base-refresh").length); - if (visibilityResponse && request.created === "2026-01-07T23:59:59.000Z..*") { + if (visibilityResponse && request.created === "2026-01-08T00:00:00.000Z..*") { assert.equal(request.event, "repository_dispatch"); const response = visibilityResponse(request, postedRuns); if (response) return {data: response}; @@ -1077,6 +1118,7 @@ async function runDispatcher({ paginate: async (endpoint, request, map) => { if (typeof endpoint === "string") { assert.equal(endpoint, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); + recordApiRequest("paginate.jobs", request); ciJobRequests.push(request); return ciEvidence.jobs ?? [ciGate]; } @@ -1092,25 +1134,65 @@ async function runDispatcher({ }; const originalDateNow = Date.now; const originalSetTimeout = global.setTimeout; - let fakeNow = Date.parse("2026-01-08T00:00:00Z"); + const FakeDate = class extends Date { + constructor(...args) { super(...(args.length ? args : [fakeNow])); } + static now() { return fakeNow; } + }; + const DeadlineAbortSignal = { + timeout(milliseconds) { + assert(Number.isSafeInteger(milliseconds) && milliseconds > 0, "AbortSignal.timeout must receive positive remaining wall time"); + const signal = { + timeoutMs: milliseconds, + deadline: fakeNow + milliseconds, + get aborted() { return fakeNow >= this.deadline; }, + }; + deadlineSignals.push(signal); + return signal; + }, + }; global.setTimeout = (resolve, millis) => { timerPostCounts.push(dispatches.filter(item => item.event_type === "pr-runtime-base-refresh").length); - waitedMillis += millis; fakeNow += millis; resolve(); + waitedMillis += millis; + fakeNow += millis; + resolve(); }; Date.now = () => fakeNow; + let fatalError = null; try { - await new AsyncFunction("github", "context", "core", dispatcherScript)(github, context, core); + await new AsyncFunction("github", "context", "core", "Date", "AbortSignal", "setTimeout", dispatcherScript)( + github, context, core, FakeDate, DeadlineAbortSignal, global.setTimeout, + ); + } catch (error) { + if (!expireAfterFirstApiRequest) throw error; + fatalError = error; } finally { Date.now = originalDateNow; global.setTimeout = originalSetTimeout; } - return { dispatches, errors, infos, warnings, inventoryCalls, observationPostCounts, timerPostCounts, waitedMillis, ciJobRequests, pullListRequests, refRequests }; + return { dispatches, errors, infos, warnings, inventoryCalls, observationPostCounts, timerPostCounts, waitedMillis, + ciJobRequests, pullListRequests, refRequests, deadlineSignals, apiRequestRecords, fatalError }; } (async () => { const tuple = tupleFor(101, "a", "c"); const runtimeDispatches = (result) => result.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh"); const previewDispatches = (result) => result.dispatches.filter((item) => item.event_type === "preview-deploy"); + const assertRequestContracts = (result) => { + assert.equal(result.fatalError, null, "the mocked dispatcher must complete unless a deadline-abort fixture is selected"); + for (const {name, options} of result.apiRequestRecords) { + const request = options.request; + const oneShot = name === "repos.createDispatchEvent"; + assert.deepEqual(Object.keys(request).sort(), oneShot ? ["retries", "signal"] : ["signal"], + `${name} must retain its exact request-options shape`); + assert(oneShot ? request.retries === 0 : !Object.hasOwn(request, "retries"), + `${name} must be one-shot only for dispatch POSTs`); + assert(result.deadlineSignals.includes(request.signal), `${name} must use a source-derived AbortSignal timeout`); + assert(Number.isSafeInteger(request.signal.timeoutMs) && request.signal.timeoutMs > 0, + `${name} must receive a positive remaining wall-clock deadline`); + assert.equal(result.apiRequestRecords.find((call) => call.name === name && call.options === options).abortedAtIssue, + false, `${name} must not issue a request with an already-expired signal`); + } + }; const source = { ...tuple, headRef: "feature/parent" }; const child = { ...tupleFor(102, "d", "e", source.headSha), baseRef: source.headRef }; const prCallback = { event: "pull_request", head_branch: source.headRef, head_sha: source.headSha }; @@ -1125,8 +1207,13 @@ async function runDispatcher({ head_sha: candidate.headSha, merge_sha: candidate.mergeSha, }, "CI callback may dispatch only the independently verified exact source or dependent tuple"); } - assert.deepEqual(reconcile.ciJobRequests, [{ owner: "owner", repo: "repo", run_id: 7001, attempt_number: 1, per_page: 100 }], - "PR callbacks require exact current native CI attempt jobs"); + assert.equal(reconcile.ciJobRequests.length, 1, "PR callbacks require one exact current native CI attempt jobs request"); + const {request: ciJobRequestOptions, ...ciJobRequest} = reconcile.ciJobRequests[0]; + assert.deepEqual(ciJobRequest, { owner: "owner", repo: "repo", run_id: 7001, attempt_number: 1, per_page: 100 }, + "PR callbacks require the exact current native CI attempt jobs request shape"); + assert.deepEqual(Object.keys(ciJobRequestOptions).sort(), ["signal"], "CI job listing carries only its AbortSignal request option"); + assert.equal(reconcile.deadlineSignals[0].timeoutMs, 12 * 60 * 1000, "the first fan-out API call receives the full wall-clock budget"); + assertRequestContracts(reconcile); for (const branch of ["main", "develop", "feature/parent"]) { const branchSource = { ...source, headRef: branch, baseRef: branch === "develop" ? "main" : "develop" }; const dependent = { ...child, baseRef: branch }; @@ -1291,7 +1378,6 @@ async function runDispatcher({ "main", "refs/heads/feature]/test", "refs/heads/feature/@/test", - "refs/heads/feature./test", ]) { const refSuffixedPath = await runDispatcher({ tuples: [tuple], @@ -1302,7 +1388,7 @@ async function runDispatcher({ assert.equal(refSuffixedPath.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 0, `the exact owning workflow path with valid Git ref ${validRef} must remain eligible`); } - for (const invalidRef of ["@", "refs/heads/trailing.", "refs/heads/feature[/test"]) { + for (const invalidRef of ["@", "refs/heads/trailing.", "refs/heads/feature./test", "refs/heads/feature[/test"]) { const invalidRefPath = await runDispatcher({ tuples: [tuple], inventories: { pull_request: [producer(tuple, "pull_request", "in_progress", null, { @@ -1404,11 +1490,21 @@ async function runDispatcher({ inventories: { pull_request: [producer(tuple, "pull_request", "in_progress")] }, }); assert.deepEqual(numbers(existingFirst), ["102"], "existing first PR must not starve second"); - assert.equal(existingFirst.errors.length, 0); + assert.equal(existingFirst.errors.length, 0, existingFirst.errors.join("\n")); const skippedFirst = await runDispatcher({ tuples: [tuple, sibling], filesByPr: { "101": [{ filename: "README.md" }] }, }); assert.deepEqual(numbers(skippedFirst), ["102"], "non-runtime first PR must not starve second"); + const requestDeadlineAbort = await runDispatcher({tuples: [tuple], expireAfterFirstApiRequest: true}); + assert.equal(requestDeadlineAbort.fatalError?.name, "TimeoutError", + "a request crossing its actual AbortSignal deadline must surface the mocked timeout"); + assert.equal(requestDeadlineAbort.apiRequestRecords.length, 1, + "wall-clock expiry must stop further GitHub API requests"); + assert.equal(requestDeadlineAbort.apiRequestRecords[0].name, "git.getRef"); + assert.equal(requestDeadlineAbort.apiRequestRecords[0].options.request.signal.timeoutMs, 12 * 60 * 1000); + assert.equal(requestDeadlineAbort.apiRequestRecords[0].options.request.signal.aborted, true, + "the API mock observes the signal expiring as its wall clock advances to the deadline"); + assert.equal(requestDeadlineAbort.dispatches.length, 0, "deadline abort must fail closed before any handoff"); const failedPost = await runDispatcher({ tuples: [tuple, sibling], postFailurePr: "101" }); assert.deepEqual(numbers(failedPost), ["101", "102"], "ambiguous first POST must not retry or starve second"); assert(failedPost.warnings.some(message => message.includes("ambiguous POST timeout")), @@ -1435,8 +1531,13 @@ async function runDispatcher({ const cutoffBeforePost = await runDispatcher({tuples: [tuple], fanoutCutoffAfterInventory: true}); assert.deepEqual(numbers(cutoffBeforePost), [], "the twelve-minute reservation cutoff prevents a new runtime POST"); assert(cutoffBeforePost.errors.some(message => message.includes("fan-out cutoff") && - message.includes("before the runtime POST for PR #101") && message.includes("#101 remain incomplete")), - "a necessary target stopped before its POST is explicitly reported incomplete"); + message.includes("during runtime tuple proof") && message.includes("#101 remain incomplete")), + `a necessary target stopped before its POST is explicitly reported incomplete: ${cutoffBeforePost.errors.join("; ")}`); + assertRequestContracts(cutoffBeforePost); + assert(cutoffBeforePost.apiRequestRecords.some(({name}) => name === "actions.listWorkflowRuns"), + "deadline fixture must issue and observe its bounded inventory request before cutoff"); + assert(!cutoffBeforePost.apiRequestRecords.some(({name}) => name === "repos.createDispatchEvent"), + "an expired fan-out deadline must prevent the runtime POST from reaching the API mock"); const cutoffAtBoundary = await runDispatcher({ tuples: [{...tuple, labels: [{name: "preview:priority"}]}, sibling], fanoutCutoffAfterPreviewPr: "101", @@ -1447,7 +1548,7 @@ async function runDispatcher({ assert(cutoffAtBoundary.errors.some(message => message.includes("fan-out cutoff") && message.includes("at a target boundary") && message.includes("#102 remain incomplete"))); assert(cutoffAtBoundary.inventoryCalls.some((request, index) => - request.created === "2026-01-07T23:59:59.000Z..*" && cutoffAtBoundary.observationPostCounts[index] === 1), + request.created === "2026-01-08T00:00:00.000Z..*" && cutoffAtBoundary.observationPostCounts[index] === 1), "runtime handoffs sent before cutoff are still observed"); assert(!cutoffAtBoundary.errors.some(message => message.includes("visibility is unknown"))); const transientFirst = await runDispatcher({ @@ -1569,9 +1670,9 @@ async function runDispatcher({ ], "one timeout must identify every invisible handoff"); assert.equal(manyInvisible.timerPostCounts[0], 12, "all runtime POSTs precede the first visibility wait"); assert.equal(manyInvisible.waitedMillis, 120000, "fan-out shares exactly one visibility window"); - const visibilityFloor = "2026-01-07T23:59:59.000Z..*"; + const visibilityFloor = "2026-01-08T00:00:00.000Z..*"; const observations = manyInvisible.inventoryCalls.filter(request => request.created === visibilityFloor); - assert.equal(observations.length, 25, "each five-second observation queries one narrow dispatch page"); + assert.equal(observations.length, 24, "each five-second interval before the deadline queries one narrow dispatch page"); assert(observations.every(request => request.event === "repository_dispatch" && request.page === 1 && request.per_page === 100)); assert(manyInvisible.inventoryCalls.some(request => request.event === "pull_request" && request.created !== visibilityFloor), "broad preflight still checks native producers"); @@ -3039,6 +3140,11 @@ function dispatchRun(id, base, head, merge) { event: "repository_dispatch", run_attempt: 1, head_sha: base, + head_branch: "develop", + workflow_id: 7, + path: id === 602 ? ".github/workflows/runtime-images.yml@develop" : ".github/workflows/runtime-images.yml", + repository: {full_name: "owner/repo"}, + head_repository: {full_name: "owner/repo"}, }; } @@ -3053,6 +3159,7 @@ const context = { repo: { owner: "owner", repo: "repo" }, sha: mergeSha, payload: { + repository: {full_name: "owner/repo", default_branch: "develop"}, pull_request: { number: 42, created_at: "2026-09-01T00:00:00Z", @@ -3069,6 +3176,12 @@ const jobQueries = []; let repositoryDispatchQueryCount = 0; let onRepositoryDispatchQuery = null; const github = { + request: async (route, {run_id, attempt_number}) => { + if (route !== "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}") throw new Error("unexpected exact run lookup"); + const result = availableRuns.find(row => row.id === run_id && row.run_attempt === attempt_number); + if (!result) throw new Error("missing exact run attempt"); + return {data: result}; + }, rest: { pulls: { get: async () => ({ @@ -3087,6 +3200,13 @@ const github = { }, }, repos: { + getContent: async ({path, ref}) => { + if (path !== ".github/workflows/runtime-images.yml" || !availableRuns.some(row => row.event === "repository_dispatch" && row.head_sha === ref)) { + throw new Error("typed runtime proof must pin its executed workflow definition"); + } + const bytes = fs.readFileSync(path); + return {data: {type: "file", path, size: bytes.length, encoding: "base64", content: bytes.toString("base64")}}; + }, getCommit: async ({ ref }) => { requestedCommitRefs.push(ref); return { @@ -3098,6 +3218,7 @@ const github = { }, }, actions: { listWorkflowRuns, listJobsForWorkflowRun, + getWorkflow: async ({workflow_id}) => ({data: {id: workflow_id, path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images"}}), getWorkflowRun: async ({run_id}) => ({data: availableRuns.find(run => run.id === run_id)}), }, }, @@ -3106,8 +3227,11 @@ const github = { method === "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs") { jobQueries.push(input); const run = availableRuns.find(row => row.id === input.run_id); + const typed = run?.event === "repository_dispatch"; return [{ - name: "PR Full-Stack Smoke", + id: 881, + name: typed ? "PR Full-Stack Smoke (runtime-required=true)" : "PR Full-Stack Smoke", + check_run_url: "https://api.github.com/repos/owner/repo/check-runs/881", run_id: input.run_id, run_attempt: input.attempt_number, head_sha: run?.head_sha, @@ -3117,7 +3241,11 @@ const github = { name: "Run credential-free full-stack smoke", status: "completed", conclusion: smokeStepConclusion, - }], + }, ...(typed ? [ + {name: "Known canonical transition PLAY failure with successful authenticated cleanup", status: "completed", conclusion: "skipped"}, + {name: "Stop smoke stack", status: "completed", conclusion: "success"}, + {name: "Require successful runtime smoke and authenticated cleanup", status: "completed", conclusion: "success"}, + ] : [])], }]; } throw new Error("unexpected paginated method"); @@ -3272,7 +3400,7 @@ checkPartialPaginationRetry().then(checkIdentityQuotaFailures).then(() => { if (dispatchQuery.created !== "2026-09-01T00:00:00Z..*" || Object.hasOwn(dispatchQuery, "head_sha")) { throw new Error("same-anchor replacement lookup must be bounded to PR-created dispatch runs without head-SHA assumptions"); } - if (jobQueries.length !== jobStart + 1 || jobQueries.at(-1).run_id !== 602) { + if (jobQueries.length !== jobStart + 2 || !jobQueries.slice(jobStart).every(query => query.run_id === 602 && query.attempt_number === 1)) { throw new Error("Smoke Gate must wait for and validate the exact dispatch replacement smoke job"); } if (currentBaseLookups <= currentBaseLookupStart) { @@ -3417,7 +3545,7 @@ checkPartialPaginationRetry().then(checkIdentityQuotaFailures).then(() => { if (requestedCommitRefs.at(-1) !== currentMergeSha) { throw new Error("dispatch fallback must verify the exact current PR merge commit"); } - if (jobQueries.length !== jobStart + 1 || jobQueries.at(-1).run_id !== 501) { + if (jobQueries.length !== jobStart + 2 || !jobQueries.slice(jobStart).every(query => query.run_id === 501 && query.attempt_number === 1)) { throw new Error("Smoke Gate must accept only the successful smoke run for the current tuple"); } }); @@ -3432,12 +3560,12 @@ checkPartialPaginationRetry().then(checkIdentityQuotaFailures).then(() => { availableRuns = [dispatchRun(506, liveBaseSha, headSha, currentMergeSha)]; const jobStart = jobQueries.length; await check("success", false); - if (jobQueries.length !== jobStart + 1 || jobQueries.at(-1).run_id !== 506) { + if (jobQueries.length !== jobStart + 2 || !jobQueries.slice(jobStart).every(query => query.run_id === 506 && query.attempt_number === 1)) { throw new Error("missing event merge must require exact current typed refresh proof"); } currentMergeParents = [{ sha: headSha }, { sha: liveBaseSha }]; await check("success", true, "Timed out waiting for the exact runtime-images/full-smoke run"); - if (jobQueries.length !== jobStart + 1) { + if (jobQueries.length !== jobStart + 2) { throw new Error("missing event merge must reject reversed current parents"); } currentMergeParents = [{ sha: liveBaseSha }, { sha: headSha }]; diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 803550a80f..d91dc8c98d 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -83,8 +83,9 @@ resolver_script="$fixture_dir/resolver.js" dispatch_script="$fixture_dir/dispatch.js" smoke_scope_script="$fixture_dir/runtime-smoke-scope.js" refresh_selector_script="$fixture_dir/runtime-refresh-selector.js" +failed_reconcile_script="$fixture_dir/failed-runtime-reconcile.js" -python3 - "$WORKFLOW" "$RUNTIME_WORKFLOW" "$validation_script" "$publisher_script" "$runtime_script" "$resolver_script" "$dispatch_script" "$smoke_scope_script" "$refresh_selector_script" <<'PY' +python3 - "$WORKFLOW" "$RUNTIME_WORKFLOW" "$validation_script" "$publisher_script" "$runtime_script" "$resolver_script" "$dispatch_script" "$smoke_scope_script" "$refresh_selector_script" "$failed_reconcile_script" <<'PY' import re import sys from pathlib import Path @@ -141,9 +142,18 @@ smoke_scope = next(step for step in image_meta["steps"] if step.get("name") == " Path(sys.argv[8]).write_text(smoke_scope["with"]["script"], encoding="utf-8") refresh_job = runtime_definition["jobs"]["dispatch-pr-base-refreshes"] refresh_script = next(step["with"]["script"] for step in refresh_job["steps"] if "with" in step and "script" in step["with"]) +deadline_start = refresh_script.index("const dispatcherStartedAt = Date.now();") +deadline_end = refresh_script.index("const workflowRun = context.payload.workflow_run;", deadline_start) selector_start = refresh_script.index("const runtimePrefixes = [") selector_end = refresh_script.index("const dependencyBotAuthors = new Set([", selector_start) -Path(sys.argv[9]).write_text(refresh_script[selector_start:selector_end], encoding="utf-8") +Path(sys.argv[9]).write_text( + refresh_script[deadline_start:deadline_end] + refresh_script[selector_start:selector_end], + encoding="utf-8", +) +publisher_definition = yaml.load(workflow, Loader=yaml.BaseLoader) +reconcile_job = publisher_definition["jobs"]["reconcile-failed-pr-runtime"] +reconcile_step = next(step for step in reconcile_job["steps"] if step.get("name") == "Reconcile exact failed original runtime") +Path(sys.argv[10]).write_text(reconcile_step["with"]["script"], encoding="utf-8") handoff = runtime_workflow.split(" dispatch-pr-runtime-publication:\n", 1)[1].split(" smoke-full:\n", 1)[0] for required in ["needs: [image-meta, pr-local-smoke, pr-controller-smoke]", "github.event_name == 'repository_dispatch'", "github.event.action == 'pr-runtime-base-refresh'", "github.ref == format('refs/heads/{0}', github.event.repository.default_branch)", "needs.image-meta.result == 'success'", "needs.pr-local-smoke.result == 'success'", "needs.pr-controller-smoke.result == 'success'", "needs.image-meta.outputs.controller_smoke_required == 'false'", "needs.pr-controller-smoke.result == 'skipped'", "contents: write"]: if required not in handoff: @@ -175,11 +185,12 @@ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; const resolver = new AsyncFunction("github", "context", "core", "Date", "setTimeout", fs.readFileSync(process.argv[2], "utf8")); const dispatch = new AsyncFunction("github", "context", fs.readFileSync(process.argv[3], "utf8")); const smokeScope = new AsyncFunction("github", "context", "core", fs.readFileSync(process.argv[7], "utf8")); -const refreshSelector = new AsyncFunction("github", "context", "core", `${fs.readFileSync(process.argv[8], "utf8")}\nreturn hasRuntimeChange;`); +const refreshSelector = new AsyncFunction("github", "context", "core", "Date", "AbortSignal", + `${fs.readFileSync(process.argv[8], "utf8")}\nreturn hasRuntimeChange;`); const sha = character => character.repeat(40); const title = `Build Runtime Images secure-pr-artifact pr-42 base-${sha("b")} head-${sha("a")} merge-${sha("c")} mode-required`; const repository = { full_name: "benhook1013/FireMUD", default_branch: "develop" }; -const source = { id: 4242, workflow_id: 777, path: ".github/workflows/runtime-images.yml", name: title, display_title: title, event: "repository_dispatch", repository, head_repository: repository, head_branch: "develop", head_sha: sha("b"), status: "completed", conclusion: "success" }; +const source = { id: 4242, workflow_id: 777, run_attempt: 1, path: ".github/workflows/runtime-images.yml", name: title, display_title: title, event: "repository_dispatch", repository, head_repository: repository, head_branch: "develop", head_sha: sha("b"), status: "completed", conclusion: "success" }; const baseContext = { eventName: "repository_dispatch", ref: "refs/heads/develop", repo: {owner: "benhook1013", repo: "FireMUD"}, runId: 4242, payload: { repository, action: "pr-runtime-image-publication", client_payload: { source_run_id: "4242" } } }; async function resolve({ context = baseContext, runs = [source], workflow = { id: 777, name: "Build Runtime Images", path: source.path }, error = false, jobs = [] } = {}) { let reads = 0, clock = 0; @@ -214,15 +225,39 @@ async function smokeDecision(paths) { return outputs.runtime_smoke_required; } const refreshEntries = []; +let refreshNow = Date.parse("2026-01-08T00:00:00Z"); +const refreshDeadline = refreshNow + 12 * 60 * 1000; +const refreshSignals = []; +const refreshRequests = []; const runtimeSelector = refreshSelector( - {rest: {pulls: {listFiles: "listFiles"}}, paginate: async () => refreshEntries}, + {rest: {pulls: {listFiles: "listFiles"}}, paginate: async (_endpoint, request) => { + refreshRequests.push(request); + refreshNow += 250; + return refreshEntries; + }}, {repo: {}, payload: {}}, {warning: () => {}}, + {now: () => refreshNow}, + {timeout: milliseconds => { + const signal = {timeoutMs: milliseconds}; + refreshSignals.push(signal); + return signal; + }}, ); async function refreshDecision(paths) { refreshEntries.splice(0, refreshEntries.length, ...paths.map(filename => ({filename}))); + const requestIndex = refreshRequests.length; + const nowBeforeRequest = refreshNow; const hasRuntimeChange = await runtimeSelector; - return hasRuntimeChange({number: 42, changed_files: refreshEntries.length}); + const result = await hasRuntimeChange({number: 42, changed_files: refreshEntries.length}); + assert.equal(refreshRequests.length, requestIndex + 1, "changed-file selection performs exactly one paginated API request"); + const {request, ...normalOptions} = refreshRequests[requestIndex]; + assert.deepEqual(normalOptions, {pull_number: 42, per_page: 100}, "changed-file request preserves its exact normal option shape"); + assert.deepEqual(Object.keys(request).sort(), ["signal"], "changed-file request has only the source-derived AbortSignal option"); + assert.equal(request.signal, refreshSignals.at(-1)); + assert.equal(request.signal.timeoutMs, refreshDeadline - nowBeforeRequest, + "changed-file request timeout is computed from the remaining actual wall-clock budget"); + return result; } const handoffCondition = runtimeWorkflow.split(" dispatch-pr-runtime-publication:\n")[1].match(/^ if: \$\{\{ (.*) \}\}$/m)[1] .replace(/needs\.([a-z-]+)/g, (_, key) => `needs[${JSON.stringify(key)}]`); @@ -255,6 +290,17 @@ for (const publishable of ["false", "", undefined]) { assert.equal(await smokeDecision([path]), "true", `${path} must continue to require runtime smoke`); assert.equal(await refreshDecision([path]), true, `${path} must continue to select a runtime refresh`); } + const requestCountBeforeDeadline = refreshRequests.length; + const signalCountBeforeDeadline = refreshSignals.length; + refreshNow = refreshDeadline; + const hasRuntimeChange = await runtimeSelector; + await assert.rejects(hasRuntimeChange({number: 42, changed_files: 1}), error => + error.code === "REQUEST_DEADLINE_EXPIRED" && /request not issued/.test(error.message), + "changed-file lookup must fail closed at the actual fan-out wall-clock deadline"); + assert.equal(refreshRequests.length, requestCountBeforeDeadline, + "an expired changed-file deadline must not reach the GitHub API mock"); + assert.equal(refreshSignals.length, signalCountBeforeDeadline, + "an expired deadline must not manufacture an already-expired AbortSignal"); let dispatched; await dispatch({rest: {repos: {createDispatchEvent: async payload => {dispatched = payload;}}}}, baseContext); assert.deepEqual(dispatched, {...baseContext.repo, event_type: "pr-runtime-image-publication", client_payload: {source_run_id: "4242"}}); @@ -317,6 +363,210 @@ for (const publishable of ["false", "", undefined]) { })().catch(error => { console.error(error); process.exitCode = 1; }); JS +# Execute the actual failed-source reconciler with mocked GitHub APIs. The clock +# and AbortSignal mocks preserve its wall-clock semantics without network access. +node - "$failed_reconcile_script" <<'JS' +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; +const reconcile = new AsyncFunction( + "github", "context", "core", "Date", "AbortSignal", "setTimeout", + fs.readFileSync(process.argv[2], "utf8"), +); +const sha = letter => letter.repeat(40); +const repository = "benhook1013/FireMUD"; +const owner = "benhook1013"; +const repo = "FireMUD"; +const base = sha("b"); +const head = sha("a"); +const merge = sha("c"); +const sourceTitle = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; +const ciTitle = `CI — Validation pr-42 base-${base} head-${head}`; +const source = { + id: 4242, workflow_id: 777, run_attempt: 1, path: ".github/workflows/runtime-images.yml", + name: "Build Runtime Images", display_title: sourceTitle, event: "pull_request", + status: "completed", conclusion: "failure", repository: {full_name: repository}, + head_repository: {full_name: repository}, head_sha: head, head_branch: "feature/ci", + created_at: "2026-01-01T00:00:00Z", +}; +const ciRun = { + id: 7001, workflow_id: 778, run_attempt: 1, path: ".github/workflows/ci.yml", + name: "CI — Validation", display_title: ciTitle, event: "pull_request", status: "completed", + conclusion: "success", repository: {full_name: repository}, head_repository: {full_name: repository}, + head_sha: head, head_branch: "feature/ci", +}; +const pullRequest = { + number: 42, state: "open", head: {sha: head, ref: "feature/ci", repo: {full_name: repository}}, + base: {ref: "develop", repo: {full_name: repository}}, mergeable: true, merge_commit_sha: merge, +}; +const gate = { + id: 8001, run_id: ciRun.id, run_attempt: ciRun.run_attempt, head_sha: head, + workflow_name: "CI — Validation", name: "Validation Gate", status: "completed", conclusion: "success", + check_run_url: `https://api.github.com/repos/${repository}/check-runs/8001`, + steps: [ + {name: "Preserve successful required gate on metadata-only edit", status: "completed", conclusion: "skipped"}, + {name: "Enforce validation success", status: "completed", conclusion: "success"}, + ], +}; + +async function runReconcile({ambiguousPost = true, expireFirstRequest = false} = {}) { + let now = Date.parse("2026-01-08T00:00:00Z"); + let expire = expireFirstRequest; + let visibleRun = null; + let postAttempts = 0; + const requests = []; + const signals = []; + const dispatchRequests = []; + const warnings = []; + const infos = []; + class FixtureDate extends Date { + constructor(...args) { super(...(args.length ? args : [now])); } + static now() { return now; } + } + const timeoutSignals = { + timeout(milliseconds) { + assert(Number.isSafeInteger(milliseconds) && milliseconds > 0, + "AbortSignal.timeout must receive positive remaining wall-clock time"); + const expiresAt = now + milliseconds; + const signal = {timeoutMs: milliseconds, get aborted() { return now >= expiresAt; }}; + signals.push(signal); + return signal; + }, + }; + const record = (name, options, expectedNormal, oneShot = false) => { + assert(options && typeof options === "object", `${name} must receive its normal request object`); + const {request, ...normal} = options; + assert.deepEqual(normal, expectedNormal, `${name} must preserve its exact normal request shape`); + assert(request && typeof request === "object", `${name} must receive the AbortSignal request option`); + assert.deepEqual(Object.keys(request).sort(), oneShot ? ["retries", "signal"] : ["signal"], + `${name} must preserve its exact request-option shape`); + if (oneShot) assert.equal(request.retries, 0, "repository dispatch must explicitly disable transport retries"); + assert(signals.includes(request.signal), `${name} must use the source-derived wall-clock AbortSignal`); + assert(Number.isSafeInteger(request.signal.timeoutMs) && request.signal.timeoutMs > 0, + `${name} must use a positive remaining deadline`); + assert.equal(request.signal.aborted, false, `${name} must not be issued with an already-expired signal`); + requests.push({name, options, signal: request.signal}); + if (expire) { + expire = false; + now += request.signal.timeoutMs; + assert.equal(request.signal.aborted, true, "API mock must observe AbortSignal expiry as wall time advances"); + const error = new Error("mocked API request aborted at its deadline"); + error.name = "TimeoutError"; + throw error; + } + return request.signal; + }; + const context = { + eventName: "workflow_run", + repo: {owner, repo}, + payload: { + repository: {full_name: repository, default_branch: "develop"}, + workflow_run: source, + }, + }; + const github = { + rest: { + actions: { + getWorkflow: async options => { + const workflowId = options.workflow_id; + record("actions.getWorkflow", options, {owner, repo, workflow_id: workflowId}); + return {data: workflowId === "runtime-images.yml" + ? {id: 777, path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images"} + : {id: 778, path: ".github/workflows/ci.yml", name: "CI — Validation"}}; + }, + getWorkflowRun: async options => { + record("actions.getWorkflowRun", options, {owner, repo, run_id: options.run_id}); + return {data: options.run_id === source.id ? source : ciRun}; + }, + listWorkflowRuns: async options => { + const {workflow_id: workflowId, event, head_sha: requestedHead, created, per_page, page} = options; + const normal = {owner, repo, workflow_id: workflowId, event, per_page, page}; + if (requestedHead !== undefined) normal.head_sha = requestedHead; + if (created !== undefined) normal.created = created; + record("actions.listWorkflowRuns", options, normal); + let runs = []; + if (workflowId === "ci.yml") runs = [ciRun]; + if (workflowId === "runtime-images.yml" && event === "repository_dispatch" && visibleRun) runs = [visibleRun]; + return {data: {total_count: runs.length, workflow_runs: runs}}; + }, + }, + pulls: { + get: async options => { + record("pulls.get", options, {owner, repo, pull_number: 42}); + return {data: pullRequest}; + }, + }, + git: { + getRef: async options => { + record("git.getRef", options, {owner, repo, ref: "heads/develop"}); + return {data: {ref: "refs/heads/develop", object: {sha: base}}}; + }, + }, + repos: { + getCommit: async options => { + record("repos.getCommit", options, {owner, repo, ref: merge}); + return {data: {sha: merge, parents: [{sha: base}, {sha: head}]}}; + }, + createDispatchEvent: async options => { + record("repos.createDispatchEvent", options, { + owner, repo, event_type: "pr-runtime-base-refresh", + client_payload: {pr_number: "42", base_ref: "develop", base_sha: base, head_sha: head, merge_sha: merge}, + }, true); + postAttempts += 1; + dispatchRequests.push(options); + now += 1000; + visibleRun = { + id: 9001, workflow_id: 777, run_attempt: 1, + path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images", + display_title: sourceTitle, event: "repository_dispatch", status: "queued", conclusion: null, + repository: {full_name: repository}, head_repository: {full_name: repository}, + head_branch: "develop", head_sha: base, created_at: new FixtureDate().toISOString(), + }; + if (ambiguousPost) throw new Error("simulated ambiguous dispatch response"); + }, + }, + }, + paginate: async (route, options) => { + assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); + record("paginate.jobs", options, {owner, repo, run_id: ciRun.id, attempt_number: 1, per_page: 100}); + return [gate]; + }, + }; + let failure = null; + try { + await reconcile(github, context, {warning: message => warnings.push(message), info: message => infos.push(message)}, + FixtureDate, timeoutSignals, (resolve, milliseconds) => { now += milliseconds; resolve(); }); + } catch (error) { + failure = error; + } + return {failure, now, requests, signals, dispatchRequests, postAttempts, warnings, infos}; +} + +(async () => { + const uncertainPost = await runReconcile(); + assert.equal(uncertainPost.failure, null, "visible exact refresh reconciles an ambiguous response"); + assert.equal(uncertainPost.postAttempts, 1, "an uncertain repository dispatch POST is never retransmitted"); + assert.equal(uncertainPost.dispatchRequests.length, 1); + assert.equal(uncertainPost.dispatchRequests[0].request.retries, 0, + "the production one-shot request explicitly disables Octokit retries"); + assert(uncertainPost.warnings.some(message => message.includes("no retry issued") && message.includes("ambiguous dispatch response"))); + assert(uncertainPost.infos.some(message => message.includes("exact refresh is visible"))); + assert(uncertainPost.requests.some(({name}) => name === "actions.listWorkflowRuns"), + "the one-shot handoff must be followed by source-derived visibility observation"); + assert(uncertainPost.requests.every(({signal}) => signal.timeoutMs > 0), + "every mocked GitHub request receives a positive wall-clock AbortSignal budget"); + const expiredRequest = await runReconcile({expireFirstRequest: true}); + assert.equal(expiredRequest.failure?.name, "TimeoutError", "request abortion at the wall-clock deadline remains visible"); + assert.equal(expiredRequest.requests.length, 1, "deadline abortion prevents subsequent GitHub API requests"); + assert.equal(expiredRequest.requests[0].name, "actions.getWorkflow"); + assert.equal(expiredRequest.requests[0].signal.timeoutMs, 120000, + "the reconciler starts with its exact two-minute pre-dispatch wall-clock budget"); + assert.equal(expiredRequest.requests[0].signal.aborted, true, "the API mock observed the signal expire"); + assert.equal(expiredRequest.postAttempts, 0, "deadline abortion fails closed before repository dispatch"); + process.stdout.write("Failed-source reconciliation deadline and one-shot fixtures passed\n"); +})().catch(error => { console.error(error); process.exitCode = 1; }); +JS + artifact_root="$fixture_dir/artifacts" fake_bin="$fixture_dir/bin" mkdir -p "$fake_bin" @@ -746,7 +996,6 @@ for valid_ref in \ "refs/heads/develop" \ "refs/heads/feature]/test" \ "refs/heads/feature/@/test" \ - "refs/heads/feature./test" \ "$head_sha"; do set_source_run_path ".github/workflows/runtime-images.yml@$valid_ref" run_validation || { @@ -762,6 +1011,7 @@ for invalid_path in \ '.github/workflows/runtime-images.yml@@' \ '.github/workflows/runtime-images.yml@refs/heads/trailing.' \ '.github/workflows/runtime-images.yml@refs/heads/feature[/test' \ + '.github/workflows/runtime-images.yml@refs/heads/feature./test' \ '.github/workflows/runtime-images.yml@.hidden' \ '.github/workflows/runtime-images.yml@feature/.lock'; do set_source_run_path "$invalid_path" diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index a5822a2b12..027fbd0216 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -662,8 +662,8 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { String snapshotIdentity = "sha256:" + "e".repeat(64); String callerWorkload = "controlled-capacity-fixture"; Instant evaluatedAt = Instant.now().truncatedTo(ChronoUnit.MICROS); - Instant evaluationExpiresAt = evaluatedAt.plusSeconds(30); - Instant reservationExpiresAt = evaluatedAt.plusSeconds(60); + Instant evaluationExpiresAt = evaluatedAt.plusSeconds(60); + Instant reservationExpiresAt = evaluatedAt.plusSeconds(30); Instant reconcileDeadline = reservationExpiresAt.plusSeconds(60); transaction.executeWithoutResult(status -> { dsl.execute( @@ -771,11 +771,135 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { failure -> assertThat(failure.sqlState()).isEqualTo("23514")); assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + String insertedDecision = + "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, refusal_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING"; + assertThat( + dsl.fetchOne( + "SELECT 1 FROM account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", + acceptedTenant.canonicalTenantId())) + .isNull(); + var acceptedAfterMigration = freshAcceptedAttempt(); + transaction.executeWithoutResult(status -> + insertAcceptedCapacityAttempt( + dsl, acceptedTenant.canonicalTenantId(), acceptedAfterMigration, 1, 2)); + assertThat( + dsl.fetchOne( + "SELECT 1 FROM account_capacity_origin_refusal_slots WHERE tenant_uuid = ?", + acceptedTenant.canonicalTenantId())) + .isNull(); + assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + assertTenantCapacityInventoryMatches(dsl, acceptedTenant.canonicalTenantId()); + + var acceptedOriginsBeforeReplay = originRows(dsl, acceptedTenant.canonicalTenantId()); + var acceptedReservationsBeforeReplay = reservationRows(dsl, acceptedTenant.canonicalTenantId()); + var acceptedUsageBeforeReplay = usageRows(dsl, acceptedTenant.canonicalTenantId()); + assertThat(acceptedOriginsBeforeReplay) + .anySatisfy(row -> + assertThat(row) + .containsEntry("request_id", acceptedAfterMigration.requestId()) + .containsEntry("admission_id", acceptedAfterMigration.admissionId()) + .containsEntry("admission_attempt_id", acceptedAfterMigration.attemptId()) + .containsEntry("mutation_digest", acceptedAfterMigration.digest()) + .containsEntry("decision", "ACCEPTED") + .containsEntry( + "payload", java.util.HexFormat.of().formatHex(acceptedAfterMigration.payload()))); + assertThat(acceptedReservationsBeforeReplay) + .anySatisfy(row -> + assertThat(row) + .containsEntry("request_id", acceptedAfterMigration.requestId()) + .containsEntry("admission_id", acceptedAfterMigration.admissionId()) + .containsEntry("admission_attempt_id", acceptedAfterMigration.attemptId()) + .containsEntry("mutation_digest", acceptedAfterMigration.digest()) + .containsEntry("capacity_delta", 1L) + .containsEntry( + "payload", java.util.HexFormat.of().formatHex(acceptedAfterMigration.payload()))); + + assertThat( + dsl.execute( + insertedDecision, + acceptedTenant.canonicalTenantId(), + acceptedAfterMigration.requestId(), + acceptedAfterMigration.admissionId(), + 1L, + acceptedAfterMigration.attemptId(), + acceptedAfterMigration.digest(), + acceptedAfterMigration.payload(), + "ACCEPTED", + UUID.randomUUID(), + null)) + .isZero(); + assertThat(originRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedOriginsBeforeReplay); + assertThat(reservationRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedReservationsBeforeReplay); + assertThat(usageRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedUsageBeforeReplay); + + var rolledBackAccepted = freshAcceptedAttempt(); + transaction.executeWithoutResult(status -> { + insertAcceptedCapacityAttempt( + dsl, acceptedTenant.canonicalTenantId(), rolledBackAccepted, 2, 3); + status.setRollbackOnly(); + }); + assertThat( + dsl.fetchOne( + "SELECT 1 FROM account_capacity_origin_decisions WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + acceptedTenant.canonicalTenantId(), + rolledBackAccepted.requestId(), + rolledBackAccepted.admissionId())) + .isNull(); + assertThat( + dsl.fetchOne( + "SELECT 1 FROM account_tenant_capacity_reservations WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + acceptedTenant.canonicalTenantId(), + rolledBackAccepted.requestId(), + rolledBackAccepted.admissionId())) + .isNull(); + assertThat( + dsl.fetchOne( + "SELECT 1 FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + rolledBackAccepted.evaluationIdentity())) + .isNull(); + assertThat(originRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedOriginsBeforeReplay); + assertThat(reservationRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedReservationsBeforeReplay); + assertThat(usageRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedUsageBeforeReplay); + assertTenantCapacityInventoryMatches(dsl, acceptedTenant.canonicalTenantId()); + + UUID refusedWithoutBudgetRequest = UUID.randomUUID(); + UUID refusedWithoutBudgetAdmission = UUID.randomUUID(); + assertThatThrownBy(() -> + dsl.execute( + insertedDecision, + acceptedTenant.canonicalTenantId(), + refusedWithoutBudgetRequest, + refusedWithoutBudgetAdmission, + 1L, + UUID.randomUUID(), + "7".repeat(64), + new byte[] {24, 25}, + "NO_ACCEPT", + UUID.randomUUID(), + "CAPACITY_QUOTA_EXCEEDED")) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> { + assertThat(failure.sqlState()).isEqualTo("23514"); + assertThat(failure).hasMessageContaining("Capacity refusal budget is unavailable"); + }); + assertThat(originRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedOriginsBeforeReplay); + assertThat(reservationRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedReservationsBeforeReplay); + assertThat(usageRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedUsageBeforeReplay); + assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + transaction.executeWithoutResult(status -> new AccountCapacityRefusalBudgetRepository(dsl) .provision(historicalTenant.canonicalTenantId(), 3)); - String insertedDecision = - "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, refusal_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING"; UUID freshRequest = UUID.randomUUID(); UUID freshAdmission = UUID.randomUUID(); UUID freshAttempt = UUID.randomUUID(); @@ -859,7 +983,7 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { assertThat(failure.sqlState()).isEqualTo("23514"); assertThat(failure).hasMessageContaining("Capacity refusal budget is exhausted"); }); - assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))).isEqualTo(4); + assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))).isEqualTo(5); assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); assertThatThrownBy(() -> @@ -902,6 +1026,136 @@ private static List refusalSlots(org.jooq.DSLContext dsl) { row.get("decision_id", UUID.class))); } + private static AcceptedCapacityAttempt freshAcceptedAttempt() { + UUID requestId = UUID.randomUUID(); + Instant evaluatedAt = Instant.now().truncatedTo(ChronoUnit.MICROS); + Instant evaluationExpiresAt = evaluatedAt.plusSeconds(60); + Instant reservationExpiresAt = evaluatedAt.plusSeconds(30); + return new AcceptedCapacityAttempt( + requestId, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID().toString().replace("-", "").repeat(2), + ("fresh accepted capacity payload " + requestId).getBytes(StandardCharsets.UTF_8), + "sha256:" + UUID.randomUUID().toString().replace("-", "").repeat(2), + "sha256:" + UUID.randomUUID().toString().replace("-", "").repeat(2), + evaluatedAt, + evaluationExpiresAt, + reservationExpiresAt, + reservationExpiresAt.plusSeconds(60)); + } + + private static void insertAcceptedCapacityAttempt( + org.jooq.DSLContext dsl, + UUID tenantUuid, + AcceptedCapacityAttempt attempt, + long expectedHeldUnits, + long newHeldUnits) { + assertThat(attempt.reservationExpiresAt()).isBefore(attempt.evaluationExpiresAt()); + String callerWorkload = "controlled-capacity-fixture"; + 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 (?, ?, ?, ?, 'game-session-service', ?, ?::timestamptz, ?::timestamptz)", + attempt.evaluationIdentity(), + attempt.snapshotIdentity(), + tenantUuid, + callerWorkload, + ("fresh accepted evaluation " + attempt.requestId()).getBytes(StandardCharsets.UTF_8), + AccountTenantCapacityRepository.at(attempt.evaluatedAt()), + AccountTenantCapacityRepository.at(attempt.evaluationExpiresAt())); + assertThat( + dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = ?, usage_revision = ? WHERE tenant_uuid = ? AND owner_service = 'game-session-service' AND held_units = ? AND used_units = 0 AND usage_revision = ?", + newHeldUnits, + newHeldUnits + 1, + tenantUuid, + expectedHeldUnits, + expectedHeldUnits + 1)) + .isEqualTo(1); + assertThat( + 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, refusal_code) VALUES (?, ?, ?, 1, ?, ?, ?, 'ACCEPTED', ?, NULL)", + tenantUuid, + attempt.requestId(), + attempt.admissionId(), + attempt.attemptId(), + attempt.digest(), + attempt.payload(), + attempt.decisionId())) + .isEqualTo(1); + assertThat( + 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, reconcile_deadline, state, execution_status) VALUES (?, ?, ?, ?, 'game-session-service', ?, ?, 1, 1, ?, ?, ?, 1, ?::timestamptz, ?::timestamptz, 'RESERVED', 'OWNER_EXECUTION_PENDING')", + tenantUuid, + attempt.requestId(), + attempt.admissionId(), + attempt.reservationId(), + callerWorkload, + attempt.attemptId(), + attempt.digest(), + attempt.payload(), + attempt.evaluationIdentity(), + AccountTenantCapacityRepository.at(attempt.reservationExpiresAt()), + AccountTenantCapacityRepository.at(attempt.reconcileDeadline()))) + .isEqualTo(1); + } + + private static List> originRows( + org.jooq.DSLContext dsl, UUID tenantUuid) { + return dsl.fetch( + "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM account_capacity_origin_decisions WHERE tenant_uuid = ? ORDER BY decision_id", + tenantUuid) + .intoMaps(); + } + + private static List> reservationRows( + org.jooq.DSLContext dsl, UUID tenantUuid) { + return dsl.fetch( + "SELECT tenant_uuid, request_id, admission_id, reservation_id, owner_service, caller_workload, admission_attempt_id, capacity_rearm_fence, reservation_fence, mutation_digest, encode(canonical_payload, 'hex') AS payload, evaluation_identity, capacity_delta, expires_at, reconcile_deadline, state, execution_status, recovery_owner, recovery_claim_fence, recovery_claim_expires_at, next_reconcile_at, recovery_policy_version, recovery_attempt_count, recovery_escalated_at, encode(owner_readback, 'hex') AS owner_readback, owner_readback_digest, xmin::text AS row_version FROM account_tenant_capacity_reservations WHERE tenant_uuid = ? ORDER BY request_id, admission_id", + tenantUuid) + .intoMaps(); + } + + private static List> usageRows( + org.jooq.DSLContext dsl, UUID tenantUuid) { + return dsl.fetch( + "SELECT tenant_uuid, owner_service, bootstrap_request_id, creation_evidence_digest, held_units, used_units, usage_revision, xmin::text AS row_version FROM account_tenant_capacity_usage WHERE tenant_uuid = ? ORDER BY owner_service", + tenantUuid) + .intoMaps(); + } + + private static void assertTenantCapacityInventoryMatches( + org.jooq.DSLContext dsl, UUID tenantUuid) { + var rows = + dsl.fetch( + "SELECT u.owner_service, u.held_units, u.used_units, COALESCE(sum(r.capacity_delta) FILTER (WHERE r.state IN ('RESERVED', 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION')), 0) AS reservation_held_units, COALESCE(sum(r.capacity_delta) FILTER (WHERE r.state = 'FINALIZED'), 0) AS reservation_used_units FROM account_tenant_capacity_usage u LEFT JOIN account_tenant_capacity_reservations r ON r.tenant_uuid = u.tenant_uuid AND r.owner_service = u.owner_service WHERE u.tenant_uuid = ? GROUP BY u.owner_service, u.held_units, u.used_units ORDER BY u.owner_service", + tenantUuid) + .intoMaps(); + assertThat(rows).hasSize(2); + for (var row : rows) { + assertThat(((Number) row.get("held_units")).longValue()) + .isEqualTo(((Number) row.get("reservation_held_units")).longValue()); + assertThat(((Number) row.get("used_units")).longValue()) + .isEqualTo(((Number) row.get("reservation_used_units")).longValue()); + } + } + + private record AcceptedCapacityAttempt( + UUID requestId, + UUID admissionId, + UUID attemptId, + UUID decisionId, + UUID reservationId, + String digest, + byte[] payload, + String evaluationIdentity, + String snapshotIdentity, + Instant evaluatedAt, + Instant evaluationExpiresAt, + Instant reservationExpiresAt, + Instant reconcileDeadline) {} + private record RefusalSlot(UUID tenantUuid, long slot, UUID decisionId) {} private static Account creator() { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java index beb5dfd8f9..7709b82477 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java @@ -206,7 +206,7 @@ public void ping(PingRequest request, StreamObserver observer) { try { var first = submitCall.apply(startFirst); var second = submitCall.apply(startSecond); - assertThat(selected.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(selected.await(15, TimeUnit.SECONDS)).isTrue(); if (close) { client.close(); assertThatThrownBy(client::requirePublishedExplicitStub) From 27f148231c18f636f0ea603646f85af9698b6e01 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 14:48:37 +1300 Subject: [PATCH 33/96] Verify delayed smoke markers within the exact attempt deadline --- .../workflows/publish-pr-runtime-images.yml | 20 +-- .github/workflows/smoke.yml | 8 +- .../pr-required-gate-context-contract.sh | 133 +++++++++++------- 3 files changed, 96 insertions(+), 65 deletions(-) diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 092e427b9e..6ccda32627 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -440,10 +440,14 @@ jobs: } // Keep the shared lock during observation even when the one POST response was lost. const deadline = Date.now() + 120000; - for (;;) { + while (Date.now() < deadline) { try { - if (await newerRefresh(dispatchStarted, deadline, dispatchStarted)) break; + if (await newerRefresh(dispatchStarted, deadline, dispatchStarted)) { + core.info(`Reconciled failed original runtime for PR #${number}; exact refresh is visible.`); + return; + } } catch (error) { + if (error?.code === "REQUEST_DEADLINE_EXPIRED") break; const status = error?.status ?? error?.response?.status; const code = error?.code ?? error?.cause?.code; const transient = [408, 425, 429, 500, 502, 503, 504].includes(status) || @@ -453,14 +457,14 @@ jobs: if (!transient) throw error; core.warning("Exact refresh visibility read is temporarily unavailable; keep observing without retrying the POST."); } - if (Date.now() >= deadline) { - throw new Error(responseUnknown - ? "Refresh dispatch attempted but visibility is unknown; no retry issued" - : "Refresh dispatch accepted but visibility is unknown; no retry issued"); + const remainingMs = deadline - Date.now(); + if (remainingMs > 0) { + await new Promise(resolve => setTimeout(resolve, Math.min(5000, remainingMs))); } - await new Promise(resolve => setTimeout(resolve, Math.min(5000, deadline - Date.now()))); } - core.info(`Reconciled failed original runtime for PR #${number}; exact refresh is visible.`); + throw new Error(responseUnknown + ? "Refresh dispatch attempted but visibility is unknown; no retry issued" + : "Refresh dispatch accepted but visibility is unknown; no retry issued"); source: name: Resolve Exact Runtime Publication Source diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index a01ec45799..cae8b37ace 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -1817,12 +1817,8 @@ jobs: core.warning(`Canonical smoke producer proof is unavailable: ${error.message}`); } if (canonicalProducerVerified) break; - const markers = (fullSmokeJob.steps ?? []).filter((step) => - step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" - ); - const markerPending = markers.length === 0 || - (markers.length === 1 && markers[0].status !== "completed"); - if (!markerPending && fullSmokeStep?.status === "completed") break; + // The exact-attempt marker check below handles incomplete marker snapshots. + if (fullSmokeStep?.status === "completed") break; } else if (fullSmokeStep?.status === "completed") { // The native pull_request path keeps its existing step-proof behavior. break; diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 176e222d6d..da38e93d1b 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -3702,6 +3702,8 @@ const start = script.indexOf("function isRuntimeSourceWorkflowPath("); const end = script.indexOf("// Commit objects", start); const fn = script.slice(start, end); const workflowPath = ".github/workflows/runtime-images.yml"; +const isRuntimeSourceWorkflowPath = new Function("workflowPath", `${script.slice(start, + script.indexOf("function isSuccessfulRuntimeWorkflowDefinition(", start))}; return isRuntimeSourceWorkflowPath;`)(workflowPath); const repositoryName = "benhook1013/FireMUD"; const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; const canonicalRuntimeWorkflowSha256 = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); @@ -3819,15 +3821,43 @@ const refreshEnd = script.indexOf("// Commit objects", refreshStart); const refreshFunction = script.slice(refreshStart, refreshEnd); async function recoveredFailure(options = {}, selectedRun = null, selectedIdentity = identity, raw = false) { const original = selectedRun ?? {id: 98, event: "pull_request", status: "completed", conclusion: "failure", ...options.original}; - const replacement = options.absent ? null : {id: original.id + 1, run_attempt: 2, event: "repository_dispatch", + const replacement = options.absent ? null : {...source, head_sha: workflowSha, id: original.id + 1, run_attempt: 2, event: "repository_dispatch", status: "completed", conclusion: "success", ...options.replacement}; const selectedTitle = `Build Runtime Images secure-pr-artifact pr-3390 base-${selectedIdentity.baseSha} ` + `head-${selectedIdentity.headSha} merge-${selectedIdentity.mergeSha} mode-required`; const selectedCandidate = {...candidate, run_id: replacement?.id, run_attempt: replacement?.run_attempt, head_sha: workflowSha, conclusion: replacement?.conclusion, ...options.candidate}; let verified = 0, queries = 0; + async function verifyReplacement(selected, job, proofIdentity, knownPlay, allowIncompleteSteps, allowOrdinary) { + if (knownPlay) verified++; + assert.deepEqual(proofIdentity, selectedIdentity); + assert.equal(selected, replacement); + assert.deepEqual(job, options.noProducer ? undefined : selectedCandidate); + return verify(data => { + data.identity = structuredClone(selectedIdentity); + Object.assign(data.run, structuredClone(replacement)); + for (const native of [data.source, data.latest]) Object.assign(native, structuredClone(replacement), { + display_title: selectedTitle, head_sha: workflowSha, + }); + Object.assign(data.candidate, structuredClone(selectedCandidate)); + Object.assign(data.jobs[0], structuredClone(selectedCandidate)); + if (options.noProducer) data.jobs = []; + data.currentPullRequest.head.sha = selectedIdentity.headSha; + data.currentPullRequest.base.ref = selectedIdentity.baseRef; + data.currentPullRequest.merge_commit_sha = selectedIdentity.mergeSha; + data.currentBase = {ref: `refs/heads/${selectedIdentity.baseRef}`, object: {sha: selectedIdentity.baseSha}}; + if (options.legacyProof) { + data.legacyDefinition = true; + for (const job of [data.candidate, data.jobs[0]]) { + for (const step of job.steps) if (failures.includes(step.name)) step.conclusion = "failure"; + } + } + if (options.mutateProof) options.mutateProof(data); + }, "repository_dispatch", knownPlay, allowIncompleteSteps, allowOrdinary); + } const execute = new Function("repositoryName", "prNumber", "positiveInteger", "findMatchingRuntimeImagesRun", - "withTransientGitHubRetry", "github", "owner", "repo", "canonicalSmokeJobName", "verifyKnownPlayFailure", "context", + "withTransientGitHubRetry", "github", "owner", "repo", "canonicalSmokeJobName", "verifyKnownPlayFailure", + "verifyCanonicalSmokeProducer", "context", `${refreshFunction}; return verifyFailedPullCanonicalRefresh;`); const recover = execute(options.repository || repositoryName, "3390", value => Number.isSafeInteger(value) && value > 0, async (event, title, selected) => { @@ -3844,32 +3874,12 @@ async function recoveredFailure(options = {}, selectedRun = null, selectedIdenti }, rest: {actions: {getWorkflowRun: async ({run_id}) => { assert.equal(run_id, replacement.id); return {data: {...replacement, ...options.latest}}; - }}}}, "benhook1013", "FireMUD", canonicalSmokeJobName, async (selected, job, proofIdentity, allowIncompleteSteps, allowOrdinary) => { - verified++; - assert.deepEqual(proofIdentity, selectedIdentity); - assert.equal(selected, replacement); assert.deepEqual(job, options.noProducer ? undefined : selectedCandidate); - return verify(data => { - data.identity = structuredClone(selectedIdentity); - Object.assign(data.run, replacement); - for (const native of [data.source, data.latest]) Object.assign(native, replacement, { - display_title: selectedTitle, head_sha: workflowSha, - }); - Object.assign(data.candidate, structuredClone(selectedCandidate)); - Object.assign(data.jobs[0], structuredClone(selectedCandidate)); - if (options.noProducer) data.jobs = []; - data.currentPullRequest.head.sha = selectedIdentity.headSha; - data.currentPullRequest.base.ref = selectedIdentity.baseRef; - data.currentPullRequest.merge_commit_sha = selectedIdentity.mergeSha; - data.currentBase = {ref: `refs/heads/${selectedIdentity.baseRef}`, object: {sha: selectedIdentity.baseSha}}; - if (options.legacyProof) { - data.legacyDefinition = true; - for (const job of [data.candidate, data.jobs[0]]) { - for (const step of job.steps) if (failures.includes(step.name)) step.conclusion = "failure"; - } - } - if (options.mutateProof) options.mutateProof(data); - }, "repository_dispatch", true, allowIncompleteSteps, allowOrdinary); - }, {payload: {pull_request: {head: {repo: {full_name: options.headRepository || repositoryName}}}}}); + }}}}, "benhook1013", "FireMUD", canonicalSmokeJobName, + (selected, job, proofIdentity, allowIncompleteSteps, allowOrdinary) => + verifyReplacement(selected, job, proofIdentity, true, allowIncompleteSteps, allowOrdinary), + (selected, job, proofIdentity, requireTerminalSmokeProof) => + verifyReplacement(selected, job, proofIdentity, false, requireTerminalSmokeProof), + {payload: {pull_request: {head: {repo: {full_name: options.headRepository || repositoryName}}}}}); const proof = await recover(original, selectedIdentity); return {accepted: raw ? proof : proof?.status === "verified" ? true : proof?.status === "snapshot-pending" ? "snapshot-pending" : proof, verified, queries}; @@ -3958,15 +3968,16 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { core.summary = {addHeading() {return this;}, addRaw() {return this;}, async write() {writes++;}}; const original = {...source, id: 98, event: "pull_request", status: "completed", conclusion: options.originalConclusion || "failure"}; - const execute = new Function("repositoryName", "github", "owner", "repo", + const execute = new Function("repositoryName", "workflowPath", "isRuntimeSourceWorkflowPath", "github", "owner", "repo", "canonicalSmokeJobName", "withTransientGitHubRetry", "verifyKnownPlayFailure", + "verifyCanonicalSmokeProducer", "isTransientGitHubFailure", "verifyFailedPullCanonicalRefresh", "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", "core", "resolveCurrentIdentity", "identityKey", "setTimeout", "sleepMs", "Date", "started", "timeoutMs", "pullRequestCheckInterval", "findMatchingRuntimeImagesRun", "prNumber", "identityDiagnostic", "cancelledReplacementTimeoutMs", "context", - "refreshDiscoveryTimeoutMs", "completedSnapshotTimeoutMs", "positiveInteger", "isCurrentCanonicalAttempt", + "refreshDiscoveryTimeoutMs", "completedSnapshotTimeoutMs", "snapshotSleepMs", "positiveInteger", "isCurrentCanonicalAttempt", `return (async () => { let pollIteration = 0; ${actualPollingLoop} })();`); - await execute(repositoryName, {rest: {actions: {listJobsForWorkflowRun: "jobs"}}, paginate: async () => { + await execute(repositoryName, workflowPath, isRuntimeSourceWorkflowPath, {rest: {actions: {listJobsForWorkflowRun: "jobs"}}, paginate: async () => { if (options.originalError) throw options.originalError; const job = structuredClone(candidate); if (options.ordinaryAfterDrift) job.steps.find(s => s.name.startsWith("Known canonical")).conclusion = "skipped"; @@ -3987,7 +3998,12 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { }, "repository_dispatch"); } return Boolean(options.directProof || (options.recoverDrift && run.event === "repository_dispatch")); - }, + }, async (selected, _job, proofIdentity, required) => { + assert.equal(selected.event, "repository_dispatch"); + assert.equal(required, true); + return Boolean(options.ordinaryAfterDrift && proofIdentity.baseSha === options.finalIdentity.baseSha && + proofIdentity.mergeSha === options.finalIdentity.mergeSha); + }, isTransientGitHubFailure, async (selectedRun, selectedIdentity) => { if (options.directSnapshots && selectedRun.event === "repository_dispatch") return false; assert.equal(selectedRun.id, original.id); @@ -4038,7 +4054,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { return original; }, "3390", "test identity", 60, {payload: {pull_request: {head: {repo: {full_name: options.headRepository || repositoryName}}}}}, - 120, 60, value => Number.isSafeInteger(value) && value > 0, async selected => { + 120, 60, 30, value => Number.isSafeInteger(value) && value > 0, async selected => { finalChecks++; if (!options.directProof && !options.recoverDrift) { assert.equal(selected.id, 99); @@ -4112,18 +4128,23 @@ async function movedCancellation(ordinaryProof, listedOldReplacement = false) { const refresh = {...source, event: "repository_dispatch", status: "completed", conclusion: "success"}; const failures = [], outputs = []; const core = {info() {}, warning() {}, setFailed: x => failures.push(x), setOutput: (...x) => outputs.push(x)}; - const execute = new Function("repositoryName", "workflowPath", "canonicalSmokeJobName", "withTransientGitHubRetry", - "verifyKnownPlayFailure", "isCurrentPullRequestObsolete", "core", "resolveCurrentIdentity", "identityKey", + const execute = new Function("repositoryName", "workflowPath", "isRuntimeSourceWorkflowPath", "canonicalSmokeJobName", "withTransientGitHubRetry", + "verifyKnownPlayFailure", "verifyCanonicalSmokeProducer", "isTransientGitHubFailure", + "isCurrentPullRequestObsolete", "core", "resolveCurrentIdentity", "identityKey", "setTimeout", "sleepMs", "Date", "started", "timeoutMs", "pullRequestCheckInterval", "findMatchingRuntimeImagesRun", "prNumber", "identityDiagnostic", "cancelledReplacementTimeoutMs", "context", "refreshDiscoveryTimeoutMs", "completedSnapshotTimeoutMs", "positiveInteger", "isCurrentCanonicalAttempt", `return (async () => { let pollIteration = 0; ${actualPollingLoop} })();`); - await execute(repositoryName, workflowPath, canonicalSmokeJobName, (_label, call) => call(), + await execute(repositoryName, workflowPath, isRuntimeSourceWorkflowPath, canonicalSmokeJobName, (_label, call) => call(), async (run, candidate, selected, incomplete, ordinary) => { - proofReads++; assert.equal(run, refresh); assert.equal(candidate, null); + assert.equal(run, refresh); assert.equal(candidate, null); assert.deepEqual(selected, moved); assert.equal(incomplete, true); assert.equal(ordinary, true); - return ordinaryProof ? "ordinary" : false; - }, async () => false, core, async (_label, live) => live ? moved : eventIdentity, + return false; + }, async (run, candidate, selected, required) => { + proofReads++; assert.equal(run, refresh); assert.equal(candidate, null); + assert.deepEqual(selected, moved); assert.equal(required, true); + return ordinaryProof; + }, isTransientGitHubFailure, async () => false, core, async (_label, live) => live ? moved : eventIdentity, selected => JSON.stringify(selected), resolve => {now += 10; resolve();}, 10, {now: () => now}, 0, 100, 1, async (event, _title, selected) => { if (event === "pull_request") return old; @@ -4627,12 +4648,14 @@ async function run(kind, shared = {visible: false, posts: 0}) { const wake = kind.startsWith("wake-"); if (wake) kind = kind.slice("wake-".length); const cancelledCase = kind.startsWith("cancel-"); + if (kind === "qualified-runtime") source.path = qualified(runtimePath); const olderCi = cancelledCase && kind !== "cancel-older-failed" ? {...ci, conclusion: "success"} : ci; - const newerCancelled = {...ci, id: 91, conclusion: "cancelled"}; - const refresh = {...source, id: 110, event: "repository_dispatch", head_branch: "develop", head_sha: "d".repeat(40)}; + const newerCancelled = {...ci, id: 91, conclusion: "cancelled", + path: kind === "cancel-qualified" ? qualified(validationPath) : validationPath}; + const refresh = {...source, id: 110, event: "repository_dispatch", head_branch: "develop", head_sha: "d".repeat(40), + created_at: shared.refreshCreatedAt ?? source.created_at}; const event = structuredClone(wake ? newerCancelled : source); event.name = event.display_title; - if (["qualified-runtime", "cancel-qualified"].includes(kind)) event.path = qualified(event.path); if (kind === "malformed-callback-path") event.path += "@refs/heads/a..b"; if (kind === "cancel-wake-wrong-id") event.workflow_id = source.workflow_id; if (kind === "cancel-wake-stale-head") event.head_sha = base; @@ -4648,7 +4671,7 @@ async function run(kind, shared = {visible: false, posts: 0}) { actions: { getWorkflow: async ({workflow_id}) => ({data: workflow_id === "ci.yml" ? {id: 8, path: ".github/workflows/ci.yml", name: "CI — Validation"} - : {id: 7, path: source.path, name: source.name}}), + : {id: 7, path: runtimePath, name: source.name}}), getWorkflowRun: async ({run_id}) => { if (run_id === 91) metadataReads++; if (cancelledCase && run_id === 90) return {data: olderCi}; @@ -4656,6 +4679,8 @@ async function run(kind, shared = {visible: false, posts: 0}) { ...(kind === "cancel-rerun" && metadataReads > 1 ? {run_attempt: 2} : {}), ...(kind === "cancel-native-failure" ? {conclusion: "failure"} : {})}}; if (run_id === 90 || run_id === 91) return {data: {...ci, id: run_id, + ...((run_id === 91 && ["pending-newer", "late-ci-pending"].includes(kind) || run_id === 90 && kind === "ci-pending") + ? {status: "in_progress", conclusion: null} : {}), ...(kind === "ci-rerun" || ["new-meta-rerun", "old-meta-rerun"].includes(kind) && run_id === 91 && metadataReads > 1 ? {run_attempt: 2} : {})}}; sourceReads++; return {data: {...source, ...((kind === "stale-attempt" || kind === "late-rerun" && sourceReads > 1) ? {run_attempt: 2} : {})}}; @@ -4700,8 +4725,9 @@ async function run(kind, shared = {visible: false, posts: 0}) { runs = Array.from({length: 100}, (_, i) => ({...refresh, id: 1000 + i, display_title: "unrelated"})).concat(refresh); } if (created !== undefined) { - assert.match(created, /^>=/); - const floor = Date.parse(created.slice(2)); + const range = /^(.+)\.\.\*$/.exec(created); + assert.ok(range, `expected an open-ended created range, got ${created}`); + const floor = Date.parse(range[1]); assert(Number.isFinite(floor)); runs = runs.filter(run => Date.parse(run.created_at) >= floor); } @@ -4716,11 +4742,13 @@ async function run(kind, shared = {visible: false, posts: 0}) { git: {getRef: async ({ref}) => ({data: {ref: `refs/${kind === "wrong-ref" ? "heads/main" : ref}`, object: {sha: kind === "ref-moved" || kind === "late-drift" && tupleReads > 1 ? head : base}}})}, repos: { getCommit: async () => ({data: {sha: merge, parents: kind === "parents-reversed" ? [{sha: head}, {sha: base}] : [{sha: base}, {sha: head}]}}), - createDispatchEvent: async (request) => { - assert.deepEqual(request, {owner: "example", repo: "firemud", event_type: "pr-runtime-base-refresh", + createDispatchEvent: async ({request, ...payload}) => { + assert.equal(request.retries, 0); + assert.ok(request.signal instanceof AbortSignal && !request.signal.aborted); + assert.deepEqual(payload, {owner: "example", repo: "firemud", event_type: "pr-runtime-base-refresh", client_payload: {pr_number: "42", base_ref: "develop", base_sha: base, head_sha: head, merge_sha: merge}}); shared.posts++; - refresh.created_at = new Date(clock).toISOString(); + shared.refreshCreatedAt = refresh.created_at = new Date(clock + 1000).toISOString(); if (["ambiguous-post", "ambiguous-visible"].includes(kind)) throw new Error("unknown POST outcome"); if (kind === "rejected-post") throw Object.assign(new Error("validation rejected"), {status: 422, response: {status: 422}}); if (kind !== "invisible") shared.visible = true; @@ -4792,7 +4820,10 @@ async function run(kind, shared = {visible: false, posts: 0}) { payload: {workflow_run: event, repository: {full_name: repository, default_branch: "develop"}}}, {info: () => {}, warning: message => { (shared.warnings ??= []).push(message); }, setFailed: message => { shared.failure = message; }}, - class extends Date { static now() { return clock; } }, callback => {clock += 5000; callback();}); + class extends Date { + constructor(...args) { super(...(args.length ? args : [clock])); } + static now() { return clock; } + }, (callback, delay) => {clock += delay; callback();}); if (kind === "merge-unknown") assert.equal(tupleReads, 6, "unresolved mergeability retries are bounded"); if (kind === "merge-pending") assert.equal(tupleReads, 3, "one convergence retry plus final current tuple fence"); return shared.posts; @@ -4856,7 +4887,7 @@ async function run(kind, shared = {visible: false, posts: 0}) { assert.equal(readTransient.observations, 2); assert.equal(readTransient.warnings.length, 1); for (const [scenario, reason, observations] of [ - ["post-read-timeout", /accepted but visibility is unknown/, 25], + ["post-read-timeout", /accepted but visibility is unknown/, 24], ["post-read-forbidden", /visibility forbidden/, 1], ["post-read-incomplete", /inventory is incomplete/, 1], ]) { @@ -4872,7 +4903,7 @@ async function run(kind, shared = {visible: false, posts: 0}) { const ambiguousInvisible = {visible: false, posts: 0}; await assert.rejects(run("ambiguous-post", ambiguousInvisible), /attempted but visibility is unknown/); assert.equal(ambiguousInvisible.posts, 1); - assert.equal(ambiguousInvisible.observations, 25, "ambiguous invisible POST holds lock for the existing bounded observation"); + assert.equal(ambiguousInvisible.observations, 24, "ambiguous invisible POST holds lock for the existing bounded observation"); const ambiguousVisible = {visible: false, posts: 0}; assert.equal(await run("ambiguous-visible", ambiguousVisible), 1); assert.equal(ambiguousVisible.observations, 2, "observe an exact late handoff after losing the POST response"); From 9634d30b99c00dcc53220494c9a1d836f5c88792 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 15:20:21 +1300 Subject: [PATCH 34/96] Finish exact smoke, dispatch, and capacity follow-up findings --- .../workflows/publish-pr-runtime-images.yml | 36 +- .github/workflows/runtime-images.yml | 36 +- .github/workflows/smoke.yml | 88 +- .../trusted-runtime-workflow-definitions.txt | 345 --- ...ca914a699e08c7c47791b80b89ceba2a5104f5.yml | 2149 ++++++++++++++++ ...5bfc6129723cff130081a66a25986cf18555bc.yml | 2118 +++++++++++++++ ...81c438ddf473c94ad0424ad9a979d7070091e4.yml | 2149 ++++++++++++++++ ...19ad85ad2fa867b978ec009b078eb950ae1b97.yml | 2149 ++++++++++++++++ ...4c33d57a6c44c44258bdbfdae6aa3f59b31ecf.yml | 2266 +++++++++++++++++ .../pr-required-gate-context-contract.sh | 82 +- .../tests/pr-retarget-workflow-contract.sh | 31 +- .../pr-runtime-image-publication-contract.sh | 3 +- .../service/AccountTenantCapacityOwner.java | 2 + ...antCreatorBootstrapIntegrationFixture.java | 89 + ...acityMigrationPostgresIntegrationTest.java | 101 +- ...titlementOwnerPostgresIntegrationTest.java | 82 +- .../AccountTenantCapacityOwnerTest.java | 10 +- ...stractReloadingBlockingGrpcClientTest.java | 3 +- .../AccountTenantCapacityClientMtlsTest.java | 102 +- 19 files changed, 11251 insertions(+), 590 deletions(-) delete mode 100644 dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.txt create mode 100644 dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/1eca914a699e08c7c47791b80b89ceba2a5104f5.yml create mode 100644 dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/2c5bfc6129723cff130081a66a25986cf18555bc.yml create mode 100644 dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/3b81c438ddf473c94ad0424ad9a979d7070091e4.yml create mode 100644 dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/3f19ad85ad2fa867b978ec009b078eb950ae1b97.yml create mode 100644 dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/6b4c33d57a6c44c44258bdbfdae6aa3f59b31ecf.yml create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreatorBootstrapIntegrationFixture.java diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 6ccda32627..3986eac19a 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -73,7 +73,7 @@ jobs: return code <= 32 || code === 127 || forbidden.has(character); })) return false; return ref.split("/").every(part => part.length > 0 && !part.startsWith(".") && - !part.endsWith(".") && !part.endsWith(".lock")); + !part.endsWith(".lock")); }; const matchesPath = (path, expected) => { if (path === expected) return true; @@ -374,7 +374,8 @@ jobs: const newerRefresh = async ( createdSince = event.created_at, deadline = prePostDeadline, - strictlyAfter = null + strictlyAfter = null, + previousIds = null ) => { const phase = deadline === prePostDeadline ? "Pre-dispatch" : "Refresh visibility"; const runs = await inventory( @@ -395,15 +396,23 @@ jobs: throw new Error("Exact refresh has an invalid creation timestamp"); } } - // Completed refresh also owns this recovery; never retry a refresh from its completion callback. - // Run timestamps can have second precision, so equality is not post-dispatch visibility proof. - return strictlyAfter === null ? exact.length > 0 : exact.some(run => - Date.parse(run.created_at) > Date.parse(strictlyAfter) - ); + const ids = new Set(runs.map(run => run.id)); + if (strictlyAfter === null) return {found: exact.length > 0, ids}; + if (!(previousIds instanceof Set)) throw new Error("Final pre-dispatch refresh inventory IDs are missing"); + const dispatchTime = Date.parse(strictlyAfter); + if (!Number.isFinite(dispatchTime)) throw new Error("Invalid refresh dispatch timestamp"); + // Run timestamps may have only second precision. Compare from the + // POST's timestamp second and require one exact run absent from the + // final complete pre-POST inventory. + const secondFloor = Math.floor(dispatchTime / 1000) * 1000; + const unseen = exact.filter(run => !previousIds.has(run.id)); + const visible = unseen.filter(run => Date.parse(run.created_at) >= secondFloor); + if (visible.length > 1) throw new Error("Multiple new exact refreshes are visible; dispatch outcome is ambiguous"); + return {found: visible.length === 1, ids}; }; if (typeof event.created_at !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(event.created_at) || !Number.isFinite(Date.parse(event.created_at))) throw new Error("Invalid original run creation timestamp"); - if (await newerRefresh()) return; + if ((await newerRefresh()).found) return; // Re-list the complete exact-tuple CI inventory before the POST: a newer // pending/substantive attempt may have appeared since the first selection. const selectedCi = ci; @@ -413,11 +422,13 @@ jobs: if (!matchesCi(finalCi) || finalCi.conclusion !== ci.conclusion || !await wakeCurrent() || !await sourceCurrent() || await originalSuperseded() || await currentTuple() !== baseRef) return; // Repeat the complete trusted refresh preflight after all current-source fences. // This is the final read before POST, so a late replacement owns recovery. - if (await newerRefresh()) return; + const finalRefreshInventory = await newerRefresh(); + if (finalRefreshInventory.found) return; + const previousRefreshIds = finalRefreshInventory.ids; if (Date.now() >= prePostDeadline) { throw new Error("Pre-dispatch deadline reached; no refresh POST issued and visibility reserve retained"); } - const dispatchStarted = new Date().toISOString(); + const dispatchStarted = new Date(Math.floor(Date.now() / 1000) * 1000).toISOString(); let responseUnknown = false; try { await github.rest.repos.createDispatchEvent(prePostOptions({ @@ -442,7 +453,7 @@ jobs: const deadline = Date.now() + 120000; while (Date.now() < deadline) { try { - if (await newerRefresh(dispatchStarted, deadline, dispatchStarted)) { + if ((await newerRefresh(dispatchStarted, deadline, dispatchStarted, previousRefreshIds)).found) { core.info(`Reconciled failed original runtime for PR #${number}; exact refresh is visible.`); return; } @@ -521,7 +532,7 @@ jobs: character.charCodeAt(0) <= 32 || character.charCodeAt(0) === 127 || "~^:?*[\\".includes(character))) return false; return ref.split("/").every(part => part && part !== "." && part !== ".." && - !part.startsWith(".") && !part.endsWith(".") && !part.endsWith(".lock")); + !part.startsWith(".") && !part.endsWith(".lock")); } const titlePattern = /^Build Runtime Images secure-pr-artifact pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40}) merge-([0-9a-f]{40}) mode-required$/; const deadline = Date.now() + 120000; @@ -701,7 +712,6 @@ jobs: return all( part and part not in {".", ".."} and not part.startswith(".") and - not part.endswith(".") and not part.endswith(".lock") for part in ref.split("/") ) diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index b6caebff94..4930f5c5ac 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -764,7 +764,7 @@ jobs: return code <= 32 || code === 127 || forbidden.has(character); })) return false; return ref.split("/").every(part => part.length > 0 && !part.startsWith(".") && - !part.endsWith(".") && !part.endsWith(".lock")); + !part.endsWith(".lock")); }; const workflowPathMatches = (path, expected = expectedWorkflowPath) => { if (path === expected) { @@ -828,11 +828,14 @@ jobs: return [newest]; } if (newest.status === "completed") { - // A refresh created after this CI completed already owns this callback's recovery. - // A later substantive CI signal may still recover publication from an older producer. + // Same-second or incomparable completion evidence is ambiguous and + // suppresses a duplicate; only a valid, strictly older producer may recover. const ciCompleted = Date.parse(workflowRun.updated_at || ""); - if (newest.event === "repository_dispatch" && Number.isFinite(ciCompleted) && - Date.parse(newest.created_at) > ciCompleted) return [newest]; + if (newest.event === "repository_dispatch" && + (!Number.isFinite(ciCompleted) || + Math.floor(Date.parse(newest.created_at) / 1000) >= Math.floor(ciCompleted / 1000))) { + return [newest]; + } return []; } throw new Error(`run ${newest.id} has an unknown status and cannot be classified`); @@ -1102,7 +1105,10 @@ jobs: break; } const previousIds = new Set(inventory?.runs?.map(run => run.id) || []); - const dispatchSince = new Date().toISOString(); + // Actions run timestamps may omit sub-second precision. Inventory + // from the start of this second so a handoff created in the POST's + // timestamp second remains observable. + const dispatchSince = new Date(Math.floor(Date.now() / 1000) * 1000).toISOString(); const pending = {tuple, previousIds, dispatchSince, responseUnknown: false}; visibilitySince ??= dispatchSince; pendingVisibility.push(pending); @@ -1231,21 +1237,27 @@ jobs: for (let index = pendingVisibility.length - 1; index >= 0; index--) { const {tuple, previousIds, dispatchSince, responseUnknown} = pendingVisibility[index]; const exactTitle = `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; - // Equal second-granularity timestamps cannot prove the run followed this POST. - const freshExactRuns = observed.runs.filter(run => run.event === "repository_dispatch" && - run.display_title === exactTitle && !previousIds.has(run.id) && - validTimestamp(run.created_at) && Date.parse(run.created_at) > Date.parse(dispatchSince)); - for (const run of freshExactRuns) { + // The floor includes this POST's second; the complete pre-POST ID + // snapshot distinguishes new candidates from already-visible runs. + const unseenExactRuns = observed.runs.filter(run => run.event === "repository_dispatch" && + run.display_title === exactTitle && !previousIds.has(run.id)); + for (const run of unseenExactRuns) { if (!Number.isSafeInteger(run.id) || run.id <= 0 || run.workflow_id !== runtimeWorkflow.id || !workflowPathMatches(run.path) || ![runtimeWorkflow.name, exactTitle].includes(run.name) || run.repository?.full_name !== expectedRepository || run.head_repository?.full_name !== expectedRepository || run.head_branch !== defaultBranch || - typeof run.head_sha !== "string" || !/^[0-9a-f]{40}$/.test(run.head_sha)) { + typeof run.head_sha !== "string" || !/^[0-9a-f]{40}$/.test(run.head_sha) || + !validTimestamp(run.created_at)) { throw new Error(`run ${run.id} has the exact PR tuple title but untrusted native workflow identity`); } } + const dispatchSecond = Math.floor(Date.parse(dispatchSince) / 1000) * 1000; + const freshExactRuns = unseenExactRuns.filter(run => Date.parse(run.created_at) >= dispatchSecond); + if (freshExactRuns.length > 1) { + throw new Error(`multiple new exact runtime handoffs are visible for PR #${tuple.prNumber}`); + } if (freshExactRuns.length > 0) { pendingVisibility.splice(index, 1); if (responseUnknown) core.info(`Runtime refresh for PR #${tuple.prNumber} became visible after an unknown POST response.`); diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index cae8b37ace..73e4976816 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -632,7 +632,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "71b6f3cf41d6cc5369b84a8ae1c8b026e201709b634ea6ba53aa28a29343c0d8"; + const canonicalRuntimeWorkflowSha256 = "e86f75e3220be624f1644b8368c66b7165b98fba9905142f107819d926db8055"; // Only authenticated default-branch refreshes may use retained successful definitions. // Keep the pre-rollout default and predecessor definitions for mixed-version runs. const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set([ @@ -762,9 +762,14 @@ jobs: if (typeof value !== "string" || !value.startsWith(prefix)) return false; const rawRef = value.slice(prefix.length); const ref = rawRef.startsWith("refs/heads/") ? rawRef.slice("refs/heads/".length) : rawRef; + const forbiddenRefCharacters = new Set(["~", "^", ":", "?", "*", "[", "\\"]); return (!rawRef.startsWith("refs/") || rawRef.startsWith("refs/heads/")) && - /^[A-Za-z0-9_][A-Za-z0-9_.\/-]{0,254}$/.test(ref) && - !ref.includes("..") && !ref.endsWith(".") && + rawRef !== "@" && ref.length > 0 && ref.length <= 255 && !ref.startsWith("-") && + !ref.includes("..") && !ref.includes("@{") && !ref.endsWith(".") && + !Array.from(ref).some((character) => { + const code = character.charCodeAt(0); + return code <= 0x20 || code === 0x7f || forbiddenRefCharacters.has(character); + }) && ref.split("/").every(part => part && !part.startsWith(".") && !part.endsWith(".lock")); } @@ -874,6 +879,30 @@ jobs: latest.status === "completed" && latest.conclusion === "success"; } + function hasPendingCanonicalSmokeTerminalEvidence(job) { + if (!job || job.status !== "completed" || !Array.isArray(job.steps)) return true; + const markerName = "Known canonical transition PLAY failure with successful authenticated cleanup"; + const markerMatches = job.steps.filter((step) => step.name === markerName); + if (markerMatches.length > 1) return false; + for (const name of [ + "Stop smoke stack", + "Require successful runtime smoke and authenticated cleanup", + ]) { + const matches = job.steps.filter((step) => step.name === name); + if (matches.length > 1) return false; + if (matches.length === 0 || matches[0].status !== "completed") return true; + if (matches[0].conclusion !== "success") return false; + } + const smokeSteps = job.steps.filter((step) => + step.name === "Run credential-free full-stack smoke" + ); + if (smokeSteps.length > 1) return false; + if (smokeSteps.length === 1 && smokeSteps[0].status !== "completed") return true; + return job.steps.some((step) => + step.name !== markerName && step.status !== "completed" + ); + } + // Canonical-transition diagnostic acceptance never becomes passing producer proof. async function verifyKnownPlayFailure(run, candidate, identity, allowIncompleteSteps = false, allowOrdinary = false) { if (repositoryName !== "benhook1013/FireMUD" || @@ -1502,6 +1531,10 @@ jobs: } } catch (error) { if (error instanceof TerminalGitHubRequestError) throw error; + if (isTransientGitHubFailure(error)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); } try { @@ -1581,6 +1614,10 @@ jobs: } } if (refreshProof?.status === "ordinary") { + if (!await isCurrentCanonicalAttempt(refreshProof.run)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } const freshIdentity = await resolveCurrentIdentity("Fencing exact passing typed smoke recovery", true); if (freshIdentity?.obsolete) return; if (!freshIdentity || identityKey({...freshIdentity, sourceEvent: currentIdentity.sourceEvent}) !== @@ -1591,10 +1628,6 @@ jobs: } continue smokeGatePolling; } - if (!await isCurrentCanonicalAttempt(refreshProof.run)) { - await new Promise((resolve) => setTimeout(resolve, sleepMs)); - continue smokeGatePolling; - } return; } knownPlayVerified = refreshProof?.status === "verified" && @@ -1606,11 +1639,19 @@ jobs: } } catch (error) { if (error instanceof TerminalGitHubRequestError) throw error; + if (isTransientGitHubFailure(error)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); } if (knownPlayVerified) { const selectedProofRun = verifiedRefreshRun ?? matching; const needsLiveTuple = refreshVerified || matching.event === "repository_dispatch"; + if (!await isCurrentCanonicalAttempt(selectedProofRun)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } const freshIdentity = await resolveCurrentIdentity( "Stopping stale canonical transition PLAY exception", requireCurrentIdentity || needsLiveTuple); // Original event proof keeps its immutable tuple semantics. Refreshed @@ -1633,10 +1674,6 @@ jobs: core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); return; } - if (!await isCurrentCanonicalAttempt(selectedProofRun)) { - await new Promise((resolve) => setTimeout(resolve, sleepMs)); - continue smokeGatePolling; - } core.setOutput("known_play_exception", "true"); core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); await core.summary.addHeading("Canonical PLAY transition exception accepted") @@ -1719,10 +1756,13 @@ jobs: core.setFailed("Moved cancelled-run recovery did not supply authenticated smoke proof."); return; } + if (!await isCurrentCanonicalAttempt(matching)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } const freshIdentity = await resolveCurrentIdentity("Fencing moved cancelled-run recovery", true); if (freshIdentity?.obsolete) return; - if (!freshIdentity || identityKey(freshIdentity) !== identityKey(currentIdentity) || - !await isCurrentCanonicalAttempt(matching)) { + if (!freshIdentity || identityKey(freshIdentity) !== identityKey(currentIdentity)) { if (freshIdentity) currentIdentity = freshIdentity; await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; @@ -1817,8 +1857,10 @@ jobs: core.warning(`Canonical smoke producer proof is unavailable: ${error.message}`); } if (canonicalProducerVerified) break; - // The exact-attempt marker check below handles incomplete marker snapshots. - if (fullSmokeStep?.status === "completed") break; + // Marker-only lag retains its dedicated exact-attempt proof below. + // Other missing terminal evidence keeps this typed snapshot pending. + if (!hasPendingCanonicalSmokeTerminalEvidence(fullSmokeJob) && + fullSmokeStep?.status === "completed") break; } else if (fullSmokeStep?.status === "completed") { // The native pull_request path keeps its existing step-proof behavior. break; @@ -1930,6 +1972,10 @@ jobs: return; } const needsLiveTuple = matching.event === "repository_dispatch"; + if (!await isCurrentCanonicalAttempt(matching)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } const freshIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception", requireCurrentIdentity || needsLiveTuple); const comparableFreshIdentity = needsLiveTuple && freshIdentity ? {...freshIdentity, sourceEvent: currentIdentity.sourceEvent} @@ -1944,10 +1990,6 @@ jobs: core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); return; } - if (!await isCurrentCanonicalAttempt(matching)) { - await new Promise((resolve) => setTimeout(resolve, sleepMs)); - continue smokeGatePolling; - } core.setOutput("known_play_exception", "true"); core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); await core.summary.addHeading("Canonical PLAY transition exception accepted") @@ -1992,6 +2034,10 @@ jobs: ); return; } + if (typedRuntimeProof && !await isCurrentCanonicalAttempt(matching)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } const finalIdentity = await fenceCompletedRuntimeIdentity("Stopping stale smoke gate before accepting full-stack proof"); if (finalIdentity?.obsolete) { return; @@ -2003,10 +2049,6 @@ jobs: ); continue smokeGatePolling; } - if (typedRuntimeProof && !await isCurrentCanonicalAttempt(matching)) { - await new Promise((resolve) => setTimeout(resolve, sleepMs)); - continue smokeGatePolling; - } return; } diff --git a/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.txt b/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.txt deleted file mode 100644 index 934ab25a8f..0000000000 --- a/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.txt +++ /dev/null @@ -1,345 +0,0 @@ -/Td6WFoAAATm1rRGAgAhARwAAAAQz1jM6B//THldABiZSGYjQs1zFlY5j5VBz0W4JDhZhp0H5edF -Kt7LibZvccY3iyubavjShTuz+nJDka63C7ThK6hGwo+lfREBZ6lHAOsnX+4GkoX/wQBTqeprkEJ8 -SQ0hRrnXMWiFEUjkmMK7a6vI+wb9jlrpHGAijy0PlqE1fdkdKO5Aik1m+DFEFy5YU381bfhd1kBo -E9BOYJOlpo3fBM9UU2C7bei/xTMtGtwNwsTEXWPsHdHWnbcd25Dc9to8v0TNfh/jxQHed3f1iJh9 -J6xZg69c+6GwwFD+IX1nva/Uoe+6ew3oz/wUGO3q9ReBk2eiXPZUUMsLvFeYrCg/yXgXUJtcGi55 -qKue8MUkmuTDlVPzHPEoXJ4Ee8Yh4FOpGHQ61DEbpCwUKIcqXtmZHXFaOa3scVsDmO+4u4JUSHbj -HHs9pggHwDWihMKqka2EH1Wy1i3xLGILPYGd6voZfSUIhKVemZGJKJP0BFOJRguhbjHMkCAYUlY/ -vecKeHYoIgn2pYVgDe9GDCsXN89Lwlc4Am+AMG8hKteE7gZ1/Ly1Hie15UhfNtLg0JHhWeHVK2wm -S527D2CGFeodeJrxwndctfBT6lRRXv9tndgC+c7cacG+lGOCDbTMpj79Sqnwuj5fIxhunb7vM18p -PnDprzr/D6DoeiHZfFaEDWDobO4RcCPtglwNAo6VEcngQvDQnvgIithXDQ5FLOYXwsG6D+c8jHaa -jwQZssKUlAH3kHqx1HAanP8v7ngQuqniQ25JBSXxlL1xIO4ZmNKq26M8/4xb4jvLaQw05oMBgiv7 -p0pHX2sOPNp76CLZOmPRwoihNT+YWhX9ms7TYTLoHlXS04Y1sRcloghimnuBifi9IIM0l2YeJiA+ -UaQTA7moz+uGa0pZNJZ4sVVav7Fh0dmQ7ftyRnfm0NEHtj8w3i4SBC6gVdvltLNYrVQI16uI60bT -MzhpzXMal0/CVas1mZEoaq0ME/xFOLbqEZAgLS0svUJxWhvzc9xx1H5wfACJWZa4sp3GXcfkc4jm -pUQQhCfzHMd26wO4CuiWPgzOTFu7BtHO212dcI1jwvWbwa/Qo0Z0EX/uTnP5vnPTCvfDCXhGoG4n -0XWzUnnck/0y2EDxkOTyiVVpISv7AUdFl60Ajp/S/XtIeWvMI5u8YJGoNRIubI71IZLaju28LWgr -EE3PCJKHZo29WlnMcYbeYvmeqkvzs0d01YD3Nma1ASC/T/48E0Eg9vThdWe7PH3BojsApVfxD1d3 -JgDhseF/Kw6/ST2UlIRARhAOCCJ2sNY6SZyhxdc9q7usIhYJL8xXgVhs7TSQlQZ62lZsCH8/Ejn5 -ovvN9tgbIdTX8GNJ3OtnBSG3gfxY4PTS8sHaudHzyn92Vck6cwZRimsEhE0aJUuhgkd/TI6uNfsi -S8W0EHGZIxfLxJOz4KSAFOoPLiBAfo7iZa6UTNnD6o0CIzZySZn/U2n/ok+5skXnHFIaRqct5523 -knzpydA253hyPBhTCNXG1daFIth7Vo4tY4FvQRQIYun/BpJO1jLFHQbwcqv2fyjia0sbKkZPjdOz -I+Jemx8a0+YQ51RnBEv2zFumUSLPPcziYEa4HEw2zUNqgZfpDJcAh0YO2YqE6QzcCedHWYFIzsO9 -rKLdWDnC5pACoddpt+6+EjEMy6LD/WTswYpBfPcOFUylq9hPg8YvgNFM1andT6sYTvWQsYmk8WrN -dH35Ls+p9I4ZJtj8wxvVuD8c+NylpPSQ2j3uNOOSWsTvZYQUNr5owXlHw9fW4jCFzahGInacH0Jj -gEzpqRWDaWsJ/IS0HB9bPj4gvBhd9LNusixjzv6pLgGNS+FqsrpTtCtQofgxjkR+v5oQjxKJL87Z -7P3I2z1Sh44ub9uiihAx91S0JNMznvBxshda58CtWThUAIBwxqf+FJK31iLfSfYi8qq/4gs1eKSS -KOZS06NoL69/0B6CPPc5UW1zTmzBjI5pPGduvhRlNlXAHI/J8iRIdwAmfTvOYq7x0zedwRWOKEY6 -wyGMtX9laUfWCo1tuWkMQZ3Q1HjYJmGMAXXtDQHpRxEfa6VX150vycMc/t7mWqfdQvRfCcx9ytjR -MeUkLrStACnm7VCoc405OtILqFT8xB435NtGS2sv37V9wZjMNgP+kc+RSzJb6kZdHlA8cOSmc7hB -O9G0m0ICy0JgzNNrIF6AomN7i8FOad1sREdSlCn4+c55geWl9rWR2QgIGW2IAwDTCbQKDVKZxzRK -/r9QoDlQBBTmYaCEqE3i8AA0zD/32szKXmZ9rwfRK+XYIWiOl27Taqxl8LLHoqzyp6bWZE6MJ6/c -Ve36ojMt/9voHJA8tYdZkUCAobgKCalxdXuss3GwHL9FTHOqX5qW79tOZ9SlnMOIKED4cRTLDacx -hga5ZVb6f5k1ZmROK01SnVxaA3mJSFpeFvz0Kt6OSRXeUjvtF5drJltQMwL7oHWVj2o2/ewU/KES -WzzAygNkDCsNcmqqAJWqvnX5pYFxwQhyE2gFxHRlmvJw+v4x0muJN9XS6dmXZejjAWAZrS9S2ggT -kzHqObUZ8YyK9fuO5S3ZsWDuOVgBTfuDCGuMarzo2QNFJQTekxqCEHOoyCpKMDruWcQg+H8qJgi0 -MEuX1eTFj2agWAr0Uk4MF6GpQ3ElLFYdh5dWuYmbUEfvT60C+G/WtnFrkwEm1a/DclWpGEkZc4vF -egzr+HfknXHqmwju1XYLZ555U2iNZeEtxlTeZ6XbIAApScRCVxy9LJQexGxBH8RQ0RpMYyRVrsYM -BNBjDe67LoFPDV5+dgGgsCj/dIjfBCe0tOWpUZ92ANuF+Vl85CmXaNzycVTh6dXoF+kYRhjc8CNn -NRNCIIVcogdk86U6MG9fTVgM9u2y3gr2rPNm4U/jTef9nJOJwdnQOeWVOD5ktVjm2Sm0mMZsYYya -JzIqaOnT/XxK7fbQfmPY//SAfpPwwOVlppCrTLgLSaS+S9+qau6KJq871tPGNBWkPxktSx6x3V+j -6IxqtjxJYZkaTnAqKI1FWdLq10mLojuSTgZzyzUbY/HmlmWxhlNsF+/yJeArN9SiBF+g25Yv+mjP -+JIBd48pCQJxF/FAFUEiie/DOd5yZA3jYTqogkqnvyk6pncDtom5VDhCKn/DGK7hVDuI0c0XbUil -8XoJ9jb3ilCXe15vvhpMbHlWRb+9mT/cgcoF895e2DUrXrFqt5RTNqNC/nO7ksY+GledDCX47AFD -RPmHC2mev/VsKWSBAw1N29wa4X/5zjighu3ITaqzu6RFGQHji6AV2KqZTBkNUrJIA9rr0QtklXLh -oUPn65Qx0SnxjbyC98K4v4daehrc34T+1YQUl6o+o0reBuI1rlE9OVr3S9BfRyyuKcQQcEzIzNhc -kOakkZ4RAXtHaVWPFki7ScmDZnXngaKW/bSfN26P5V+C5hh1yRPVz3UfXWx02AiLyG5Fg65sFc99 -sOprifjDICsJzVcavvh7qyw3XINSay0jts37qhWX4Z+syvxetv0m6weBlaOwGdRZd+zwPkSb1Qix -Cmb7SGB/2/3sXGRcPRK0bVc/vKVv9LAnd9r0HCRjJYDMJDrUO6Fw0DJpe4qdV26o5yLjMMUlcJee -Qpiso6eP1ecZWYf6al1b7XeJuj8TFgJ9ooz0dqjXxhaywofWpSC/2nxjNij+1ES/v+Flej5S2VNb -veVMbyYpqaQcjM3zmYlsp9oljennhm9qjkmvxbcI4N4O3ua/UKtTQ1f+Z8mG9+sZUVwNoq0oIYlr -dJnWubVntiuRXIRxqFhN7/nTykyoXY4qLwFAVShy/XI0nzu9OKxJhSBUTwGUJc1AmhviXS5D7clI -wkSoC3/VJgpQdqPlQD+BpmDaIYfV97jMPCin+CJRwex/mTF0JGxXwEslr2ETv1k57oZu/Au2r72W -T9t9qKmSMVthd2PslIf4CjocsMPslSk8ohWCW1SXhiD3LPaBu6/IhxSwAhY36lShtLptNvld5EF9 -paWW1kghOgLwipvT0JMgBMMu6kOTrG+tjwKB21UUmike+YEFltlG/foieFQ5wvxuQiFp4wN8E/+h -zE6lAKm0wDS0zD1iOpwz5pNrmFfcqWyXzLPkBMS1QmB+IY+AmyBVpkerHiMFGUmNVQsWlg1cdT2r -IbCC69YyZPqUXHn+XpvZM/qF/AXAx8fjQR8u++T5nBNx8GjiggtLjG+1oQ8Bd/XiVrNUexIsJ447 -ZnSywrkFjfhQn1+QcG+lypAdGz2+ucbzQJ857R1xFKon9ZYjapufBr05qqTzr9kFl626xd2vZB1P -XfnzU4IDTUMDsiQ22RLyC9OzcuTruSrfXfS8kYvENV0X7FIgShpw5aYVtIg1CH9JfVQBAs8LtdRk -CvZrm5FAbqsXpdkyA3e/v4+DgKL7AvJ2vALp/GCelhMI/vo++mdrmVI4TK8ia4k0w68aU39uE4xE -oyIzn+Udx/3nXGj4+rNPTdzU12s1SXCKSCdCWdp6vXmER+fl6jwkNZ62/10+EB4IaAiMo13PAYT/ -XiQSIzLcl+Z4NcIY2zYVkuvTeY83CqmfvGgCb3SiMX0sDYtoKPPKQb1G9YWzBoEKdKYgvXuznlJT -/2x8XUVGhsS4qR9ihKPQHX6Vqzv4eZtussNRQM7dT73XLJRvKCMLOPQQAhIIqsk7v2IQPjP/7gCI -PGpFylujHcvl1KQDDoEbhqqx38v0bTYSyiPJoZRVUukSOtPRnMGtjSfR3GQFAb834kHO7x+B2OiH -oTSzPsV0asScqr8X+junqrV+JiXdVnPmOg44tVwskRHiUjnmNPOlgtACrHdJxo/sl4SvWIpqM8e2 -6zOlzWTzRb/qEzDG66jz15v2pfR2St8fhCwyAcKqMeU4bjD5jGmmmaPbhjR3w0AkJcAUIFTSlrek -QvqVf0kK5+3WE3akX7t0T9PM/IEph+a1ApVSEzrasZ5Ue+jqPCV4sNCnMJ41/3QYH4ZBFVEQsedG -p0n4E5/enSCzSqSy/nRlUHdwHHcMqdItkxxGGA/qKxiHYGb28vpaCxvBTY2J+Sp81ZM6RgSUrAQj -Cf7IV6FClxaZEqMe2sj8uH6pzfEToae3zvCpGW7Su/H4ZKbNzQctKWnAaYy4iMWTjIePLlw6bsFU -uLomt/uQSA4/KwPmVwnYzARhsibStza8Ug3j2SIn0/jEBlgkXd7qeOyvS6KkLU5GB09zzHspIJBo -20tgLtMMwXeaS4FOdSBDKsCBZ2i7ldO4g+ojE4bMuZO+HkjMqvT3Y8DoweyVqD3YB+sF2+JhOJIB -DTtxYTPube6WQRYm28nbdrVUQR9Ahsf0V/Q6Yqb8ZKaDbI5zhO5uOl7anUWBWbyXW5wWBlTZSdHP -4tHGH/CvBQqfoeewGXp7do2phdMGlvsk9rBO5ehMJ3JKXy9hpjBrYuQe4uhqfBW0LrPLzPP+fe4+ -SnLf0krQw/SowPKMM6bJTt3gB5gTmdX2vpypPzC4aKvDlw8zi6aAULXO3Xw+7hPALeit/2QGdJjr -AU5RniGESlX8QWfTtevIzxRHskAbb4POIABZ07qf9rexautWyOx+cWB/8ASYLNnVryZaWM9GK1pn -qNJm7+JT2D1u/q7hkfuTTuP2Sc1pBqBtK4jq4KXWKLbfarvbG9QYCXhJyAlX8TgHezib8vlJ1pmr -fFQaDnRdeyjydhRXP50NRncnhTPe/CuY31gCmBtasscBt/eAoic5g0Ku1OYShqGHumcVvDvJkadV -GOJFdRqfNqmsy5LXyMJ4g7qz/beIgugP/jgxy/nJN6ZU9Ppq2apY9EebAl7mQu8rAE5SLnq60qnS -uKMbt9rsS6GHESLFUHsfpJecdkf3W4p+hSX+cIZKiq7BH1sLuAq/+Rafx3SsTh08x2YsfqUw1rH0 -edDNPLU5gaLxKe3RoK819rf2+TU2zsKJEZZZnpFIzMG9X9HkgoZ9mvGYEU46MXGAju2sZGexEjC2 -z41HDx2+LEFQk4tQ3l6OH83AMfEOKnuFG+C75yqYJRPXs0BrLEencNkhWR2U44M6ncPsD1CZyoIk -+aTfZEIENfdt9jVCwbcYa9ymHK7xANthoXdJmYSk7zt1iN9ggM4SoEhhnPFHR4e09eWgAfK9Foc7 -JWelW7NenhAP/rcHipooINkTCRnvi2ogLtS1kpAeMpn7n3kvnWoc1Tm3M2RAuc6eXVJTpNqGwLTw -pNoOYtyK0ht3rQisy0erXEnzCkEOPHvqUF7VNQTuK1wPQ3RCL7D8Okj+F75HHiAL6QUre5BFm1Gw -vFOpVDLJrHxBNpeMWG4eymqwqJqyxFaRk5rVcKOeGKrJzgJ92rGa2Bc4I9Mw6crUFvxpyRtixHP/ -ZSakabfGX/kmQRIYTQPIgKJyh+a1kriqGphYOw02ZLf7pnfT1UeWctZXbPNw+z3qvLHRYBXSZ8Mk -5eJZbna0B+M8H6RHrtxNVZey+n8Ps1RR5wRvr2MYsFeFQkMo+K9zucP1vxtzfy8DnjknnSzbly2V -Bo9Sl+GyvfraF/u7OkOWDCF5bRK4YmDwII5sPgtlmMXvMrK6b7VAei04igS9EoIQn/yFLxxhDcro -ENuN9XLUnG3HGfFmkCTHjOwmDqOqbUiOsK9iLTdOKfm5C4ID0e7BWNjaE3TQHmYBQB2mUvccOvYP -Hpwoiaa7g+ON2qX8x1wnePPnoNS9QUro0BkeZmDA6hV20a6tdaPb1H/0DBy/+esfx6ogQnxXCCLs -dAXEcwzOihszO97tdFdSM5M0TP8j4MVxNgbcyROSuJXANbean6ZKeTZwnRhIadN4fBG6dSy4i8aw -aJOEFZ7zk5zw45iiFGktpvG1pXDBXdK9w+YfpJhd7tYUWwFlDxTl3uxzp12BynwPrNxUtiPpkkI3 -eFKz6jj8IpMEQlFKWKqnD8ZoVZEbZiYzg71o/zUjV2HBKnk3NGyhhb3+Oty5RgQs+kMqwZUOKH0P -T05epqFodQYZ0pL06bYBwashQ1GHk+ZTkYe0nESth1hEqhZ2Y8Eb/9KbBQ6V0vs7H3OUqiSAhouL -Uz2v5RaBuaU3hieEu3Kz24DWfL1CMQVMEJ8+JmaQzcurgPh8t3Mn7NqEjAsFgkhtuX0YZiroihUm -WTxH6P6jyJtKfXwmSjhj/LkGaUfJAK+PEBvwLTlr/tVNUU/vDvBUpnQxQZNJUnsUIuXj8y/0rPMV -/E9kszTS9Do3oBu/8WJA1XEdixwV8bfl8d7ogFwsjfY4lPyKlhC3VvJP5GjWG05KlGpft3wWRmVu -iPbXJfI2lGv1NTx0Ey0Fou0qTUQTAMulUbIv7yqF4qutKpBFRPNtP23/SVoAOwcFIpBSsi8tEzfm -kShmpnypDXSdquw87Yl1alR47m+aTlfi9rDz5idMHb8WE+m3VDjhsUJcY4Y7BuksOXSd2vzMF+Y7 -RXCkHrURxVsaL5WAQZofSr5+4WFAf4bUyGem/7L7cLdhVCux0HV92PvaJmFxYZPvxG/b5jRw2fa2 -kE3ZZ3x/T/jWjfY4c4m36l6LS4SVSLeeinR//zfGrfIL+sFwXVgzBGopfOiVh6zDJ0eZhgjxZpv+ -FSS/P7bqRurBVbHKImFRdORJht+W88DZZ4nrbHQh0aBLyZpcqTOzKbIRWhJSv1s7YVlyKTcZARNt -jE535w05I8FhlWwHb/XqqIHngh9Fpr25PC6cnQCiplrhyM9oI/n97DN7fui2efg1h1r97Yy0145P -Pl7Vo9mzAFLBEDZNq7pDNGX6W6JSmENYrCq2xg0bNxIanZ4sPr0gR/AmHlhr0fSkymMZJSS0VTR7 -yDSS2/67t0ULv38MV7fi0e0O6JyK5ohlCUFrmoQ7VTDZfxOe7xSKub02VgoG39aq50fpV0/BV2vY -2bty2UatT7eslsvRE5xflO1biGsalcRGjfYZ/U2I0/2eP9fx6sLaXXosgpPrUP00iOLu43dfQaMr -kb4uQiw+7eKP8r3mvG8/hg98BxX8KfX9NYs498RTizTo1sW+Yn+YU7+PSBva1i5fu1XvyJ0AhnxW -cXOfUPgmNoy4K3WVsDCIIMpFjoiPU+W8NHHz1BJ+UFLLKR+taBR+2uhHtG4SW9hSI6PFLPyS7ENb -uBiZIWWbhjNO4dTrAdka7MMmrVuXVXqWh/foVXAZ0oZjazf76K5uaciOzuvTEkAFEaP+REnPjyAj -TJwvVUBTDgsmB8Ss3L9vzJXHfnhDTRZTxNhui5LG0MwPUckrmTDlzE4KiZ485oNrUM/etKpfZzD/ -4hNPaoXS490u9/bzyJWbMt79W3rJ7WfJAuG8S/4OUFVtRgLnypDCokcHUAn9p/atu6fpfdpoY7iN -IPJ4MpeXEaNFWg6gQfYUwEkR8W2VxNcbcOXAISUfsJ61BkskfmdasQalO+EbrWtaS17hghRCEh4D -xugzPV/ELBv6GaMuE7gqUUpA14AngbdcaaZ1ayNh5yLSDfzB/lwrmkOv/H5XMa076yPQ26cszO3h -FxDz2nLgRSAb2EzBiNESSYghuqJYCIdTK//NvNEY1sgjwiIDKI2MDtdNgZOqPE3PlYyB2bu37bjp -ifF1PoM12mLnpfRitEhsq4GLtCoT4jIpOb3OzQgkoUE2qbcQqdVFxLnj0Cu3FzWbYQHgHWta1Hs+ -i9PMPj3qf5mo1uZkLGNdbvQq21GgJp6KG4HIoQxwnCz4e1rySA3CRjUqbnJ2yv6a3b9NKeNT4nL6 -VnY+b9+RlJAS1Z8fe0D7E5XiBtMacmeiDw4KAJgZvO5tBhV4xzmak5sNkn5iCvSSiuE62DiFLhMA -1d0KN0WiRRVjp1j2K4DYkps9tDJsx1qhKx/dz4PDwqfKaEKja+f6O4uvZKBNCtH27jvEFwpZhKiQ -EwwFOH49NynOefvTUIKJcRbxh7M30uwj7fyYiX0OxPQWu6QXg74eMj3j4zmKoCtba/xgE/3n6P6h -/RsZ+Rp3DUCOSUJaHYdCW+RFUJ991o4W5X88swHeOlejUnukKgmMhd+ZBlL46srW0znuofZ6kX7M -7+1JWdAqgzKznxhwB+ilmkZ0ZoC49s1nef1Glep4msc1725nDV06FxzgN0mfeWYHOjpvDOgvGqKV -1LJbSTev+wz7k8VqOHSbRGu3RQPtzEhzgV6N42jl87pxcoZ8UqFmcVRPg0DwqfCNsFmUiHryU6pV -/7GuVFgKRGxnv5Hb8Qm+IV+3jAidAdwX3CUgoQ/COXlWjb9gpd3+g93PsFER9j6Jja7JlbfRUrF+ -w6RrCXQyro6wIpcfTAcReu3zSNoghPsjZ5bfi3yicfn6TEmukGh/mlcb6lRuwlU6OyG0KezfMHN/ -UmrV9hy7VfNW5AVS6kDsrDv2lIfzOqrIgd+GgJrzBhtv4t+ng47+Ax/ncNzfk2GBGytrCqe3qG7C -FPdCkdsDRMqDrcMLT+R4bySm++DpflyTTUFA0gbXJmtolmmc8NBORZBiQWSvhVtBREjTSxFPun3b -L67fKS/niB7JuPlCep0lUvdNNhFdQ7783aqw9KxgRWT0zRmjP6QxsslFxn6Gat6/CglkyA3kqd1D -0RNbI96VO3Z/5CblIvhSO3Xrwv0berml4B9f7rlpoMHEI9VR4h0GsJShjRQfSMGvda3dGRS0HJCt -GIG1CqFbhKLl2D5ii0gxxp7Co/R/SoIRUMxn/IRbznS9ncLF1wy2b1D7xIxb4p5ZHr11hzn0Gwmw -GiHbsvmzlyRB7QyCGpMVKq/W+d71zBtewUnbdKvJDn2IUxrUN49fRrj+hQ+A8pbALFfm/MY9rLMe -qWzShjjMoZ3TlcM/hHvSNEyRxjW2cfXCv1Wr0K0D8YyOp4GGBPuxqT0LNnMhtxnwtB8pHUOlBqnr -/FgIQ08RGGpoQ/sIs5jdhGcE8RUzVMfM4nGiKyVciWx+pXrCl0QnltaJDIW7L/Fq3DfSp96D77ZB -rQyvj+DH2wkQmOOQ4dp/h9AmutIAC7fdnKEfTA8Uu3kPRi7c1BsIoll447LlHoLYnlpfXR49HMQd -RIqVQaVGbIDCuvpL25t1SxdQV8KL0bKjQVaH52pEyrneEmod9c64fkpp+9rsNi1V0Z60tVuJ0miV -E5UuZbD1c+AYFL6MF1BTdZV/6C14DH8huyz6B3ZiF/5VhLkzmygq3W01e+rOQWSoC179PBTz1Pr+ -s/GXQ067WTONyXTu1Xe4w4e8gbmwT6oZ+NJ87ctycWcBVlRReDiYd+QdvDr7d9BV2ylgsG6aBXF4 -6VQZxbQhOFbB4rCdNoLmf0zotwHiyXJNl6LULqGbPb0lr/+LBVNhMOgqudBE/vHqFEqDfc0Zk/Ra -9S3Tp7N5sx6rbkeUZ+7tAiRqd2rjjIp1yxi2GHLsUdosuVodXeY1KRzI1Cda6ZFeFmeyAzcIwuhl -uSbrbVEi/Wgodx7PkCvgRwppC7bIje21tu7B9H0UIW+qUauPHEbEeC15+TJ8qcGeE4DR3Fyn1TcH -ncshcsjmEZyWQLOW9U4i55BaYlhTyt3lisBe6W6e3u+ed19+oNuq4aCQCQSlAojje+rVrwG/Q1h+ -sAiBMXFVPGqP8KedZgIYrstb23ttNsTny0MJF4QY0a7LdgN6yAKwaG4AWBrikBjFEG3lfM5W0fJR -wZHPuu/yHzU7O3YRq7TAHHPnuGFbvamFM0FhThR6q31tmBIS7nNpPY2tt3qKsm1zn2ANgQK1U301 -ZLjRcIFeunoq/AS4DN3dxjBLfmcLzDjSui4SxS4pPset/LzATv2o+CkWuIhrBs0iXMdW/ZTTnGRY -5O4308j2WVJ0/6Bj1cOh4LeoyaNNPVESx21RV+fQrCwDMSkkW7U3tsw5jPpMDEJbqR/L+4b/PMTt -2nChJqH0g4Yttg+OaJQXTrPUnT2DgnUHQgpAIoj3hycsPZwyYCTCkZtuAHjjfFxB0JsXLSjzT87g -MS4inzBs2qYalapVP5j7jYwzwcH4y7A40t9Z5Mno+0Cce14zVZGSOMtXfh/XwH4nEkwKrjrZJGA2 -9oBtMFR8zbBN4jmI3bD9VU5RD9OIjV6lIeE4Ce1dWXtlgl8gELKhRtB/5cb+OzY5Xhu98cPys3zZ -/u9Jozpq9dDF8kI9PAN/ezzKcVnFsBH8xyq3ak+UaBOitACtAtdj5SbnQtfMwG88V+LzsyLUprLv -7xh6ueTeVWNlZcRxDzbsqiSLQMvVSJJ9IJAuKBUstNT5Mbc/N8Wz1FO4i3O29Bb+BJjy8LrOta6+ -3nPc/LxuPmgQ3lwk6yePbk3lJ9ojLZqjfIeEQD6ZTkCxxat6Zvb9lgU6CwUWfLvzzINr7MTnGZZ9 -zJ2P9Y86u4y7JhzPdekmpfLKDnu+OqblXD2yboXvp1rLZeTQtAfz/2QL8+VeVVNac7CB88d7kjrV -KKyv9XD4vm3OMondpleleO0QQAtbR43g/rQ/JYF2CfbfjN42F79YpVBOvPDbgNtaL1vztyvJPk6Q -9EUh/rNx6aVUtNj8qqLF5izM/rb7KZlsrmhISgzgoa4aedzFYGulTGXOWka9hdcuiHyl3ZHRHhMC -CMk/IxkDQ7P+oThBdM+5MgLrlrZdQ4nQ7PmJDUhZ3heMoDYV5uckR4GuGswUNmBXP+vw02gt8rXt -YYhMu0dvhFVT28kI744EH4YXGhuhuSP7/yhcvnkzvJvLjYyw1mwBD2XGBUwkA5yf+brUEYHKhI4j -R5MSgZlUouzwzgGxCqv7rYv2VQhQm9BhKL4vKF2fBV8S/e1Lse1MqZ2fJcT4JK58FZCcSk1vdZXv -JjxV6SoHAGzIulzMA0TRgXhruQV4tpG9W7ErSRP7Rj3MJcUTeUKvezyn+FLjkuUHtji8WDDd3Nm9 -kvpxLJ8KVMAoYwDZdaEr+enQWxBf/OwqzJz7aRQ6bNRdWn/IwWW9cbg7i0FuwW/EHGqCis8ydyLo -/WW3kRMvZFzfdP8FssqNl2ispcH3lvsw4oNN4sEDXRTRwY33UX50XTfMozEhARpTV08aQncwEOOg -J+JwX5x/DQJ120yCgkTdWxcWVheCtzOT+bnhXd4ybytIWlgegb+5LqrSace/opjOGwGRHPI5jxCF -YwvvzOIEHosmxxgDRZBR0ulhQsVuJyTA4jcFokoYOpm7nt1l1nQi0UjPyMF87lbuEgIEFPNcYLEu -kN4ppdXjFrGrS5ZUb7N6+aXfxl69CJt4t7k5ZX/UHGhPjFBI1UGRSaKTJW/ZspIIPj36yaRLzYjf -S/v7aPHbEtB1C2IKhpD33cVpZ/74N63AbBjIsBkqnSbr6mkeEqaOwR8QCHWTmJaT0RN+lh8DoRus -EK2xJpiqEIP0o6OIAJTiwszEOjeAw/+27+Sz1PXOEacaDvFfB8EL0O+QLP5lTdN75F/80KnnHLdg -oDCw21cdFZoGqHveW/Ot/HHdlEckWLcvpChgFTuV3rK8mUkb5vb12fDmretaI8cBLODTdq40/8qd -1iFC/w65EbNQb64X7i0nAKvQLfk4Ii5ec4liQrRkP9aeXu2HyFvdcQhnXxO9qhAVoS641ncz7lan -xIqh/0aAg+hF1hgQ63VjvQQpvy4ZN3HrE4JftbeO4JV3z/cWCo3foFKnw4KZseZU5K2880IowJ3t -IexMF57u2LDCljk6p+IiD18+QfdXz+2mq1LgPNsDa1D3udat3MrVekuv5eY53L3iTAm3bUGHwlC3 -tlX/WtHhiHjduWqN8f4HUF/H9P8uvJ+2GlhpsB6pfyoGd9FaQ3B+fu7Wcky6GkjfYshbKlptVUFx -8jEpRvE8Hwx0xagvCpzgkrcIl0zPA/vhZci5wkwoDEFF1G2K7M43UGKwqhqg4LPhh07v+0T+niCc -F2pUsMGW0E0f/znt1wE3u7gxu+U4XOeo2REH6p5miRBBaXgX3spSf1exHvfiW6cIbFw3qYe1xrz1 -RNOuTsJK2Wa4GectjhB8iIZsUzDP+Lk6etUei/2enk/kqOHYZ2lKfty9cEhLPO5XbHRyPK+KfuRH -YONApcrGaiG5PIW0HyuOsHp9/RzYQjR2sgFJCOZvxpsKvNUWMutUhn8B1S9kTm4NfwJHW5VNINCo -n8PWa8C9ZHTXapI2Et9Oo0wMfXZN28DgkXZEV3BoBic6PiX3MBNVdxRbDfqWRN6NWtlEqRdIiEmg -a8HxwAiroM4tP9Zdw+Ct/B8mNcTX/za1BILr1C9kbaEDtwCnEhbzkDWNKiyIlL8BcyGCirBHfcge -dUO8JHSt4pJLvKXBzmSfTemcDKEALyTQtQ0BGYc+CBHfJtZjnzja9zezM8PLYwmCk7NXhB0xNsL1 -xhavZ4pwSMUMuJhpi/hek8GOIiNnT6HwoOFD1XOrspfS1ED1YdHVWnpLiUBym+3QH1Qc5IfibCNX -h1C4HS8wn05qU3lP7RxktOh+UqvHQ+M76u8iFKDQKQM/ADfyAKg2iHbnGT5s9Y11qiswN0Ze2WtO -TsZkjSNvuVq+zi923Wm/3vsua76CK+ye9u0DFiQK3Y6zDYlNeywCYImrzofdXHJ9y+JPPY5NgaFm -Ocn6akzjNfkwJxg8peWA0ZdT/E7HiGaASVNlIAXXQIiQnA03S/PkCKTMPSrPogYrCjalHvXpS6Nm -OVdFpgQbMRTFp5YIwBvzjqQc+4wGKWDanoWztf/3ek5PpSSyYUlVO66VQs5cts2PDe5K18KGVbJs -dMf+LsCJptWhTl8479N3pcetlXL4tTHKf8cJIEq+SA3IK6akD4G0eBtTrZmX97lkVeBZkiTpAd0e -Hgjz3jmKxC56jYyP1TOGmCo2uOgu8h4FaJyxHlKpvLMZiGHoz/QxboBxw+r1FQ4xSPhdzF+ZSdoQ -6rSrUCH7H/NRxhoZr/mYF2Ml2veW21YSLN2EopX8N3TozcrjCokedJDm9QsbsSpW3E70UUKeka7l -nafb4fHZdJLVU4wTKMGwrL6sBzDTrxIqXfhb+0h6dHk+eiOqi2GdPvWv/0C1p5+ePXL4BWLSMWi0 -VjW9FjpcHPsj4W0U5mmii0NjxhQKkLzFSNIp+aQDeW6QVJcHP1DmfyDxd97Ae3QK5BL7l42/yeY9 -IzStiLUtJVEER1Y/7BsxPH+QhwJYrYr+FxBxR+TBEAl6gdrPn4ON5nFXm0Pi7mGiSP348+PFODC+ -yGNWvZB/yp3F0g0EH4gsAHaEQwOAsGPMW80IYDJnR/BOM5FTMHrkUK0iEyYz4ouceTb5qF0l6tJp -Y/M+IGc/vocUXue/u9xSFkxis6ZvPX1gk3e8R78YWtrDde0hlgL+BxFWR/K8+EHJxbDGrFzyvcUw -F82pvYewk64wbthCJuI2QbG9dP43tJcVOSFM2z0KJUmtoot583lUU6EXe37Ej7pEJEWy5/Nmer8R -LwL9VApJJiIr7hV5wNjwREif/hiJ/4nyCur85WmkHVof8LaA2NhBW5jz0w4KZUcRHb45M12nlQgw -k59vXrjf4tz7SEWOA7QFHlIYbEbU8WkbLBc5ckQJS6754zTyZLIs5nNQCEsNgl9hBwEci6pKrDSJ -WrQCW1+qhy8l/WtfjO0BR+TnCxvvEySWLF8iHQYwJuf1hSmVz1HKTY9vRm/izL7L8etWHVfezpqY -FsPim9BjpdcpPu5g7by0qpq8X4pj+3EPMaw43SA2sDpB60RjXzXz6854muLHyjR9Wlpx0Ks3UP0J -PWSfxV0N4PHegwkBJct4d+7FszzMEJ+siKkcgwhXO5+UxRMsGYfhQaM5RNYCkiYHLjcyztOJMWAK -GlPzlnGz8M8Wg05xxU5OkTqr96AhSSAbAwIY2YdBHOze4HGQw8AQjm3xnVyi5SnUdjGgCiWMeJ29 -FrSZlnpB5WLPoXOB48+WgOzQ9HWGGVnnb6jhPudVbgz1ETse44iz9ii2lrVvChN7YoIhM5fwqHRB -TJAYW7TYsG72XSZz/gF9QW8sUjrYMd7nRFI+zd55bWwS2dOc/HLiWEcfYiWmgZ3oAQOpDOUYvmig -fD2tvLDbU9JgiR6rMBcz/rx8OZWZuWY26N09UaRqjr8v0KXAdGW/esrt0HQMx28KJ/1QH3G7BX2M -tL5FIWNv5mEdSLELEQ9jTCBVS26BqA4aSoiS9ngESVKTLKPDehCVSI39KL2gStwnwRGqWb/LG/X/ -KKuLfh9HYjmW1XbsbF+R9B9jQZDnZwlaJIG0bXK43s3mSAIV6/e1bgz2PD5Le+s6yLzoPrIlRr0B -U3dXsc6QpurhlQXSJFrzA5zMnwiWzAWCADhpph2dCxKvI2t8vYViyd4M+y1C4mxHAi0H1MxsNyTw -m/uhm3Es20lt4nlL9blRukyslmTavj3nYj8rcv888SKoSK3ioZofucMAmw98Oa0iadk126L/7UJB -nZOcpuLAZC/q5wB5hFhUv7ayBCDyrKVecWilpgrAG6YMqtC+Rj6QFrMjQxd++bs5QTrWbkCJAgOz -rMlqJ1kR+YZst12kSNIErjCGqko00YUKq5XN3Hc4FaEo8+Vvlx+WNoVI3TBZS9GKILnpB8inHTub -psWeCjtfUhhjv44WyRRUwrG4Sxa/8Y2D4QEWoTQJOhbboRV1d0MtTnINJqOehMO3YxhHDTeR2Upd -rUF3rqptJCRNdvOIidTSJQmX9Yi2tZ8XgKUjRWVYOqtWne2JeLcog+KRtS1RPu8Z0/07XzvJOew4 -r9QisbaWr7M95O81nAUq/u3t5vPv/HyOKl4b+BxlxeJK94u422wQ+dPdDnV3ygzByR38OISobFin -VHb+I2bZ60IwKrNpkJRIRVYRxCNlY5GKtQI4/c7NuW0rMNA38DtRu6b35RrpDxvK7uknD+kjYoGs -y2jP+NwnMJuquRrTsuiWprZilZwUrAfYgFCrpCw+sbWbZ/+ACpeqemzhNqhYrEhJi5XV3jBO4sDm -IEdIaVurnfGy/Ccty51SFn8vMxoTWh9mA9iSagNz/8t7sG+PqlXkhm9cJmiQuFpWsEmfRK6WtXIX -px9cIoeepP/hipQ06wQi+f9LmZ9L8zGoduhrJFMx2X1uobXNuxorMZHJPmbgbhuc+x2YW9/JyVip -NhD/60Lk7Jq3h5uDrtdKGywEOngC9KqAFx8ZHciMQ+znzGtZL90246eBt8qlwoTik2UR31JtaXej -WZMD+ZHdcRPLEuG9LQqAK4eZHJGOOpgGYKrV+WO2LCAHz0Xz7zjGt67I8IkShhqSN2MiAjtV0WSb -HvgS6LDoRNrzF8Z/1guWNJapsUkVuECVO3B+gk38VYF2frKMh3UljdAOgtjRs3snNKNL6q4rhoUs -UecvDpdSTD0QmZp41ApObSj0+aEdeeeXMwfLWeMwPgt6sv7NXdF/t/Exj2nErv1QmWcjinrzq4/w -rPXGh98To1c5+ppmdXy4zEsUvV7+mKAWk2gYsOY8qCGtQ8zNBxLn1UCWEGOtECwXBX/Mja3i9unU -JJ3EYguD5Z7ly+0SD+za2XXzKgFZi7nPlM6x1+Nut3iKuUrUQFfrkk06zjWQSZC35lXd65EhqBUN -s0oBLZ5UpZ+Sjo4a8i9a16n5HszSZjQm0sxxaJJMxPV2YvMlNSsYAg7N4eMid3wsfLt8xA2jklzI -+cj7s8bjDkH3E71G83WJ+FwBVV8hF+Lz7Lg9jBH/iPvMD028PL5sjnha2BcIu16ODbNDWFheZLvw -J6EsKwHO0euWmMwrzkD6LAyx74Vdtt2bQPSUT38/EMsOszrlh1XrLE2hMqnDcujNXYHRyx5EowNa -7/Ybor0YXfF62JsYabyhGXoxci7Liynoy9R5BJA9OCXvUjeFGAgSb+lk+lfWk/4NpZjG24Vnrm5U -eXcr8oaqbtBbUoHy5MXfq3LC7wmrHdvk5qbkiyKX7bVTAm/ED2Ces0ELQoM8AHI4auuHC/OIfv31 -M1u0ca6ljdKsYT2+kxYWVxBWAUKURbxL2r8ADUH8UARP9OFQ3zjmaNLa4cSavHWp7RCct90jTZIe -ZOh4ezLGxH507ObDL06ZlnuMLKuiT1piLQCRezTZlTlxFiJNGxQdVHyTopjDBtJ6qS/JuXzbYYLW -IPW7XA+9/3VFiUwgRsIgjEHmzBzci2G8gGNfP7zuYfxaFhMVImEDqOspOrzbMEHz0Bk4ncqmKcPl -/KUD/WqvlXZx32qTfFv0uFjFUAZTwFBa4sNKf7bexpRswjVFJZLxqnQkE3Ln8IiMd8epjkuiKhfp -ZUjx51xvd/w1VLV/9doQdPL4GZg7XFMilnWgeMmyjZXMYjRZlx5c/+35S/8JU5/yB7H/nxL8VSg+ -FtL2/geYdYxOsaxvhfYEOLnUDt+j2455RlmGwStOi4YyHA1QTLVYZ08N/1LB8pAH5aNlfvfNEBbZ -+ZT9K9byAfZaQjfNreRcnTaJ/+7EWpCojLhqjYs5RJZxPeHUYa5+ZUekNUgpuJr948IgHM7a1xGI -USwi2X9TxVZHL/3/XNhVEZO9wg4vpQHnQ27B3la01YTt5riH0uRP3hJkxdRsbGPExnmg3v4kgRcU -g9PReh9CqM4931zKxaH2CXPt80w4W/zoTypiawXbozNqcK67Qj8JfSct9jF9Xh5w4Gy08K4NyngZ -OUcTRywSSMCh93cAkPMjI9tciP4DgTaOSPfD2CQrdda66MZ9s9U+fIe/c0qM5mKTQOwRIBe3vUsE -oRhhknsG40//vVRPZdspTFWR4khnUI3FA9pxS7rdpDWVBasCAWcC8TbmvmZlGC8p3q6enLBMmmK4 -i07Ij3l1e3zMUodcp5q7bRT1W2Q8ovjr8BAzGnNx9Tz27wdzkrvP6iHV2BRfG6E91NBF0eGhbV8s -0+FzK6bx218Nh6AJracx0QySSmLZ2fr1zQ1HMwF5LVh78Ox3gbwEIJjBuG/ZN3KCMT8psLCskffJ -XUORGuxUEcNINUVDf0cfR34RQtABXHws/d9Sym1hOTYwJrssNT7M6wXM7T5M9E5ojqg3uLoIypvA -jEvSfpzvBH9BlObRbux91J8u0oizHtBSO3dqfpOBGdJsgj76ReTomuEYScb6ujZSlDZVQTxLynvg -A43YF9OdeOpg0ceUViivBlEbfPhzgafl84L8h8WQ+0nSvSGW2xC99gb5YPPi1YNLHZtZk/Rl2HN6 -kh9XH/fUAbtNDLKiXvyrqQosd3L/6WLIHH/3U7MGXiCL8S5FyFi5MVldhFQdZlNKCQhcps2Qm+WG -IdTBw1dbCrE4EwTxO6VevHKTgay72W4FEODBPR4MGWV1GEENSTK1gc8beio0fVkuqgq+3wEG8bZT -HWUetpXRS/xDsT2CGQthJTG5LfZyJ2mZ8Vws4/7gr6P+ncwDkn0rBLnxYb+Q35zizv9Sy9y0m0sp -OzcT/RMhKUa5OYeNRDr1OBrQ2Ot3twKs7jzL4H9YNiYVJZLPmz4QXSgoIyLpcMmVHM3uHlljd0R4 -mhx4rP0FJztejXhtsGtgsIzby3PhF27MMWIiQPECaTnmhusLOGdadF5RGH5rq5cmj6D9InqQ4esx -i9UuU/+1wyvC6MK+QUj1cO0Md2cteJUW5aAhSn+0meH91LKidqKsmciO+YLL7iWFwq5HlpGwu4ef -YxrmuLywz2wnQgAjrvfkbqF4IsuX6MiLMaaIthGHQIzajQtt56PaLR5BrMbzoWMZQYCUIV3RV8AX -az+lF07nvktX3c8wnQFv6nuIXw1+8j1QLZHml0T3bcjgKwwbYTdYXZxu78VhvLrTzU3F77nLTyHi -PwNyknaxIaqah/EAlrzn3rS6W442w/WnC6bthOaKace3RcdvhBUfijt/0h8u/sTcccaEQrGPGK2k -m4YdPzZV6pNbs3WMFe8GuOdskrdSJJ4ecwcjwA/55VGG8F4UKm4shH1SpYVWRSBNUuRPa1XZdTDX -/1QtYxZMcWcbbXGqa/lUoNzeoHrVliJgaDzXurzHDdpAXECxkAfklqDGcIw2demigskpaeSqNsVw -jLIRAdO0VEhR6/K4c3L0SVCylShIOWviv623Oc9GMML2bJjxyIYwCJroh2iZEmbVeIBnkGCrqf/X -kF4m9hETkXwIvv2RTjR0/GBRqvwju/0OBFAKFLDjUH1mRO6IH2bB/ZRlWpaAUGqebHFm7ReMVaYW -xDeajZx6YzAXJkV2h3/BgPRdXEc01qW+gJCLhG+1QjqVjKJMg8K0uOhR8LtJC8dJeXCdSj/v2t+Q -gEUOyBtoPJYmMm7ZsjWU8mJHdgxX5w30JfXGwgMizEuuw5mVVwdx7y96kkP6F18/Bn4R3X0lONVW -M3aAfeF96Mvpr1Fo51RC3VSIBhumIneK+o7SAlAk0SCo7jRfpTe1NW0kxXgzkaw70dtDlm9pQczB -0iwbuBtcy2WBf68Zlc4lJI6RgYom11wtfzzAunxJAg+T+3UK5Qw6vGHiJUpVLcJJGrY8q7pxUF53 -6crPqZRoEOWs7yBLUu7Pfqd+bftb/GimQGt71zD5930IRQkEpsKGX+QyW5E/p0FZykmvKtNeB3ku -p42Zl2Ciq76iymt3muHKfSJCbupDu/92bmr+Y1DesYYrQh1IAf9+iNmD6JMyG+0cFrwIaRBs7xOM -r3VN0rJnB8+gbRBLltPWOBAYZ6+KnEQ80civi2aZTTj+2raIfjWUm6sw3DnMW6GoUnbzj8bw/ytn -qcdohAB5/mOlqsi9EES682nOp4vpUeMjrL1BPF22YneZy0oj/Wj4T8S1QCURqmj8lgV7rH9oK9RN -SaF4gOIqhVnw0mubveYV2c1T3lkzWyjWCJOPX1O9a87LOBn7JJBGMOWIgpeJfddcJbAEWiC6u0KG -RuEsstbjmHQykmH6BfcU93lDqNv5v0t6j0SE8NtYm0+St/Whn/sMJim1Doz/X4BgD/IMkwGlLzXh -C6Q2EzYUCkvB6yHuoK4QyipdZm9iw2MaiyeC8PQpnJwXCTSmzrb9oWYmys4MByVkbM6xZezH2XSc -7ogWw3apXcRGHvup2/JGGv94dH4IWY8bj/WY6noaI3Rr4HsG21ED2wPumOXZNa9ygXRdyP990pjo -nTMjomNBqN//XY1KYrehdhSgcsiNYe7vO1+GuriDoBT9JNlnITTS58q3zSPY+ivPtMdUydHRAWL6 -q7afCLhDGAWPENuTs9tnJPuQSHJuNQNEKBmuy8MfrnM+SKa0kf9cnqy0MaxRCwDBP3taTDrmxSZd -6Bf0ZLUvdsQXxETi8n7w/uXci3v6eS2AA0m63r5jqYgPT3LyTkEGSq9APVBEz1NYK4EeP0UhDFqH -PT5GrUaebQRo5U7kcKBziep8mLig/mfG9dPvtO1NWtPAT5Y6O/PmJZxwct6hwAclnt0Xvl3lS7n0 -/ZQuRYIxeeGnWybarLLlsNhTFEyCjmjL2FFUly1Cb+8tIyco/QjGBrACJKoLKqJKQKn/vKT/wgs6 -XXlWmaUliK7g+HiZ8VMvqMZueW6rFE0ZFDP9DcIeK79Kza1CfwkOYPHx72/c6/2amaN5nq6JCsv4 -gGK/2Ys7d/jkLtIhpcfmnehPAZBWneUKNWtn4UwQNNewDA7tF5o2iyLGf0nh+olq38jHZ9eujw3z -A/Y/UyZvKTz9w4AwMI7Ek8Ud9VkiHtrm+E0DjbTrgk/Slgk4VV17G5PlHt0zKlpYUIA4aIlfNvzf -YGBfoJFbqdX/X6zNCPFwFDWDa1zh+WbmIgG20yoSdDfY04OqXQwizIhsm82+iadHqZqLBFuPdstl -2dqSiYqfhtfAIoQerzcp6xpMTAQ0hVtl6YT8gxE4hNmcoY6uGRXY0gkSJcl29jynO64FL/ZqjB1k -NmRY7XhNeVhIjABasUegTbHOx/PIikFbK+Clzx+tAhxxw9ODTBPYyB4lLcxHCZGKkX7uExJCJTzP -tb4gPWmITI2WVGtwKRpR52vp3JCU6mRj0V88I03A1Xopv99hcqy/mLQnjcVzCDTf3uY4BCSuX82I -rpnyL0b7f31gmWPczU8XKDtFMcnotD9eWTwsmHFYuFi+zGd3ZgMZqDXPzMKQQNC9XvN0S9ynHuVT -MNXpInEZzyWYeKxWr1nnfE4qbit/SOasQrFY5BM+O1O8v4F7zY/muHnhSfjJrL6LeTJKl5NNh2FR -S/eSpEmNyJHQbEqyejAowLWYnn48kZfDqoM+/hVuUfjFkQx4TN7gmfAShALFIjCA6E2ZSU10FZxQ -2jHyUgKk6SfRr5L9Cc4VnJ6T+6NBj94lsuMEog7RuA9axhYBXFBLhDnbUnwuISM9AbpjV4OaSYD8 -OCcsjcNRGOAH8ZXCij8YcavflUzmkXBs3FLsihwdYabTSDuHcAXczHxNuLWOw2CeCiq9YfLbp9+L -vXFIop4rW+NYtc1sm+doUS2cKsYHrA9JxQQe5PXUvZkt+sBV7Gx98vFc8F/nYB43wXUernU/PTEF -z/qu0EZ6g4HpgnfEXpdykRQ1CjuEoHuiEA9U10A8OexViOEs1IftB2m5UnTW9af/VuU37lq/t5w0 -gSj4P1L/jugd7vntavB8xMMX8jFmXyOVvqB2+Uox/gZNXYYm4fVQBoc4BQH6LIV7jtqKmaEEaJ/Z -Rsiii/z/6QKvfkjiBHFVMB+QGPhsQ8WRO6Q4it7cEGl3yiKI/hJVUHgeJlBHREHaqUlbxYby93XX -6Fkf7JIBQioKygtBdNo9gJeq7eA5w632noGQn30kO4qoCa+7UiwXY6W1Aw14Nkk0UYPQhMnvK1f1 -WaEBdC9zd4la/mgj0D47XCfbf+Y7d+3MipjFPndH2/YxoOTol9toO7bjPlWQxmE5nsb82QdLr8ov -/GpkJlQMZhvl+AjvW5cjtVMXhtbjyq/iulstJj03929whRTG085y3v1L3C8tWu2g0ZIyiqRFEXfH -kD7Bu3Z7XNA0TZciO4JnC+d2BqaWSPoQlcUC+QfHBTpN1cL2pmSp3004tapF4uRRgnBXz6VUfMc3 -vGhia0F/wAajVLFIJHTvOepfpZKPaU5kpCE9JQyRu8BX40KSgRRmQTuFYIqOZZjSHR3RbsBb5gRK -HLXbeO276SfyzI3jJcd2hKxDbWLdLKJg97B4i14tvCxWDATwDz6EvFw+CuPPsilVt6pSpUywWm9z -tYbMAOEclZHZQfVxi2zKN83xLp2xA/CP7GaoZAYdWZz7i+WAYMfA3m2b3zKqsgX4In8ApjaXwYQe -VLbFDwnAes2lDKEAsnG5zsmtSg+NoqxoD5QhrO1VaIH51lS8UoWTTFWjq1zdhSBYwGOcWuwewlWS -KHuMvffJkzHUS+5FXreT8Boa8naFELg7GwVTz/5+JtSWZsHnJKw1ao6aXga8B/+f8acv3QqQ256T -gESRQzwAq6/En4HZSNBhxXI0HK9wsr3hwLEzWOJHh+YBCrWYOmZXqYBsXfxmLxHPKzo4RUuHjX3h -VKCERy14rWCuYhuB0GnhAWJtovjdGGHB0NEeI+q4hyQJ4CokX/ZbUOHmaVXjvFZ9otScS8226hnY -VQ4LAHd+wa1gs081HgfqYQB1lVUFGuC1i+eHrMo7FMOuUq1mAksYt5rg5J58dsVAc41w1KgRI/+5 -QEkSbC0gXYIpXH/XYyk0oyyVmp/AbY+01jRfHCDkyBqG+Aa+Tx7OFJax0wua1AcBbhvk9fRO+VVs -MU+n7Sr1Jq8yTBYG0oBz7tzKB/hOY0bUyZ2SKOxWBdE4TLbkYwX7fnaZZ2sZFh8tksgbRmoSJ0fg -hjjjMJ8YPoJrrKqm+zT/v37BfUTT01RnPGYtM6SUgkf2NtafOMf8s9/NW3wyUnfBHSzqHvbpUdyj -byVmy0kPod4EUFqmWMoc1ah+UQFBmWM4cyI3j8ppuFMMr1c4at4QnM4QrgeJ2kB+xjyZZDnVVseJ -iQ6CZ33gNN6Ztipg/KMuWQV8Z25NLHIgdqkapPwIz/vQCA4YtpY488IOQX1ic7Mr5Yel1drFS2gW -PE8ExTeQQB+Qjk9jYlXuSWGwKyvM4/+bc9hrt7RqnC+ShXkb2nQXhpQlky1fTfxjc4/xCq38UdZ6 -e0sVtUuOAtAr33gQgIgaaA3sLr4KsrKfpPPqpq07+HFPoiKL4stsn5MGAuIPwEoRWyv8sBdmWi+Z -cSi3b2Ir8ym+qolJc7VxHaxipsQomnD2YUSB7MaPWSTeRRihy8A/vcsGaF6CjcVtI2jGVCIgZkAZ -1ovdiXR6OaiqWJLWjJFpyhugEilexue5o1AlNRE7nmRYi7NKRgHtKafLcWYQPhb7CuQLPp2aGNkL -LjdsV5tEw3JCfdtihZYpFNGJyaUjZ+z8mEhoAjHpN6UvLM1TrCkbrs7thFebGt/W8uXhUgWnnTcd -qGRt86fPC83um6GKN9ZISxdxc4WhChXSNZf2TWlzWYoSCR8XEQN0crkUjBNmG4fnW/RC4BDmC0EA -RNX8RtwAnWVFcklkE91dWqy9w00vGbv5gEtwRuMtDlZdil8E4zfzvWdwhuAVg5EMaMWu6kpux7+q -wkBv82JJSukNh+nkOYkv13qvEBGJXTVUDnXkPgBNE0FtLoMoA6EogAtqgefxPaDFAWsAQsBm2xmW -+jh+OCcd8D1mGsFsdqSh9Z3v9fPj4YdfQDJhr4IpKBi8UwfFkhN/6TzWyMtm1wSziRht7IeL5emi -eyNW+DcGtm72oK0GMyddsyLUzmobR/Urogu6fY5G/2PB51w+8XeG3GLoK/mNC5nD2sOGaRlOVsnd -YVlU1tZI1+LyTyphnXWGIlNUxPO7r3aJ5nk5FrlIi65YLQX8ZVZvXcMeMyZp0b47/k5ewFi2VPvj -3jlOg8XTSIxd3/JrbvP8wQnicr4h+5vGTdHqC/gNP0SIYdQqU2dCzEQXyGs52182sMMub5hH1wBZ -8p0n2qMC2PJzXjYwmpY+9OkIWuW6mxqo/HDmpWs3RvhvNINaykGir3F5H86cU20w62QKhapyx+qp -CJB/FY2iq+A3OLFgu4MA0f13SDrGfkhppfjL+CLbGQzWOSy8W4SL6KRegOD6Yg7qvko+2xo1FR6k -Z22yX/q5tg2X0lJIXUxKcISucvfy3UXzuGjL8R29MRn6UmWRV2lmesJ0DucT8d0a0ZgibKi8Fh1S -9aJL3chrpy55kVMcbUzxQKKHwitVsuDT8HhjTVt10mHi75xSX3wlRzKrAf3+3xhZfg0E6upmLTBx -ow6hbxXmKD591jku3b1uTeVLZj1aPJLg07dNAH7JVsdFtnRG0dAOQ43dk2RH5pSPET79hTz1jWm0 -E8lKwqaaV8uZuYVCQw4QdxY1uqftqQ3ZF+yNgqCDmPAKyIHNJbK6aqVXI0c+aZnAl0ghTaZB5t4u -Qqp0pOBh23w+IX1B/1m4MRp6tCNdHZ5SCVCnZ2QrStd0IHhCZEfSpcV5UyWt+Dhne/g2VewEkOc0 -Mi6NE7tqnuQJI923LTBnp1n3PcHuYvLIOJ7GQ/1YMPvnSun2NZoOjvILdi987dzjq65jEuX3rG+D -8wD7pGDXTX7vL5F0Ji+1rA8dCa7HzA5N3k5hk2YS3tITT0LAdyBFV7VxT6t7JgZKz+RtNz/gSsN4 -/CFlAQx27SmcIyAVImuiUiROmWIRrKDUyWHgkPdibxf6Pk267PpLLQqJ1WXkqqvwlm7K8E3U+MkF -MHhoYwBwSYoAYWSe87cHHZG1XLHLZJQPkDCb6phYmWZQaXwtzVl+FndEGC2Yp6A7GoCU7eV84HuY -H818SuSZ9ybWc3nL4D+T8zCdK1YH8h96CaE1ZzNMY27zN/gEP5tyhu6gWThxrWHNwsWAZvY+RMGQ -t644eK6k/quQsdHh5MDzvDfYaa0e/kVbXMJbjwAAQsTbPfpe38OCk7AC5xsx8T/UEB1PFT1OQ962 -hkSEKQeSnQNuPev668z7c71DJvk9ALHMHhrxVwFYhnfMShvd4rFA3gkw6OIro73W4M5yv0o5F2MR -nyfcDfymCtJNdVVS0ipiqap+nVdgF9bGHsd+eZYnk+ext/twiz+/SpjcOyxAfSVdxYc2WPL0bfoc -4/INme2G2naNv7KNwpswnuF226MFf0+Hre+siTDOJpyC7gL1ZQpeocgJ5dXnDN02jDu0gmEFX1i6 -bEa7JXBMDi315gwKbOJJlP9BgrPHiiTYbsyOuZe6TGUirDG6QCNkoSZfz5SNIcaiFf8fswKg2D8F -1ETZcuj7uRrGuSCZe0kT45+RDWaX63JAm7FzcanKeDDXsdaXyJhffKbTYkHjHDj2CUWZvzUCyAnv -sFiclG7z+oT7LTV1q0qkg8atb3Ub+gC/++bCFbWGXXe/PkrKOsraQVMFaQavj/EoloERyD98pkhr -b6+sI84n0zDG8oi4IXM2b6oVl7dNrbfDkqRv1ARRqKAjfHwKe+midxMOqxxLeDbE4Qmx/dNdU2EW -JjmLgWNM5pvXt0NGACKD0ll7MPTPLz2LUTTixq5QFvlNqwrfu4gK9gAUVZwVT259SCjaC0D6P4rD -D5byloovjTHm6lJLXkksRrlNO70KZ6QrHHoDAW+UI0SU2Euhk3knLiIHaIa4JMOBktkS44cS4vNS -uI7DrPYjpmsYQqPrR6vmOEVtUxRd7vioqZivis6Ze2ygzNGM2ZEma6FZWiglnLHsWeu55zpk2Ca0 -7DdBmNr2R1BggMdM/61VPWF/u6wWDe8eha7VuMC//p+aflDQPDvFtKGFbTdWapXC0JXyfqIiyWt7 -IW8mCGhjuCrzv8P2tEYS/183pL/wJGfcIqWfHBGBh5N/J8/s/Osea+g6kXUjnSBJdEJ2P5649nG+ -DFQpvXUUGnzFtOzRbrxyVBqsjWIceIRBuayUg6pyXQLYEDeLG8orTlKEXcHwBJsPWYEcIzj7c+66 -qdfnZ/bqXct4Yq1o3dvEZkFpHRNbtKRZukq3H4xyXAGbtJe49Q+KCp1ymJyWDY6lkyR2aSIRaxmh -siQye6kuolliICj0Acqfnlc6Trmpl/wXXubU/hx/9H4fxdRymNNK+e2iyVP4KsUo0nlru/HZ5U3L -c1wTVKCYJWbvqMWrbOjDaOHyJrw2MlTxyW1leVfTFAtmkt8P4bCpWm2NzjmXQxib3BMizUVB6DjM -7Kxvadc4De8byelbf1mbP3eEKsNrSi9Qc4terUvVJ3/YI1gd8qEMY9QBwan57lJmpiCr7frKpMcX -rx61xkvE/IS6qp1KI4Oj73LFYRQQJDPtVzlh7Va+NuyUSqpIWzCd8eaCxRrLLoVsbsceis21OMoA -AAAAABLnff+ELabaAAGVmQGAwCAvnfX7scRn+wIAAAAABFla diff --git a/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/1eca914a699e08c7c47791b80b89ceba2a5104f5.yml b/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/1eca914a699e08c7c47791b80b89ceba2a5104f5.yml new file mode 100644 index 0000000000..959cbe3153 --- /dev/null +++ b/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/1eca914a699e08c7c47791b80b89ceba2a5104f5.yml @@ -0,0 +1,2149 @@ +name: Build Runtime Images + +on: + pull_request: + types: [opened, synchronize, reopened, edited] + paths: + - 'build.gradle.kts' + - 'settings.gradle.kts' + - 'gradle.properties' + - 'gradlew' + - 'gradlew.bat' + - 'buildSrc/**' + - 'gradle/**' + - 'protos/**' + - 'docker/**' + - '.dockerignore' + - '.github/workflows/runtime-images.yml' + - '.github/workflows/publish-pr-runtime-images.yml' + - '.github/workflows/smoke.yml' + - '.github/workflows/smoke-full.yml' + - 'services/**' + - '.github/actions/load-workflow-tool-versions/**' + - '.github/actions/setup-python/**' + - '.python-version' + - 'config/workflow-tool-versions.env' + - 'config/python/smoke-requirements.txt' + - 'config/python/smoke-requirements.in' + - 'dev-tools/build-compose-service-jars.sh' + - 'dev-tools/validation/run-gradle-with-dependency-recovery.sh' + - 'dev-tools/validation/run-locked-gradle.sh' + - 'dev-tools/validation/gradle-run-supervisor.py' + - 'dev-tools/build-local-smoke-images.sh' + - 'dev-tools/backups/verify-backups.sh' + - 'dev-tools/backups/pg-dump-s3-selection.shlib' + - 'dev-tools/backups/smoke-backup-verifier-image.sh' + - 'docker/backup-verifier.Dockerfile' + - 'dev-tools/certs/generate-dev-certs.sh' + - 'dev-tools/minio/**' + - 'dev-tools/hosted/controller/smoke-paused-controller-image.sh' + - 'dev-tools/smoke/**' + - 'dev-tools/verify-compose-health.sh' + - 'dev-tools/verify-fresh-bootstrap.sh' + - 'dev-tools/verify-restart-state.sh' + - 'dev-tools/verify-smoke-images.sh' + workflow_run: + workflows: ["CI — Validation"] + types: [completed] + repository_dispatch: + types: [pr-runtime-base-refresh] + workflow_dispatch: + +run-name: Build Runtime Images ${{ (github.event_name == 'pull_request' || github.event_name == 'repository_dispatch') && format('secure-pr-artifact pr-{0} base-{1} head-{2} merge-{3} mode-{4}', github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number, github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.client_payload.base_sha, github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.event.client_payload.head_sha, github.event_name == 'pull_request' && github.sha || github.event.client_payload.merge_sha, github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required') || github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success' && format('trusted-branch branch-{0} sha-{1}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha) || github.event_name == 'workflow_run' && format('base-refresh-only branch-{0} sha-{1} ci-{2}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha, github.event.workflow_run.conclusion) || github.ref_name }} + +permissions: + contents: read + +concurrency: + group: runtime-images-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha, github.sha)) || (github.event_name == 'repository_dispatch' && github.event.client_payload.pr_number != '' && github.event.client_payload.base_sha != '' && github.event.client_payload.head_sha != '' && github.event.client_payload.merge_sha != '' && format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.client_payload.pr_number, github.event.client_payload.base_sha, github.event.client_payload.head_sha, github.event.client_payload.merge_sha)) || (github.event_name == 'repository_dispatch' && format('repository-dispatch-run-{0}', github.run_id)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && format('ci-pr-run-{0}-attempt-{1}', github.event.workflow_run.id, github.event.workflow_run.run_attempt)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && format('branch-{0}', github.event.workflow_run.head_branch)) || github.ref }}-${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required' }} + cancel-in-progress: true + +jobs: + image-meta: + name: Derive Runtime Image Metadata + if: ${{ (github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || (github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh') || github.event_name == 'workflow_dispatch' || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && github.event.workflow_run.conclusion == 'success' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop')) }} + runs-on: ubuntu-latest + outputs: + pr_number: ${{ steps.meta.outputs.pr_number }} + base_ref: ${{ steps.meta.outputs.base_ref }} + base_sha: ${{ steps.meta.outputs.base_sha }} + head_sha: ${{ steps.meta.outputs.head_sha }} + merge_sha: ${{ steps.meta.outputs.merge_sha }} + head_branch: ${{ steps.meta.outputs.head_branch }} + checkout_ref: ${{ steps.meta.outputs.checkout_ref }} + image_tag: ${{ steps.meta.outputs.image_tag }} + candidate_tag: ${{ steps.meta.outputs.candidate_tag }} + base_image: ${{ steps.meta.outputs.base_image }} + canonical_play_transition: ${{ steps.meta.outputs.canonical_play_transition }} + runtime_smoke_required: ${{ steps.smoke_scope.outputs.runtime_smoke_required }} + controller_smoke_required: ${{ steps.smoke_scope.outputs.controller_smoke_required }} + permissions: + actions: read + contents: read + pull-requests: read + steps: + - name: Harden runner + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 + with: + egress-policy: audit + + - name: Check out trusted workflow helpers + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - name: Set up canonical GitHub CLI + uses: ./.github/actions/setup-gh + + - name: Set up canonical Python + uses: ./.github/actions/setup-python + + - name: Derive image tags + id: meta + env: + GH_TOKEN: ${{ github.token }} + EVENT_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.client_payload.head_sha || '' }} + EVENT_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch || '' }} + EVENT_PR_NUMBER: ${{ github.event.pull_request.number || github.event.client_payload.pr_number || '' }} + EVENT_BASE_REF: ${{ github.event.pull_request.base.ref || github.event.client_payload.base_ref || '' }} + EVENT_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.client_payload.base_sha || '' }} + EVENT_MERGE_SHA: ${{ github.event.client_payload.merge_sha || '' }} + EVENT_ACTION: ${{ github.event.action || '' }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + run: | + set -euo pipefail + EVENT_NAME="${{ github.event_name }}" + PR_NUMBER="" + BASE_REF="" + BASE_SHA="" + MERGE_SHA="" + CANONICAL_PLAY_TRANSITION=false + if [ "$EVENT_NAME" = "pull_request" ]; then + PR_NUMBER="$EVENT_PR_NUMBER" + BASE_REF="$EVENT_BASE_REF" + BASE_SHA="$EVENT_BASE_SHA" + HEAD_SHA="$EVENT_HEAD_SHA" + HEAD_BRANCH="" + MERGE_SHA="${GITHUB_SHA}" + CHECKOUT_REF="$MERGE_SHA" + [[ "$MERGE_SHA" =~ ^[0-9a-f]{40}$ ]] || { + echo "PR merge SHA is not a lowercase 40-character commit SHA." >&2 + exit 1 + } + [[ "$BASE_SHA" =~ ^[0-9a-f]{40}$ && "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]] || { + echo "PR event base/head SHAs are not lowercase 40-character commit SHAs." >&2 + exit 1 + } + merge_commit_json="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${MERGE_SHA}")" + jq -e \ + --arg base_sha "$BASE_SHA" \ + --arg head_sha "$HEAD_SHA" \ + --arg merge_sha "$MERGE_SHA" \ + '.sha == $merge_sha and (.parents | type) == "array" and (.parents | length) == 2 and .parents[0].sha == $base_sha and .parents[1].sha == $head_sha' \ + <<<"$merge_commit_json" >/dev/null || { + echo "PR event merge commit does not have the event's exact base/head parents; refusing a stale PR artifact." >&2 + exit 1 + } + elif [ "$EVENT_NAME" = "repository_dispatch" ]; then + [[ "$EVENT_ACTION" == "pr-runtime-base-refresh" ]] || { + echo "Runtime PR refresh requires the typed pr-runtime-base-refresh dispatch." >&2 + exit 1 + } + [[ "$GITHUB_REF" == "refs/heads/${DEFAULT_BRANCH}" ]] || { + echo "Runtime PR refresh must run from the repository default branch." >&2 + exit 1 + } + PR_NUMBER="$EVENT_PR_NUMBER" + BASE_REF="$EVENT_BASE_REF" + BASE_SHA="$EVENT_BASE_SHA" + MERGE_SHA="$EVENT_MERGE_SHA" + HEAD_SHA="$EVENT_HEAD_SHA" + HEAD_BRANCH="" + CHECKOUT_REF="$MERGE_SHA" + [[ "$PR_NUMBER" =~ ^[1-9][0-9]{0,50}$ ]] || { + echo "Runtime PR refresh payload has an invalid pull request number." >&2 + exit 1 + } + git check-ref-format "refs/heads/${BASE_REF}" >/dev/null || { + echo "Runtime PR refresh payload has an invalid base ref." >&2 + exit 1 + } + for sha_name in BASE_SHA HEAD_SHA MERGE_SHA; do + sha_value="${!sha_name}" + [[ "$sha_value" =~ ^[0-9a-f]{40}$ ]] || { + echo "Runtime PR refresh payload has an invalid ${sha_name}." >&2 + exit 1 + } + done + + encoded_base_ref="$(python3 -c 'import sys; from urllib.parse import quote; print(quote(sys.argv[1], safe="/"))' "$BASE_REF")" + current_base_ref_json="$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/heads/${encoded_base_ref}")" + jq -e \ + --arg base_sha "$BASE_SHA" \ + --arg base_ref "refs/heads/${BASE_REF}" \ + '.ref == $base_ref and .object.sha == $base_sha' \ + <<<"$current_base_ref_json" >/dev/null || { + echo "Runtime PR refresh base SHA is not the current ${BASE_REF} branch ref." >&2 + exit 1 + } + pull_request_json="$(gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}")" + jq -e \ + --arg repository "$GITHUB_REPOSITORY" \ + --arg base_ref "$BASE_REF" \ + --arg head_sha "$HEAD_SHA" \ + --arg merge_sha "$MERGE_SHA" \ + '( + .state == "open" and + .base.ref == $base_ref and + .base.repo.full_name == $repository and + .head.sha == $head_sha and + .head.repo.full_name == $repository and + (.mergeable | type) == "boolean" and + .mergeable == true and + (.mergeable_state | type) == "string" and + .mergeable_state != "dirty" and + .mergeable_state != "conflicting" and + .mergeable_state != "unknown" and + .merge_commit_sha == $merge_sha + )' <<<"$pull_request_json" >/dev/null || { + echo "Runtime PR refresh payload is stale, conflicted, fork-owned, closed, or has an invalid merge tuple." >&2 + exit 1 + } + merge_commit_json="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${MERGE_SHA}")" + jq -e \ + --arg base_sha "$BASE_SHA" \ + --arg head_sha "$HEAD_SHA" \ + --arg merge_sha "$MERGE_SHA" \ + '.sha == $merge_sha and (.parents | type) == "array" and (.parents | length) == 2 and .parents[0].sha == $base_sha and .parents[1].sha == $head_sha' \ + <<<"$merge_commit_json" >/dev/null || { + echo "Runtime PR refresh merge commit does not have the exact current base/head parents." >&2 + exit 1 + } + # Only the verified live same-repository PR can authorize this + # diagnostic marker; dispatch payload labels carry no authority. + if jq -e '(.labels | type) == "array" and any(.labels[]; .name == "canonical-play-transition")' \ + <<<"$pull_request_json" >/dev/null; then + CANONICAL_PLAY_TRANSITION=true + fi + elif [ "${{ github.event_name }}" = "workflow_run" ]; then + [[ "${{ github.event.workflow_run.event }}" == "push" ]] || { + echo "Runtime branch publication requires a CI push workflow run." >&2 + exit 1 + } + [[ "${{ github.event.workflow_run.conclusion }}" == "success" ]] || { + echo "Runtime branch publication requires a successful CI workflow run." >&2 + exit 1 + } + HEAD_SHA="${EVENT_HEAD_SHA:-${{ github.event.workflow_run.head_sha }}}" + HEAD_BRANCH="$EVENT_HEAD_BRANCH" + CHECKOUT_REF="$HEAD_SHA" + else + HEAD_SHA="${GITHUB_SHA}" + CHECKOUT_REF="${GITHUB_SHA}" + HEAD_BRANCH="${GITHUB_REF_NAME}" + fi + + [[ "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]] || { + echo "Runtime publication head SHA is not a lowercase 40-character commit SHA." >&2 + exit 1 + } + if [ "$EVENT_NAME" != "pull_request" ] && [ "$EVENT_NAME" != "repository_dispatch" ]; then + [[ "$HEAD_BRANCH" == main || "$HEAD_BRANCH" == develop ]] || { + echo "Runtime branch publication is restricted to main or develop." >&2 + exit 1 + } + fi + + if [ "$EVENT_NAME" = "pull_request" ] || [ "$EVENT_NAME" = "repository_dispatch" ]; then + IMAGE_TAG="pr-merge-${MERGE_SHA}" + else + IMAGE_TAG="${HEAD_SHA}" + fi + CANDIDATE_TAG="candidate-${HEAD_SHA}-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + if [ "$EVENT_NAME" = "pull_request" ] || [ "$EVENT_NAME" = "repository_dispatch" ]; then + BASE_IMAGE="ghcr.io/benhook1013/firemud-base:${MERGE_SHA}" + else + BASE_IMAGE="ghcr.io/benhook1013/firemud-base:${CANDIDATE_TAG}" + fi + + { + echo "pr_number=${PR_NUMBER}" + echo "base_ref=${BASE_REF}" + echo "base_sha=${BASE_SHA}" + echo "head_sha=${HEAD_SHA}" + echo "merge_sha=${MERGE_SHA}" + echo "head_branch=${HEAD_BRANCH}" + echo "checkout_ref=${CHECKOUT_REF}" + echo "image_tag=${IMAGE_TAG}" + echo "candidate_tag=${CANDIDATE_TAG}" + echo "base_image=${BASE_IMAGE}" + echo "canonical_play_transition=${CANONICAL_PLAY_TRANSITION}" + } >> "$GITHUB_OUTPUT" + + - name: Verify successful CI push for manual publication + if: ${{ github.event_name == 'workflow_dispatch' }} + env: + GH_TOKEN: ${{ github.token }} + EXPECTED_SHA: ${{ steps.meta.outputs.head_sha }} + EXPECTED_BRANCH: ${{ steps.meta.outputs.head_branch }} + run: | + set -euo pipefail + ci_runs="$(gh api --paginate --slurp \ + "repos/${GITHUB_REPOSITORY}/actions/workflows/ci.yml/runs?event=push&head_sha=${EXPECTED_SHA}&per_page=100")" + jq -e \ + --arg expected_sha "$EXPECTED_SHA" \ + --arg expected_branch "$EXPECTED_BRANCH" \ + '[.[].workflow_runs[]?] | any(.[]; .head_sha == $expected_sha and .head_branch == $expected_branch and .event == "push" and .status == "completed" and .conclusion == "success")' \ + <<<"$ci_runs" >/dev/null || { + echo "No successful CI push run exists for manual runtime publication ${EXPECTED_BRANCH}@${EXPECTED_SHA}." >&2 + exit 1 + } + + - name: Detect PR smoke scopes + id: smoke_scope + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + let runtimeSmokeRequired = true; + let controllerSmokeRequired = true; + if (context.eventName === "pull_request" || context.eventName === "repository_dispatch") { + try { + const pullNumber = context.eventName === "pull_request" + ? context.payload.pull_request.number + : context.payload.client_payload.pr_number; + const changedFiles = await github.paginate( + github.rest.pulls.listFiles, + { + ...context.repo, + pull_number: pullNumber, + per_page: 100, + }, + (response) => response.data + ); + const expectedFileCount = context.eventName === "pull_request" + ? context.payload.pull_request.changed_files + : (await github.rest.pulls.get({ + ...context.repo, + pull_number: pullNumber, + })).data.changed_files; + const validFileEntries = changedFiles.every((file) => + file && + typeof file.filename === "string" && + file.filename.length > 0 && + (file.previous_filename === undefined || + (typeof file.previous_filename === "string" && file.previous_filename.length > 0)) + ); + if (!Number.isInteger(expectedFileCount) || changedFiles.length !== expectedFileCount || !validFileEntries) { + core.warning("PR smoke scope detection was incomplete; running both local smokes."); + } else { + const paths = changedFiles.flatMap((file) => + [file.filename, file.previous_filename].filter(Boolean) + ); + const runtimePrefixes = [ + "buildSrc/", + "docker/", + "dev-tools/minio/", + "dev-tools/smoke/", + "gradle/", + "protos/", + ".github/actions/load-workflow-tool-versions/", + ".github/actions/setup-python/", + ]; + const workflowToolAuthorityPath = "config/workflow-tool-versions.env"; + const runtimeFiles = new Set([ + ".dockerignore", + ".github/workflows/publish-pr-runtime-images.yml", + ".github/workflows/runtime-images.yml", + ".github/workflows/smoke-full.yml", + ".github/workflows/smoke.yml", + ".github/actions/load-workflow-tool-versions/action.yml", + ".python-version", + "build.gradle.kts", + "config/python/smoke-requirements.txt", + "config/python/smoke-requirements.in", + "dev-tools/build-compose-service-jars.sh", + "dev-tools/validation/run-gradle-with-dependency-recovery.sh", + "dev-tools/validation/run-locked-gradle.sh", + "dev-tools/validation/gradle-run-supervisor.py", + "dev-tools/build-local-smoke-images.sh", + "dev-tools/backups/verify-backups.sh", + "dev-tools/backups/pg-dump-s3-selection.shlib", + "dev-tools/backups/smoke-backup-verifier-image.sh", + "dev-tools/certs/generate-dev-certs.sh", + "dev-tools/verify-compose-health.sh", + "dev-tools/verify-fresh-bootstrap.sh", + "dev-tools/verify-restart-state.sh", + "dev-tools/verify-smoke-images.sh", + "gradle.properties", + "docker/backup-verifier.Dockerfile", + "gradlew", + "gradlew.bat", + "settings.gradle.kts", + ]); + const controllerPrefixes = [ + "buildSrc/", + "gradle/", + "services/hosted-environment-identity-controller/", + ]; + const controllerFiles = new Set([ + ".dockerignore", + ".github/workflows/runtime-images.yml", + "build.gradle.kts", + "dev-tools/hosted/controller/smoke-paused-controller-image.sh", + "docker/base.Dockerfile", + "gradle.properties", + "gradlew", + "gradlew.bat", + "settings.gradle.kts", + ]); + const authorityChanged = paths.includes(workflowToolAuthorityPath); + const nonAuthorityPaths = paths.filter( + (path) => path !== workflowToolAuthorityPath + ); + runtimeSmokeRequired = nonAuthorityPaths.some( + (path) => + runtimeFiles.has(path) || + runtimePrefixes.some((prefix) => path.startsWith(prefix)) || + (path.startsWith("services/") && + !path.startsWith( + "services/hosted-environment-identity-controller/" + )) + ); + runtimeSmokeRequired = runtimeSmokeRequired || authorityChanged; + controllerSmokeRequired = paths.some( + (path) => + controllerFiles.has(path) || + controllerPrefixes.some((prefix) => path.startsWith(prefix)) + ); + } + } catch (error) { + core.warning( + `PR smoke scope detection failed; running both local smokes: ${error.message}` + ); + } + } + core.setOutput("runtime_smoke_required", String(runtimeSmokeRequired)); + core.setOutput("controller_smoke_required", String(controllerSmokeRequired)); + + dispatch-pr-base-refreshes: + name: Dispatch PR Base Refreshes + if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.status == 'completed' && (github.event.workflow_run.event == 'pull_request' || (github.event.workflow_run.event == 'push' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop'))) && github.event.workflow_run.head_repository.full_name == github.repository }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + actions: read + contents: write + pull-requests: read + steps: + - name: Harden runner + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 + with: + egress-policy: audit + + - name: Dispatch exact PR runtime refreshes and preview reconciles + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + const workflowRun = context.payload.workflow_run; + const refreshBranch = workflowRun.head_branch; + const refreshSha = workflowRun.head_sha; + const shaPattern = /^[0-9a-f]{40}$/; + const runtimePrefixes = [ + "buildSrc/", + "docker/", + "dev-tools/minio/", + "dev-tools/smoke/", + "gradle/", + "protos/", + ".github/actions/load-workflow-tool-versions/", + ".github/actions/setup-python/", + ]; + const runtimeFiles = new Set([ + ".dockerignore", + ".github/workflows/publish-pr-runtime-images.yml", + ".github/workflows/runtime-images.yml", + ".github/workflows/smoke-full.yml", + ".github/workflows/smoke.yml", + ".github/actions/load-workflow-tool-versions/action.yml", + ".python-version", + "build.gradle.kts", + "config/workflow-tool-versions.env", + "config/python/smoke-requirements.txt", + "config/python/smoke-requirements.in", + "dev-tools/build-compose-service-jars.sh", + "dev-tools/validation/run-gradle-with-dependency-recovery.sh", + "dev-tools/validation/run-locked-gradle.sh", + "dev-tools/validation/gradle-run-supervisor.py", + "dev-tools/build-local-smoke-images.sh", + "dev-tools/backups/verify-backups.sh", + "dev-tools/backups/pg-dump-s3-selection.shlib", + "dev-tools/backups/smoke-backup-verifier-image.sh", + "dev-tools/certs/generate-dev-certs.sh", + "dev-tools/hosted/controller/smoke-paused-controller-image.sh", + "dev-tools/verify-compose-health.sh", + "dev-tools/verify-fresh-bootstrap.sh", + "dev-tools/verify-restart-state.sh", + "dev-tools/verify-smoke-images.sh", + "gradle.properties", + "gradlew", + "gradlew.bat", + "settings.gradle.kts", + ]); + const runtimeRunEvents = ["pull_request", "repository_dispatch"]; + const runtimeRunPageSize = 100; + const runtimeRunLookbackMilliseconds = 7 * 24 * 60 * 60 * 1000; + + const waitForMergeRefresh = async () => { + await new Promise((resolve) => setTimeout(resolve, 2000)); + }; + + const hasRuntimeChange = async (pullRequest) => { + const files = await github.paginate( + github.rest.pulls.listFiles, + { + ...context.repo, + pull_number: pullRequest.number, + per_page: 100, + }, + (response) => response.data + ); + const expectedFileCount = pullRequest.changed_files; + const validFileEntries = Number.isInteger(expectedFileCount) && + files.length === expectedFileCount && + files.every((file) => + file && + typeof file.filename === "string" && + file.filename.length > 0 && + (file.previous_filename === undefined || + (typeof file.previous_filename === "string" && file.previous_filename.length > 0)) + ); + if (!validFileEntries) { + core.warning(`PR #${pullRequest.number} changed-file metadata was incomplete; refreshing its runtime images.`); + return true; + } + return files.flatMap((file) => [file.filename, file.previous_filename].filter(Boolean)).some((path) => + runtimeFiles.has(path) || + runtimePrefixes.some((prefix) => path.startsWith(prefix)) || + path.startsWith("services/") + ); + }; + + const dependencyBotAuthors = new Set([ + "app/dependabot", + "dependabot[bot]", + "app/renovate", + "renovate[bot]", + ]); + + const isPreviewEligible = (pullRequest) => { + const labels = pullRequest.labels; + return typeof pullRequest.user?.login === "string" && + pullRequest.user.login.length > 0 && + !dependencyBotAuthors.has(pullRequest.user.login) && + Array.isArray(labels) && + labels.every((label) => label && typeof label.name === "string") && + (["main", "develop"].includes(pullRequest.base?.ref) || + labels.some((label) => label.name === "preview:priority")); + }; + + const resolveExactMerge = async (number, baseBranch = refreshBranch, baseSha = refreshSha, expectedHeadSha = null) => { + for (let attempt = 1; attempt <= 5; attempt += 1) { + const response = await github.rest.pulls.get({ + ...context.repo, + pull_number: number, + }); + const pullRequest = response.data; + const currentHeadSha = pullRequest.head?.sha; + const currentBaseRef = pullRequest.base?.ref; + const headRepository = pullRequest.head?.repo?.full_name; + const baseRepository = pullRequest.base?.repo?.full_name; + if (pullRequest.state !== "open" || + headRepository !== context.payload.repository.full_name || + baseRepository !== context.payload.repository.full_name || + currentBaseRef !== baseBranch || + !shaPattern.test(currentHeadSha || "") || + (expectedHeadSha !== null && currentHeadSha !== expectedHeadSha)) { + return null; + } + + const mergeableState = typeof pullRequest.mergeable_state === "string" + ? pullRequest.mergeable_state + : pullRequest.mergeable_state === null ? "unknown" : "invalid"; + if (pullRequest.mergeable === false || + mergeableState === "dirty" || + mergeableState === "conflicting") { + core.warning(`Skipping PR #${number}: GitHub reports a merge conflict.`); + return null; + } + if (pullRequest.mergeable === null || mergeableState === "unknown") { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: GitHub did not produce a ready merge tuple.`); + return null; + } + if (pullRequest.mergeable !== true || mergeableState === "invalid") { + core.warning(`Skipping PR #${number}: GitHub returned invalid merge metadata.`); + return null; + } + + const mergeSha = pullRequest.merge_commit_sha; + if (!shaPattern.test(mergeSha || "")) { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: merge SHA is null or invalid.`); + return null; + } + + try { + const commit = await github.rest.repos.getCommit({ + ...context.repo, + ref: mergeSha, + }); + const parents = commit.data.parents?.map((parent) => parent.sha) || []; + if (commit.data.sha !== mergeSha || + parents.length !== 2 || + parents[0] !== baseSha || + parents[1] !== currentHeadSha) { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: merge commit parents do not match the current base/head.`); + return null; + } + } catch (error) { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: exact merge commit could not be read (${error.message}).`); + return null; + } + + return { + tuple: { + prNumber: String(number), + baseRef: baseBranch, + baseSha, + headSha: currentHeadSha, + mergeSha, + }, + pullRequest, + }; + } + return null; + }; + + const loadExistingRuntimeRuns = async () => { + const readInventory = async (createdSince) => { + const inventory = []; + let complete = true; + let incompleteReason = null; + for (const event of runtimeRunEvents) { + const response = await github.rest.actions.listWorkflowRuns({ + ...context.repo, + workflow_id: "runtime-images.yml", + event, + created: `${createdSince}..*`, + per_page: runtimeRunPageSize, + page: 1, + }); + const payload = response?.data; + if (!payload || !Number.isInteger(payload.total_count) || + payload.total_count < 0 || !Array.isArray(payload.workflow_runs)) { + throw new Error(`runtime-images ${event} recent run inventory is malformed`); + } + if (payload.total_count > runtimeRunPageSize) { + complete = false; + incompleteReason ??= `runtime-images ${event} has more than ${runtimeRunPageSize} runs since ${createdSince}`; + } + const expectedPageLength = Math.min(payload.total_count, runtimeRunPageSize); + if (payload.workflow_runs.length !== expectedPageLength) { + throw new Error(`runtime-images ${event} recent run inventory is incomplete`); + } + inventory.push(...payload.workflow_runs); + } + return {complete, runs: inventory, reason: incompleteReason}; + }; + + const createdSince = new Date(Date.now() - runtimeRunLookbackMilliseconds).toISOString(); + const initial = await readInventory(createdSince); + if (initial.complete) { + return initial; + } + + const inFlightStatuses = ["queued", "waiting", "requested", "pending", "in_progress"]; + const inFlightRuns = initial.runs.filter((run) => inFlightStatuses.includes(run?.status)); + if (inFlightRuns.length === 0) { + return initial; + } + + const validTimestamp = (value) => typeof value === "string" && + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(value) && + Number.isFinite(Date.parse(value)); + if (inFlightRuns.some((run) => !runtimeRunEvents.includes(run.event) || + !Number.isSafeInteger(run.id) || run.id <= 0 || !validTimestamp(run.created_at))) { + return { + ...initial, + reason: "truncated recent inventory contains an in-flight run without a valid event, id, or creation timestamp", + }; + } + + const refinementSince = inFlightRuns + .map((run) => run.created_at) + .sort()[0]; + // The inclusive created lower bound makes the refined pages a complete candidate set without relying on API ordering. + const refined = await readInventory(refinementSince); + if (!refined.complete) { + return { + ...refined, + reason: refined.reason || "refined runtime run inventory is incomplete", + }; + } + const refinedIds = new Set(refined.runs.map((run) => `${run?.event}:${run?.id}`)); + if (inFlightRuns.some((run) => !refinedIds.has(`${run.event}:${run.id}`))) { + return { + ...refined, + complete: false, + reason: "refined inventory did not retain every initially observed in-flight run", + }; + } + return refined; + }; + + const findExactExistingProducer = (tuple, inventory) => { + const expectedWorkflowPath = ".github/workflows/runtime-images.yml"; + const workflowPathMatches = (path) => { + if (path === expectedWorkflowPath) { + return true; + } + const prefix = `${expectedWorkflowPath}@`; + if (typeof path !== "string" || !path.startsWith(prefix)) { + return false; + } + const ref = path.slice(prefix.length); + if (ref.length === 0 || ref === "@" || ref.endsWith(".") || + /[\u0000-\u0020\u007f]/.test(ref) || + ["~", "^", ":", "?", "*", "[", "\\"].some((character) => ref.includes(character)) || + ref.includes("..") || ref.includes("@{")) { + return false; + } + return ref.split("/").every((part) => + part.length > 0 && part !== "." && part !== ".." && + !part.startsWith(".") && + !part.endsWith(".lock") + ); + }; + const expectedTitle = + `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} ` + + `base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; + const matching = inventory.runs.filter((run) => + run?.display_title === expectedTitle + ); + const ordered = []; + const matchingIds = new Set(); + for (const run of matching) { + if (!runtimeRunEvents.includes(run.event) || + !Number.isSafeInteger(run.id) || run.id <= 0 || matchingIds.has(run.id) || + typeof run.created_at !== "string" || + !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(run.created_at) || + !Number.isFinite(Date.parse(run.created_at)) || + !workflowPathMatches(run.path) || + !["Build Runtime Images", expectedTitle].includes(run.name) || + run.repository?.full_name !== context.payload.repository.full_name || + run.head_repository?.full_name !== context.payload.repository.full_name) { + throw new Error(`run ${run.id} has the exact tuple title but invalid workflow or repository identity`); + } + matchingIds.add(run.id); + ordered.push(run); + if (run.event === "pull_request") { + if (run.head_sha !== tuple.headSha) { + throw new Error(`run ${run.id} has the exact tuple title but a different PR head SHA`); + } + const pullRequests = run.pull_requests; + if (!Array.isArray(pullRequests) || (pullRequests.length > 0 && !pullRequests.some((pullRequest) => + String(pullRequest?.number) === tuple.prNumber && + pullRequest?.head?.sha === tuple.headSha + ))) { + throw new Error(`run ${run.id} has incomplete or conflicting PR association evidence`); + } + } + } + ordered.sort((left, right) => right.created_at.localeCompare(left.created_at)); + if (ordered.length > 1 && ordered[0].created_at === ordered[1].created_at) { + throw new Error("newest exact runtime producer has an ambiguous created_at timestamp"); + } + const newest = ordered[0]; + if (!newest) { + return []; + } + if (["queued", "waiting", "requested", "pending", "in_progress"].includes(newest.status)) { + if (newest.conclusion !== null && newest.conclusion !== undefined) { + throw new Error(`run ${newest.id} has a conclusion while still ${newest.status}`); + } + return [newest]; + } + if (newest.status === "completed") { + // Completed source success does not prove publication remains usable; preserve recovery dispatch. + return []; + } + throw new Error(`run ${newest.id} has an unknown status and cannot be classified`); + }; + + if (!shaPattern.test(refreshSha) || typeof refreshBranch !== "string" || + refreshBranch.length === 0) { + core.setFailed("Completed CI callback did not identify a branch and lowercase SHA."); + return; + } + let sourcePrNumber = null; + if (workflowRun.event === "pull_request") { + // Completion is a reconcile signal only for a substantive CI attempt. + // Metadata edits also complete CI, but must never reconstruct runtime. + const positiveInteger = (value) => Number.isSafeInteger(value) && value > 0; + const ciPath = ".github/workflows/ci.yml"; + const ciName = "CI — Validation"; + const titleMatch = /^CI — Validation pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40})$/.exec(workflowRun.display_title || ""); + const matchesSource = (run) => + positiveInteger(workflowRun.id) && positiveInteger(workflowRun.run_attempt) && + positiveInteger(workflowRun.workflow_id) && + run.id === workflowRun.id && run.run_attempt === workflowRun.run_attempt && + run.workflow_id === workflowRun.workflow_id && run.event === "pull_request" && + run.status === "completed" && typeof run.conclusion === "string" && run.conclusion.length > 0 && + run.repository?.full_name === context.payload.repository.full_name && + run.head_repository?.full_name === context.payload.repository.full_name && + run.head_branch === refreshBranch && run.head_sha === refreshSha && + run.display_title === workflowRun.display_title && + [ciName, workflowRun.display_title].includes(run.name) && + (run.path === ciPath || (typeof run.path === "string" && + run.path.startsWith(`${ciPath}@`) && run.path.length > ciPath.length + 1)); + if (!titleMatch || titleMatch[3] !== refreshSha) { + core.warning("Skipping PR runtime reconciliation: callback lacks exact CI PR/base/head title metadata."); + return; + } + const {data: ciWorkflow} = await github.rest.actions.getWorkflow({ + ...context.repo, workflow_id: "ci.yml", + }); + const {data: source} = await github.rest.actions.getWorkflowRun({ + ...context.repo, run_id: workflowRun.id, + }); + if (ciWorkflow.id !== workflowRun.workflow_id || ciWorkflow.path !== ciPath || + ciWorkflow.name !== ciName || !matchesSource(source)) { + core.warning("Skipping PR runtime reconciliation: current CI workflow/run identity differs from callback."); + return; + } + const jobs = await github.paginate( + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + {...context.repo, run_id: source.id, attempt_number: source.run_attempt, per_page: 100} + ); + const gates = jobs.filter((job) => job.name === "Validation Gate"); + const gate = gates.length === 1 ? gates[0] : null; + const preservation = gate?.steps?.filter((step) => + step.name === "Preserve successful required gate on metadata-only edit") || []; + const enforcement = gate?.steps?.filter((step) => step.name === "Enforce validation success") || []; + const checkPrefix = `https://api.github.com/repos/${context.payload.repository.full_name}/check-runs/`; + if (!gate || !positiveInteger(gate.id) || gate.run_id !== source.id || + gate.run_attempt !== source.run_attempt || gate.head_sha !== source.head_sha || + ![ciName, source.display_title].includes(gate.workflow_name) || gate.status !== "completed" || + typeof gate.check_run_url !== "string" || !gate.check_run_url.startsWith(checkPrefix) || + !/^[1-9][0-9]*$/.test(gate.check_run_url.slice(checkPrefix.length)) || + preservation.length !== 1 || preservation[0].status !== "completed" || + preservation[0].conclusion !== "skipped" || enforcement.length !== 1 || + enforcement[0].status !== "completed" || !["success", "failure"].includes(enforcement[0].conclusion)) { + core.info("Skipping PR runtime reconciliation: exact CI attempt is metadata-only or lacks substantive native gate evidence."); + return; + } + const {data: latest} = await github.rest.actions.getWorkflowRun({ + ...context.repo, run_id: source.id, + }); + if (!matchesSource(latest)) { + core.warning("Skipping PR runtime reconciliation: CI attempt was superseded during classification."); + return; + } + sourcePrNumber = titleMatch[1]; + } + let currentBranch; + try { + currentBranch = await github.rest.git.getRef({ + ...context.repo, + ref: `heads/${refreshBranch}`, + }); + } catch (error) { + if (error.status !== 404) throw error; + core.info(`Skipping obsolete CI callback: branch ${refreshBranch} no longer exists.`); + return; + } + if (currentBranch.data.object?.sha !== refreshSha) { + core.warning(`Skipping PR base refresh: ${refreshBranch} advanced beyond the completed CI callback ${refreshSha}.`); + return; + } + + // Protected push callbacks own dependent fan-out; PR callbacks for + // those heads still reconcile their own exact source PR below. + const protectedPrHead = workflowRun.event === "pull_request" && + ["main", "develop"].includes(refreshBranch); + const pullRequests = protectedPrHead ? [] : await github.paginate( + github.rest.pulls.list, + { + ...context.repo, + state: "open", + base: refreshBranch, + per_page: 100, + }, + (response) => response.data + ); + const refreshTargets = []; + for (const listedPullRequest of pullRequests) { + if (listedPullRequest.state !== "open" || + listedPullRequest.base?.ref !== refreshBranch || + listedPullRequest.head?.repo?.full_name !== context.payload.repository.full_name || + listedPullRequest.base?.repo?.full_name !== context.payload.repository.full_name) { + continue; + } + const resolved = await resolveExactMerge(listedPullRequest.number); + if (resolved) { + refreshTargets.push(resolved); + } + } + if (workflowRun.event === "pull_request") { + // A retarget/edit can carry an unusable event merge SHA. CI completion + // is only a reconcile signal: re-read its source's current exact tuple. + const sourcePullRequests = await github.paginate( + github.rest.pulls.list, + { + ...context.repo, + state: "open", + head: `${context.repo.owner}:${refreshBranch}`, + per_page: 100, + }, + (response) => response.data + ); + for (const source of sourcePullRequests) { + if (String(source.number) !== sourcePrNumber || + source.state !== "open" || source.head?.sha !== refreshSha || + source.head?.ref !== refreshBranch || + source.head?.repo?.full_name !== context.payload.repository.full_name || + source.base?.repo?.full_name !== context.payload.repository.full_name || + typeof source.base?.ref !== "string" || + source.base.ref.length === 0) { + continue; + } + const sourceBase = await github.rest.git.getRef({ + ...context.repo, + ref: `heads/${source.base.ref}`, + }); + const sourceBaseSha = sourceBase.data.object?.sha; + if (!shaPattern.test(sourceBaseSha || "")) { + core.warning(`Skipping source PR #${source.number}: current base ref SHA is invalid.`); + continue; + } + const resolved = await resolveExactMerge(source.number, source.base.ref, sourceBaseSha, refreshSha); + if (resolved && !refreshTargets.some((target) => target.tuple.prNumber === resolved.tuple.prNumber)) { + refreshTargets.push(resolved); + } + } + } + let runtimeInventoryPromise; + let runtimeInventoryError = null; + for (const resolved of refreshTargets) { + const {tuple, pullRequest} = resolved; + if (await hasRuntimeChange(pullRequest)) { + let existingProducers = []; + let fallbackReason = null; + let inventory; + if (runtimeInventoryError) { + fallbackReason = runtimeInventoryError; + } else { + try { + runtimeInventoryPromise ??= loadExistingRuntimeRuns(); + inventory = await runtimeInventoryPromise; + } catch (error) { + fallbackReason = error.message || String(error); + runtimeInventoryError = fallbackReason; + } + } + if (!fallbackReason) { + try { + existingProducers = findExactExistingProducer(tuple, inventory); + if (!inventory.complete) { + // The REST contract does not specify a sort order, so a truncated page cannot prove omitted runs are older. + existingProducers = []; + fallbackReason = inventory.reason || "recent run inventory is incomplete"; + } + } catch (error) { + fallbackReason = error.message || String(error); + } + } + if (fallbackReason) { + core.warning( + `Cannot verify recent runtime producer evidence for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}); falling back to the required refresh dispatch: ${fallbackReason}` + ); + } + if (existingProducers.length > 0) { + const producer = existingProducers[0]; + core.info( + `Skipping duplicate PR runtime refresh for #${tuple.prNumber}: exact tuple producer ${producer.id} remains ${producer.status}.` + ); + } else { + core.info(`No reusable in-flight exact producer was verified in the bounded recent inventory; dispatching required PR runtime refresh for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); + await github.rest.repos.createDispatchEvent({ + ...context.repo, + event_type: "pr-runtime-base-refresh", + client_payload: { + pr_number: tuple.prNumber, + base_ref: tuple.baseRef, + base_sha: tuple.baseSha, + head_sha: tuple.headSha, + merge_sha: tuple.mergeSha, + }, + }); + } + } else { + core.info(`Skipping PR runtime image refresh for #${tuple.prNumber}: no runtime-changing files.`); + } + if (!isPreviewEligible(pullRequest)) { + core.info(`Skipping preview deploy reconciliation for #${tuple.prNumber}: target is not preview-eligible.`); + continue; + } + core.info(`Dispatching preview deploy reconciliation for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); + await github.rest.repos.createDispatchEvent({ + ...context.repo, + event_type: "preview-deploy", + client_payload: { + action: "deploy", + pr_number: tuple.prNumber, + base_ref: tuple.baseRef, + base_sha: tuple.baseSha, + head_sha: tuple.headSha, + merge_sha: tuple.mergeSha, + preview_domain: "preview.firedevops.net", + }, + }); + } + + build-base-image: + name: Build Runtime Base Image + needs: [image-meta] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + runs-on: ubuntu-latest + outputs: + digest: ${{ steps.select_base_image_digest.outputs.digest }} + permissions: + # This job publishes the shared runtime base image to GHCR. + contents: read + packages: write + steps: + - name: Harden runner + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 + with: + egress-policy: audit + + - name: ⬇️ Checkout Code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push runtime base image + id: build_base_image_first + continue-on-error: true + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: ./docker/base.Dockerfile + push: true + tags: ${{ needs.image-meta.outputs.base_image }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache + type=registry,ref=ghcr.io/benhook1013/firemud-base:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache,mode=max + type=gha,mode=max + + - name: Retry build and push runtime base image + id: build_base_image_retry + if: ${{ steps.build_base_image_first.outcome == 'failure' }} + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: ./docker/base.Dockerfile + push: true + tags: ${{ needs.image-meta.outputs.base_image }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache + type=registry,ref=ghcr.io/benhook1013/firemud-base:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache,mode=max + type=gha,mode=max + + - name: Select exact published runtime base digest + id: select_base_image_digest + if: ${{ !cancelled() }} + env: + FIRST_OUTCOME: ${{ steps.build_base_image_first.outcome }} + FIRST_DIGEST: ${{ steps.build_base_image_first.outputs.digest }} + RETRY_OUTCOME: ${{ steps.build_base_image_retry.outcome }} + RETRY_DIGEST: ${{ steps.build_base_image_retry.outputs.digest }} + run: | + set -euo pipefail + published_digests=() + if [[ "$FIRST_OUTCOME" == "success" ]]; then + published_digests+=("$FIRST_DIGEST") + fi + if [[ "$RETRY_OUTCOME" == "success" ]]; then + published_digests+=("$RETRY_DIGEST") + fi + if ((${#published_digests[@]} != 1)); then + echo "Expected exactly one successful runtime base-image publication digest." >&2 + exit 1 + fi + base_image_digest="${published_digests[0]}" + [[ "$base_image_digest" =~ ^sha256:[0-9a-f]{64}$ ]] || { + echo "Runtime base-image publisher returned an invalid sha256 digest." >&2 + exit 1 + } + echo "digest=$base_image_digest" >> "$GITHUB_OUTPUT" + + build-runtime-images: + name: Build Runtime Images (${{ matrix.service }}) + needs: [image-meta, build-base-image] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + runs-on: ubuntu-latest + permissions: + # This job publishes only unique staging service tags. Canonical aliases + # are written by publish-runtime-images after the exact candidate passes smoke. + contents: read + packages: write + strategy: + fail-fast: false + matrix: + service: + - account-service + - automation-scripting-service + - entity-management-service + - game-design-service + - game-logic-service + - game-session-service + - logging-admin-service + - social-groups-service + - spring-cloud-gateway + - tcp-proxy-service + - world-management-service + steps: + - name: Harden runner + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 + with: + egress-policy: audit + + - name: ⬇️ Checkout Code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: ⚙️ Set Up Java + uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: ⚙️ Set Up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: false + + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + + - name: Build service JAR + run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- :${{ matrix.service }}:bootJar + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push runtime service image + id: build_runtime_image_first + continue-on-error: true + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: ./services/${{ matrix.service }}/build/libs + file: ./services/${{ matrix.service }}/Dockerfile + push: true + build-contexts: | + repo_root=. + build-args: | + BASE_IMAGE=ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }} + tags: ghcr.io/benhook1013/${{ matrix.service }}:${{ needs.image-meta.outputs.candidate_tag }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache,mode=max + type=gha,mode=max + + - name: Retry build and push runtime service image + if: ${{ steps.build_runtime_image_first.outcome == 'failure' }} + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: ./services/${{ matrix.service }}/build/libs + file: ./services/${{ matrix.service }}/Dockerfile + push: true + build-contexts: | + repo_root=. + build-args: | + BASE_IMAGE=ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }} + tags: ghcr.io/benhook1013/${{ matrix.service }}:${{ needs.image-meta.outputs.candidate_tag }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache,mode=max + type=gha,mode=max + + build-backup-verifier: + name: Build Backup Verifier Image + needs: [image-meta] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') }} + runs-on: ubuntu-latest + timeout-minutes: 15 + outputs: + image_id: ${{ steps.smoke.outputs.image_id }} + permissions: + contents: read + env: + BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 + with: + egress-policy: audit + + - name: Checkout trusted branch commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Load workflow tool versions + id: workflow-tool-versions + uses: ./.github/actions/load-workflow-tool-versions + + - name: Build backup verifier image + run: | + docker build \ + --file docker/backup-verifier.Dockerfile \ + --tag "$BACKUP_VERIFIER_IMAGE" \ + . + + - name: Smoke backup verifier image + id: smoke + env: + VELERO_VERSION: ${{ steps.workflow-tool-versions.outputs.velero-version }} + run: | + set -euo pipefail + bash ./dev-tools/backups/smoke-backup-verifier-image.sh "$BACKUP_VERIFIER_IMAGE" "$VELERO_VERSION" + image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" + [[ "$image_id" =~ ^sha256:[0-9a-f]{64}$ ]] || { + echo "Backup verifier image did not return an exact image ID." >&2 + exit 1 + } + echo "image_id=$image_id" >> "$GITHUB_OUTPUT" + + - name: Export exact verified backup verifier image artifact + env: + VERIFIED_IMAGE_ID: ${{ steps.smoke.outputs.image_id }} + run: | + set -euo pipefail + current_image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" + [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Backup verifier image changed after its smoke proof; refusing artifact export." >&2 + exit 1 + } + docker save "$BACKUP_VERIFIER_IMAGE" | gzip -1 > "$RUNNER_TEMP/backup-verifier.tar.gz" + + - name: Upload exact verified backup verifier image artifact + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: backup-verifier-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/backup-verifier.tar.gz + if-no-files-found: error + retention-days: 1 + + publish-backup-verifier: + name: Publish Trusted Backup Verifier Image + needs: [image-meta, build-backup-verifier] + if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-backup-verifier.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + packages: write + id-token: write + attestations: write + env: + BACKUP_VERIFIER_IMAGE_NAME: ghcr.io/benhook1013/backup-verifier + BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 + with: + egress-policy: audit + + - name: Checkout trusted publication commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Download exact verified backup verifier image artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: backup-verifier-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/backup-verifier-artifact + + - name: Load and verify exact backup verifier image + env: + BACKUP_VERIFIER_ARCHIVE: ${{ runner.temp }}/backup-verifier-artifact/backup-verifier.tar.gz + VERIFIED_IMAGE_ID: ${{ needs.build-backup-verifier.outputs.image_id }} + run: | + set -euo pipefail + [[ -f "$BACKUP_VERIFIER_ARCHIVE" ]] || { + echo "Verified backup verifier image artifact is missing." >&2 + exit 1 + } + gzip -dc "$BACKUP_VERIFIER_ARCHIVE" | docker load + loaded_image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" + [[ "$loaded_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Loaded backup verifier image does not match the exact verified build image." >&2 + exit 1 + } + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Publish exact verified backup verifier image + id: publish + run: | + set -euo pipefail + bash ./dev-tools/hosted/shared/push-verified-image.sh "$BACKUP_VERIFIER_IMAGE" + + - name: Attest trusted backup verifier image provenance + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-name: ${{ env.BACKUP_VERIFIER_IMAGE_NAME }} + subject-digest: ${{ steps.publish.outputs.digest }} + push-to-registry: true + create-storage-record: false + + build-hosted-identity-controller: + name: Build Trusted Hosted Identity Controller + needs: [image-meta, build-base-image] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-base-image.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 25 + outputs: + image_id: ${{ steps.smoke.outputs.image_id }} + permissions: + contents: read + packages: read + env: + CONTROLLER_IMAGE_NAME: ghcr.io/benhook1013/firemud-hosted-identity-controller + CONTROLLER_IMAGE: ghcr.io/benhook1013/firemud-hosted-identity-controller:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 + with: + egress-policy: audit + + - name: Checkout trusted branch commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up Java + uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: false + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + + - name: Build controller JAR and image locally + run: | + set -euo pipefail + bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- :hosted-environment-identity-controller:bootJar + docker build \ + --file services/hosted-environment-identity-controller/Dockerfile \ + --build-arg BASE_IMAGE="ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }}" \ + --tag "$CONTROLLER_IMAGE" \ + services/hosted-environment-identity-controller/build/libs + + - name: Smoke exact controller image + id: smoke + run: | + set -euo pipefail + smoked_image_id="$(bash ./dev-tools/hosted/controller/smoke-paused-controller-image.sh "$CONTROLLER_IMAGE")" + local_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$smoked_image_id" == "$local_image_id" ]] || { + echo "Controller smoke did not execute the exact locally tagged image." >&2 + exit 1 + } + echo "image_id=$local_image_id" >> "$GITHUB_OUTPUT" + + - name: Export exact verified controller image artifact + env: + VERIFIED_IMAGE_ID: ${{ steps.smoke.outputs.image_id }} + run: | + set -euo pipefail + current_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Controller image changed after its smoke proof; refusing artifact export." >&2 + exit 1 + } + docker save "$CONTROLLER_IMAGE" | gzip -1 > "$RUNNER_TEMP/hosted-identity-controller.tar.gz" + + - name: Upload exact verified controller image artifact + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: hosted-identity-controller-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/hosted-identity-controller.tar.gz + if-no-files-found: error + retention-days: 1 + + publish-hosted-identity-controller: + name: Publish Trusted Hosted Identity Controller + needs: [image-meta, build-base-image, build-hosted-identity-controller] + if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-base-image.result == 'success' && needs.build-hosted-identity-controller.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 25 + permissions: + contents: read + packages: write + id-token: write + attestations: write + env: + CONTROLLER_IMAGE_NAME: ghcr.io/benhook1013/firemud-hosted-identity-controller + CONTROLLER_IMAGE: ghcr.io/benhook1013/firemud-hosted-identity-controller:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 + with: + egress-policy: audit + + - name: Checkout trusted publication commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Download exact verified controller image artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: hosted-identity-controller-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/hosted-identity-controller-artifact + + - name: Load and verify exact controller image + env: + CONTROLLER_ARCHIVE: ${{ runner.temp }}/hosted-identity-controller-artifact/hosted-identity-controller.tar.gz + VERIFIED_IMAGE_ID: ${{ needs.build-hosted-identity-controller.outputs.image_id }} + run: | + set -euo pipefail + [[ -f "$CONTROLLER_ARCHIVE" ]] || { + echo "Verified hosted identity controller image artifact is missing." >&2 + exit 1 + } + gzip -dc "$CONTROLLER_ARCHIVE" | docker load + loaded_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$loaded_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Loaded controller image does not match the exact verified build image." >&2 + exit 1 + } + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Publish exact verified controller image + id: publish + env: + VERIFIED_IMAGE_ID: ${{ needs.build-hosted-identity-controller.outputs.image_id }} + run: | + set -euo pipefail + current_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Controller image changed after its verification proof; refusing publication." >&2 + exit 1 + } + bash ./dev-tools/hosted/shared/push-verified-image.sh "$CONTROLLER_IMAGE" + + - name: Attest trusted controller image provenance + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-name: ${{ env.CONTROLLER_IMAGE_NAME }} + subject-digest: ${{ steps.publish.outputs.digest }} + push-to-registry: true + create-storage-record: false + + pr-local-smoke: + outputs: + publishable: ${{ steps.runtime-artifact.outcome == 'success' }} + name: PR Full-Stack Smoke (runtime-required=${{ needs.image-meta.outputs.runtime_smoke_required }}) + needs: [image-meta] + if: ${{ (github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || github.event_name == 'repository_dispatch' }} + runs-on: ubuntu-latest + timeout-minutes: 45 + permissions: + # PR-controlled source receives no registry or repository write credential. + contents: read + env: + COMPOSE_PROJECT_NAME: smoke-full-${{ github.run_id }}-${{ github.run_attempt }} + SMOKE_TIMEOUT_SECONDS: 20 + SMOKE_IMAGE_TAG: ${{ needs.image-meta.outputs.image_tag }} + SMOKE_IMAGE_LOCAL_ONLY: 'true' + SMOKE_MINIO_LOCAL_ONLY: 'true' + SMOKE_MINIO_SERVER_IMAGE: >- + firemud-minio-server-smoke:${{ github.run_id }}-${{ github.run_attempt }} + SMOKE_MINIO_CLIENT_IMAGE: >- + firemud-minio-client-smoke:${{ github.run_id }}-${{ github.run_attempt }} + BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 + with: + egress-policy: audit + + - name: Checkout PR merge + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Load workflow tool versions + id: workflow-tool-versions + uses: ./.github/actions/load-workflow-tool-versions + + - name: Set up canonical Python + if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} + uses: ./.github/actions/setup-python + with: + requirements: smoke + + - name: Set up Java + uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: true + + - name: Build local PR runtime images + id: runtime-images-build + env: + MERGE_SHA: ${{ needs.image-meta.outputs.merge_sha }} + run: | + set -euo pipefail + bash ./dev-tools/build-local-smoke-images.sh "$MERGE_SHA" + for service in \ + account-service \ + automation-scripting-service \ + entity-management-service \ + game-design-service \ + game-logic-service \ + game-session-service \ + logging-admin-service \ + social-groups-service \ + spring-cloud-gateway \ + tcp-proxy-service \ + world-management-service; do + docker tag \ + "ghcr.io/benhook1013/${service}:${MERGE_SHA}" \ + "ghcr.io/benhook1013/${service}:${SMOKE_IMAGE_TAG}" + done + + - name: Retain runtime bootJar compile-failure evidence + if: ${{ failure() && steps.runtime-images-build.outcome == 'failure' }} + continue-on-error: true + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: runtime-bootjar-compile-failure-${{ github.run_id }}-attempt-${{ github.run_attempt }} + path: ${{ steps.runtime-images-build.outputs.runtime_compile_failure_path || format('build/reports/compile-failure/runtime-bootjar/unavailable-{0}-{1}', github.run_id, github.run_attempt) }} + if-no-files-found: warn + retention-days: 3 + + - name: Build PR backup verifier image + run: | + docker build \ + --file docker/backup-verifier.Dockerfile \ + --tag "$BACKUP_VERIFIER_IMAGE" \ + . + + - name: Smoke PR backup verifier image + env: + VELERO_VERSION: ${{ steps.workflow-tool-versions.outputs.velero-version }} + run: bash ./dev-tools/backups/smoke-backup-verifier-image.sh "$BACKUP_VERIFIER_IMAGE" "$VELERO_VERSION" + + - name: Build and smoke pinned MinIO sources for PR Compose + id: minio-source + if: >- + ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} + run: | + bash ./dev-tools/minio/build-and-smoke-images.sh \ + "$SMOKE_MINIO_SERVER_IMAGE" "$SMOKE_MINIO_CLIENT_IMAGE" + + - name: Run credential-free full-stack smoke + id: runtime-smoke + # The terminal guard admits only the classified, labeled transition failure. + continue-on-error: true + if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} + env: + FIREMUD_SMOKE_ADMISSION_QUALIFICATION: held + SMOKE_MINIO_SERVER_IMAGE_ID: >- + ${{ steps.minio-source.outputs.server_image_id }} + SMOKE_MINIO_CLIENT_IMAGE_ID: >- + ${{ steps.minio-source.outputs.client_image_id }} + run: bash ./dev-tools/verify-smoke-images.sh --keep-running + + - name: Export fixed-tag preview image artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} + run: | + service_manifest=/tmp/pr-runtime-services.txt + provenance=/tmp/pr-runtime-provenance.json + : > "$service_manifest" + images=() + for service in \ + account-service \ + automation-scripting-service \ + entity-management-service \ + game-design-service \ + game-logic-service \ + game-session-service \ + logging-admin-service \ + social-groups-service \ + spring-cloud-gateway \ + tcp-proxy-service \ + world-management-service; do + printf '%s\n' "$service" >> "$service_manifest" + images+=("ghcr.io/benhook1013/${service}:${SMOKE_IMAGE_TAG}") + done + printf '%s\n' 'backup-verifier' >> "$service_manifest" + images+=("$BACKUP_VERIFIER_IMAGE") + PR_NUMBER="${{ needs.image-meta.outputs.pr_number }}" \ + BASE_SHA="${{ needs.image-meta.outputs.base_sha }}" \ + HEAD_SHA="${{ needs.image-meta.outputs.head_sha }}" \ + MERGE_SHA="${{ needs.image-meta.outputs.merge_sha }}" \ + IMAGE_TAG="${SMOKE_IMAGE_TAG}" \ + SOURCE_RUN_ID="${{ github.run_id }}" \ + REPOSITORY="${GITHUB_REPOSITORY}" \ + PROVENANCE_PATH="$provenance" \ + python3 - <<'PY' + import json + import os + + services = [ + "account-service", + "automation-scripting-service", + "entity-management-service", + "game-design-service", + "game-logic-service", + "game-session-service", + "logging-admin-service", + "social-groups-service", + "spring-cloud-gateway", + "tcp-proxy-service", + "world-management-service", + "backup-verifier", + ] + provenance = { + "repository": os.environ["REPOSITORY"], + "prNumber": int(os.environ["PR_NUMBER"]), + "baseSha": os.environ["BASE_SHA"], + "headSha": os.environ["HEAD_SHA"], + "mergeSha": os.environ["MERGE_SHA"], + "imageTag": os.environ["IMAGE_TAG"], + "sourceRunId": int(os.environ["SOURCE_RUN_ID"]), + "services": services, + } + with open(os.environ["PROVENANCE_PATH"], "w", encoding="utf-8") as output: + json.dump(provenance, output, separators=(",", ":"), sort_keys=True) + output.write("\n") + PY + docker save "${images[@]}" | gzip -1 > /tmp/pr-runtime-images.tar.gz + + - name: Upload preview image artifact + id: runtime-artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: pr-runtime-images-${{ needs.image-meta.outputs.image_tag }} + path: | + /tmp/pr-runtime-images.tar.gz + /tmp/pr-runtime-services.txt + /tmp/pr-runtime-provenance.json + if-no-files-found: error + retention-days: 1 + + - name: Summarize secure PR runtime artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} + env: + PR_NUMBER: ${{ needs.image-meta.outputs.pr_number }} + BASE_SHA: ${{ needs.image-meta.outputs.base_sha }} + HEAD_SHA: ${{ needs.image-meta.outputs.head_sha }} + MERGE_SHA: ${{ needs.image-meta.outputs.merge_sha }} + ARTIFACT_NAME: pr-runtime-images-${{ needs.image-meta.outputs.image_tag }} + run: | + { + echo "### PR runtime images and applicable full-stack smoke" + echo + echo "- Pull request: #${PR_NUMBER}" + echo "- Base SHA: \`${BASE_SHA}\`" + echo "- PR head SHA: \`${HEAD_SHA}\`" + echo "- Built PR merge SHA (full-stack smoke runs when required): \`${MERGE_SHA}\`" + echo "- Merge-scoped publication tag: \`pr-merge-${MERGE_SHA}\`" + echo "- Artifact: \`${ARTIFACT_NAME}\`" + echo + echo "This read-only PR workflow built the PR merge commit and runs full-stack smoke when required by change scope. The trusted default-branch publisher uploads only the exact merge-scoped artifact from this successful run." + } >> "$GITHUB_STEP_SUMMARY" + + - name: Dump Docker Compose logs on failure + if: >- + ${{ always() && steps.runtime-smoke.outcome == 'failure' && + needs.image-meta.outputs.runtime_smoke_required == 'true' && + steps.minio-source.outputs.server_image_id != '' && + steps.minio-source.outputs.client_image_id != '' }} + env: + SMOKE_MINIO_SERVER_IMAGE_ID: >- + ${{ steps.minio-source.outputs.server_image_id }} + SMOKE_MINIO_CLIENT_IMAGE_ID: >- + ${{ steps.minio-source.outputs.client_image_id }} + run: | + docker compose \ + -f docker/docker-compose.yml \ + -f docker/docker-compose.override.yml \ + -f docker/docker-compose.smoke-images.override.yml \ + -f docker/docker-compose.pr-local-minio.override.yml \ + logs || true + + - name: Stop smoke stack + id: runtime-cleanup + if: >- + ${{ always() && + needs.image-meta.outputs.runtime_smoke_required == 'true' && + steps.minio-source.outputs.server_image_id != '' && + steps.minio-source.outputs.client_image_id != '' }} + env: + SMOKE_MINIO_SERVER_IMAGE_ID: >- + ${{ steps.minio-source.outputs.server_image_id }} + SMOKE_MINIO_CLIENT_IMAGE_ID: >- + ${{ steps.minio-source.outputs.client_image_id }} + run: | + source ./dev-tools/smoke/run-owned-compose.sh + if ! stop_run_owned_compose_project \ + -f docker/docker-compose.yml \ + -f docker/docker-compose.override.yml \ + -f docker/docker-compose.smoke-images.override.yml \ + -f docker/docker-compose.pr-local-minio.override.yml; then + echo "Unable to prove or release the smoke Compose project; refusing unowned teardown." >&2 + exit 1 + fi + + # Canonical-transition diagnostic evidence, not runtime qualification. The + # native smoke outcome remains failed; only the bounded CI exception may pass. + - name: Known canonical transition PLAY failure with successful authenticated cleanup + id: canonical-play-transition + if: >- + ${{ always() && + github.repository == 'benhook1013/FireMUD' && + ((github.event_name == 'pull_request' && + contains(github.event.pull_request.labels.*.name, 'canonical-play-transition')) || + (github.event_name == 'repository_dispatch' && + github.event.action == 'pr-runtime-base-refresh' && + needs.image-meta.outputs.canonical_play_transition == 'true')) && + needs.image-meta.outputs.runtime_smoke_required == 'true' && + steps.runtime-smoke.outcome == 'failure' && + steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login' && + steps.runtime-cleanup.outcome == 'success' }} + run: | + echo '### Canonical PLAY transition exception evidence' >> "$GITHUB_STEP_SUMMARY" + echo 'LOGIN succeeded; direct backend PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE. Held-admission qualification and authenticated cleanup passed. No runtime qualification, image export, or publication.' >> "$GITHUB_STEP_SUMMARY" + + - name: Require successful runtime smoke and authenticated cleanup + if: ${{ always() }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + env: + RUNTIME_SMOKE_REQUIRED: ${{ needs.image-meta.outputs.runtime_smoke_required }} + RUNTIME_SMOKE_OUTCOME: ${{ steps.runtime-smoke.outcome }} + RUNTIME_CLEANUP_OUTCOME: ${{ steps.runtime-cleanup.outcome }} + KNOWN_PLAY_EXCEPTION_OUTCOME: ${{ steps.canonical-play-transition.outcome }} + with: + script: | + const required = process.env.RUNTIME_SMOKE_REQUIRED; + if (required !== "true" && required !== "false") { + core.setFailed("Runtime smoke scope is unavailable or invalid."); + } else if (required === "true" && ( + process.env.RUNTIME_CLEANUP_OUTCOME !== "success" || + (process.env.RUNTIME_SMOKE_OUTCOME !== "success" && !( + process.env.RUNTIME_SMOKE_OUTCOME === "failure" && + process.env.KNOWN_PLAY_EXCEPTION_OUTCOME === "success" + )) + )) { + core.setFailed("Required runtime smoke and authenticated cleanup must both execute successfully, unless the exact canonical PLAY transition exception is attested."); + } else if (required === "true" && process.env.RUNTIME_SMOKE_OUTCOME === "failure") { + core.warning("CI passed under the canonical PLAY transition exception. Runtime qualification and image publication remain blocked."); + } + + pr-controller-smoke: + name: PR Hosted Identity Controller Smoke + needs: [image-meta] + if: ${{ ((github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || github.event_name == 'repository_dispatch') && needs.image-meta.outputs.controller_smoke_required == 'true' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + # PR-controlled source receives no registry or repository write credential. + contents: read + env: + BASE_IMAGE: ${{ needs.image-meta.outputs.base_image }} + CONTROLLER_IMAGE: firemud-hosted-identity-controller-local:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 + with: + egress-policy: audit + + - name: Checkout PR merge + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up Java + uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: true + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Build exact local runtime base image + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: docker/base.Dockerfile + push: false + load: true + tags: ${{ env.BASE_IMAGE }} + cache-from: type=gha,scope=pr-controller-smoke + cache-to: type=gha,mode=max,scope=pr-controller-smoke + + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + + - name: Build controller image for credential-free local validation + run: | + set -euo pipefail + bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh \ + --runner ./gradlew -- :hosted-environment-identity-controller:bootJar + docker build \ + --file services/hosted-environment-identity-controller/Dockerfile \ + --build-arg BASE_IMAGE="$BASE_IMAGE" \ + --tag "$CONTROLLER_IMAGE" \ + services/hosted-environment-identity-controller/build/libs + + - name: Smoke controller image entrypoint and paused health + run: | + set -euo pipefail + bash ./dev-tools/hosted/controller/smoke-paused-controller-image.sh "$CONTROLLER_IMAGE" >/dev/null + + dispatch-pr-runtime-publication: + name: Dispatch Trusted PR Runtime Publication + needs: [image-meta, pr-local-smoke, pr-controller-smoke] + if: ${{ always() && !cancelled() && github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && needs.image-meta.result == 'success' && needs.pr-local-smoke.result == 'success' && needs.pr-local-smoke.outputs.publishable == 'true' && (needs.pr-controller-smoke.result == 'success' || (needs.image-meta.outputs.controller_smoke_required == 'false' && needs.pr-controller-smoke.result == 'skipped')) }} + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + # This trusted no-checkout job only sends an exact source-run handoff. + contents: write + steps: + - name: Harden runner + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 + with: + egress-policy: audit + + - name: Dispatch exact runtime publication source + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + await github.rest.repos.createDispatchEvent({ + ...context.repo, + event_type: "pr-runtime-image-publication", + client_payload: { source_run_id: String(context.runId) }, + }); + + smoke-full: + name: Published Runtime Full-Stack Smoke + needs: [image-meta, build-runtime-images] + if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.build-runtime-images.result == 'success' }} + permissions: + # The trusted branch smoke workflow only pulls the staged candidate images. + contents: read + packages: read + uses: ./.github/workflows/smoke-full.yml + with: + action: full + head_sha: ${{ needs.image-meta.outputs.head_sha }} + checkout_ref: ${{ needs.image-meta.outputs.checkout_ref }} + image_tag: ${{ needs.image-meta.outputs.candidate_tag }} + secrets: inherit + + publish-runtime-images: + name: Promote Smoke-Tested Runtime Images + needs: [image-meta, build-runtime-images, smoke-full] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.build-runtime-images.result == 'success' && needs.smoke-full.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + packages: write + env: + HEAD_SHA: ${{ needs.image-meta.outputs.head_sha }} + HEAD_BRANCH: ${{ needs.image-meta.outputs.head_branch }} + CANDIDATE_TAG: ${{ needs.image-meta.outputs.candidate_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 + with: + egress-policy: audit + + - name: Checkout trusted publication source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up canonical GitHub CLI + uses: ./.github/actions/setup-gh + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Promote smoke-tested service digests + env: + GH_TOKEN: ${{ github.token }} + GHCR_USERNAME: ${{ github.actor }} + GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + + services=( + account-service + automation-scripting-service + entity-management-service + game-design-service + game-logic-service + game-session-service + logging-admin-service + social-groups-service + spring-cloud-gateway + tcp-proxy-service + world-management-service + ) + + declare -A registry_tokens=() + registry_manifest_state() { + local image="$1" + local image_path="${image#ghcr.io/}" + local repository_path="${image_path%:*}" + local tag="${image_path##*:}" + local manifest_url="https://ghcr.io/v2/${repository_path}/manifests/${tag}" + local registry_token="${registry_tokens[$repository_path]:-}" + local status + + [[ -n "${GHCR_USERNAME:-}" && -n "${GHCR_TOKEN:-}" ]] || { + echo "GHCR credentials are unavailable for authenticated manifest preflight: $image" >&2 + return 1 + } + if [[ -z "$registry_token" ]]; then + if ! registry_token="$(curl --silent --show-error --location --fail \ + --connect-timeout 10 --max-time 30 \ + --user "${GHCR_USERNAME}:${GHCR_TOKEN}" \ + --get \ + --data-urlencode 'service=ghcr.io' \ + --data-urlencode "scope=repository:${repository_path}:pull" \ + --header 'Accept: application/json' \ + 'https://ghcr.io/token' | jq -er '.token // .access_token // empty')"; then + echo "GHCR bearer-token exchange failed for $image; refusing to infer absence." >&2 + return 1 + fi + registry_tokens["$repository_path"]="$registry_token" + fi + # `docker manifest inspect "$image"` conflates a 404 with auth, + # registry, and network failures, so it is never an absence check. + if ! status="$(curl --silent --show-error --location --head \ + --connect-timeout 10 --max-time 30 \ + --header "Authorization: Bearer ${registry_token}" \ + --header 'Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json' \ + --output /dev/null --write-out '%{http_code}' "$manifest_url")"; then + echo "Authenticated OCI manifest HEAD failed for $image; refusing to infer absence." >&2 + return 1 + fi + case "$status" in + 200) printf 'existing\n' ;; + 404) printf 'missing\n' ;; + *) + echo "Authenticated OCI manifest HEAD returned HTTP ${status} for $image; refusing to push." >&2 + return 1 + ;; + esac + } + + registry_digest() { + local image="$1" + local inspect_output inspect_status + local digest + if inspect_output="$(docker buildx imagetools inspect "$image")"; then + : + else + inspect_status=$? + echo "Unable to inspect exact registry digest for $image (imagetools exit $inspect_status); refusing to publish." >&2 + return "$inspect_status" + fi + digest="$(awk '$1 == "Digest:" && $2 ~ /^sha256:[0-9a-f]{64}$/ { print $2; exit }' <<<"$inspect_output")" + [[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]] || { + echo "Registry manifest for $image has no exact digest." >&2 + return 1 + } + printf '%s\n' "$digest" + } + + assert_current_branch_head() { + local current_sha + current_sha="$(gh api \ + "repos/${GITHUB_REPOSITORY}/git/ref/heads/${HEAD_BRANCH}" \ + --jq '.object.sha')" + [[ "$current_sha" == "$HEAD_SHA" ]] || { + echo "Refusing canonical runtime publication: ${HEAD_BRANCH} moved from ${HEAD_SHA} to ${current_sha}." >&2 + exit 1 + } + } + + promote_alias() { + local source="$1" target="$2" fixed="$3" + local source_digest existing_digest target_digest + source_digest="$(registry_digest "$source")" + local target_state + if ! target_state="$(registry_manifest_state "$target")"; then + echo "Immutable target preflight failed for $target; refusing to publish." >&2 + exit 1 + fi + if [[ "$target_state" == missing ]]; then + docker buildx imagetools create --tag "$target" "$source" + else + existing_digest="$(registry_digest "$target")" + if [[ "$fixed" == true && "$existing_digest" != "$source_digest" ]]; then + echo "Refusing to overwrite fixed runtime tag $target: existing digest $existing_digest differs from candidate $source_digest." >&2 + exit 1 + fi + if [[ "$existing_digest" != "$source_digest" ]]; then + docker buildx imagetools create --tag "$target" "$source" + fi + fi + target_digest="$(registry_digest "$target")" + [[ "$target_digest" == "$source_digest" ]] || { + echo "Promoted runtime tag $target does not match candidate digest $source_digest (got $target_digest)." >&2 + exit 1 + } + } + + for service in "${services[@]}"; do + candidate="ghcr.io/benhook1013/${service}:${CANDIDATE_TAG}" + sha_tag="ghcr.io/benhook1013/${service}:${HEAD_SHA}" + branch_tag="ghcr.io/benhook1013/${service}:${HEAD_BRANCH}" + + assert_current_branch_head + promote_alias "$candidate" "$sha_tag" true + assert_current_branch_head + promote_alias "$candidate" "$branch_tag" false + if [[ "$HEAD_BRANCH" == develop ]]; then + assert_current_branch_head + promote_alias "$candidate" "ghcr.io/benhook1013/${service}:latest" false + fi + done diff --git a/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/2c5bfc6129723cff130081a66a25986cf18555bc.yml b/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/2c5bfc6129723cff130081a66a25986cf18555bc.yml new file mode 100644 index 0000000000..c0726402e0 --- /dev/null +++ b/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/2c5bfc6129723cff130081a66a25986cf18555bc.yml @@ -0,0 +1,2118 @@ +name: Build Runtime Images + +on: + pull_request: + types: [opened, synchronize, reopened, edited] + paths: + - 'build.gradle.kts' + - 'settings.gradle.kts' + - 'gradle.properties' + - 'gradlew' + - 'gradlew.bat' + - 'buildSrc/**' + - 'gradle/**' + - 'protos/**' + - 'docker/**' + - '.dockerignore' + - '.github/workflows/runtime-images.yml' + - '.github/workflows/publish-pr-runtime-images.yml' + - '.github/workflows/smoke.yml' + - '.github/workflows/smoke-full.yml' + - 'services/**' + - '.github/actions/load-workflow-tool-versions/**' + - '.github/actions/setup-python/**' + - '.python-version' + - 'config/workflow-tool-versions.env' + - 'config/python/smoke-requirements.txt' + - 'config/python/smoke-requirements.in' + - 'dev-tools/build-compose-service-jars.sh' + - 'dev-tools/validation/run-gradle-with-dependency-recovery.sh' + - 'dev-tools/validation/run-locked-gradle.sh' + - 'dev-tools/validation/gradle-run-supervisor.py' + - 'dev-tools/build-local-smoke-images.sh' + - 'dev-tools/backups/verify-backups.sh' + - 'dev-tools/backups/pg-dump-s3-selection.shlib' + - 'dev-tools/backups/smoke-backup-verifier-image.sh' + - 'docker/backup-verifier.Dockerfile' + - 'dev-tools/certs/generate-dev-certs.sh' + - 'dev-tools/minio/**' + - 'dev-tools/hosted/controller/smoke-paused-controller-image.sh' + - 'dev-tools/smoke/**' + - 'dev-tools/verify-compose-health.sh' + - 'dev-tools/verify-fresh-bootstrap.sh' + - 'dev-tools/verify-restart-state.sh' + - 'dev-tools/verify-smoke-images.sh' + workflow_run: + workflows: ["CI — Validation"] + types: [completed] + repository_dispatch: + types: [pr-runtime-base-refresh] + workflow_dispatch: + +run-name: Build Runtime Images ${{ (github.event_name == 'pull_request' || github.event_name == 'repository_dispatch') && format('secure-pr-artifact pr-{0} base-{1} head-{2} merge-{3} mode-{4}', github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number, github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.client_payload.base_sha, github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.event.client_payload.head_sha, github.event_name == 'pull_request' && github.sha || github.event.client_payload.merge_sha, github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required') || github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success' && format('trusted-branch branch-{0} sha-{1}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha) || github.event_name == 'workflow_run' && format('base-refresh-only branch-{0} sha-{1} ci-{2}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha, github.event.workflow_run.conclusion) || github.ref_name }} + +permissions: + contents: read + +concurrency: + group: runtime-images-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha, github.sha)) || (github.event_name == 'repository_dispatch' && github.event.client_payload.pr_number != '' && github.event.client_payload.base_sha != '' && github.event.client_payload.head_sha != '' && github.event.client_payload.merge_sha != '' && format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.client_payload.pr_number, github.event.client_payload.base_sha, github.event.client_payload.head_sha, github.event.client_payload.merge_sha)) || (github.event_name == 'repository_dispatch' && format('repository-dispatch-run-{0}', github.run_id)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && format('ci-pr-run-{0}-attempt-{1}', github.event.workflow_run.id, github.event.workflow_run.run_attempt)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && format('branch-{0}', github.event.workflow_run.head_branch)) || github.ref }}-${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required' }} + cancel-in-progress: true + +jobs: + image-meta: + name: Derive Runtime Image Metadata + if: ${{ (github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || (github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh') || github.event_name == 'workflow_dispatch' || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && github.event.workflow_run.conclusion == 'success' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop')) }} + runs-on: ubuntu-latest + outputs: + pr_number: ${{ steps.meta.outputs.pr_number }} + base_ref: ${{ steps.meta.outputs.base_ref }} + base_sha: ${{ steps.meta.outputs.base_sha }} + head_sha: ${{ steps.meta.outputs.head_sha }} + merge_sha: ${{ steps.meta.outputs.merge_sha }} + head_branch: ${{ steps.meta.outputs.head_branch }} + checkout_ref: ${{ steps.meta.outputs.checkout_ref }} + image_tag: ${{ steps.meta.outputs.image_tag }} + candidate_tag: ${{ steps.meta.outputs.candidate_tag }} + base_image: ${{ steps.meta.outputs.base_image }} + canonical_play_transition: ${{ steps.meta.outputs.canonical_play_transition }} + runtime_smoke_required: ${{ steps.smoke_scope.outputs.runtime_smoke_required }} + controller_smoke_required: ${{ steps.smoke_scope.outputs.controller_smoke_required }} + permissions: + actions: read + contents: read + pull-requests: read + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Check out trusted workflow helpers + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - name: Set up canonical GitHub CLI + uses: ./.github/actions/setup-gh + + - name: Set up canonical Python + uses: ./.github/actions/setup-python + + - name: Derive image tags + id: meta + env: + GH_TOKEN: ${{ github.token }} + EVENT_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.client_payload.head_sha || '' }} + EVENT_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch || '' }} + EVENT_PR_NUMBER: ${{ github.event.pull_request.number || github.event.client_payload.pr_number || '' }} + EVENT_BASE_REF: ${{ github.event.pull_request.base.ref || github.event.client_payload.base_ref || '' }} + EVENT_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.client_payload.base_sha || '' }} + EVENT_MERGE_SHA: ${{ github.event.client_payload.merge_sha || '' }} + EVENT_ACTION: ${{ github.event.action || '' }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + run: | + set -euo pipefail + EVENT_NAME="${{ github.event_name }}" + PR_NUMBER="" + BASE_REF="" + BASE_SHA="" + MERGE_SHA="" + CANONICAL_PLAY_TRANSITION=false + if [ "$EVENT_NAME" = "pull_request" ]; then + PR_NUMBER="$EVENT_PR_NUMBER" + BASE_REF="$EVENT_BASE_REF" + BASE_SHA="$EVENT_BASE_SHA" + HEAD_SHA="$EVENT_HEAD_SHA" + HEAD_BRANCH="" + MERGE_SHA="${GITHUB_SHA}" + CHECKOUT_REF="$MERGE_SHA" + [[ "$MERGE_SHA" =~ ^[0-9a-f]{40}$ ]] || { + echo "PR merge SHA is not a lowercase 40-character commit SHA." >&2 + exit 1 + } + [[ "$BASE_SHA" =~ ^[0-9a-f]{40}$ && "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]] || { + echo "PR event base/head SHAs are not lowercase 40-character commit SHAs." >&2 + exit 1 + } + merge_commit_json="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${MERGE_SHA}")" + jq -e \ + --arg base_sha "$BASE_SHA" \ + --arg head_sha "$HEAD_SHA" \ + --arg merge_sha "$MERGE_SHA" \ + '.sha == $merge_sha and (.parents | type) == "array" and (.parents | length) == 2 and .parents[0].sha == $base_sha and .parents[1].sha == $head_sha' \ + <<<"$merge_commit_json" >/dev/null || { + echo "PR event merge commit does not have the event's exact base/head parents; refusing a stale PR artifact." >&2 + exit 1 + } + elif [ "$EVENT_NAME" = "repository_dispatch" ]; then + [[ "$EVENT_ACTION" == "pr-runtime-base-refresh" ]] || { + echo "Runtime PR refresh requires the typed pr-runtime-base-refresh dispatch." >&2 + exit 1 + } + [[ "$GITHUB_REF" == "refs/heads/${DEFAULT_BRANCH}" ]] || { + echo "Runtime PR refresh must run from the repository default branch." >&2 + exit 1 + } + PR_NUMBER="$EVENT_PR_NUMBER" + BASE_REF="$EVENT_BASE_REF" + BASE_SHA="$EVENT_BASE_SHA" + MERGE_SHA="$EVENT_MERGE_SHA" + HEAD_SHA="$EVENT_HEAD_SHA" + HEAD_BRANCH="" + CHECKOUT_REF="$MERGE_SHA" + [[ "$PR_NUMBER" =~ ^[1-9][0-9]{0,50}$ ]] || { + echo "Runtime PR refresh payload has an invalid pull request number." >&2 + exit 1 + } + git check-ref-format "refs/heads/${BASE_REF}" >/dev/null || { + echo "Runtime PR refresh payload has an invalid base ref." >&2 + exit 1 + } + for sha_name in BASE_SHA HEAD_SHA MERGE_SHA; do + sha_value="${!sha_name}" + [[ "$sha_value" =~ ^[0-9a-f]{40}$ ]] || { + echo "Runtime PR refresh payload has an invalid ${sha_name}." >&2 + exit 1 + } + done + + encoded_base_ref="$(python3 -c 'import sys; from urllib.parse import quote; print(quote(sys.argv[1], safe="/"))' "$BASE_REF")" + current_base_ref_json="$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/heads/${encoded_base_ref}")" + jq -e \ + --arg base_sha "$BASE_SHA" \ + --arg base_ref "refs/heads/${BASE_REF}" \ + '.ref == $base_ref and .object.sha == $base_sha' \ + <<<"$current_base_ref_json" >/dev/null || { + echo "Runtime PR refresh base SHA is not the current ${BASE_REF} branch ref." >&2 + exit 1 + } + pull_request_json="$(gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}")" + jq -e \ + --arg repository "$GITHUB_REPOSITORY" \ + --arg base_ref "$BASE_REF" \ + --arg head_sha "$HEAD_SHA" \ + --arg merge_sha "$MERGE_SHA" \ + '( + .state == "open" and + .base.ref == $base_ref and + .base.repo.full_name == $repository and + .head.sha == $head_sha and + .head.repo.full_name == $repository and + (.mergeable | type) == "boolean" and + .mergeable == true and + (.mergeable_state | type) == "string" and + .mergeable_state != "dirty" and + .mergeable_state != "conflicting" and + .mergeable_state != "unknown" and + .merge_commit_sha == $merge_sha + )' <<<"$pull_request_json" >/dev/null || { + echo "Runtime PR refresh payload is stale, conflicted, fork-owned, closed, or has an invalid merge tuple." >&2 + exit 1 + } + merge_commit_json="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${MERGE_SHA}")" + jq -e \ + --arg base_sha "$BASE_SHA" \ + --arg head_sha "$HEAD_SHA" \ + --arg merge_sha "$MERGE_SHA" \ + '.sha == $merge_sha and (.parents | type) == "array" and (.parents | length) == 2 and .parents[0].sha == $base_sha and .parents[1].sha == $head_sha' \ + <<<"$merge_commit_json" >/dev/null || { + echo "Runtime PR refresh merge commit does not have the exact current base/head parents." >&2 + exit 1 + } + # Only the verified live same-repository PR can authorize this + # diagnostic marker; dispatch payload labels carry no authority. + if jq -e '(.labels | type) == "array" and any(.labels[]; .name == "canonical-play-transition")' \ + <<<"$pull_request_json" >/dev/null; then + CANONICAL_PLAY_TRANSITION=true + fi + elif [ "${{ github.event_name }}" = "workflow_run" ]; then + [[ "${{ github.event.workflow_run.event }}" == "push" ]] || { + echo "Runtime branch publication requires a CI push workflow run." >&2 + exit 1 + } + [[ "${{ github.event.workflow_run.conclusion }}" == "success" ]] || { + echo "Runtime branch publication requires a successful CI workflow run." >&2 + exit 1 + } + HEAD_SHA="${EVENT_HEAD_SHA:-${{ github.event.workflow_run.head_sha }}}" + HEAD_BRANCH="$EVENT_HEAD_BRANCH" + CHECKOUT_REF="$HEAD_SHA" + else + HEAD_SHA="${GITHUB_SHA}" + CHECKOUT_REF="${GITHUB_SHA}" + HEAD_BRANCH="${GITHUB_REF_NAME}" + fi + + [[ "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]] || { + echo "Runtime publication head SHA is not a lowercase 40-character commit SHA." >&2 + exit 1 + } + if [ "$EVENT_NAME" != "pull_request" ] && [ "$EVENT_NAME" != "repository_dispatch" ]; then + [[ "$HEAD_BRANCH" == main || "$HEAD_BRANCH" == develop ]] || { + echo "Runtime branch publication is restricted to main or develop." >&2 + exit 1 + } + fi + + if [ "$EVENT_NAME" = "pull_request" ] || [ "$EVENT_NAME" = "repository_dispatch" ]; then + IMAGE_TAG="pr-merge-${MERGE_SHA}" + else + IMAGE_TAG="${HEAD_SHA}" + fi + CANDIDATE_TAG="candidate-${HEAD_SHA}-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + if [ "$EVENT_NAME" = "pull_request" ] || [ "$EVENT_NAME" = "repository_dispatch" ]; then + BASE_IMAGE="ghcr.io/benhook1013/firemud-base:${MERGE_SHA}" + else + BASE_IMAGE="ghcr.io/benhook1013/firemud-base:${CANDIDATE_TAG}" + fi + + { + echo "pr_number=${PR_NUMBER}" + echo "base_ref=${BASE_REF}" + echo "base_sha=${BASE_SHA}" + echo "head_sha=${HEAD_SHA}" + echo "merge_sha=${MERGE_SHA}" + echo "head_branch=${HEAD_BRANCH}" + echo "checkout_ref=${CHECKOUT_REF}" + echo "image_tag=${IMAGE_TAG}" + echo "candidate_tag=${CANDIDATE_TAG}" + echo "base_image=${BASE_IMAGE}" + echo "canonical_play_transition=${CANONICAL_PLAY_TRANSITION}" + } >> "$GITHUB_OUTPUT" + + - name: Verify successful CI push for manual publication + if: ${{ github.event_name == 'workflow_dispatch' }} + env: + GH_TOKEN: ${{ github.token }} + EXPECTED_SHA: ${{ steps.meta.outputs.head_sha }} + EXPECTED_BRANCH: ${{ steps.meta.outputs.head_branch }} + run: | + set -euo pipefail + ci_runs="$(gh api --paginate --slurp \ + "repos/${GITHUB_REPOSITORY}/actions/workflows/ci.yml/runs?event=push&head_sha=${EXPECTED_SHA}&per_page=100")" + jq -e \ + --arg expected_sha "$EXPECTED_SHA" \ + --arg expected_branch "$EXPECTED_BRANCH" \ + '[.[].workflow_runs[]?] | any(.[]; .head_sha == $expected_sha and .head_branch == $expected_branch and .event == "push" and .status == "completed" and .conclusion == "success")' \ + <<<"$ci_runs" >/dev/null || { + echo "No successful CI push run exists for manual runtime publication ${EXPECTED_BRANCH}@${EXPECTED_SHA}." >&2 + exit 1 + } + + - name: Detect PR smoke scopes + id: smoke_scope + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + let runtimeSmokeRequired = true; + let controllerSmokeRequired = true; + if (context.eventName === "pull_request" || context.eventName === "repository_dispatch") { + try { + const pullNumber = context.eventName === "pull_request" + ? context.payload.pull_request.number + : context.payload.client_payload.pr_number; + const changedFiles = await github.paginate( + github.rest.pulls.listFiles, + { + ...context.repo, + pull_number: pullNumber, + per_page: 100, + }, + (response) => response.data + ); + const expectedFileCount = context.eventName === "pull_request" + ? context.payload.pull_request.changed_files + : (await github.rest.pulls.get({ + ...context.repo, + pull_number: pullNumber, + })).data.changed_files; + const validFileEntries = changedFiles.every((file) => + file && + typeof file.filename === "string" && + file.filename.length > 0 && + (file.previous_filename === undefined || + (typeof file.previous_filename === "string" && file.previous_filename.length > 0)) + ); + if (!Number.isInteger(expectedFileCount) || changedFiles.length !== expectedFileCount || !validFileEntries) { + core.warning("PR smoke scope detection was incomplete; running both local smokes."); + } else { + const paths = changedFiles.flatMap((file) => + [file.filename, file.previous_filename].filter(Boolean) + ); + const runtimePrefixes = [ + "buildSrc/", + "docker/", + "dev-tools/minio/", + "dev-tools/smoke/", + "gradle/", + "protos/", + ".github/actions/load-workflow-tool-versions/", + ".github/actions/setup-python/", + ]; + const workflowToolAuthorityPath = "config/workflow-tool-versions.env"; + const runtimeFiles = new Set([ + ".dockerignore", + ".github/workflows/publish-pr-runtime-images.yml", + ".github/workflows/runtime-images.yml", + ".github/workflows/smoke-full.yml", + ".github/workflows/smoke.yml", + ".github/actions/load-workflow-tool-versions/action.yml", + ".python-version", + "build.gradle.kts", + "config/python/smoke-requirements.txt", + "config/python/smoke-requirements.in", + "dev-tools/build-compose-service-jars.sh", + "dev-tools/validation/run-gradle-with-dependency-recovery.sh", + "dev-tools/validation/run-locked-gradle.sh", + "dev-tools/validation/gradle-run-supervisor.py", + "dev-tools/build-local-smoke-images.sh", + "dev-tools/backups/verify-backups.sh", + "dev-tools/backups/pg-dump-s3-selection.shlib", + "dev-tools/backups/smoke-backup-verifier-image.sh", + "dev-tools/certs/generate-dev-certs.sh", + "dev-tools/verify-compose-health.sh", + "dev-tools/verify-fresh-bootstrap.sh", + "dev-tools/verify-restart-state.sh", + "dev-tools/verify-smoke-images.sh", + "gradle.properties", + "docker/backup-verifier.Dockerfile", + "gradlew", + "gradlew.bat", + "settings.gradle.kts", + ]); + const controllerPrefixes = [ + "buildSrc/", + "gradle/", + "services/hosted-environment-identity-controller/", + ]; + const controllerFiles = new Set([ + ".dockerignore", + ".github/workflows/runtime-images.yml", + "build.gradle.kts", + "dev-tools/hosted/controller/smoke-paused-controller-image.sh", + "docker/base.Dockerfile", + "gradle.properties", + "gradlew", + "gradlew.bat", + "settings.gradle.kts", + ]); + const authorityChanged = paths.includes(workflowToolAuthorityPath); + const nonAuthorityPaths = paths.filter( + (path) => path !== workflowToolAuthorityPath + ); + runtimeSmokeRequired = nonAuthorityPaths.some( + (path) => + runtimeFiles.has(path) || + runtimePrefixes.some((prefix) => path.startsWith(prefix)) || + (path.startsWith("services/") && + !path.startsWith( + "services/hosted-environment-identity-controller/" + )) + ); + runtimeSmokeRequired = runtimeSmokeRequired || authorityChanged; + controllerSmokeRequired = paths.some( + (path) => + controllerFiles.has(path) || + controllerPrefixes.some((prefix) => path.startsWith(prefix)) + ); + } + } catch (error) { + core.warning( + `PR smoke scope detection failed; running both local smokes: ${error.message}` + ); + } + } + core.setOutput("runtime_smoke_required", String(runtimeSmokeRequired)); + core.setOutput("controller_smoke_required", String(controllerSmokeRequired)); + + dispatch-pr-base-refreshes: + name: Dispatch PR Base Refreshes + if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.status == 'completed' && (github.event.workflow_run.event == 'pull_request' || (github.event.workflow_run.event == 'push' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop'))) && github.event.workflow_run.head_repository.full_name == github.repository }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + actions: read + contents: write + pull-requests: read + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Dispatch exact PR runtime refreshes and preview reconciles + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + const workflowRun = context.payload.workflow_run; + const refreshBranch = workflowRun.head_branch; + const refreshSha = workflowRun.head_sha; + const shaPattern = /^[0-9a-f]{40}$/; + const runtimePrefixes = [ + "buildSrc/", + "docker/", + "dev-tools/minio/", + "dev-tools/smoke/", + "gradle/", + "protos/", + ".github/actions/load-workflow-tool-versions/", + ".github/actions/setup-python/", + ]; + const runtimeFiles = new Set([ + ".dockerignore", + ".github/workflows/publish-pr-runtime-images.yml", + ".github/workflows/runtime-images.yml", + ".github/workflows/smoke-full.yml", + ".github/workflows/smoke.yml", + ".github/actions/load-workflow-tool-versions/action.yml", + ".python-version", + "build.gradle.kts", + "config/workflow-tool-versions.env", + "config/python/smoke-requirements.txt", + "config/python/smoke-requirements.in", + "dev-tools/build-compose-service-jars.sh", + "dev-tools/validation/run-gradle-with-dependency-recovery.sh", + "dev-tools/validation/run-locked-gradle.sh", + "dev-tools/validation/gradle-run-supervisor.py", + "dev-tools/build-local-smoke-images.sh", + "dev-tools/backups/verify-backups.sh", + "dev-tools/backups/pg-dump-s3-selection.shlib", + "dev-tools/backups/smoke-backup-verifier-image.sh", + "dev-tools/certs/generate-dev-certs.sh", + "dev-tools/hosted/controller/smoke-paused-controller-image.sh", + "dev-tools/verify-compose-health.sh", + "dev-tools/verify-fresh-bootstrap.sh", + "dev-tools/verify-restart-state.sh", + "dev-tools/verify-smoke-images.sh", + "gradle.properties", + "gradlew", + "gradlew.bat", + "settings.gradle.kts", + ]); + const runtimeRunEvents = ["pull_request", "repository_dispatch"]; + const runtimeRunPageSize = 100; + const runtimeRunLookbackMilliseconds = 7 * 24 * 60 * 60 * 1000; + + const waitForMergeRefresh = async () => { + await new Promise((resolve) => setTimeout(resolve, 2000)); + }; + + const hasRuntimeChange = async (pullRequest) => { + const files = await github.paginate( + github.rest.pulls.listFiles, + { + ...context.repo, + pull_number: pullRequest.number, + per_page: 100, + }, + (response) => response.data + ); + const expectedFileCount = pullRequest.changed_files; + const validFileEntries = Number.isInteger(expectedFileCount) && + files.length === expectedFileCount && + files.every((file) => + file && + typeof file.filename === "string" && + file.filename.length > 0 && + (file.previous_filename === undefined || + (typeof file.previous_filename === "string" && file.previous_filename.length > 0)) + ); + if (!validFileEntries) { + core.warning(`PR #${pullRequest.number} changed-file metadata was incomplete; refreshing its runtime images.`); + return true; + } + return files.flatMap((file) => [file.filename, file.previous_filename].filter(Boolean)).some((path) => + runtimeFiles.has(path) || + runtimePrefixes.some((prefix) => path.startsWith(prefix)) || + path.startsWith("services/") + ); + }; + + const dependencyBotAuthors = new Set([ + "app/dependabot", + "dependabot[bot]", + "app/renovate", + "renovate[bot]", + ]); + + const isPreviewEligible = (pullRequest) => { + const labels = pullRequest.labels; + return typeof pullRequest.user?.login === "string" && + pullRequest.user.login.length > 0 && + !dependencyBotAuthors.has(pullRequest.user.login) && + Array.isArray(labels) && + labels.every((label) => label && typeof label.name === "string") && + (["main", "develop"].includes(pullRequest.base?.ref) || + labels.some((label) => label.name === "preview:priority")); + }; + + const resolveExactMerge = async (number, baseBranch = refreshBranch, baseSha = refreshSha, expectedHeadSha = null) => { + for (let attempt = 1; attempt <= 5; attempt += 1) { + const response = await github.rest.pulls.get({ + ...context.repo, + pull_number: number, + }); + const pullRequest = response.data; + const currentHeadSha = pullRequest.head?.sha; + const currentBaseRef = pullRequest.base?.ref; + const headRepository = pullRequest.head?.repo?.full_name; + const baseRepository = pullRequest.base?.repo?.full_name; + if (pullRequest.state !== "open" || + headRepository !== context.payload.repository.full_name || + baseRepository !== context.payload.repository.full_name || + currentBaseRef !== baseBranch || + !shaPattern.test(currentHeadSha || "") || + (expectedHeadSha !== null && currentHeadSha !== expectedHeadSha)) { + return null; + } + + const mergeableState = typeof pullRequest.mergeable_state === "string" + ? pullRequest.mergeable_state + : pullRequest.mergeable_state === null ? "unknown" : "invalid"; + if (pullRequest.mergeable === false || + mergeableState === "dirty" || + mergeableState === "conflicting") { + core.warning(`Skipping PR #${number}: GitHub reports a merge conflict.`); + return null; + } + if (pullRequest.mergeable === null || mergeableState === "unknown") { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: GitHub did not produce a ready merge tuple.`); + return null; + } + if (pullRequest.mergeable !== true || mergeableState === "invalid") { + core.warning(`Skipping PR #${number}: GitHub returned invalid merge metadata.`); + return null; + } + + const mergeSha = pullRequest.merge_commit_sha; + if (!shaPattern.test(mergeSha || "")) { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: merge SHA is null or invalid.`); + return null; + } + + try { + const commit = await github.rest.repos.getCommit({ + ...context.repo, + ref: mergeSha, + }); + const parents = commit.data.parents?.map((parent) => parent.sha) || []; + if (commit.data.sha !== mergeSha || + parents.length !== 2 || + parents[0] !== baseSha || + parents[1] !== currentHeadSha) { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: merge commit parents do not match the current base/head.`); + return null; + } + } catch (error) { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: exact merge commit could not be read (${error.message}).`); + return null; + } + + return { + tuple: { + prNumber: String(number), + baseRef: baseBranch, + baseSha, + headSha: currentHeadSha, + mergeSha, + }, + pullRequest, + }; + } + return null; + }; + + const loadExistingRuntimeRuns = async () => { + const readInventory = async (createdSince) => { + const inventory = []; + let complete = true; + let incompleteReason = null; + for (const event of runtimeRunEvents) { + const response = await github.rest.actions.listWorkflowRuns({ + ...context.repo, + workflow_id: "runtime-images.yml", + event, + created: `${createdSince}..*`, + per_page: runtimeRunPageSize, + page: 1, + }); + const payload = response?.data; + if (!payload || !Number.isInteger(payload.total_count) || + payload.total_count < 0 || !Array.isArray(payload.workflow_runs)) { + throw new Error(`runtime-images ${event} recent run inventory is malformed`); + } + if (payload.total_count > runtimeRunPageSize) { + complete = false; + incompleteReason ??= `runtime-images ${event} has more than ${runtimeRunPageSize} runs since ${createdSince}`; + } + const expectedPageLength = Math.min(payload.total_count, runtimeRunPageSize); + if (payload.workflow_runs.length !== expectedPageLength) { + throw new Error(`runtime-images ${event} recent run inventory is incomplete`); + } + inventory.push(...payload.workflow_runs); + } + return {complete, runs: inventory, reason: incompleteReason}; + }; + + const createdSince = new Date(Date.now() - runtimeRunLookbackMilliseconds).toISOString(); + const initial = await readInventory(createdSince); + if (initial.complete) { + return initial; + } + + const inFlightStatuses = ["queued", "waiting", "requested", "pending", "in_progress"]; + const inFlightRuns = initial.runs.filter((run) => inFlightStatuses.includes(run?.status)); + if (inFlightRuns.length === 0) { + return initial; + } + + const validTimestamp = (value) => typeof value === "string" && + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(value) && + Number.isFinite(Date.parse(value)); + if (inFlightRuns.some((run) => !runtimeRunEvents.includes(run.event) || + !Number.isSafeInteger(run.id) || run.id <= 0 || !validTimestamp(run.created_at))) { + return { + ...initial, + reason: "truncated recent inventory contains an in-flight run without a valid event, id, or creation timestamp", + }; + } + + const refinementSince = inFlightRuns + .map((run) => run.created_at) + .sort()[0]; + // The inclusive created lower bound makes the refined pages a complete candidate set without relying on API ordering. + const refined = await readInventory(refinementSince); + if (!refined.complete) { + return { + ...refined, + reason: refined.reason || "refined runtime run inventory is incomplete", + }; + } + const refinedIds = new Set(refined.runs.map((run) => `${run?.event}:${run?.id}`)); + if (inFlightRuns.some((run) => !refinedIds.has(`${run.event}:${run.id}`))) { + return { + ...refined, + complete: false, + reason: "refined inventory did not retain every initially observed in-flight run", + }; + } + return refined; + }; + + const findExactExistingProducer = (tuple, inventory) => { + const expectedWorkflowPath = ".github/workflows/runtime-images.yml"; + const workflowPathMatches = (path) => { + if (path === expectedWorkflowPath) { + return true; + } + const prefix = `${expectedWorkflowPath}@`; + if (typeof path !== "string" || !path.startsWith(prefix)) { + return false; + } + const ref = path.slice(prefix.length); + if (ref.length === 0 || ref === "@" || ref.endsWith(".") || + /[\u0000-\u0020\u007f]/.test(ref) || + ["~", "^", ":", "?", "*", "[", "\\"].some((character) => ref.includes(character)) || + ref.includes("..") || ref.includes("@{")) { + return false; + } + return ref.split("/").every((part) => + part.length > 0 && part !== "." && part !== ".." && + !part.startsWith(".") && + !part.endsWith(".lock") + ); + }; + const expectedTitle = + `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} ` + + `base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; + const matching = inventory.runs.filter((run) => + run?.display_title === expectedTitle + ); + const ordered = []; + const matchingIds = new Set(); + for (const run of matching) { + if (!runtimeRunEvents.includes(run.event) || + !Number.isSafeInteger(run.id) || run.id <= 0 || matchingIds.has(run.id) || + typeof run.created_at !== "string" || + !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(run.created_at) || + !Number.isFinite(Date.parse(run.created_at)) || + !workflowPathMatches(run.path) || + !["Build Runtime Images", expectedTitle].includes(run.name) || + run.repository?.full_name !== context.payload.repository.full_name || + run.head_repository?.full_name !== context.payload.repository.full_name) { + throw new Error(`run ${run.id} has the exact tuple title but invalid workflow or repository identity`); + } + matchingIds.add(run.id); + ordered.push(run); + if (run.event === "pull_request") { + if (run.head_sha !== tuple.headSha) { + throw new Error(`run ${run.id} has the exact tuple title but a different PR head SHA`); + } + const pullRequests = run.pull_requests; + if (!Array.isArray(pullRequests) || (pullRequests.length > 0 && !pullRequests.some((pullRequest) => + String(pullRequest?.number) === tuple.prNumber && + pullRequest?.head?.sha === tuple.headSha + ))) { + throw new Error(`run ${run.id} has incomplete or conflicting PR association evidence`); + } + } + } + ordered.sort((left, right) => right.created_at.localeCompare(left.created_at)); + if (ordered.length > 1 && ordered[0].created_at === ordered[1].created_at) { + throw new Error("newest exact runtime producer has an ambiguous created_at timestamp"); + } + const newest = ordered[0]; + if (!newest) { + return []; + } + if (["queued", "waiting", "requested", "pending", "in_progress"].includes(newest.status)) { + if (newest.conclusion !== null && newest.conclusion !== undefined) { + throw new Error(`run ${newest.id} has a conclusion while still ${newest.status}`); + } + return [newest]; + } + if (newest.status === "completed") { + // Completed source success does not prove publication remains usable; preserve recovery dispatch. + return []; + } + throw new Error(`run ${newest.id} has an unknown status and cannot be classified`); + }; + + if (!shaPattern.test(refreshSha) || typeof refreshBranch !== "string" || + refreshBranch.length === 0) { + core.setFailed("Completed CI callback did not identify a branch and lowercase SHA."); + return; + } + let sourcePrNumber = null; + if (workflowRun.event === "pull_request") { + // Completion is a reconcile signal only for a substantive CI attempt. + // Metadata edits also complete CI, but must never reconstruct runtime. + const positiveInteger = (value) => Number.isSafeInteger(value) && value > 0; + const ciPath = ".github/workflows/ci.yml"; + const ciName = "CI — Validation"; + const titleMatch = /^CI — Validation pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40})$/.exec(workflowRun.display_title || ""); + const matchesSource = (run) => + positiveInteger(workflowRun.id) && positiveInteger(workflowRun.run_attempt) && + positiveInteger(workflowRun.workflow_id) && + run.id === workflowRun.id && run.run_attempt === workflowRun.run_attempt && + run.workflow_id === workflowRun.workflow_id && run.event === "pull_request" && + run.status === "completed" && typeof run.conclusion === "string" && run.conclusion.length > 0 && + run.repository?.full_name === context.payload.repository.full_name && + run.head_repository?.full_name === context.payload.repository.full_name && + run.head_branch === refreshBranch && run.head_sha === refreshSha && + run.display_title === workflowRun.display_title && + [ciName, workflowRun.display_title].includes(run.name) && + (run.path === ciPath || (typeof run.path === "string" && + run.path.startsWith(`${ciPath}@`) && run.path.length > ciPath.length + 1)); + if (!titleMatch || titleMatch[3] !== refreshSha) { + core.warning("Skipping PR runtime reconciliation: callback lacks exact CI PR/base/head title metadata."); + return; + } + const {data: ciWorkflow} = await github.rest.actions.getWorkflow({ + ...context.repo, workflow_id: "ci.yml", + }); + const {data: source} = await github.rest.actions.getWorkflowRun({ + ...context.repo, run_id: workflowRun.id, + }); + if (ciWorkflow.id !== workflowRun.workflow_id || ciWorkflow.path !== ciPath || + ciWorkflow.name !== ciName || !matchesSource(source)) { + core.warning("Skipping PR runtime reconciliation: current CI workflow/run identity differs from callback."); + return; + } + const jobs = await github.paginate( + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + {...context.repo, run_id: source.id, attempt_number: source.run_attempt, per_page: 100} + ); + const gates = jobs.filter((job) => job.name === "Validation Gate"); + const gate = gates.length === 1 ? gates[0] : null; + const preservation = gate?.steps?.filter((step) => + step.name === "Preserve successful required gate on metadata-only edit") || []; + const enforcement = gate?.steps?.filter((step) => step.name === "Enforce validation success") || []; + const checkPrefix = `https://api.github.com/repos/${context.payload.repository.full_name}/check-runs/`; + if (!gate || !positiveInteger(gate.id) || gate.run_id !== source.id || + gate.run_attempt !== source.run_attempt || gate.head_sha !== source.head_sha || + ![ciName, source.display_title].includes(gate.workflow_name) || gate.status !== "completed" || + typeof gate.check_run_url !== "string" || !gate.check_run_url.startsWith(checkPrefix) || + !/^[1-9][0-9]*$/.test(gate.check_run_url.slice(checkPrefix.length)) || + preservation.length !== 1 || preservation[0].status !== "completed" || + preservation[0].conclusion !== "skipped" || enforcement.length !== 1 || + enforcement[0].status !== "completed" || !["success", "failure"].includes(enforcement[0].conclusion)) { + core.info("Skipping PR runtime reconciliation: exact CI attempt is metadata-only or lacks substantive native gate evidence."); + return; + } + const {data: latest} = await github.rest.actions.getWorkflowRun({ + ...context.repo, run_id: source.id, + }); + if (!matchesSource(latest)) { + core.warning("Skipping PR runtime reconciliation: CI attempt was superseded during classification."); + return; + } + sourcePrNumber = titleMatch[1]; + } + let currentBranch; + try { + currentBranch = await github.rest.git.getRef({ + ...context.repo, + ref: `heads/${refreshBranch}`, + }); + } catch (error) { + if (error.status !== 404) throw error; + core.info(`Skipping obsolete CI callback: branch ${refreshBranch} no longer exists.`); + return; + } + if (currentBranch.data.object?.sha !== refreshSha) { + core.warning(`Skipping PR base refresh: ${refreshBranch} advanced beyond the completed CI callback ${refreshSha}.`); + return; + } + + // Protected push callbacks own dependent fan-out; PR callbacks for + // those heads still reconcile their own exact source PR below. + const protectedPrHead = workflowRun.event === "pull_request" && + ["main", "develop"].includes(refreshBranch); + const pullRequests = protectedPrHead ? [] : await github.paginate( + github.rest.pulls.list, + { + ...context.repo, + state: "open", + base: refreshBranch, + per_page: 100, + }, + (response) => response.data + ); + const refreshTargets = []; + for (const listedPullRequest of pullRequests) { + if (listedPullRequest.state !== "open" || + listedPullRequest.base?.ref !== refreshBranch || + listedPullRequest.head?.repo?.full_name !== context.payload.repository.full_name || + listedPullRequest.base?.repo?.full_name !== context.payload.repository.full_name) { + continue; + } + const resolved = await resolveExactMerge(listedPullRequest.number); + if (resolved) { + refreshTargets.push(resolved); + } + } + if (workflowRun.event === "pull_request") { + // A retarget/edit can carry an unusable event merge SHA. CI completion + // is only a reconcile signal: re-read its source's current exact tuple. + const sourcePullRequests = await github.paginate( + github.rest.pulls.list, + { + ...context.repo, + state: "open", + head: `${context.repo.owner}:${refreshBranch}`, + per_page: 100, + }, + (response) => response.data + ); + for (const source of sourcePullRequests) { + if (String(source.number) !== sourcePrNumber || + source.state !== "open" || source.head?.sha !== refreshSha || + source.head?.ref !== refreshBranch || + source.head?.repo?.full_name !== context.payload.repository.full_name || + source.base?.repo?.full_name !== context.payload.repository.full_name || + typeof source.base?.ref !== "string" || + source.base.ref.length === 0) { + continue; + } + const sourceBase = await github.rest.git.getRef({ + ...context.repo, + ref: `heads/${source.base.ref}`, + }); + const sourceBaseSha = sourceBase.data.object?.sha; + if (!shaPattern.test(sourceBaseSha || "")) { + core.warning(`Skipping source PR #${source.number}: current base ref SHA is invalid.`); + continue; + } + const resolved = await resolveExactMerge(source.number, source.base.ref, sourceBaseSha, refreshSha); + if (resolved && !refreshTargets.some((target) => target.tuple.prNumber === resolved.tuple.prNumber)) { + refreshTargets.push(resolved); + } + } + } + let runtimeInventoryPromise; + let runtimeInventoryError = null; + for (const resolved of refreshTargets) { + const {tuple, pullRequest} = resolved; + if (await hasRuntimeChange(pullRequest)) { + let existingProducers = []; + let fallbackReason = null; + let inventory; + if (runtimeInventoryError) { + fallbackReason = runtimeInventoryError; + } else { + try { + runtimeInventoryPromise ??= loadExistingRuntimeRuns(); + inventory = await runtimeInventoryPromise; + } catch (error) { + fallbackReason = error.message || String(error); + runtimeInventoryError = fallbackReason; + } + } + if (!fallbackReason) { + try { + existingProducers = findExactExistingProducer(tuple, inventory); + if (!inventory.complete) { + // The REST contract does not specify a sort order, so a truncated page cannot prove omitted runs are older. + existingProducers = []; + fallbackReason = inventory.reason || "recent run inventory is incomplete"; + } + } catch (error) { + fallbackReason = error.message || String(error); + } + } + if (fallbackReason) { + core.warning( + `Cannot verify recent runtime producer evidence for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}); falling back to the required refresh dispatch: ${fallbackReason}` + ); + } + if (existingProducers.length > 0) { + const producer = existingProducers[0]; + core.info( + `Skipping duplicate PR runtime refresh for #${tuple.prNumber}: exact tuple producer ${producer.id} remains ${producer.status}.` + ); + } else { + core.info(`No reusable in-flight exact producer was verified in the bounded recent inventory; dispatching required PR runtime refresh for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); + await github.rest.repos.createDispatchEvent({ + ...context.repo, + event_type: "pr-runtime-base-refresh", + client_payload: { + pr_number: tuple.prNumber, + base_ref: tuple.baseRef, + base_sha: tuple.baseSha, + head_sha: tuple.headSha, + merge_sha: tuple.mergeSha, + }, + }); + } + } else { + core.info(`Skipping PR runtime image refresh for #${tuple.prNumber}: no runtime-changing files.`); + } + if (!isPreviewEligible(pullRequest)) { + core.info(`Skipping preview deploy reconciliation for #${tuple.prNumber}: target is not preview-eligible.`); + continue; + } + core.info(`Dispatching preview deploy reconciliation for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); + await github.rest.repos.createDispatchEvent({ + ...context.repo, + event_type: "preview-deploy", + client_payload: { + action: "deploy", + pr_number: tuple.prNumber, + base_ref: tuple.baseRef, + base_sha: tuple.baseSha, + head_sha: tuple.headSha, + merge_sha: tuple.mergeSha, + preview_domain: "preview.firedevops.net", + }, + }); + } + + build-base-image: + name: Build Runtime Base Image + needs: [image-meta] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + runs-on: ubuntu-latest + outputs: + digest: ${{ steps.select_base_image_digest.outputs.digest }} + permissions: + # This job publishes the shared runtime base image to GHCR. + contents: read + packages: write + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: ⬇️ Checkout Code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Login to GHCR + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push runtime base image + id: build_base_image_first + continue-on-error: true + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: ./docker/base.Dockerfile + push: true + tags: ${{ needs.image-meta.outputs.base_image }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache + type=registry,ref=ghcr.io/benhook1013/firemud-base:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache,mode=max + type=gha,mode=max + + - name: Retry build and push runtime base image + id: build_base_image_retry + if: ${{ steps.build_base_image_first.outcome == 'failure' }} + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: ./docker/base.Dockerfile + push: true + tags: ${{ needs.image-meta.outputs.base_image }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache + type=registry,ref=ghcr.io/benhook1013/firemud-base:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache,mode=max + type=gha,mode=max + + - name: Select exact published runtime base digest + id: select_base_image_digest + if: ${{ !cancelled() }} + env: + FIRST_OUTCOME: ${{ steps.build_base_image_first.outcome }} + FIRST_DIGEST: ${{ steps.build_base_image_first.outputs.digest }} + RETRY_OUTCOME: ${{ steps.build_base_image_retry.outcome }} + RETRY_DIGEST: ${{ steps.build_base_image_retry.outputs.digest }} + run: | + set -euo pipefail + published_digests=() + if [[ "$FIRST_OUTCOME" == "success" ]]; then + published_digests+=("$FIRST_DIGEST") + fi + if [[ "$RETRY_OUTCOME" == "success" ]]; then + published_digests+=("$RETRY_DIGEST") + fi + if ((${#published_digests[@]} != 1)); then + echo "Expected exactly one successful runtime base-image publication digest." >&2 + exit 1 + fi + base_image_digest="${published_digests[0]}" + [[ "$base_image_digest" =~ ^sha256:[0-9a-f]{64}$ ]] || { + echo "Runtime base-image publisher returned an invalid sha256 digest." >&2 + exit 1 + } + echo "digest=$base_image_digest" >> "$GITHUB_OUTPUT" + + build-runtime-images: + name: Build Runtime Images (${{ matrix.service }}) + needs: [image-meta, build-base-image] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + runs-on: ubuntu-latest + permissions: + # This job publishes only unique staging service tags. Canonical aliases + # are written by publish-runtime-images after the exact candidate passes smoke. + contents: read + packages: write + strategy: + fail-fast: false + matrix: + service: + - account-service + - automation-scripting-service + - entity-management-service + - game-design-service + - game-logic-service + - game-session-service + - logging-admin-service + - social-groups-service + - spring-cloud-gateway + - tcp-proxy-service + - world-management-service + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: ⬇️ Checkout Code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: ⚙️ Set Up Java + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: ⚙️ Set Up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: false + + - name: Build service JAR + run: ./gradlew :${{ matrix.service }}:bootJar + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Login to GHCR + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push runtime service image + id: build_runtime_image_first + continue-on-error: true + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: ./services/${{ matrix.service }}/build/libs + file: ./services/${{ matrix.service }}/Dockerfile + push: true + build-contexts: | + repo_root=. + build-args: | + BASE_IMAGE=ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }} + tags: ghcr.io/benhook1013/${{ matrix.service }}:${{ needs.image-meta.outputs.candidate_tag }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache,mode=max + type=gha,mode=max + + - name: Retry build and push runtime service image + if: ${{ steps.build_runtime_image_first.outcome == 'failure' }} + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: ./services/${{ matrix.service }}/build/libs + file: ./services/${{ matrix.service }}/Dockerfile + push: true + build-contexts: | + repo_root=. + build-args: | + BASE_IMAGE=ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }} + tags: ghcr.io/benhook1013/${{ matrix.service }}:${{ needs.image-meta.outputs.candidate_tag }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache,mode=max + type=gha,mode=max + + build-backup-verifier: + name: Build Backup Verifier Image + needs: [image-meta] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') }} + runs-on: ubuntu-latest + timeout-minutes: 15 + outputs: + image_id: ${{ steps.smoke.outputs.image_id }} + permissions: + contents: read + env: + BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Checkout trusted branch commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Load workflow tool versions + id: workflow-tool-versions + uses: ./.github/actions/load-workflow-tool-versions + + - name: Build backup verifier image + run: | + docker build \ + --file docker/backup-verifier.Dockerfile \ + --tag "$BACKUP_VERIFIER_IMAGE" \ + . + + - name: Smoke backup verifier image + id: smoke + env: + VELERO_VERSION: ${{ steps.workflow-tool-versions.outputs.velero-version }} + run: | + set -euo pipefail + bash ./dev-tools/backups/smoke-backup-verifier-image.sh "$BACKUP_VERIFIER_IMAGE" "$VELERO_VERSION" + image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" + [[ "$image_id" =~ ^sha256:[0-9a-f]{64}$ ]] || { + echo "Backup verifier image did not return an exact image ID." >&2 + exit 1 + } + echo "image_id=$image_id" >> "$GITHUB_OUTPUT" + + - name: Export exact verified backup verifier image artifact + env: + VERIFIED_IMAGE_ID: ${{ steps.smoke.outputs.image_id }} + run: | + set -euo pipefail + current_image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" + [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Backup verifier image changed after its smoke proof; refusing artifact export." >&2 + exit 1 + } + docker save "$BACKUP_VERIFIER_IMAGE" | gzip -1 > "$RUNNER_TEMP/backup-verifier.tar.gz" + + - name: Upload exact verified backup verifier image artifact + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: backup-verifier-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/backup-verifier.tar.gz + if-no-files-found: error + retention-days: 1 + + publish-backup-verifier: + name: Publish Trusted Backup Verifier Image + needs: [image-meta, build-backup-verifier] + if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-backup-verifier.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + packages: write + id-token: write + attestations: write + env: + BACKUP_VERIFIER_IMAGE_NAME: ghcr.io/benhook1013/backup-verifier + BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Checkout trusted publication commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Download exact verified backup verifier image artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: backup-verifier-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/backup-verifier-artifact + + - name: Load and verify exact backup verifier image + env: + BACKUP_VERIFIER_ARCHIVE: ${{ runner.temp }}/backup-verifier-artifact/backup-verifier.tar.gz + VERIFIED_IMAGE_ID: ${{ needs.build-backup-verifier.outputs.image_id }} + run: | + set -euo pipefail + [[ -f "$BACKUP_VERIFIER_ARCHIVE" ]] || { + echo "Verified backup verifier image artifact is missing." >&2 + exit 1 + } + gzip -dc "$BACKUP_VERIFIER_ARCHIVE" | docker load + loaded_image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" + [[ "$loaded_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Loaded backup verifier image does not match the exact verified build image." >&2 + exit 1 + } + + - name: Login to GHCR + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Publish exact verified backup verifier image + id: publish + run: | + set -euo pipefail + bash ./dev-tools/hosted/shared/push-verified-image.sh "$BACKUP_VERIFIER_IMAGE" + + - name: Attest trusted backup verifier image provenance + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-name: ${{ env.BACKUP_VERIFIER_IMAGE_NAME }} + subject-digest: ${{ steps.publish.outputs.digest }} + push-to-registry: true + create-storage-record: false + + build-hosted-identity-controller: + name: Build Trusted Hosted Identity Controller + needs: [image-meta, build-base-image] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-base-image.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 25 + outputs: + image_id: ${{ steps.smoke.outputs.image_id }} + permissions: + contents: read + packages: read + env: + CONTROLLER_IMAGE_NAME: ghcr.io/benhook1013/firemud-hosted-identity-controller + CONTROLLER_IMAGE: ghcr.io/benhook1013/firemud-hosted-identity-controller:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Checkout trusted branch commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up Java + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: false + + - name: Login to GHCR + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build controller JAR and image locally + run: | + set -euo pipefail + ./gradlew :hosted-environment-identity-controller:bootJar + docker build \ + --file services/hosted-environment-identity-controller/Dockerfile \ + --build-arg BASE_IMAGE="ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }}" \ + --tag "$CONTROLLER_IMAGE" \ + services/hosted-environment-identity-controller/build/libs + + - name: Smoke exact controller image + id: smoke + run: | + set -euo pipefail + smoked_image_id="$(bash ./dev-tools/hosted/controller/smoke-paused-controller-image.sh "$CONTROLLER_IMAGE")" + local_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$smoked_image_id" == "$local_image_id" ]] || { + echo "Controller smoke did not execute the exact locally tagged image." >&2 + exit 1 + } + echo "image_id=$local_image_id" >> "$GITHUB_OUTPUT" + + - name: Export exact verified controller image artifact + env: + VERIFIED_IMAGE_ID: ${{ steps.smoke.outputs.image_id }} + run: | + set -euo pipefail + current_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Controller image changed after its smoke proof; refusing artifact export." >&2 + exit 1 + } + docker save "$CONTROLLER_IMAGE" | gzip -1 > "$RUNNER_TEMP/hosted-identity-controller.tar.gz" + + - name: Upload exact verified controller image artifact + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: hosted-identity-controller-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/hosted-identity-controller.tar.gz + if-no-files-found: error + retention-days: 1 + + publish-hosted-identity-controller: + name: Publish Trusted Hosted Identity Controller + needs: [image-meta, build-base-image, build-hosted-identity-controller] + if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-base-image.result == 'success' && needs.build-hosted-identity-controller.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 25 + permissions: + contents: read + packages: write + id-token: write + attestations: write + env: + CONTROLLER_IMAGE_NAME: ghcr.io/benhook1013/firemud-hosted-identity-controller + CONTROLLER_IMAGE: ghcr.io/benhook1013/firemud-hosted-identity-controller:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Checkout trusted publication commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Download exact verified controller image artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: hosted-identity-controller-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/hosted-identity-controller-artifact + + - name: Load and verify exact controller image + env: + CONTROLLER_ARCHIVE: ${{ runner.temp }}/hosted-identity-controller-artifact/hosted-identity-controller.tar.gz + VERIFIED_IMAGE_ID: ${{ needs.build-hosted-identity-controller.outputs.image_id }} + run: | + set -euo pipefail + [[ -f "$CONTROLLER_ARCHIVE" ]] || { + echo "Verified hosted identity controller image artifact is missing." >&2 + exit 1 + } + gzip -dc "$CONTROLLER_ARCHIVE" | docker load + loaded_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$loaded_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Loaded controller image does not match the exact verified build image." >&2 + exit 1 + } + + - name: Login to GHCR + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Publish exact verified controller image + id: publish + env: + VERIFIED_IMAGE_ID: ${{ needs.build-hosted-identity-controller.outputs.image_id }} + run: | + set -euo pipefail + current_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Controller image changed after its verification proof; refusing publication." >&2 + exit 1 + } + bash ./dev-tools/hosted/shared/push-verified-image.sh "$CONTROLLER_IMAGE" + + - name: Attest trusted controller image provenance + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-name: ${{ env.CONTROLLER_IMAGE_NAME }} + subject-digest: ${{ steps.publish.outputs.digest }} + push-to-registry: true + create-storage-record: false + + pr-local-smoke: + name: PR Full-Stack Smoke (runtime-required=${{ needs.image-meta.outputs.runtime_smoke_required }}) + needs: [image-meta] + if: ${{ (github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || github.event_name == 'repository_dispatch' }} + runs-on: ubuntu-latest + timeout-minutes: 45 + permissions: + # PR-controlled source receives no registry or repository write credential. + contents: read + env: + COMPOSE_PROJECT_NAME: smoke-full-${{ github.run_id }}-${{ github.run_attempt }} + SMOKE_TIMEOUT_SECONDS: 20 + SMOKE_IMAGE_TAG: ${{ needs.image-meta.outputs.image_tag }} + SMOKE_IMAGE_LOCAL_ONLY: 'true' + SMOKE_MINIO_LOCAL_ONLY: 'true' + SMOKE_MINIO_SERVER_IMAGE: >- + firemud-minio-server-smoke:${{ github.run_id }}-${{ github.run_attempt }} + SMOKE_MINIO_CLIENT_IMAGE: >- + firemud-minio-client-smoke:${{ github.run_id }}-${{ github.run_attempt }} + BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Checkout PR merge + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Load workflow tool versions + id: workflow-tool-versions + uses: ./.github/actions/load-workflow-tool-versions + + - name: Set up canonical Python + if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} + uses: ./.github/actions/setup-python + with: + requirements: smoke + + - name: Set up Java + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: true + + - name: Build local PR runtime images + id: runtime-images-build + env: + MERGE_SHA: ${{ needs.image-meta.outputs.merge_sha }} + run: | + set -euo pipefail + bash ./dev-tools/build-local-smoke-images.sh "$MERGE_SHA" + for service in \ + account-service \ + automation-scripting-service \ + entity-management-service \ + game-design-service \ + game-logic-service \ + game-session-service \ + logging-admin-service \ + social-groups-service \ + spring-cloud-gateway \ + tcp-proxy-service \ + world-management-service; do + docker tag \ + "ghcr.io/benhook1013/${service}:${MERGE_SHA}" \ + "ghcr.io/benhook1013/${service}:${SMOKE_IMAGE_TAG}" + done + + - name: Retain runtime bootJar compile-failure evidence + if: ${{ failure() && steps.runtime-images-build.outcome == 'failure' }} + continue-on-error: true + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: runtime-bootjar-compile-failure-${{ github.run_id }}-attempt-${{ github.run_attempt }} + path: ${{ steps.runtime-images-build.outputs.runtime_compile_failure_path || format('build/reports/compile-failure/runtime-bootjar/unavailable-{0}-{1}', github.run_id, github.run_attempt) }} + if-no-files-found: warn + retention-days: 3 + + - name: Build PR backup verifier image + run: | + docker build \ + --file docker/backup-verifier.Dockerfile \ + --tag "$BACKUP_VERIFIER_IMAGE" \ + . + + - name: Smoke PR backup verifier image + env: + VELERO_VERSION: ${{ steps.workflow-tool-versions.outputs.velero-version }} + run: bash ./dev-tools/backups/smoke-backup-verifier-image.sh "$BACKUP_VERIFIER_IMAGE" "$VELERO_VERSION" + + - name: Build and smoke pinned MinIO sources for PR Compose + id: minio-source + if: >- + ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} + run: | + bash ./dev-tools/minio/build-and-smoke-images.sh \ + "$SMOKE_MINIO_SERVER_IMAGE" "$SMOKE_MINIO_CLIENT_IMAGE" + + - name: Run credential-free full-stack smoke + id: runtime-smoke + if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} + env: + FIREMUD_SMOKE_ADMISSION_QUALIFICATION: held + SMOKE_MINIO_SERVER_IMAGE_ID: >- + ${{ steps.minio-source.outputs.server_image_id }} + SMOKE_MINIO_CLIENT_IMAGE_ID: >- + ${{ steps.minio-source.outputs.client_image_id }} + run: bash ./dev-tools/verify-smoke-images.sh --keep-running + + - name: Export fixed-tag preview image artifact + run: | + service_manifest=/tmp/pr-runtime-services.txt + provenance=/tmp/pr-runtime-provenance.json + : > "$service_manifest" + images=() + for service in \ + account-service \ + automation-scripting-service \ + entity-management-service \ + game-design-service \ + game-logic-service \ + game-session-service \ + logging-admin-service \ + social-groups-service \ + spring-cloud-gateway \ + tcp-proxy-service \ + world-management-service; do + printf '%s\n' "$service" >> "$service_manifest" + images+=("ghcr.io/benhook1013/${service}:${SMOKE_IMAGE_TAG}") + done + printf '%s\n' 'backup-verifier' >> "$service_manifest" + images+=("$BACKUP_VERIFIER_IMAGE") + PR_NUMBER="${{ needs.image-meta.outputs.pr_number }}" \ + BASE_SHA="${{ needs.image-meta.outputs.base_sha }}" \ + HEAD_SHA="${{ needs.image-meta.outputs.head_sha }}" \ + MERGE_SHA="${{ needs.image-meta.outputs.merge_sha }}" \ + IMAGE_TAG="${SMOKE_IMAGE_TAG}" \ + SOURCE_RUN_ID="${{ github.run_id }}" \ + REPOSITORY="${GITHUB_REPOSITORY}" \ + PROVENANCE_PATH="$provenance" \ + python3 - <<'PY' + import json + import os + + services = [ + "account-service", + "automation-scripting-service", + "entity-management-service", + "game-design-service", + "game-logic-service", + "game-session-service", + "logging-admin-service", + "social-groups-service", + "spring-cloud-gateway", + "tcp-proxy-service", + "world-management-service", + "backup-verifier", + ] + provenance = { + "repository": os.environ["REPOSITORY"], + "prNumber": int(os.environ["PR_NUMBER"]), + "baseSha": os.environ["BASE_SHA"], + "headSha": os.environ["HEAD_SHA"], + "mergeSha": os.environ["MERGE_SHA"], + "imageTag": os.environ["IMAGE_TAG"], + "sourceRunId": int(os.environ["SOURCE_RUN_ID"]), + "services": services, + } + with open(os.environ["PROVENANCE_PATH"], "w", encoding="utf-8") as output: + json.dump(provenance, output, separators=(",", ":"), sort_keys=True) + output.write("\n") + PY + docker save "${images[@]}" | gzip -1 > /tmp/pr-runtime-images.tar.gz + + - name: Upload preview image artifact + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: pr-runtime-images-${{ needs.image-meta.outputs.image_tag }} + path: | + /tmp/pr-runtime-images.tar.gz + /tmp/pr-runtime-services.txt + /tmp/pr-runtime-provenance.json + if-no-files-found: error + retention-days: 1 + + - name: Summarize secure PR runtime artifact + env: + PR_NUMBER: ${{ needs.image-meta.outputs.pr_number }} + BASE_SHA: ${{ needs.image-meta.outputs.base_sha }} + HEAD_SHA: ${{ needs.image-meta.outputs.head_sha }} + MERGE_SHA: ${{ needs.image-meta.outputs.merge_sha }} + ARTIFACT_NAME: pr-runtime-images-${{ needs.image-meta.outputs.image_tag }} + run: | + { + echo "### PR runtime images and applicable full-stack smoke" + echo + echo "- Pull request: #${PR_NUMBER}" + echo "- Base SHA: \`${BASE_SHA}\`" + echo "- PR head SHA: \`${HEAD_SHA}\`" + echo "- Built PR merge SHA (full-stack smoke runs when required): \`${MERGE_SHA}\`" + echo "- Merge-scoped publication tag: \`pr-merge-${MERGE_SHA}\`" + echo "- Artifact: \`${ARTIFACT_NAME}\`" + echo + echo "This read-only PR workflow built the PR merge commit and runs full-stack smoke when required by change scope. The trusted default-branch publisher uploads only the exact merge-scoped artifact from this successful run." + } >> "$GITHUB_STEP_SUMMARY" + + - name: Dump Docker Compose logs on failure + if: >- + ${{ failure() && + needs.image-meta.outputs.runtime_smoke_required == 'true' && + steps.minio-source.outputs.server_image_id != '' && + steps.minio-source.outputs.client_image_id != '' }} + env: + SMOKE_MINIO_SERVER_IMAGE_ID: >- + ${{ steps.minio-source.outputs.server_image_id }} + SMOKE_MINIO_CLIENT_IMAGE_ID: >- + ${{ steps.minio-source.outputs.client_image_id }} + run: | + docker compose \ + -f docker/docker-compose.yml \ + -f docker/docker-compose.override.yml \ + -f docker/docker-compose.smoke-images.override.yml \ + -f docker/docker-compose.pr-local-minio.override.yml \ + logs || true + + - name: Stop smoke stack + id: runtime-cleanup + if: >- + ${{ always() && + needs.image-meta.outputs.runtime_smoke_required == 'true' && + steps.minio-source.outputs.server_image_id != '' && + steps.minio-source.outputs.client_image_id != '' }} + env: + SMOKE_MINIO_SERVER_IMAGE_ID: >- + ${{ steps.minio-source.outputs.server_image_id }} + SMOKE_MINIO_CLIENT_IMAGE_ID: >- + ${{ steps.minio-source.outputs.client_image_id }} + run: | + source ./dev-tools/smoke/run-owned-compose.sh + if ! stop_run_owned_compose_project \ + -f docker/docker-compose.yml \ + -f docker/docker-compose.override.yml \ + -f docker/docker-compose.smoke-images.override.yml \ + -f docker/docker-compose.pr-local-minio.override.yml; then + echo "Unable to prove or release the smoke Compose project; refusing unowned teardown." >&2 + exit 1 + fi + + # Canonical-transition diagnostic evidence, not runtime qualification. The + # original failed step and the final required-smoke failure remain red. + - name: Known canonical transition PLAY failure with successful authenticated cleanup + if: >- + ${{ always() && + github.repository == 'benhook1013/FireMUD' && + ((github.event_name == 'pull_request' && + contains(github.event.pull_request.labels.*.name, 'canonical-play-transition')) || + (github.event_name == 'repository_dispatch' && + github.event.action == 'pr-runtime-base-refresh' && + needs.image-meta.outputs.canonical_play_transition == 'true')) && + needs.image-meta.outputs.runtime_smoke_required == 'true' && + steps.runtime-smoke.outcome == 'failure' && + steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login' && + steps.runtime-cleanup.outcome == 'success' }} + run: | + echo '### Canonical PLAY transition exception evidence' >> "$GITHUB_STEP_SUMMARY" + echo 'LOGIN succeeded; direct backend PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE. Held-admission qualification and authenticated cleanup passed. No runtime qualification, image export, or publication.' >> "$GITHUB_STEP_SUMMARY" + + - name: Require successful runtime smoke and authenticated cleanup + if: ${{ always() }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + env: + RUNTIME_SMOKE_REQUIRED: ${{ needs.image-meta.outputs.runtime_smoke_required }} + RUNTIME_SMOKE_OUTCOME: ${{ steps.runtime-smoke.outcome }} + RUNTIME_CLEANUP_OUTCOME: ${{ steps.runtime-cleanup.outcome }} + with: + script: | + const required = process.env.RUNTIME_SMOKE_REQUIRED; + if (required !== "true" && required !== "false") { + core.setFailed("Runtime smoke scope is unavailable or invalid."); + } else if (required === "true" && ( + process.env.RUNTIME_SMOKE_OUTCOME !== "success" || + process.env.RUNTIME_CLEANUP_OUTCOME !== "success" + )) { + core.setFailed("Required runtime smoke and authenticated cleanup must both execute successfully."); + } + + pr-controller-smoke: + name: PR Hosted Identity Controller Smoke + needs: [image-meta] + if: ${{ ((github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || github.event_name == 'repository_dispatch') && needs.image-meta.outputs.controller_smoke_required == 'true' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + # PR-controlled source receives no registry or repository write credential. + contents: read + env: + BASE_IMAGE: ${{ needs.image-meta.outputs.base_image }} + CONTROLLER_IMAGE: firemud-hosted-identity-controller-local:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Checkout PR merge + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up Java + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: true + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Build exact local runtime base image + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: docker/base.Dockerfile + push: false + load: true + tags: ${{ env.BASE_IMAGE }} + cache-from: type=gha,scope=pr-controller-smoke + cache-to: type=gha,mode=max,scope=pr-controller-smoke + + - name: Build controller image for credential-free local validation + run: | + set -euo pipefail + ./gradlew :hosted-environment-identity-controller:bootJar + docker build \ + --file services/hosted-environment-identity-controller/Dockerfile \ + --build-arg BASE_IMAGE="$BASE_IMAGE" \ + --tag "$CONTROLLER_IMAGE" \ + services/hosted-environment-identity-controller/build/libs + + - name: Smoke controller image entrypoint and paused health + run: | + set -euo pipefail + bash ./dev-tools/hosted/controller/smoke-paused-controller-image.sh "$CONTROLLER_IMAGE" >/dev/null + + dispatch-pr-runtime-publication: + name: Dispatch Trusted PR Runtime Publication + needs: [image-meta, pr-local-smoke, pr-controller-smoke] + if: ${{ always() && !cancelled() && github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && needs.image-meta.result == 'success' && needs.pr-local-smoke.result == 'success' && (needs.pr-controller-smoke.result == 'success' || (needs.image-meta.outputs.controller_smoke_required == 'false' && needs.pr-controller-smoke.result == 'skipped')) }} + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + # This trusted no-checkout job only sends an exact source-run handoff. + contents: write + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Dispatch exact runtime publication source + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + await github.rest.repos.createDispatchEvent({ + ...context.repo, + event_type: "pr-runtime-image-publication", + client_payload: { source_run_id: String(context.runId) }, + }); + + smoke-full: + name: Published Runtime Full-Stack Smoke + needs: [image-meta, build-runtime-images] + if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.build-runtime-images.result == 'success' }} + permissions: + # The trusted branch smoke workflow only pulls the staged candidate images. + contents: read + packages: read + uses: ./.github/workflows/smoke-full.yml + with: + action: full + head_sha: ${{ needs.image-meta.outputs.head_sha }} + checkout_ref: ${{ needs.image-meta.outputs.checkout_ref }} + image_tag: ${{ needs.image-meta.outputs.candidate_tag }} + secrets: inherit + + publish-runtime-images: + name: Promote Smoke-Tested Runtime Images + needs: [image-meta, build-runtime-images, smoke-full] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.build-runtime-images.result == 'success' && needs.smoke-full.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + packages: write + env: + HEAD_SHA: ${{ needs.image-meta.outputs.head_sha }} + HEAD_BRANCH: ${{ needs.image-meta.outputs.head_branch }} + CANDIDATE_TAG: ${{ needs.image-meta.outputs.candidate_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Checkout trusted publication source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up canonical GitHub CLI + uses: ./.github/actions/setup-gh + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Login to GHCR + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Promote smoke-tested service digests + env: + GH_TOKEN: ${{ github.token }} + GHCR_USERNAME: ${{ github.actor }} + GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + + services=( + account-service + automation-scripting-service + entity-management-service + game-design-service + game-logic-service + game-session-service + logging-admin-service + social-groups-service + spring-cloud-gateway + tcp-proxy-service + world-management-service + ) + + declare -A registry_tokens=() + registry_manifest_state() { + local image="$1" + local image_path="${image#ghcr.io/}" + local repository_path="${image_path%:*}" + local tag="${image_path##*:}" + local manifest_url="https://ghcr.io/v2/${repository_path}/manifests/${tag}" + local registry_token="${registry_tokens[$repository_path]:-}" + local status + + [[ -n "${GHCR_USERNAME:-}" && -n "${GHCR_TOKEN:-}" ]] || { + echo "GHCR credentials are unavailable for authenticated manifest preflight: $image" >&2 + return 1 + } + if [[ -z "$registry_token" ]]; then + if ! registry_token="$(curl --silent --show-error --location --fail \ + --connect-timeout 10 --max-time 30 \ + --user "${GHCR_USERNAME}:${GHCR_TOKEN}" \ + --get \ + --data-urlencode 'service=ghcr.io' \ + --data-urlencode "scope=repository:${repository_path}:pull" \ + --header 'Accept: application/json' \ + 'https://ghcr.io/token' | jq -er '.token // .access_token // empty')"; then + echo "GHCR bearer-token exchange failed for $image; refusing to infer absence." >&2 + return 1 + fi + registry_tokens["$repository_path"]="$registry_token" + fi + # `docker manifest inspect "$image"` conflates a 404 with auth, + # registry, and network failures, so it is never an absence check. + if ! status="$(curl --silent --show-error --location --head \ + --connect-timeout 10 --max-time 30 \ + --header "Authorization: Bearer ${registry_token}" \ + --header 'Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json' \ + --output /dev/null --write-out '%{http_code}' "$manifest_url")"; then + echo "Authenticated OCI manifest HEAD failed for $image; refusing to infer absence." >&2 + return 1 + fi + case "$status" in + 200) printf 'existing\n' ;; + 404) printf 'missing\n' ;; + *) + echo "Authenticated OCI manifest HEAD returned HTTP ${status} for $image; refusing to push." >&2 + return 1 + ;; + esac + } + + registry_digest() { + local image="$1" + local inspect_output inspect_status + local digest + if inspect_output="$(docker buildx imagetools inspect "$image")"; then + : + else + inspect_status=$? + echo "Unable to inspect exact registry digest for $image (imagetools exit $inspect_status); refusing to publish." >&2 + return "$inspect_status" + fi + digest="$(awk '$1 == "Digest:" && $2 ~ /^sha256:[0-9a-f]{64}$/ { print $2; exit }' <<<"$inspect_output")" + [[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]] || { + echo "Registry manifest for $image has no exact digest." >&2 + return 1 + } + printf '%s\n' "$digest" + } + + assert_current_branch_head() { + local current_sha + current_sha="$(gh api \ + "repos/${GITHUB_REPOSITORY}/git/ref/heads/${HEAD_BRANCH}" \ + --jq '.object.sha')" + [[ "$current_sha" == "$HEAD_SHA" ]] || { + echo "Refusing canonical runtime publication: ${HEAD_BRANCH} moved from ${HEAD_SHA} to ${current_sha}." >&2 + exit 1 + } + } + + promote_alias() { + local source="$1" target="$2" fixed="$3" + local source_digest existing_digest target_digest + source_digest="$(registry_digest "$source")" + local target_state + if ! target_state="$(registry_manifest_state "$target")"; then + echo "Immutable target preflight failed for $target; refusing to publish." >&2 + exit 1 + fi + if [[ "$target_state" == missing ]]; then + docker buildx imagetools create --tag "$target" "$source" + else + existing_digest="$(registry_digest "$target")" + if [[ "$fixed" == true && "$existing_digest" != "$source_digest" ]]; then + echo "Refusing to overwrite fixed runtime tag $target: existing digest $existing_digest differs from candidate $source_digest." >&2 + exit 1 + fi + if [[ "$existing_digest" != "$source_digest" ]]; then + docker buildx imagetools create --tag "$target" "$source" + fi + fi + target_digest="$(registry_digest "$target")" + [[ "$target_digest" == "$source_digest" ]] || { + echo "Promoted runtime tag $target does not match candidate digest $source_digest (got $target_digest)." >&2 + exit 1 + } + } + + for service in "${services[@]}"; do + candidate="ghcr.io/benhook1013/${service}:${CANDIDATE_TAG}" + sha_tag="ghcr.io/benhook1013/${service}:${HEAD_SHA}" + branch_tag="ghcr.io/benhook1013/${service}:${HEAD_BRANCH}" + + assert_current_branch_head + promote_alias "$candidate" "$sha_tag" true + assert_current_branch_head + promote_alias "$candidate" "$branch_tag" false + if [[ "$HEAD_BRANCH" == develop ]]; then + assert_current_branch_head + promote_alias "$candidate" "ghcr.io/benhook1013/${service}:latest" false + fi + done diff --git a/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/3b81c438ddf473c94ad0424ad9a979d7070091e4.yml b/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/3b81c438ddf473c94ad0424ad9a979d7070091e4.yml new file mode 100644 index 0000000000..d3d85fa62b --- /dev/null +++ b/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/3b81c438ddf473c94ad0424ad9a979d7070091e4.yml @@ -0,0 +1,2149 @@ +name: Build Runtime Images + +on: + pull_request: + types: [opened, synchronize, reopened, edited] + paths: + - 'build.gradle.kts' + - 'settings.gradle.kts' + - 'gradle.properties' + - 'gradlew' + - 'gradlew.bat' + - 'buildSrc/**' + - 'gradle/**' + - 'protos/**' + - 'docker/**' + - '.dockerignore' + - '.github/workflows/runtime-images.yml' + - '.github/workflows/publish-pr-runtime-images.yml' + - '.github/workflows/smoke.yml' + - '.github/workflows/smoke-full.yml' + - 'services/**' + - '.github/actions/load-workflow-tool-versions/**' + - '.github/actions/setup-python/**' + - '.python-version' + - 'config/workflow-tool-versions.env' + - 'config/python/smoke-requirements.txt' + - 'config/python/smoke-requirements.in' + - 'dev-tools/build-compose-service-jars.sh' + - 'dev-tools/validation/run-gradle-with-dependency-recovery.sh' + - 'dev-tools/validation/run-locked-gradle.sh' + - 'dev-tools/validation/gradle-run-supervisor.py' + - 'dev-tools/build-local-smoke-images.sh' + - 'dev-tools/backups/verify-backups.sh' + - 'dev-tools/backups/pg-dump-s3-selection.shlib' + - 'dev-tools/backups/smoke-backup-verifier-image.sh' + - 'docker/backup-verifier.Dockerfile' + - 'dev-tools/certs/generate-dev-certs.sh' + - 'dev-tools/minio/**' + - 'dev-tools/hosted/controller/smoke-paused-controller-image.sh' + - 'dev-tools/smoke/**' + - 'dev-tools/verify-compose-health.sh' + - 'dev-tools/verify-fresh-bootstrap.sh' + - 'dev-tools/verify-restart-state.sh' + - 'dev-tools/verify-smoke-images.sh' + workflow_run: + workflows: ["CI — Validation"] + types: [completed] + repository_dispatch: + types: [pr-runtime-base-refresh] + workflow_dispatch: + +run-name: Build Runtime Images ${{ (github.event_name == 'pull_request' || github.event_name == 'repository_dispatch') && format('secure-pr-artifact pr-{0} base-{1} head-{2} merge-{3} mode-{4}', github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number, github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.client_payload.base_sha, github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.event.client_payload.head_sha, github.event_name == 'pull_request' && github.sha || github.event.client_payload.merge_sha, github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required') || github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success' && format('trusted-branch branch-{0} sha-{1}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha) || github.event_name == 'workflow_run' && format('base-refresh-only branch-{0} sha-{1} ci-{2}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha, github.event.workflow_run.conclusion) || github.ref_name }} + +permissions: + contents: read + +concurrency: + group: runtime-images-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha, github.sha)) || (github.event_name == 'repository_dispatch' && github.event.client_payload.pr_number != '' && github.event.client_payload.base_sha != '' && github.event.client_payload.head_sha != '' && github.event.client_payload.merge_sha != '' && format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.client_payload.pr_number, github.event.client_payload.base_sha, github.event.client_payload.head_sha, github.event.client_payload.merge_sha)) || (github.event_name == 'repository_dispatch' && format('repository-dispatch-run-{0}', github.run_id)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && format('ci-pr-run-{0}-attempt-{1}', github.event.workflow_run.id, github.event.workflow_run.run_attempt)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && format('branch-{0}', github.event.workflow_run.head_branch)) || github.ref }}-${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required' }} + cancel-in-progress: true + +jobs: + image-meta: + name: Derive Runtime Image Metadata + if: ${{ (github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || (github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh') || github.event_name == 'workflow_dispatch' || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && github.event.workflow_run.conclusion == 'success' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop')) }} + runs-on: ubuntu-latest + outputs: + pr_number: ${{ steps.meta.outputs.pr_number }} + base_ref: ${{ steps.meta.outputs.base_ref }} + base_sha: ${{ steps.meta.outputs.base_sha }} + head_sha: ${{ steps.meta.outputs.head_sha }} + merge_sha: ${{ steps.meta.outputs.merge_sha }} + head_branch: ${{ steps.meta.outputs.head_branch }} + checkout_ref: ${{ steps.meta.outputs.checkout_ref }} + image_tag: ${{ steps.meta.outputs.image_tag }} + candidate_tag: ${{ steps.meta.outputs.candidate_tag }} + base_image: ${{ steps.meta.outputs.base_image }} + canonical_play_transition: ${{ steps.meta.outputs.canonical_play_transition }} + runtime_smoke_required: ${{ steps.smoke_scope.outputs.runtime_smoke_required }} + controller_smoke_required: ${{ steps.smoke_scope.outputs.controller_smoke_required }} + permissions: + actions: read + contents: read + pull-requests: read + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Check out trusted workflow helpers + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - name: Set up canonical GitHub CLI + uses: ./.github/actions/setup-gh + + - name: Set up canonical Python + uses: ./.github/actions/setup-python + + - name: Derive image tags + id: meta + env: + GH_TOKEN: ${{ github.token }} + EVENT_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.client_payload.head_sha || '' }} + EVENT_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch || '' }} + EVENT_PR_NUMBER: ${{ github.event.pull_request.number || github.event.client_payload.pr_number || '' }} + EVENT_BASE_REF: ${{ github.event.pull_request.base.ref || github.event.client_payload.base_ref || '' }} + EVENT_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.client_payload.base_sha || '' }} + EVENT_MERGE_SHA: ${{ github.event.client_payload.merge_sha || '' }} + EVENT_ACTION: ${{ github.event.action || '' }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + run: | + set -euo pipefail + EVENT_NAME="${{ github.event_name }}" + PR_NUMBER="" + BASE_REF="" + BASE_SHA="" + MERGE_SHA="" + CANONICAL_PLAY_TRANSITION=false + if [ "$EVENT_NAME" = "pull_request" ]; then + PR_NUMBER="$EVENT_PR_NUMBER" + BASE_REF="$EVENT_BASE_REF" + BASE_SHA="$EVENT_BASE_SHA" + HEAD_SHA="$EVENT_HEAD_SHA" + HEAD_BRANCH="" + MERGE_SHA="${GITHUB_SHA}" + CHECKOUT_REF="$MERGE_SHA" + [[ "$MERGE_SHA" =~ ^[0-9a-f]{40}$ ]] || { + echo "PR merge SHA is not a lowercase 40-character commit SHA." >&2 + exit 1 + } + [[ "$BASE_SHA" =~ ^[0-9a-f]{40}$ && "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]] || { + echo "PR event base/head SHAs are not lowercase 40-character commit SHAs." >&2 + exit 1 + } + merge_commit_json="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${MERGE_SHA}")" + jq -e \ + --arg base_sha "$BASE_SHA" \ + --arg head_sha "$HEAD_SHA" \ + --arg merge_sha "$MERGE_SHA" \ + '.sha == $merge_sha and (.parents | type) == "array" and (.parents | length) == 2 and .parents[0].sha == $base_sha and .parents[1].sha == $head_sha' \ + <<<"$merge_commit_json" >/dev/null || { + echo "PR event merge commit does not have the event's exact base/head parents; refusing a stale PR artifact." >&2 + exit 1 + } + elif [ "$EVENT_NAME" = "repository_dispatch" ]; then + [[ "$EVENT_ACTION" == "pr-runtime-base-refresh" ]] || { + echo "Runtime PR refresh requires the typed pr-runtime-base-refresh dispatch." >&2 + exit 1 + } + [[ "$GITHUB_REF" == "refs/heads/${DEFAULT_BRANCH}" ]] || { + echo "Runtime PR refresh must run from the repository default branch." >&2 + exit 1 + } + PR_NUMBER="$EVENT_PR_NUMBER" + BASE_REF="$EVENT_BASE_REF" + BASE_SHA="$EVENT_BASE_SHA" + MERGE_SHA="$EVENT_MERGE_SHA" + HEAD_SHA="$EVENT_HEAD_SHA" + HEAD_BRANCH="" + CHECKOUT_REF="$MERGE_SHA" + [[ "$PR_NUMBER" =~ ^[1-9][0-9]{0,50}$ ]] || { + echo "Runtime PR refresh payload has an invalid pull request number." >&2 + exit 1 + } + git check-ref-format "refs/heads/${BASE_REF}" >/dev/null || { + echo "Runtime PR refresh payload has an invalid base ref." >&2 + exit 1 + } + for sha_name in BASE_SHA HEAD_SHA MERGE_SHA; do + sha_value="${!sha_name}" + [[ "$sha_value" =~ ^[0-9a-f]{40}$ ]] || { + echo "Runtime PR refresh payload has an invalid ${sha_name}." >&2 + exit 1 + } + done + + encoded_base_ref="$(python3 -c 'import sys; from urllib.parse import quote; print(quote(sys.argv[1], safe="/"))' "$BASE_REF")" + current_base_ref_json="$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/heads/${encoded_base_ref}")" + jq -e \ + --arg base_sha "$BASE_SHA" \ + --arg base_ref "refs/heads/${BASE_REF}" \ + '.ref == $base_ref and .object.sha == $base_sha' \ + <<<"$current_base_ref_json" >/dev/null || { + echo "Runtime PR refresh base SHA is not the current ${BASE_REF} branch ref." >&2 + exit 1 + } + pull_request_json="$(gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}")" + jq -e \ + --arg repository "$GITHUB_REPOSITORY" \ + --arg base_ref "$BASE_REF" \ + --arg head_sha "$HEAD_SHA" \ + --arg merge_sha "$MERGE_SHA" \ + '( + .state == "open" and + .base.ref == $base_ref and + .base.repo.full_name == $repository and + .head.sha == $head_sha and + .head.repo.full_name == $repository and + (.mergeable | type) == "boolean" and + .mergeable == true and + (.mergeable_state | type) == "string" and + .mergeable_state != "dirty" and + .mergeable_state != "conflicting" and + .mergeable_state != "unknown" and + .merge_commit_sha == $merge_sha + )' <<<"$pull_request_json" >/dev/null || { + echo "Runtime PR refresh payload is stale, conflicted, fork-owned, closed, or has an invalid merge tuple." >&2 + exit 1 + } + merge_commit_json="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${MERGE_SHA}")" + jq -e \ + --arg base_sha "$BASE_SHA" \ + --arg head_sha "$HEAD_SHA" \ + --arg merge_sha "$MERGE_SHA" \ + '.sha == $merge_sha and (.parents | type) == "array" and (.parents | length) == 2 and .parents[0].sha == $base_sha and .parents[1].sha == $head_sha' \ + <<<"$merge_commit_json" >/dev/null || { + echo "Runtime PR refresh merge commit does not have the exact current base/head parents." >&2 + exit 1 + } + # Only the verified live same-repository PR can authorize this + # diagnostic marker; dispatch payload labels carry no authority. + if jq -e '(.labels | type) == "array" and any(.labels[]; .name == "canonical-play-transition")' \ + <<<"$pull_request_json" >/dev/null; then + CANONICAL_PLAY_TRANSITION=true + fi + elif [ "${{ github.event_name }}" = "workflow_run" ]; then + [[ "${{ github.event.workflow_run.event }}" == "push" ]] || { + echo "Runtime branch publication requires a CI push workflow run." >&2 + exit 1 + } + [[ "${{ github.event.workflow_run.conclusion }}" == "success" ]] || { + echo "Runtime branch publication requires a successful CI workflow run." >&2 + exit 1 + } + HEAD_SHA="${EVENT_HEAD_SHA:-${{ github.event.workflow_run.head_sha }}}" + HEAD_BRANCH="$EVENT_HEAD_BRANCH" + CHECKOUT_REF="$HEAD_SHA" + else + HEAD_SHA="${GITHUB_SHA}" + CHECKOUT_REF="${GITHUB_SHA}" + HEAD_BRANCH="${GITHUB_REF_NAME}" + fi + + [[ "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]] || { + echo "Runtime publication head SHA is not a lowercase 40-character commit SHA." >&2 + exit 1 + } + if [ "$EVENT_NAME" != "pull_request" ] && [ "$EVENT_NAME" != "repository_dispatch" ]; then + [[ "$HEAD_BRANCH" == main || "$HEAD_BRANCH" == develop ]] || { + echo "Runtime branch publication is restricted to main or develop." >&2 + exit 1 + } + fi + + if [ "$EVENT_NAME" = "pull_request" ] || [ "$EVENT_NAME" = "repository_dispatch" ]; then + IMAGE_TAG="pr-merge-${MERGE_SHA}" + else + IMAGE_TAG="${HEAD_SHA}" + fi + CANDIDATE_TAG="candidate-${HEAD_SHA}-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + if [ "$EVENT_NAME" = "pull_request" ] || [ "$EVENT_NAME" = "repository_dispatch" ]; then + BASE_IMAGE="ghcr.io/benhook1013/firemud-base:${MERGE_SHA}" + else + BASE_IMAGE="ghcr.io/benhook1013/firemud-base:${CANDIDATE_TAG}" + fi + + { + echo "pr_number=${PR_NUMBER}" + echo "base_ref=${BASE_REF}" + echo "base_sha=${BASE_SHA}" + echo "head_sha=${HEAD_SHA}" + echo "merge_sha=${MERGE_SHA}" + echo "head_branch=${HEAD_BRANCH}" + echo "checkout_ref=${CHECKOUT_REF}" + echo "image_tag=${IMAGE_TAG}" + echo "candidate_tag=${CANDIDATE_TAG}" + echo "base_image=${BASE_IMAGE}" + echo "canonical_play_transition=${CANONICAL_PLAY_TRANSITION}" + } >> "$GITHUB_OUTPUT" + + - name: Verify successful CI push for manual publication + if: ${{ github.event_name == 'workflow_dispatch' }} + env: + GH_TOKEN: ${{ github.token }} + EXPECTED_SHA: ${{ steps.meta.outputs.head_sha }} + EXPECTED_BRANCH: ${{ steps.meta.outputs.head_branch }} + run: | + set -euo pipefail + ci_runs="$(gh api --paginate --slurp \ + "repos/${GITHUB_REPOSITORY}/actions/workflows/ci.yml/runs?event=push&head_sha=${EXPECTED_SHA}&per_page=100")" + jq -e \ + --arg expected_sha "$EXPECTED_SHA" \ + --arg expected_branch "$EXPECTED_BRANCH" \ + '[.[].workflow_runs[]?] | any(.[]; .head_sha == $expected_sha and .head_branch == $expected_branch and .event == "push" and .status == "completed" and .conclusion == "success")' \ + <<<"$ci_runs" >/dev/null || { + echo "No successful CI push run exists for manual runtime publication ${EXPECTED_BRANCH}@${EXPECTED_SHA}." >&2 + exit 1 + } + + - name: Detect PR smoke scopes + id: smoke_scope + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + let runtimeSmokeRequired = true; + let controllerSmokeRequired = true; + if (context.eventName === "pull_request" || context.eventName === "repository_dispatch") { + try { + const pullNumber = context.eventName === "pull_request" + ? context.payload.pull_request.number + : context.payload.client_payload.pr_number; + const changedFiles = await github.paginate( + github.rest.pulls.listFiles, + { + ...context.repo, + pull_number: pullNumber, + per_page: 100, + }, + (response) => response.data + ); + const expectedFileCount = context.eventName === "pull_request" + ? context.payload.pull_request.changed_files + : (await github.rest.pulls.get({ + ...context.repo, + pull_number: pullNumber, + })).data.changed_files; + const validFileEntries = changedFiles.every((file) => + file && + typeof file.filename === "string" && + file.filename.length > 0 && + (file.previous_filename === undefined || + (typeof file.previous_filename === "string" && file.previous_filename.length > 0)) + ); + if (!Number.isInteger(expectedFileCount) || changedFiles.length !== expectedFileCount || !validFileEntries) { + core.warning("PR smoke scope detection was incomplete; running both local smokes."); + } else { + const paths = changedFiles.flatMap((file) => + [file.filename, file.previous_filename].filter(Boolean) + ); + const runtimePrefixes = [ + "buildSrc/", + "docker/", + "dev-tools/minio/", + "dev-tools/smoke/", + "gradle/", + "protos/", + ".github/actions/load-workflow-tool-versions/", + ".github/actions/setup-python/", + ]; + const workflowToolAuthorityPath = "config/workflow-tool-versions.env"; + const runtimeFiles = new Set([ + ".dockerignore", + ".github/workflows/publish-pr-runtime-images.yml", + ".github/workflows/runtime-images.yml", + ".github/workflows/smoke-full.yml", + ".github/workflows/smoke.yml", + ".github/actions/load-workflow-tool-versions/action.yml", + ".python-version", + "build.gradle.kts", + "config/python/smoke-requirements.txt", + "config/python/smoke-requirements.in", + "dev-tools/build-compose-service-jars.sh", + "dev-tools/validation/run-gradle-with-dependency-recovery.sh", + "dev-tools/validation/run-locked-gradle.sh", + "dev-tools/validation/gradle-run-supervisor.py", + "dev-tools/build-local-smoke-images.sh", + "dev-tools/backups/verify-backups.sh", + "dev-tools/backups/pg-dump-s3-selection.shlib", + "dev-tools/backups/smoke-backup-verifier-image.sh", + "dev-tools/certs/generate-dev-certs.sh", + "dev-tools/verify-compose-health.sh", + "dev-tools/verify-fresh-bootstrap.sh", + "dev-tools/verify-restart-state.sh", + "dev-tools/verify-smoke-images.sh", + "gradle.properties", + "docker/backup-verifier.Dockerfile", + "gradlew", + "gradlew.bat", + "settings.gradle.kts", + ]); + const controllerPrefixes = [ + "buildSrc/", + "gradle/", + "services/hosted-environment-identity-controller/", + ]; + const controllerFiles = new Set([ + ".dockerignore", + ".github/workflows/runtime-images.yml", + "build.gradle.kts", + "dev-tools/hosted/controller/smoke-paused-controller-image.sh", + "docker/base.Dockerfile", + "gradle.properties", + "gradlew", + "gradlew.bat", + "settings.gradle.kts", + ]); + const authorityChanged = paths.includes(workflowToolAuthorityPath); + const nonAuthorityPaths = paths.filter( + (path) => path !== workflowToolAuthorityPath + ); + runtimeSmokeRequired = nonAuthorityPaths.some( + (path) => + runtimeFiles.has(path) || + runtimePrefixes.some((prefix) => path.startsWith(prefix)) || + (path.startsWith("services/") && + !path.startsWith( + "services/hosted-environment-identity-controller/" + )) + ); + runtimeSmokeRequired = runtimeSmokeRequired || authorityChanged; + controllerSmokeRequired = paths.some( + (path) => + controllerFiles.has(path) || + controllerPrefixes.some((prefix) => path.startsWith(prefix)) + ); + } + } catch (error) { + core.warning( + `PR smoke scope detection failed; running both local smokes: ${error.message}` + ); + } + } + core.setOutput("runtime_smoke_required", String(runtimeSmokeRequired)); + core.setOutput("controller_smoke_required", String(controllerSmokeRequired)); + + dispatch-pr-base-refreshes: + name: Dispatch PR Base Refreshes + if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.status == 'completed' && (github.event.workflow_run.event == 'pull_request' || (github.event.workflow_run.event == 'push' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop'))) && github.event.workflow_run.head_repository.full_name == github.repository }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + actions: read + contents: write + pull-requests: read + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Dispatch exact PR runtime refreshes and preview reconciles + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + const workflowRun = context.payload.workflow_run; + const refreshBranch = workflowRun.head_branch; + const refreshSha = workflowRun.head_sha; + const shaPattern = /^[0-9a-f]{40}$/; + const runtimePrefixes = [ + "buildSrc/", + "docker/", + "dev-tools/minio/", + "dev-tools/smoke/", + "gradle/", + "protos/", + ".github/actions/load-workflow-tool-versions/", + ".github/actions/setup-python/", + ]; + const runtimeFiles = new Set([ + ".dockerignore", + ".github/workflows/publish-pr-runtime-images.yml", + ".github/workflows/runtime-images.yml", + ".github/workflows/smoke-full.yml", + ".github/workflows/smoke.yml", + ".github/actions/load-workflow-tool-versions/action.yml", + ".python-version", + "build.gradle.kts", + "config/workflow-tool-versions.env", + "config/python/smoke-requirements.txt", + "config/python/smoke-requirements.in", + "dev-tools/build-compose-service-jars.sh", + "dev-tools/validation/run-gradle-with-dependency-recovery.sh", + "dev-tools/validation/run-locked-gradle.sh", + "dev-tools/validation/gradle-run-supervisor.py", + "dev-tools/build-local-smoke-images.sh", + "dev-tools/backups/verify-backups.sh", + "dev-tools/backups/pg-dump-s3-selection.shlib", + "dev-tools/backups/smoke-backup-verifier-image.sh", + "dev-tools/certs/generate-dev-certs.sh", + "dev-tools/hosted/controller/smoke-paused-controller-image.sh", + "dev-tools/verify-compose-health.sh", + "dev-tools/verify-fresh-bootstrap.sh", + "dev-tools/verify-restart-state.sh", + "dev-tools/verify-smoke-images.sh", + "gradle.properties", + "gradlew", + "gradlew.bat", + "settings.gradle.kts", + ]); + const runtimeRunEvents = ["pull_request", "repository_dispatch"]; + const runtimeRunPageSize = 100; + const runtimeRunLookbackMilliseconds = 7 * 24 * 60 * 60 * 1000; + + const waitForMergeRefresh = async () => { + await new Promise((resolve) => setTimeout(resolve, 2000)); + }; + + const hasRuntimeChange = async (pullRequest) => { + const files = await github.paginate( + github.rest.pulls.listFiles, + { + ...context.repo, + pull_number: pullRequest.number, + per_page: 100, + }, + (response) => response.data + ); + const expectedFileCount = pullRequest.changed_files; + const validFileEntries = Number.isInteger(expectedFileCount) && + files.length === expectedFileCount && + files.every((file) => + file && + typeof file.filename === "string" && + file.filename.length > 0 && + (file.previous_filename === undefined || + (typeof file.previous_filename === "string" && file.previous_filename.length > 0)) + ); + if (!validFileEntries) { + core.warning(`PR #${pullRequest.number} changed-file metadata was incomplete; refreshing its runtime images.`); + return true; + } + return files.flatMap((file) => [file.filename, file.previous_filename].filter(Boolean)).some((path) => + runtimeFiles.has(path) || + runtimePrefixes.some((prefix) => path.startsWith(prefix)) || + path.startsWith("services/") + ); + }; + + const dependencyBotAuthors = new Set([ + "app/dependabot", + "dependabot[bot]", + "app/renovate", + "renovate[bot]", + ]); + + const isPreviewEligible = (pullRequest) => { + const labels = pullRequest.labels; + return typeof pullRequest.user?.login === "string" && + pullRequest.user.login.length > 0 && + !dependencyBotAuthors.has(pullRequest.user.login) && + Array.isArray(labels) && + labels.every((label) => label && typeof label.name === "string") && + (["main", "develop"].includes(pullRequest.base?.ref) || + labels.some((label) => label.name === "preview:priority")); + }; + + const resolveExactMerge = async (number, baseBranch = refreshBranch, baseSha = refreshSha, expectedHeadSha = null) => { + for (let attempt = 1; attempt <= 5; attempt += 1) { + const response = await github.rest.pulls.get({ + ...context.repo, + pull_number: number, + }); + const pullRequest = response.data; + const currentHeadSha = pullRequest.head?.sha; + const currentBaseRef = pullRequest.base?.ref; + const headRepository = pullRequest.head?.repo?.full_name; + const baseRepository = pullRequest.base?.repo?.full_name; + if (pullRequest.state !== "open" || + headRepository !== context.payload.repository.full_name || + baseRepository !== context.payload.repository.full_name || + currentBaseRef !== baseBranch || + !shaPattern.test(currentHeadSha || "") || + (expectedHeadSha !== null && currentHeadSha !== expectedHeadSha)) { + return null; + } + + const mergeableState = typeof pullRequest.mergeable_state === "string" + ? pullRequest.mergeable_state + : pullRequest.mergeable_state === null ? "unknown" : "invalid"; + if (pullRequest.mergeable === false || + mergeableState === "dirty" || + mergeableState === "conflicting") { + core.warning(`Skipping PR #${number}: GitHub reports a merge conflict.`); + return null; + } + if (pullRequest.mergeable === null || mergeableState === "unknown") { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: GitHub did not produce a ready merge tuple.`); + return null; + } + if (pullRequest.mergeable !== true || mergeableState === "invalid") { + core.warning(`Skipping PR #${number}: GitHub returned invalid merge metadata.`); + return null; + } + + const mergeSha = pullRequest.merge_commit_sha; + if (!shaPattern.test(mergeSha || "")) { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: merge SHA is null or invalid.`); + return null; + } + + try { + const commit = await github.rest.repos.getCommit({ + ...context.repo, + ref: mergeSha, + }); + const parents = commit.data.parents?.map((parent) => parent.sha) || []; + if (commit.data.sha !== mergeSha || + parents.length !== 2 || + parents[0] !== baseSha || + parents[1] !== currentHeadSha) { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: merge commit parents do not match the current base/head.`); + return null; + } + } catch (error) { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: exact merge commit could not be read (${error.message}).`); + return null; + } + + return { + tuple: { + prNumber: String(number), + baseRef: baseBranch, + baseSha, + headSha: currentHeadSha, + mergeSha, + }, + pullRequest, + }; + } + return null; + }; + + const loadExistingRuntimeRuns = async () => { + const readInventory = async (createdSince) => { + const inventory = []; + let complete = true; + let incompleteReason = null; + for (const event of runtimeRunEvents) { + const response = await github.rest.actions.listWorkflowRuns({ + ...context.repo, + workflow_id: "runtime-images.yml", + event, + created: `${createdSince}..*`, + per_page: runtimeRunPageSize, + page: 1, + }); + const payload = response?.data; + if (!payload || !Number.isInteger(payload.total_count) || + payload.total_count < 0 || !Array.isArray(payload.workflow_runs)) { + throw new Error(`runtime-images ${event} recent run inventory is malformed`); + } + if (payload.total_count > runtimeRunPageSize) { + complete = false; + incompleteReason ??= `runtime-images ${event} has more than ${runtimeRunPageSize} runs since ${createdSince}`; + } + const expectedPageLength = Math.min(payload.total_count, runtimeRunPageSize); + if (payload.workflow_runs.length !== expectedPageLength) { + throw new Error(`runtime-images ${event} recent run inventory is incomplete`); + } + inventory.push(...payload.workflow_runs); + } + return {complete, runs: inventory, reason: incompleteReason}; + }; + + const createdSince = new Date(Date.now() - runtimeRunLookbackMilliseconds).toISOString(); + const initial = await readInventory(createdSince); + if (initial.complete) { + return initial; + } + + const inFlightStatuses = ["queued", "waiting", "requested", "pending", "in_progress"]; + const inFlightRuns = initial.runs.filter((run) => inFlightStatuses.includes(run?.status)); + if (inFlightRuns.length === 0) { + return initial; + } + + const validTimestamp = (value) => typeof value === "string" && + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(value) && + Number.isFinite(Date.parse(value)); + if (inFlightRuns.some((run) => !runtimeRunEvents.includes(run.event) || + !Number.isSafeInteger(run.id) || run.id <= 0 || !validTimestamp(run.created_at))) { + return { + ...initial, + reason: "truncated recent inventory contains an in-flight run without a valid event, id, or creation timestamp", + }; + } + + const refinementSince = inFlightRuns + .map((run) => run.created_at) + .sort()[0]; + // The inclusive created lower bound makes the refined pages a complete candidate set without relying on API ordering. + const refined = await readInventory(refinementSince); + if (!refined.complete) { + return { + ...refined, + reason: refined.reason || "refined runtime run inventory is incomplete", + }; + } + const refinedIds = new Set(refined.runs.map((run) => `${run?.event}:${run?.id}`)); + if (inFlightRuns.some((run) => !refinedIds.has(`${run.event}:${run.id}`))) { + return { + ...refined, + complete: false, + reason: "refined inventory did not retain every initially observed in-flight run", + }; + } + return refined; + }; + + const findExactExistingProducer = (tuple, inventory) => { + const expectedWorkflowPath = ".github/workflows/runtime-images.yml"; + const workflowPathMatches = (path) => { + if (path === expectedWorkflowPath) { + return true; + } + const prefix = `${expectedWorkflowPath}@`; + if (typeof path !== "string" || !path.startsWith(prefix)) { + return false; + } + const ref = path.slice(prefix.length); + if (ref.length === 0 || ref === "@" || ref.endsWith(".") || + /[\u0000-\u0020\u007f]/.test(ref) || + ["~", "^", ":", "?", "*", "[", "\\"].some((character) => ref.includes(character)) || + ref.includes("..") || ref.includes("@{")) { + return false; + } + return ref.split("/").every((part) => + part.length > 0 && part !== "." && part !== ".." && + !part.startsWith(".") && + !part.endsWith(".lock") + ); + }; + const expectedTitle = + `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} ` + + `base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; + const matching = inventory.runs.filter((run) => + run?.display_title === expectedTitle + ); + const ordered = []; + const matchingIds = new Set(); + for (const run of matching) { + if (!runtimeRunEvents.includes(run.event) || + !Number.isSafeInteger(run.id) || run.id <= 0 || matchingIds.has(run.id) || + typeof run.created_at !== "string" || + !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(run.created_at) || + !Number.isFinite(Date.parse(run.created_at)) || + !workflowPathMatches(run.path) || + !["Build Runtime Images", expectedTitle].includes(run.name) || + run.repository?.full_name !== context.payload.repository.full_name || + run.head_repository?.full_name !== context.payload.repository.full_name) { + throw new Error(`run ${run.id} has the exact tuple title but invalid workflow or repository identity`); + } + matchingIds.add(run.id); + ordered.push(run); + if (run.event === "pull_request") { + if (run.head_sha !== tuple.headSha) { + throw new Error(`run ${run.id} has the exact tuple title but a different PR head SHA`); + } + const pullRequests = run.pull_requests; + if (!Array.isArray(pullRequests) || (pullRequests.length > 0 && !pullRequests.some((pullRequest) => + String(pullRequest?.number) === tuple.prNumber && + pullRequest?.head?.sha === tuple.headSha + ))) { + throw new Error(`run ${run.id} has incomplete or conflicting PR association evidence`); + } + } + } + ordered.sort((left, right) => right.created_at.localeCompare(left.created_at)); + if (ordered.length > 1 && ordered[0].created_at === ordered[1].created_at) { + throw new Error("newest exact runtime producer has an ambiguous created_at timestamp"); + } + const newest = ordered[0]; + if (!newest) { + return []; + } + if (["queued", "waiting", "requested", "pending", "in_progress"].includes(newest.status)) { + if (newest.conclusion !== null && newest.conclusion !== undefined) { + throw new Error(`run ${newest.id} has a conclusion while still ${newest.status}`); + } + return [newest]; + } + if (newest.status === "completed") { + // Completed source success does not prove publication remains usable; preserve recovery dispatch. + return []; + } + throw new Error(`run ${newest.id} has an unknown status and cannot be classified`); + }; + + if (!shaPattern.test(refreshSha) || typeof refreshBranch !== "string" || + refreshBranch.length === 0) { + core.setFailed("Completed CI callback did not identify a branch and lowercase SHA."); + return; + } + let sourcePrNumber = null; + if (workflowRun.event === "pull_request") { + // Completion is a reconcile signal only for a substantive CI attempt. + // Metadata edits also complete CI, but must never reconstruct runtime. + const positiveInteger = (value) => Number.isSafeInteger(value) && value > 0; + const ciPath = ".github/workflows/ci.yml"; + const ciName = "CI — Validation"; + const titleMatch = /^CI — Validation pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40})$/.exec(workflowRun.display_title || ""); + const matchesSource = (run) => + positiveInteger(workflowRun.id) && positiveInteger(workflowRun.run_attempt) && + positiveInteger(workflowRun.workflow_id) && + run.id === workflowRun.id && run.run_attempt === workflowRun.run_attempt && + run.workflow_id === workflowRun.workflow_id && run.event === "pull_request" && + run.status === "completed" && typeof run.conclusion === "string" && run.conclusion.length > 0 && + run.repository?.full_name === context.payload.repository.full_name && + run.head_repository?.full_name === context.payload.repository.full_name && + run.head_branch === refreshBranch && run.head_sha === refreshSha && + run.display_title === workflowRun.display_title && + [ciName, workflowRun.display_title].includes(run.name) && + (run.path === ciPath || (typeof run.path === "string" && + run.path.startsWith(`${ciPath}@`) && run.path.length > ciPath.length + 1)); + if (!titleMatch || titleMatch[3] !== refreshSha) { + core.warning("Skipping PR runtime reconciliation: callback lacks exact CI PR/base/head title metadata."); + return; + } + const {data: ciWorkflow} = await github.rest.actions.getWorkflow({ + ...context.repo, workflow_id: "ci.yml", + }); + const {data: source} = await github.rest.actions.getWorkflowRun({ + ...context.repo, run_id: workflowRun.id, + }); + if (ciWorkflow.id !== workflowRun.workflow_id || ciWorkflow.path !== ciPath || + ciWorkflow.name !== ciName || !matchesSource(source)) { + core.warning("Skipping PR runtime reconciliation: current CI workflow/run identity differs from callback."); + return; + } + const jobs = await github.paginate( + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + {...context.repo, run_id: source.id, attempt_number: source.run_attempt, per_page: 100} + ); + const gates = jobs.filter((job) => job.name === "Validation Gate"); + const gate = gates.length === 1 ? gates[0] : null; + const preservation = gate?.steps?.filter((step) => + step.name === "Preserve successful required gate on metadata-only edit") || []; + const enforcement = gate?.steps?.filter((step) => step.name === "Enforce validation success") || []; + const checkPrefix = `https://api.github.com/repos/${context.payload.repository.full_name}/check-runs/`; + if (!gate || !positiveInteger(gate.id) || gate.run_id !== source.id || + gate.run_attempt !== source.run_attempt || gate.head_sha !== source.head_sha || + ![ciName, source.display_title].includes(gate.workflow_name) || gate.status !== "completed" || + typeof gate.check_run_url !== "string" || !gate.check_run_url.startsWith(checkPrefix) || + !/^[1-9][0-9]*$/.test(gate.check_run_url.slice(checkPrefix.length)) || + preservation.length !== 1 || preservation[0].status !== "completed" || + preservation[0].conclusion !== "skipped" || enforcement.length !== 1 || + enforcement[0].status !== "completed" || !["success", "failure"].includes(enforcement[0].conclusion)) { + core.info("Skipping PR runtime reconciliation: exact CI attempt is metadata-only or lacks substantive native gate evidence."); + return; + } + const {data: latest} = await github.rest.actions.getWorkflowRun({ + ...context.repo, run_id: source.id, + }); + if (!matchesSource(latest)) { + core.warning("Skipping PR runtime reconciliation: CI attempt was superseded during classification."); + return; + } + sourcePrNumber = titleMatch[1]; + } + let currentBranch; + try { + currentBranch = await github.rest.git.getRef({ + ...context.repo, + ref: `heads/${refreshBranch}`, + }); + } catch (error) { + if (error.status !== 404) throw error; + core.info(`Skipping obsolete CI callback: branch ${refreshBranch} no longer exists.`); + return; + } + if (currentBranch.data.object?.sha !== refreshSha) { + core.warning(`Skipping PR base refresh: ${refreshBranch} advanced beyond the completed CI callback ${refreshSha}.`); + return; + } + + // Protected push callbacks own dependent fan-out; PR callbacks for + // those heads still reconcile their own exact source PR below. + const protectedPrHead = workflowRun.event === "pull_request" && + ["main", "develop"].includes(refreshBranch); + const pullRequests = protectedPrHead ? [] : await github.paginate( + github.rest.pulls.list, + { + ...context.repo, + state: "open", + base: refreshBranch, + per_page: 100, + }, + (response) => response.data + ); + const refreshTargets = []; + for (const listedPullRequest of pullRequests) { + if (listedPullRequest.state !== "open" || + listedPullRequest.base?.ref !== refreshBranch || + listedPullRequest.head?.repo?.full_name !== context.payload.repository.full_name || + listedPullRequest.base?.repo?.full_name !== context.payload.repository.full_name) { + continue; + } + const resolved = await resolveExactMerge(listedPullRequest.number); + if (resolved) { + refreshTargets.push(resolved); + } + } + if (workflowRun.event === "pull_request") { + // A retarget/edit can carry an unusable event merge SHA. CI completion + // is only a reconcile signal: re-read its source's current exact tuple. + const sourcePullRequests = await github.paginate( + github.rest.pulls.list, + { + ...context.repo, + state: "open", + head: `${context.repo.owner}:${refreshBranch}`, + per_page: 100, + }, + (response) => response.data + ); + for (const source of sourcePullRequests) { + if (String(source.number) !== sourcePrNumber || + source.state !== "open" || source.head?.sha !== refreshSha || + source.head?.ref !== refreshBranch || + source.head?.repo?.full_name !== context.payload.repository.full_name || + source.base?.repo?.full_name !== context.payload.repository.full_name || + typeof source.base?.ref !== "string" || + source.base.ref.length === 0) { + continue; + } + const sourceBase = await github.rest.git.getRef({ + ...context.repo, + ref: `heads/${source.base.ref}`, + }); + const sourceBaseSha = sourceBase.data.object?.sha; + if (!shaPattern.test(sourceBaseSha || "")) { + core.warning(`Skipping source PR #${source.number}: current base ref SHA is invalid.`); + continue; + } + const resolved = await resolveExactMerge(source.number, source.base.ref, sourceBaseSha, refreshSha); + if (resolved && !refreshTargets.some((target) => target.tuple.prNumber === resolved.tuple.prNumber)) { + refreshTargets.push(resolved); + } + } + } + let runtimeInventoryPromise; + let runtimeInventoryError = null; + for (const resolved of refreshTargets) { + const {tuple, pullRequest} = resolved; + if (await hasRuntimeChange(pullRequest)) { + let existingProducers = []; + let fallbackReason = null; + let inventory; + if (runtimeInventoryError) { + fallbackReason = runtimeInventoryError; + } else { + try { + runtimeInventoryPromise ??= loadExistingRuntimeRuns(); + inventory = await runtimeInventoryPromise; + } catch (error) { + fallbackReason = error.message || String(error); + runtimeInventoryError = fallbackReason; + } + } + if (!fallbackReason) { + try { + existingProducers = findExactExistingProducer(tuple, inventory); + if (!inventory.complete) { + // The REST contract does not specify a sort order, so a truncated page cannot prove omitted runs are older. + existingProducers = []; + fallbackReason = inventory.reason || "recent run inventory is incomplete"; + } + } catch (error) { + fallbackReason = error.message || String(error); + } + } + if (fallbackReason) { + core.warning( + `Cannot verify recent runtime producer evidence for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}); falling back to the required refresh dispatch: ${fallbackReason}` + ); + } + if (existingProducers.length > 0) { + const producer = existingProducers[0]; + core.info( + `Skipping duplicate PR runtime refresh for #${tuple.prNumber}: exact tuple producer ${producer.id} remains ${producer.status}.` + ); + } else { + core.info(`No reusable in-flight exact producer was verified in the bounded recent inventory; dispatching required PR runtime refresh for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); + await github.rest.repos.createDispatchEvent({ + ...context.repo, + event_type: "pr-runtime-base-refresh", + client_payload: { + pr_number: tuple.prNumber, + base_ref: tuple.baseRef, + base_sha: tuple.baseSha, + head_sha: tuple.headSha, + merge_sha: tuple.mergeSha, + }, + }); + } + } else { + core.info(`Skipping PR runtime image refresh for #${tuple.prNumber}: no runtime-changing files.`); + } + if (!isPreviewEligible(pullRequest)) { + core.info(`Skipping preview deploy reconciliation for #${tuple.prNumber}: target is not preview-eligible.`); + continue; + } + core.info(`Dispatching preview deploy reconciliation for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); + await github.rest.repos.createDispatchEvent({ + ...context.repo, + event_type: "preview-deploy", + client_payload: { + action: "deploy", + pr_number: tuple.prNumber, + base_ref: tuple.baseRef, + base_sha: tuple.baseSha, + head_sha: tuple.headSha, + merge_sha: tuple.mergeSha, + preview_domain: "preview.firedevops.net", + }, + }); + } + + build-base-image: + name: Build Runtime Base Image + needs: [image-meta] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + runs-on: ubuntu-latest + outputs: + digest: ${{ steps.select_base_image_digest.outputs.digest }} + permissions: + # This job publishes the shared runtime base image to GHCR. + contents: read + packages: write + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: ⬇️ Checkout Code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push runtime base image + id: build_base_image_first + continue-on-error: true + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: ./docker/base.Dockerfile + push: true + tags: ${{ needs.image-meta.outputs.base_image }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache + type=registry,ref=ghcr.io/benhook1013/firemud-base:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache,mode=max + type=gha,mode=max + + - name: Retry build and push runtime base image + id: build_base_image_retry + if: ${{ steps.build_base_image_first.outcome == 'failure' }} + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: ./docker/base.Dockerfile + push: true + tags: ${{ needs.image-meta.outputs.base_image }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache + type=registry,ref=ghcr.io/benhook1013/firemud-base:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache,mode=max + type=gha,mode=max + + - name: Select exact published runtime base digest + id: select_base_image_digest + if: ${{ !cancelled() }} + env: + FIRST_OUTCOME: ${{ steps.build_base_image_first.outcome }} + FIRST_DIGEST: ${{ steps.build_base_image_first.outputs.digest }} + RETRY_OUTCOME: ${{ steps.build_base_image_retry.outcome }} + RETRY_DIGEST: ${{ steps.build_base_image_retry.outputs.digest }} + run: | + set -euo pipefail + published_digests=() + if [[ "$FIRST_OUTCOME" == "success" ]]; then + published_digests+=("$FIRST_DIGEST") + fi + if [[ "$RETRY_OUTCOME" == "success" ]]; then + published_digests+=("$RETRY_DIGEST") + fi + if ((${#published_digests[@]} != 1)); then + echo "Expected exactly one successful runtime base-image publication digest." >&2 + exit 1 + fi + base_image_digest="${published_digests[0]}" + [[ "$base_image_digest" =~ ^sha256:[0-9a-f]{64}$ ]] || { + echo "Runtime base-image publisher returned an invalid sha256 digest." >&2 + exit 1 + } + echo "digest=$base_image_digest" >> "$GITHUB_OUTPUT" + + build-runtime-images: + name: Build Runtime Images (${{ matrix.service }}) + needs: [image-meta, build-base-image] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + runs-on: ubuntu-latest + permissions: + # This job publishes only unique staging service tags. Canonical aliases + # are written by publish-runtime-images after the exact candidate passes smoke. + contents: read + packages: write + strategy: + fail-fast: false + matrix: + service: + - account-service + - automation-scripting-service + - entity-management-service + - game-design-service + - game-logic-service + - game-session-service + - logging-admin-service + - social-groups-service + - spring-cloud-gateway + - tcp-proxy-service + - world-management-service + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: ⬇️ Checkout Code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: ⚙️ Set Up Java + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: ⚙️ Set Up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: false + + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + + - name: Build service JAR + run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- :${{ matrix.service }}:bootJar + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push runtime service image + id: build_runtime_image_first + continue-on-error: true + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: ./services/${{ matrix.service }}/build/libs + file: ./services/${{ matrix.service }}/Dockerfile + push: true + build-contexts: | + repo_root=. + build-args: | + BASE_IMAGE=ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }} + tags: ghcr.io/benhook1013/${{ matrix.service }}:${{ needs.image-meta.outputs.candidate_tag }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache,mode=max + type=gha,mode=max + + - name: Retry build and push runtime service image + if: ${{ steps.build_runtime_image_first.outcome == 'failure' }} + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: ./services/${{ matrix.service }}/build/libs + file: ./services/${{ matrix.service }}/Dockerfile + push: true + build-contexts: | + repo_root=. + build-args: | + BASE_IMAGE=ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }} + tags: ghcr.io/benhook1013/${{ matrix.service }}:${{ needs.image-meta.outputs.candidate_tag }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache,mode=max + type=gha,mode=max + + build-backup-verifier: + name: Build Backup Verifier Image + needs: [image-meta] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') }} + runs-on: ubuntu-latest + timeout-minutes: 15 + outputs: + image_id: ${{ steps.smoke.outputs.image_id }} + permissions: + contents: read + env: + BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Checkout trusted branch commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Load workflow tool versions + id: workflow-tool-versions + uses: ./.github/actions/load-workflow-tool-versions + + - name: Build backup verifier image + run: | + docker build \ + --file docker/backup-verifier.Dockerfile \ + --tag "$BACKUP_VERIFIER_IMAGE" \ + . + + - name: Smoke backup verifier image + id: smoke + env: + VELERO_VERSION: ${{ steps.workflow-tool-versions.outputs.velero-version }} + run: | + set -euo pipefail + bash ./dev-tools/backups/smoke-backup-verifier-image.sh "$BACKUP_VERIFIER_IMAGE" "$VELERO_VERSION" + image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" + [[ "$image_id" =~ ^sha256:[0-9a-f]{64}$ ]] || { + echo "Backup verifier image did not return an exact image ID." >&2 + exit 1 + } + echo "image_id=$image_id" >> "$GITHUB_OUTPUT" + + - name: Export exact verified backup verifier image artifact + env: + VERIFIED_IMAGE_ID: ${{ steps.smoke.outputs.image_id }} + run: | + set -euo pipefail + current_image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" + [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Backup verifier image changed after its smoke proof; refusing artifact export." >&2 + exit 1 + } + docker save "$BACKUP_VERIFIER_IMAGE" | gzip -1 > "$RUNNER_TEMP/backup-verifier.tar.gz" + + - name: Upload exact verified backup verifier image artifact + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: backup-verifier-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/backup-verifier.tar.gz + if-no-files-found: error + retention-days: 1 + + publish-backup-verifier: + name: Publish Trusted Backup Verifier Image + needs: [image-meta, build-backup-verifier] + if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-backup-verifier.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + packages: write + id-token: write + attestations: write + env: + BACKUP_VERIFIER_IMAGE_NAME: ghcr.io/benhook1013/backup-verifier + BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Checkout trusted publication commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Download exact verified backup verifier image artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: backup-verifier-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/backup-verifier-artifact + + - name: Load and verify exact backup verifier image + env: + BACKUP_VERIFIER_ARCHIVE: ${{ runner.temp }}/backup-verifier-artifact/backup-verifier.tar.gz + VERIFIED_IMAGE_ID: ${{ needs.build-backup-verifier.outputs.image_id }} + run: | + set -euo pipefail + [[ -f "$BACKUP_VERIFIER_ARCHIVE" ]] || { + echo "Verified backup verifier image artifact is missing." >&2 + exit 1 + } + gzip -dc "$BACKUP_VERIFIER_ARCHIVE" | docker load + loaded_image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" + [[ "$loaded_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Loaded backup verifier image does not match the exact verified build image." >&2 + exit 1 + } + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Publish exact verified backup verifier image + id: publish + run: | + set -euo pipefail + bash ./dev-tools/hosted/shared/push-verified-image.sh "$BACKUP_VERIFIER_IMAGE" + + - name: Attest trusted backup verifier image provenance + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-name: ${{ env.BACKUP_VERIFIER_IMAGE_NAME }} + subject-digest: ${{ steps.publish.outputs.digest }} + push-to-registry: true + create-storage-record: false + + build-hosted-identity-controller: + name: Build Trusted Hosted Identity Controller + needs: [image-meta, build-base-image] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-base-image.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 25 + outputs: + image_id: ${{ steps.smoke.outputs.image_id }} + permissions: + contents: read + packages: read + env: + CONTROLLER_IMAGE_NAME: ghcr.io/benhook1013/firemud-hosted-identity-controller + CONTROLLER_IMAGE: ghcr.io/benhook1013/firemud-hosted-identity-controller:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Checkout trusted branch commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up Java + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: false + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + + - name: Build controller JAR and image locally + run: | + set -euo pipefail + bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- :hosted-environment-identity-controller:bootJar + docker build \ + --file services/hosted-environment-identity-controller/Dockerfile \ + --build-arg BASE_IMAGE="ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }}" \ + --tag "$CONTROLLER_IMAGE" \ + services/hosted-environment-identity-controller/build/libs + + - name: Smoke exact controller image + id: smoke + run: | + set -euo pipefail + smoked_image_id="$(bash ./dev-tools/hosted/controller/smoke-paused-controller-image.sh "$CONTROLLER_IMAGE")" + local_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$smoked_image_id" == "$local_image_id" ]] || { + echo "Controller smoke did not execute the exact locally tagged image." >&2 + exit 1 + } + echo "image_id=$local_image_id" >> "$GITHUB_OUTPUT" + + - name: Export exact verified controller image artifact + env: + VERIFIED_IMAGE_ID: ${{ steps.smoke.outputs.image_id }} + run: | + set -euo pipefail + current_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Controller image changed after its smoke proof; refusing artifact export." >&2 + exit 1 + } + docker save "$CONTROLLER_IMAGE" | gzip -1 > "$RUNNER_TEMP/hosted-identity-controller.tar.gz" + + - name: Upload exact verified controller image artifact + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: hosted-identity-controller-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/hosted-identity-controller.tar.gz + if-no-files-found: error + retention-days: 1 + + publish-hosted-identity-controller: + name: Publish Trusted Hosted Identity Controller + needs: [image-meta, build-base-image, build-hosted-identity-controller] + if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-base-image.result == 'success' && needs.build-hosted-identity-controller.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 25 + permissions: + contents: read + packages: write + id-token: write + attestations: write + env: + CONTROLLER_IMAGE_NAME: ghcr.io/benhook1013/firemud-hosted-identity-controller + CONTROLLER_IMAGE: ghcr.io/benhook1013/firemud-hosted-identity-controller:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Checkout trusted publication commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Download exact verified controller image artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: hosted-identity-controller-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/hosted-identity-controller-artifact + + - name: Load and verify exact controller image + env: + CONTROLLER_ARCHIVE: ${{ runner.temp }}/hosted-identity-controller-artifact/hosted-identity-controller.tar.gz + VERIFIED_IMAGE_ID: ${{ needs.build-hosted-identity-controller.outputs.image_id }} + run: | + set -euo pipefail + [[ -f "$CONTROLLER_ARCHIVE" ]] || { + echo "Verified hosted identity controller image artifact is missing." >&2 + exit 1 + } + gzip -dc "$CONTROLLER_ARCHIVE" | docker load + loaded_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$loaded_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Loaded controller image does not match the exact verified build image." >&2 + exit 1 + } + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Publish exact verified controller image + id: publish + env: + VERIFIED_IMAGE_ID: ${{ needs.build-hosted-identity-controller.outputs.image_id }} + run: | + set -euo pipefail + current_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Controller image changed after its verification proof; refusing publication." >&2 + exit 1 + } + bash ./dev-tools/hosted/shared/push-verified-image.sh "$CONTROLLER_IMAGE" + + - name: Attest trusted controller image provenance + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-name: ${{ env.CONTROLLER_IMAGE_NAME }} + subject-digest: ${{ steps.publish.outputs.digest }} + push-to-registry: true + create-storage-record: false + + pr-local-smoke: + outputs: + publishable: ${{ steps.runtime-artifact.outcome == 'success' }} + name: PR Full-Stack Smoke (runtime-required=${{ needs.image-meta.outputs.runtime_smoke_required }}) + needs: [image-meta] + if: ${{ (github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || github.event_name == 'repository_dispatch' }} + runs-on: ubuntu-latest + timeout-minutes: 45 + permissions: + # PR-controlled source receives no registry or repository write credential. + contents: read + env: + COMPOSE_PROJECT_NAME: smoke-full-${{ github.run_id }}-${{ github.run_attempt }} + SMOKE_TIMEOUT_SECONDS: 20 + SMOKE_IMAGE_TAG: ${{ needs.image-meta.outputs.image_tag }} + SMOKE_IMAGE_LOCAL_ONLY: 'true' + SMOKE_MINIO_LOCAL_ONLY: 'true' + SMOKE_MINIO_SERVER_IMAGE: >- + firemud-minio-server-smoke:${{ github.run_id }}-${{ github.run_attempt }} + SMOKE_MINIO_CLIENT_IMAGE: >- + firemud-minio-client-smoke:${{ github.run_id }}-${{ github.run_attempt }} + BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Checkout PR merge + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Load workflow tool versions + id: workflow-tool-versions + uses: ./.github/actions/load-workflow-tool-versions + + - name: Set up canonical Python + if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} + uses: ./.github/actions/setup-python + with: + requirements: smoke + + - name: Set up Java + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: true + + - name: Build local PR runtime images + id: runtime-images-build + env: + MERGE_SHA: ${{ needs.image-meta.outputs.merge_sha }} + run: | + set -euo pipefail + bash ./dev-tools/build-local-smoke-images.sh "$MERGE_SHA" + for service in \ + account-service \ + automation-scripting-service \ + entity-management-service \ + game-design-service \ + game-logic-service \ + game-session-service \ + logging-admin-service \ + social-groups-service \ + spring-cloud-gateway \ + tcp-proxy-service \ + world-management-service; do + docker tag \ + "ghcr.io/benhook1013/${service}:${MERGE_SHA}" \ + "ghcr.io/benhook1013/${service}:${SMOKE_IMAGE_TAG}" + done + + - name: Retain runtime bootJar compile-failure evidence + if: ${{ failure() && steps.runtime-images-build.outcome == 'failure' }} + continue-on-error: true + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: runtime-bootjar-compile-failure-${{ github.run_id }}-attempt-${{ github.run_attempt }} + path: ${{ steps.runtime-images-build.outputs.runtime_compile_failure_path || format('build/reports/compile-failure/runtime-bootjar/unavailable-{0}-{1}', github.run_id, github.run_attempt) }} + if-no-files-found: warn + retention-days: 3 + + - name: Build PR backup verifier image + run: | + docker build \ + --file docker/backup-verifier.Dockerfile \ + --tag "$BACKUP_VERIFIER_IMAGE" \ + . + + - name: Smoke PR backup verifier image + env: + VELERO_VERSION: ${{ steps.workflow-tool-versions.outputs.velero-version }} + run: bash ./dev-tools/backups/smoke-backup-verifier-image.sh "$BACKUP_VERIFIER_IMAGE" "$VELERO_VERSION" + + - name: Build and smoke pinned MinIO sources for PR Compose + id: minio-source + if: >- + ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} + run: | + bash ./dev-tools/minio/build-and-smoke-images.sh \ + "$SMOKE_MINIO_SERVER_IMAGE" "$SMOKE_MINIO_CLIENT_IMAGE" + + - name: Run credential-free full-stack smoke + id: runtime-smoke + # The terminal guard admits only the classified, labeled transition failure. + continue-on-error: true + if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} + env: + FIREMUD_SMOKE_ADMISSION_QUALIFICATION: held + SMOKE_MINIO_SERVER_IMAGE_ID: >- + ${{ steps.minio-source.outputs.server_image_id }} + SMOKE_MINIO_CLIENT_IMAGE_ID: >- + ${{ steps.minio-source.outputs.client_image_id }} + run: bash ./dev-tools/verify-smoke-images.sh --keep-running + + - name: Export fixed-tag preview image artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} + run: | + service_manifest=/tmp/pr-runtime-services.txt + provenance=/tmp/pr-runtime-provenance.json + : > "$service_manifest" + images=() + for service in \ + account-service \ + automation-scripting-service \ + entity-management-service \ + game-design-service \ + game-logic-service \ + game-session-service \ + logging-admin-service \ + social-groups-service \ + spring-cloud-gateway \ + tcp-proxy-service \ + world-management-service; do + printf '%s\n' "$service" >> "$service_manifest" + images+=("ghcr.io/benhook1013/${service}:${SMOKE_IMAGE_TAG}") + done + printf '%s\n' 'backup-verifier' >> "$service_manifest" + images+=("$BACKUP_VERIFIER_IMAGE") + PR_NUMBER="${{ needs.image-meta.outputs.pr_number }}" \ + BASE_SHA="${{ needs.image-meta.outputs.base_sha }}" \ + HEAD_SHA="${{ needs.image-meta.outputs.head_sha }}" \ + MERGE_SHA="${{ needs.image-meta.outputs.merge_sha }}" \ + IMAGE_TAG="${SMOKE_IMAGE_TAG}" \ + SOURCE_RUN_ID="${{ github.run_id }}" \ + REPOSITORY="${GITHUB_REPOSITORY}" \ + PROVENANCE_PATH="$provenance" \ + python3 - <<'PY' + import json + import os + + services = [ + "account-service", + "automation-scripting-service", + "entity-management-service", + "game-design-service", + "game-logic-service", + "game-session-service", + "logging-admin-service", + "social-groups-service", + "spring-cloud-gateway", + "tcp-proxy-service", + "world-management-service", + "backup-verifier", + ] + provenance = { + "repository": os.environ["REPOSITORY"], + "prNumber": int(os.environ["PR_NUMBER"]), + "baseSha": os.environ["BASE_SHA"], + "headSha": os.environ["HEAD_SHA"], + "mergeSha": os.environ["MERGE_SHA"], + "imageTag": os.environ["IMAGE_TAG"], + "sourceRunId": int(os.environ["SOURCE_RUN_ID"]), + "services": services, + } + with open(os.environ["PROVENANCE_PATH"], "w", encoding="utf-8") as output: + json.dump(provenance, output, separators=(",", ":"), sort_keys=True) + output.write("\n") + PY + docker save "${images[@]}" | gzip -1 > /tmp/pr-runtime-images.tar.gz + + - name: Upload preview image artifact + id: runtime-artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: pr-runtime-images-${{ needs.image-meta.outputs.image_tag }} + path: | + /tmp/pr-runtime-images.tar.gz + /tmp/pr-runtime-services.txt + /tmp/pr-runtime-provenance.json + if-no-files-found: error + retention-days: 1 + + - name: Summarize secure PR runtime artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} + env: + PR_NUMBER: ${{ needs.image-meta.outputs.pr_number }} + BASE_SHA: ${{ needs.image-meta.outputs.base_sha }} + HEAD_SHA: ${{ needs.image-meta.outputs.head_sha }} + MERGE_SHA: ${{ needs.image-meta.outputs.merge_sha }} + ARTIFACT_NAME: pr-runtime-images-${{ needs.image-meta.outputs.image_tag }} + run: | + { + echo "### PR runtime images and applicable full-stack smoke" + echo + echo "- Pull request: #${PR_NUMBER}" + echo "- Base SHA: \`${BASE_SHA}\`" + echo "- PR head SHA: \`${HEAD_SHA}\`" + echo "- Built PR merge SHA (full-stack smoke runs when required): \`${MERGE_SHA}\`" + echo "- Merge-scoped publication tag: \`pr-merge-${MERGE_SHA}\`" + echo "- Artifact: \`${ARTIFACT_NAME}\`" + echo + echo "This read-only PR workflow built the PR merge commit and runs full-stack smoke when required by change scope. The trusted default-branch publisher uploads only the exact merge-scoped artifact from this successful run." + } >> "$GITHUB_STEP_SUMMARY" + + - name: Dump Docker Compose logs on failure + if: >- + ${{ always() && steps.runtime-smoke.outcome == 'failure' && + needs.image-meta.outputs.runtime_smoke_required == 'true' && + steps.minio-source.outputs.server_image_id != '' && + steps.minio-source.outputs.client_image_id != '' }} + env: + SMOKE_MINIO_SERVER_IMAGE_ID: >- + ${{ steps.minio-source.outputs.server_image_id }} + SMOKE_MINIO_CLIENT_IMAGE_ID: >- + ${{ steps.minio-source.outputs.client_image_id }} + run: | + docker compose \ + -f docker/docker-compose.yml \ + -f docker/docker-compose.override.yml \ + -f docker/docker-compose.smoke-images.override.yml \ + -f docker/docker-compose.pr-local-minio.override.yml \ + logs || true + + - name: Stop smoke stack + id: runtime-cleanup + if: >- + ${{ always() && + needs.image-meta.outputs.runtime_smoke_required == 'true' && + steps.minio-source.outputs.server_image_id != '' && + steps.minio-source.outputs.client_image_id != '' }} + env: + SMOKE_MINIO_SERVER_IMAGE_ID: >- + ${{ steps.minio-source.outputs.server_image_id }} + SMOKE_MINIO_CLIENT_IMAGE_ID: >- + ${{ steps.minio-source.outputs.client_image_id }} + run: | + source ./dev-tools/smoke/run-owned-compose.sh + if ! stop_run_owned_compose_project \ + -f docker/docker-compose.yml \ + -f docker/docker-compose.override.yml \ + -f docker/docker-compose.smoke-images.override.yml \ + -f docker/docker-compose.pr-local-minio.override.yml; then + echo "Unable to prove or release the smoke Compose project; refusing unowned teardown." >&2 + exit 1 + fi + + # Canonical-transition diagnostic evidence, not runtime qualification. The + # native smoke outcome remains failed; only the bounded CI exception may pass. + - name: Known canonical transition PLAY failure with successful authenticated cleanup + id: canonical-play-transition + if: >- + ${{ always() && + github.repository == 'benhook1013/FireMUD' && + ((github.event_name == 'pull_request' && + contains(github.event.pull_request.labels.*.name, 'canonical-play-transition')) || + (github.event_name == 'repository_dispatch' && + github.event.action == 'pr-runtime-base-refresh' && + needs.image-meta.outputs.canonical_play_transition == 'true')) && + needs.image-meta.outputs.runtime_smoke_required == 'true' && + steps.runtime-smoke.outcome == 'failure' && + steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login' && + steps.runtime-cleanup.outcome == 'success' }} + run: | + echo '### Canonical PLAY transition exception evidence' >> "$GITHUB_STEP_SUMMARY" + echo 'LOGIN succeeded; direct backend PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE. Held-admission qualification and authenticated cleanup passed. No runtime qualification, image export, or publication.' >> "$GITHUB_STEP_SUMMARY" + + - name: Require successful runtime smoke and authenticated cleanup + if: ${{ always() }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + env: + RUNTIME_SMOKE_REQUIRED: ${{ needs.image-meta.outputs.runtime_smoke_required }} + RUNTIME_SMOKE_OUTCOME: ${{ steps.runtime-smoke.outcome }} + RUNTIME_CLEANUP_OUTCOME: ${{ steps.runtime-cleanup.outcome }} + KNOWN_PLAY_EXCEPTION_OUTCOME: ${{ steps.canonical-play-transition.outcome }} + with: + script: | + const required = process.env.RUNTIME_SMOKE_REQUIRED; + if (required !== "true" && required !== "false") { + core.setFailed("Runtime smoke scope is unavailable or invalid."); + } else if (required === "true" && ( + process.env.RUNTIME_CLEANUP_OUTCOME !== "success" || + (process.env.RUNTIME_SMOKE_OUTCOME !== "success" && !( + process.env.RUNTIME_SMOKE_OUTCOME === "failure" && + process.env.KNOWN_PLAY_EXCEPTION_OUTCOME === "success" + )) + )) { + core.setFailed("Required runtime smoke and authenticated cleanup must both execute successfully, unless the exact canonical PLAY transition exception is attested."); + } else if (required === "true" && process.env.RUNTIME_SMOKE_OUTCOME === "failure") { + core.warning("CI passed under the canonical PLAY transition exception. Runtime qualification and image publication remain blocked."); + } + + pr-controller-smoke: + name: PR Hosted Identity Controller Smoke + needs: [image-meta] + if: ${{ ((github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || github.event_name == 'repository_dispatch') && needs.image-meta.outputs.controller_smoke_required == 'true' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + # PR-controlled source receives no registry or repository write credential. + contents: read + env: + BASE_IMAGE: ${{ needs.image-meta.outputs.base_image }} + CONTROLLER_IMAGE: firemud-hosted-identity-controller-local:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Checkout PR merge + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up Java + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: true + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Build exact local runtime base image + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: docker/base.Dockerfile + push: false + load: true + tags: ${{ env.BASE_IMAGE }} + cache-from: type=gha,scope=pr-controller-smoke + cache-to: type=gha,mode=max,scope=pr-controller-smoke + + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + + - name: Build controller image for credential-free local validation + run: | + set -euo pipefail + bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh \ + --runner ./gradlew -- :hosted-environment-identity-controller:bootJar + docker build \ + --file services/hosted-environment-identity-controller/Dockerfile \ + --build-arg BASE_IMAGE="$BASE_IMAGE" \ + --tag "$CONTROLLER_IMAGE" \ + services/hosted-environment-identity-controller/build/libs + + - name: Smoke controller image entrypoint and paused health + run: | + set -euo pipefail + bash ./dev-tools/hosted/controller/smoke-paused-controller-image.sh "$CONTROLLER_IMAGE" >/dev/null + + dispatch-pr-runtime-publication: + name: Dispatch Trusted PR Runtime Publication + needs: [image-meta, pr-local-smoke, pr-controller-smoke] + if: ${{ always() && !cancelled() && github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && needs.image-meta.result == 'success' && needs.pr-local-smoke.result == 'success' && needs.pr-local-smoke.outputs.publishable == 'true' && (needs.pr-controller-smoke.result == 'success' || (needs.image-meta.outputs.controller_smoke_required == 'false' && needs.pr-controller-smoke.result == 'skipped')) }} + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + # This trusted no-checkout job only sends an exact source-run handoff. + contents: write + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Dispatch exact runtime publication source + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + await github.rest.repos.createDispatchEvent({ + ...context.repo, + event_type: "pr-runtime-image-publication", + client_payload: { source_run_id: String(context.runId) }, + }); + + smoke-full: + name: Published Runtime Full-Stack Smoke + needs: [image-meta, build-runtime-images] + if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.build-runtime-images.result == 'success' }} + permissions: + # The trusted branch smoke workflow only pulls the staged candidate images. + contents: read + packages: read + uses: ./.github/workflows/smoke-full.yml + with: + action: full + head_sha: ${{ needs.image-meta.outputs.head_sha }} + checkout_ref: ${{ needs.image-meta.outputs.checkout_ref }} + image_tag: ${{ needs.image-meta.outputs.candidate_tag }} + secrets: inherit + + publish-runtime-images: + name: Promote Smoke-Tested Runtime Images + needs: [image-meta, build-runtime-images, smoke-full] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.build-runtime-images.result == 'success' && needs.smoke-full.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + packages: write + env: + HEAD_SHA: ${{ needs.image-meta.outputs.head_sha }} + HEAD_BRANCH: ${{ needs.image-meta.outputs.head_branch }} + CANDIDATE_TAG: ${{ needs.image-meta.outputs.candidate_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Checkout trusted publication source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up canonical GitHub CLI + uses: ./.github/actions/setup-gh + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Promote smoke-tested service digests + env: + GH_TOKEN: ${{ github.token }} + GHCR_USERNAME: ${{ github.actor }} + GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + + services=( + account-service + automation-scripting-service + entity-management-service + game-design-service + game-logic-service + game-session-service + logging-admin-service + social-groups-service + spring-cloud-gateway + tcp-proxy-service + world-management-service + ) + + declare -A registry_tokens=() + registry_manifest_state() { + local image="$1" + local image_path="${image#ghcr.io/}" + local repository_path="${image_path%:*}" + local tag="${image_path##*:}" + local manifest_url="https://ghcr.io/v2/${repository_path}/manifests/${tag}" + local registry_token="${registry_tokens[$repository_path]:-}" + local status + + [[ -n "${GHCR_USERNAME:-}" && -n "${GHCR_TOKEN:-}" ]] || { + echo "GHCR credentials are unavailable for authenticated manifest preflight: $image" >&2 + return 1 + } + if [[ -z "$registry_token" ]]; then + if ! registry_token="$(curl --silent --show-error --location --fail \ + --connect-timeout 10 --max-time 30 \ + --user "${GHCR_USERNAME}:${GHCR_TOKEN}" \ + --get \ + --data-urlencode 'service=ghcr.io' \ + --data-urlencode "scope=repository:${repository_path}:pull" \ + --header 'Accept: application/json' \ + 'https://ghcr.io/token' | jq -er '.token // .access_token // empty')"; then + echo "GHCR bearer-token exchange failed for $image; refusing to infer absence." >&2 + return 1 + fi + registry_tokens["$repository_path"]="$registry_token" + fi + # `docker manifest inspect "$image"` conflates a 404 with auth, + # registry, and network failures, so it is never an absence check. + if ! status="$(curl --silent --show-error --location --head \ + --connect-timeout 10 --max-time 30 \ + --header "Authorization: Bearer ${registry_token}" \ + --header 'Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json' \ + --output /dev/null --write-out '%{http_code}' "$manifest_url")"; then + echo "Authenticated OCI manifest HEAD failed for $image; refusing to infer absence." >&2 + return 1 + fi + case "$status" in + 200) printf 'existing\n' ;; + 404) printf 'missing\n' ;; + *) + echo "Authenticated OCI manifest HEAD returned HTTP ${status} for $image; refusing to push." >&2 + return 1 + ;; + esac + } + + registry_digest() { + local image="$1" + local inspect_output inspect_status + local digest + if inspect_output="$(docker buildx imagetools inspect "$image")"; then + : + else + inspect_status=$? + echo "Unable to inspect exact registry digest for $image (imagetools exit $inspect_status); refusing to publish." >&2 + return "$inspect_status" + fi + digest="$(awk '$1 == "Digest:" && $2 ~ /^sha256:[0-9a-f]{64}$/ { print $2; exit }' <<<"$inspect_output")" + [[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]] || { + echo "Registry manifest for $image has no exact digest." >&2 + return 1 + } + printf '%s\n' "$digest" + } + + assert_current_branch_head() { + local current_sha + current_sha="$(gh api \ + "repos/${GITHUB_REPOSITORY}/git/ref/heads/${HEAD_BRANCH}" \ + --jq '.object.sha')" + [[ "$current_sha" == "$HEAD_SHA" ]] || { + echo "Refusing canonical runtime publication: ${HEAD_BRANCH} moved from ${HEAD_SHA} to ${current_sha}." >&2 + exit 1 + } + } + + promote_alias() { + local source="$1" target="$2" fixed="$3" + local source_digest existing_digest target_digest + source_digest="$(registry_digest "$source")" + local target_state + if ! target_state="$(registry_manifest_state "$target")"; then + echo "Immutable target preflight failed for $target; refusing to publish." >&2 + exit 1 + fi + if [[ "$target_state" == missing ]]; then + docker buildx imagetools create --tag "$target" "$source" + else + existing_digest="$(registry_digest "$target")" + if [[ "$fixed" == true && "$existing_digest" != "$source_digest" ]]; then + echo "Refusing to overwrite fixed runtime tag $target: existing digest $existing_digest differs from candidate $source_digest." >&2 + exit 1 + fi + if [[ "$existing_digest" != "$source_digest" ]]; then + docker buildx imagetools create --tag "$target" "$source" + fi + fi + target_digest="$(registry_digest "$target")" + [[ "$target_digest" == "$source_digest" ]] || { + echo "Promoted runtime tag $target does not match candidate digest $source_digest (got $target_digest)." >&2 + exit 1 + } + } + + for service in "${services[@]}"; do + candidate="ghcr.io/benhook1013/${service}:${CANDIDATE_TAG}" + sha_tag="ghcr.io/benhook1013/${service}:${HEAD_SHA}" + branch_tag="ghcr.io/benhook1013/${service}:${HEAD_BRANCH}" + + assert_current_branch_head + promote_alias "$candidate" "$sha_tag" true + assert_current_branch_head + promote_alias "$candidate" "$branch_tag" false + if [[ "$HEAD_BRANCH" == develop ]]; then + assert_current_branch_head + promote_alias "$candidate" "ghcr.io/benhook1013/${service}:latest" false + fi + done diff --git a/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/3f19ad85ad2fa867b978ec009b078eb950ae1b97.yml b/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/3f19ad85ad2fa867b978ec009b078eb950ae1b97.yml new file mode 100644 index 0000000000..7e61a9fe8c --- /dev/null +++ b/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/3f19ad85ad2fa867b978ec009b078eb950ae1b97.yml @@ -0,0 +1,2149 @@ +name: Build Runtime Images + +on: + pull_request: + types: [opened, synchronize, reopened, edited] + paths: + - 'build.gradle.kts' + - 'settings.gradle.kts' + - 'gradle.properties' + - 'gradlew' + - 'gradlew.bat' + - 'buildSrc/**' + - 'gradle/**' + - 'protos/**' + - 'docker/**' + - '.dockerignore' + - '.github/workflows/runtime-images.yml' + - '.github/workflows/publish-pr-runtime-images.yml' + - '.github/workflows/smoke.yml' + - '.github/workflows/smoke-full.yml' + - 'services/**' + - '.github/actions/load-workflow-tool-versions/**' + - '.github/actions/setup-python/**' + - '.python-version' + - 'config/workflow-tool-versions.env' + - 'config/python/smoke-requirements.txt' + - 'config/python/smoke-requirements.in' + - 'dev-tools/build-compose-service-jars.sh' + - 'dev-tools/validation/run-gradle-with-dependency-recovery.sh' + - 'dev-tools/validation/run-locked-gradle.sh' + - 'dev-tools/validation/gradle-run-supervisor.py' + - 'dev-tools/build-local-smoke-images.sh' + - 'dev-tools/backups/verify-backups.sh' + - 'dev-tools/backups/pg-dump-s3-selection.shlib' + - 'dev-tools/backups/smoke-backup-verifier-image.sh' + - 'docker/backup-verifier.Dockerfile' + - 'dev-tools/certs/generate-dev-certs.sh' + - 'dev-tools/minio/**' + - 'dev-tools/hosted/controller/smoke-paused-controller-image.sh' + - 'dev-tools/smoke/**' + - 'dev-tools/verify-compose-health.sh' + - 'dev-tools/verify-fresh-bootstrap.sh' + - 'dev-tools/verify-restart-state.sh' + - 'dev-tools/verify-smoke-images.sh' + workflow_run: + workflows: ["CI — Validation"] + types: [completed] + repository_dispatch: + types: [pr-runtime-base-refresh] + workflow_dispatch: + +run-name: Build Runtime Images ${{ (github.event_name == 'pull_request' || github.event_name == 'repository_dispatch') && format('secure-pr-artifact pr-{0} base-{1} head-{2} merge-{3} mode-{4}', github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number, github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.client_payload.base_sha, github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.event.client_payload.head_sha, github.event_name == 'pull_request' && github.sha || github.event.client_payload.merge_sha, github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required') || github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success' && format('trusted-branch branch-{0} sha-{1}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha) || github.event_name == 'workflow_run' && format('base-refresh-only branch-{0} sha-{1} ci-{2}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha, github.event.workflow_run.conclusion) || github.ref_name }} + +permissions: + contents: read + +concurrency: + group: runtime-images-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha, github.sha)) || (github.event_name == 'repository_dispatch' && github.event.client_payload.pr_number != '' && github.event.client_payload.base_sha != '' && github.event.client_payload.head_sha != '' && github.event.client_payload.merge_sha != '' && format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.client_payload.pr_number, github.event.client_payload.base_sha, github.event.client_payload.head_sha, github.event.client_payload.merge_sha)) || (github.event_name == 'repository_dispatch' && format('repository-dispatch-run-{0}', github.run_id)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && format('ci-pr-run-{0}-attempt-{1}', github.event.workflow_run.id, github.event.workflow_run.run_attempt)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && format('branch-{0}', github.event.workflow_run.head_branch)) || github.ref }}-${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required' }} + cancel-in-progress: true + +jobs: + image-meta: + name: Derive Runtime Image Metadata + if: ${{ (github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || (github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh') || github.event_name == 'workflow_dispatch' || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && github.event.workflow_run.conclusion == 'success' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop')) }} + runs-on: ubuntu-latest + outputs: + pr_number: ${{ steps.meta.outputs.pr_number }} + base_ref: ${{ steps.meta.outputs.base_ref }} + base_sha: ${{ steps.meta.outputs.base_sha }} + head_sha: ${{ steps.meta.outputs.head_sha }} + merge_sha: ${{ steps.meta.outputs.merge_sha }} + head_branch: ${{ steps.meta.outputs.head_branch }} + checkout_ref: ${{ steps.meta.outputs.checkout_ref }} + image_tag: ${{ steps.meta.outputs.image_tag }} + candidate_tag: ${{ steps.meta.outputs.candidate_tag }} + base_image: ${{ steps.meta.outputs.base_image }} + canonical_play_transition: ${{ steps.meta.outputs.canonical_play_transition }} + runtime_smoke_required: ${{ steps.smoke_scope.outputs.runtime_smoke_required }} + controller_smoke_required: ${{ steps.smoke_scope.outputs.controller_smoke_required }} + permissions: + actions: read + contents: read + pull-requests: read + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Check out trusted workflow helpers + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - name: Set up canonical GitHub CLI + uses: ./.github/actions/setup-gh + + - name: Set up canonical Python + uses: ./.github/actions/setup-python + + - name: Derive image tags + id: meta + env: + GH_TOKEN: ${{ github.token }} + EVENT_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.client_payload.head_sha || '' }} + EVENT_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch || '' }} + EVENT_PR_NUMBER: ${{ github.event.pull_request.number || github.event.client_payload.pr_number || '' }} + EVENT_BASE_REF: ${{ github.event.pull_request.base.ref || github.event.client_payload.base_ref || '' }} + EVENT_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.client_payload.base_sha || '' }} + EVENT_MERGE_SHA: ${{ github.event.client_payload.merge_sha || '' }} + EVENT_ACTION: ${{ github.event.action || '' }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + run: | + set -euo pipefail + EVENT_NAME="${{ github.event_name }}" + PR_NUMBER="" + BASE_REF="" + BASE_SHA="" + MERGE_SHA="" + CANONICAL_PLAY_TRANSITION=false + if [ "$EVENT_NAME" = "pull_request" ]; then + PR_NUMBER="$EVENT_PR_NUMBER" + BASE_REF="$EVENT_BASE_REF" + BASE_SHA="$EVENT_BASE_SHA" + HEAD_SHA="$EVENT_HEAD_SHA" + HEAD_BRANCH="" + MERGE_SHA="${GITHUB_SHA}" + CHECKOUT_REF="$MERGE_SHA" + [[ "$MERGE_SHA" =~ ^[0-9a-f]{40}$ ]] || { + echo "PR merge SHA is not a lowercase 40-character commit SHA." >&2 + exit 1 + } + [[ "$BASE_SHA" =~ ^[0-9a-f]{40}$ && "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]] || { + echo "PR event base/head SHAs are not lowercase 40-character commit SHAs." >&2 + exit 1 + } + merge_commit_json="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${MERGE_SHA}")" + jq -e \ + --arg base_sha "$BASE_SHA" \ + --arg head_sha "$HEAD_SHA" \ + --arg merge_sha "$MERGE_SHA" \ + '.sha == $merge_sha and (.parents | type) == "array" and (.parents | length) == 2 and .parents[0].sha == $base_sha and .parents[1].sha == $head_sha' \ + <<<"$merge_commit_json" >/dev/null || { + echo "PR event merge commit does not have the event's exact base/head parents; refusing a stale PR artifact." >&2 + exit 1 + } + elif [ "$EVENT_NAME" = "repository_dispatch" ]; then + [[ "$EVENT_ACTION" == "pr-runtime-base-refresh" ]] || { + echo "Runtime PR refresh requires the typed pr-runtime-base-refresh dispatch." >&2 + exit 1 + } + [[ "$GITHUB_REF" == "refs/heads/${DEFAULT_BRANCH}" ]] || { + echo "Runtime PR refresh must run from the repository default branch." >&2 + exit 1 + } + PR_NUMBER="$EVENT_PR_NUMBER" + BASE_REF="$EVENT_BASE_REF" + BASE_SHA="$EVENT_BASE_SHA" + MERGE_SHA="$EVENT_MERGE_SHA" + HEAD_SHA="$EVENT_HEAD_SHA" + HEAD_BRANCH="" + CHECKOUT_REF="$MERGE_SHA" + [[ "$PR_NUMBER" =~ ^[1-9][0-9]{0,50}$ ]] || { + echo "Runtime PR refresh payload has an invalid pull request number." >&2 + exit 1 + } + git check-ref-format "refs/heads/${BASE_REF}" >/dev/null || { + echo "Runtime PR refresh payload has an invalid base ref." >&2 + exit 1 + } + for sha_name in BASE_SHA HEAD_SHA MERGE_SHA; do + sha_value="${!sha_name}" + [[ "$sha_value" =~ ^[0-9a-f]{40}$ ]] || { + echo "Runtime PR refresh payload has an invalid ${sha_name}." >&2 + exit 1 + } + done + + encoded_base_ref="$(python3 -c 'import sys; from urllib.parse import quote; print(quote(sys.argv[1], safe="/"))' "$BASE_REF")" + current_base_ref_json="$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/heads/${encoded_base_ref}")" + jq -e \ + --arg base_sha "$BASE_SHA" \ + --arg base_ref "refs/heads/${BASE_REF}" \ + '.ref == $base_ref and .object.sha == $base_sha' \ + <<<"$current_base_ref_json" >/dev/null || { + echo "Runtime PR refresh base SHA is not the current ${BASE_REF} branch ref." >&2 + exit 1 + } + pull_request_json="$(gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}")" + jq -e \ + --arg repository "$GITHUB_REPOSITORY" \ + --arg base_ref "$BASE_REF" \ + --arg head_sha "$HEAD_SHA" \ + --arg merge_sha "$MERGE_SHA" \ + '( + .state == "open" and + .base.ref == $base_ref and + .base.repo.full_name == $repository and + .head.sha == $head_sha and + .head.repo.full_name == $repository and + (.mergeable | type) == "boolean" and + .mergeable == true and + (.mergeable_state | type) == "string" and + .mergeable_state != "dirty" and + .mergeable_state != "conflicting" and + .mergeable_state != "unknown" and + .merge_commit_sha == $merge_sha + )' <<<"$pull_request_json" >/dev/null || { + echo "Runtime PR refresh payload is stale, conflicted, fork-owned, closed, or has an invalid merge tuple." >&2 + exit 1 + } + merge_commit_json="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${MERGE_SHA}")" + jq -e \ + --arg base_sha "$BASE_SHA" \ + --arg head_sha "$HEAD_SHA" \ + --arg merge_sha "$MERGE_SHA" \ + '.sha == $merge_sha and (.parents | type) == "array" and (.parents | length) == 2 and .parents[0].sha == $base_sha and .parents[1].sha == $head_sha' \ + <<<"$merge_commit_json" >/dev/null || { + echo "Runtime PR refresh merge commit does not have the exact current base/head parents." >&2 + exit 1 + } + # Only the verified live same-repository PR can authorize this + # diagnostic marker; dispatch payload labels carry no authority. + if jq -e '(.labels | type) == "array" and any(.labels[]; .name == "canonical-play-transition")' \ + <<<"$pull_request_json" >/dev/null; then + CANONICAL_PLAY_TRANSITION=true + fi + elif [ "${{ github.event_name }}" = "workflow_run" ]; then + [[ "${{ github.event.workflow_run.event }}" == "push" ]] || { + echo "Runtime branch publication requires a CI push workflow run." >&2 + exit 1 + } + [[ "${{ github.event.workflow_run.conclusion }}" == "success" ]] || { + echo "Runtime branch publication requires a successful CI workflow run." >&2 + exit 1 + } + HEAD_SHA="${EVENT_HEAD_SHA:-${{ github.event.workflow_run.head_sha }}}" + HEAD_BRANCH="$EVENT_HEAD_BRANCH" + CHECKOUT_REF="$HEAD_SHA" + else + HEAD_SHA="${GITHUB_SHA}" + CHECKOUT_REF="${GITHUB_SHA}" + HEAD_BRANCH="${GITHUB_REF_NAME}" + fi + + [[ "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]] || { + echo "Runtime publication head SHA is not a lowercase 40-character commit SHA." >&2 + exit 1 + } + if [ "$EVENT_NAME" != "pull_request" ] && [ "$EVENT_NAME" != "repository_dispatch" ]; then + [[ "$HEAD_BRANCH" == main || "$HEAD_BRANCH" == develop ]] || { + echo "Runtime branch publication is restricted to main or develop." >&2 + exit 1 + } + fi + + if [ "$EVENT_NAME" = "pull_request" ] || [ "$EVENT_NAME" = "repository_dispatch" ]; then + IMAGE_TAG="pr-merge-${MERGE_SHA}" + else + IMAGE_TAG="${HEAD_SHA}" + fi + CANDIDATE_TAG="candidate-${HEAD_SHA}-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + if [ "$EVENT_NAME" = "pull_request" ] || [ "$EVENT_NAME" = "repository_dispatch" ]; then + BASE_IMAGE="ghcr.io/benhook1013/firemud-base:${MERGE_SHA}" + else + BASE_IMAGE="ghcr.io/benhook1013/firemud-base:${CANDIDATE_TAG}" + fi + + { + echo "pr_number=${PR_NUMBER}" + echo "base_ref=${BASE_REF}" + echo "base_sha=${BASE_SHA}" + echo "head_sha=${HEAD_SHA}" + echo "merge_sha=${MERGE_SHA}" + echo "head_branch=${HEAD_BRANCH}" + echo "checkout_ref=${CHECKOUT_REF}" + echo "image_tag=${IMAGE_TAG}" + echo "candidate_tag=${CANDIDATE_TAG}" + echo "base_image=${BASE_IMAGE}" + echo "canonical_play_transition=${CANONICAL_PLAY_TRANSITION}" + } >> "$GITHUB_OUTPUT" + + - name: Verify successful CI push for manual publication + if: ${{ github.event_name == 'workflow_dispatch' }} + env: + GH_TOKEN: ${{ github.token }} + EXPECTED_SHA: ${{ steps.meta.outputs.head_sha }} + EXPECTED_BRANCH: ${{ steps.meta.outputs.head_branch }} + run: | + set -euo pipefail + ci_runs="$(gh api --paginate --slurp \ + "repos/${GITHUB_REPOSITORY}/actions/workflows/ci.yml/runs?event=push&head_sha=${EXPECTED_SHA}&per_page=100")" + jq -e \ + --arg expected_sha "$EXPECTED_SHA" \ + --arg expected_branch "$EXPECTED_BRANCH" \ + '[.[].workflow_runs[]?] | any(.[]; .head_sha == $expected_sha and .head_branch == $expected_branch and .event == "push" and .status == "completed" and .conclusion == "success")' \ + <<<"$ci_runs" >/dev/null || { + echo "No successful CI push run exists for manual runtime publication ${EXPECTED_BRANCH}@${EXPECTED_SHA}." >&2 + exit 1 + } + + - name: Detect PR smoke scopes + id: smoke_scope + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + let runtimeSmokeRequired = true; + let controllerSmokeRequired = true; + if (context.eventName === "pull_request" || context.eventName === "repository_dispatch") { + try { + const pullNumber = context.eventName === "pull_request" + ? context.payload.pull_request.number + : context.payload.client_payload.pr_number; + const changedFiles = await github.paginate( + github.rest.pulls.listFiles, + { + ...context.repo, + pull_number: pullNumber, + per_page: 100, + }, + (response) => response.data + ); + const expectedFileCount = context.eventName === "pull_request" + ? context.payload.pull_request.changed_files + : (await github.rest.pulls.get({ + ...context.repo, + pull_number: pullNumber, + })).data.changed_files; + const validFileEntries = changedFiles.every((file) => + file && + typeof file.filename === "string" && + file.filename.length > 0 && + (file.previous_filename === undefined || + (typeof file.previous_filename === "string" && file.previous_filename.length > 0)) + ); + if (!Number.isInteger(expectedFileCount) || changedFiles.length !== expectedFileCount || !validFileEntries) { + core.warning("PR smoke scope detection was incomplete; running both local smokes."); + } else { + const paths = changedFiles.flatMap((file) => + [file.filename, file.previous_filename].filter(Boolean) + ); + const runtimePrefixes = [ + "buildSrc/", + "docker/", + "dev-tools/minio/", + "dev-tools/smoke/", + "gradle/", + "protos/", + ".github/actions/load-workflow-tool-versions/", + ".github/actions/setup-python/", + ]; + const workflowToolAuthorityPath = "config/workflow-tool-versions.env"; + const runtimeFiles = new Set([ + ".dockerignore", + ".github/workflows/publish-pr-runtime-images.yml", + ".github/workflows/runtime-images.yml", + ".github/workflows/smoke-full.yml", + ".github/workflows/smoke.yml", + ".github/actions/load-workflow-tool-versions/action.yml", + ".python-version", + "build.gradle.kts", + "config/python/smoke-requirements.txt", + "config/python/smoke-requirements.in", + "dev-tools/build-compose-service-jars.sh", + "dev-tools/validation/run-gradle-with-dependency-recovery.sh", + "dev-tools/validation/run-locked-gradle.sh", + "dev-tools/validation/gradle-run-supervisor.py", + "dev-tools/build-local-smoke-images.sh", + "dev-tools/backups/verify-backups.sh", + "dev-tools/backups/pg-dump-s3-selection.shlib", + "dev-tools/backups/smoke-backup-verifier-image.sh", + "dev-tools/certs/generate-dev-certs.sh", + "dev-tools/verify-compose-health.sh", + "dev-tools/verify-fresh-bootstrap.sh", + "dev-tools/verify-restart-state.sh", + "dev-tools/verify-smoke-images.sh", + "gradle.properties", + "docker/backup-verifier.Dockerfile", + "gradlew", + "gradlew.bat", + "settings.gradle.kts", + ]); + const controllerPrefixes = [ + "buildSrc/", + "gradle/", + "services/hosted-environment-identity-controller/", + ]; + const controllerFiles = new Set([ + ".dockerignore", + ".github/workflows/runtime-images.yml", + "build.gradle.kts", + "dev-tools/hosted/controller/smoke-paused-controller-image.sh", + "docker/base.Dockerfile", + "gradle.properties", + "gradlew", + "gradlew.bat", + "settings.gradle.kts", + ]); + const authorityChanged = paths.includes(workflowToolAuthorityPath); + const nonAuthorityPaths = paths.filter( + (path) => path !== workflowToolAuthorityPath + ); + runtimeSmokeRequired = nonAuthorityPaths.some( + (path) => + runtimeFiles.has(path) || + runtimePrefixes.some((prefix) => path.startsWith(prefix)) || + (path.startsWith("services/") && + !path.startsWith( + "services/hosted-environment-identity-controller/" + )) + ); + runtimeSmokeRequired = runtimeSmokeRequired || authorityChanged; + controllerSmokeRequired = paths.some( + (path) => + controllerFiles.has(path) || + controllerPrefixes.some((prefix) => path.startsWith(prefix)) + ); + } + } catch (error) { + core.warning( + `PR smoke scope detection failed; running both local smokes: ${error.message}` + ); + } + } + core.setOutput("runtime_smoke_required", String(runtimeSmokeRequired)); + core.setOutput("controller_smoke_required", String(controllerSmokeRequired)); + + dispatch-pr-base-refreshes: + name: Dispatch PR Base Refreshes + if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.status == 'completed' && (github.event.workflow_run.event == 'pull_request' || (github.event.workflow_run.event == 'push' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop'))) && github.event.workflow_run.head_repository.full_name == github.repository }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + actions: read + contents: write + pull-requests: read + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Dispatch exact PR runtime refreshes and preview reconciles + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + const workflowRun = context.payload.workflow_run; + const refreshBranch = workflowRun.head_branch; + const refreshSha = workflowRun.head_sha; + const shaPattern = /^[0-9a-f]{40}$/; + const runtimePrefixes = [ + "buildSrc/", + "docker/", + "dev-tools/minio/", + "dev-tools/smoke/", + "gradle/", + "protos/", + ".github/actions/load-workflow-tool-versions/", + ".github/actions/setup-python/", + ]; + const runtimeFiles = new Set([ + ".dockerignore", + ".github/workflows/publish-pr-runtime-images.yml", + ".github/workflows/runtime-images.yml", + ".github/workflows/smoke-full.yml", + ".github/workflows/smoke.yml", + ".github/actions/load-workflow-tool-versions/action.yml", + ".python-version", + "build.gradle.kts", + "config/workflow-tool-versions.env", + "config/python/smoke-requirements.txt", + "config/python/smoke-requirements.in", + "dev-tools/build-compose-service-jars.sh", + "dev-tools/validation/run-gradle-with-dependency-recovery.sh", + "dev-tools/validation/run-locked-gradle.sh", + "dev-tools/validation/gradle-run-supervisor.py", + "dev-tools/build-local-smoke-images.sh", + "dev-tools/backups/verify-backups.sh", + "dev-tools/backups/pg-dump-s3-selection.shlib", + "dev-tools/backups/smoke-backup-verifier-image.sh", + "dev-tools/certs/generate-dev-certs.sh", + "dev-tools/hosted/controller/smoke-paused-controller-image.sh", + "dev-tools/verify-compose-health.sh", + "dev-tools/verify-fresh-bootstrap.sh", + "dev-tools/verify-restart-state.sh", + "dev-tools/verify-smoke-images.sh", + "gradle.properties", + "gradlew", + "gradlew.bat", + "settings.gradle.kts", + ]); + const runtimeRunEvents = ["pull_request", "repository_dispatch"]; + const runtimeRunPageSize = 100; + const runtimeRunLookbackMilliseconds = 7 * 24 * 60 * 60 * 1000; + + const waitForMergeRefresh = async () => { + await new Promise((resolve) => setTimeout(resolve, 2000)); + }; + + const hasRuntimeChange = async (pullRequest) => { + const files = await github.paginate( + github.rest.pulls.listFiles, + { + ...context.repo, + pull_number: pullRequest.number, + per_page: 100, + }, + (response) => response.data + ); + const expectedFileCount = pullRequest.changed_files; + const validFileEntries = Number.isInteger(expectedFileCount) && + files.length === expectedFileCount && + files.every((file) => + file && + typeof file.filename === "string" && + file.filename.length > 0 && + (file.previous_filename === undefined || + (typeof file.previous_filename === "string" && file.previous_filename.length > 0)) + ); + if (!validFileEntries) { + core.warning(`PR #${pullRequest.number} changed-file metadata was incomplete; refreshing its runtime images.`); + return true; + } + return files.flatMap((file) => [file.filename, file.previous_filename].filter(Boolean)).some((path) => + runtimeFiles.has(path) || + runtimePrefixes.some((prefix) => path.startsWith(prefix)) || + path.startsWith("services/") + ); + }; + + const dependencyBotAuthors = new Set([ + "app/dependabot", + "dependabot[bot]", + "app/renovate", + "renovate[bot]", + ]); + + const isPreviewEligible = (pullRequest) => { + const labels = pullRequest.labels; + return typeof pullRequest.user?.login === "string" && + pullRequest.user.login.length > 0 && + !dependencyBotAuthors.has(pullRequest.user.login) && + Array.isArray(labels) && + labels.every((label) => label && typeof label.name === "string") && + (["main", "develop"].includes(pullRequest.base?.ref) || + labels.some((label) => label.name === "preview:priority")); + }; + + const resolveExactMerge = async (number, baseBranch = refreshBranch, baseSha = refreshSha, expectedHeadSha = null) => { + for (let attempt = 1; attempt <= 5; attempt += 1) { + const response = await github.rest.pulls.get({ + ...context.repo, + pull_number: number, + }); + const pullRequest = response.data; + const currentHeadSha = pullRequest.head?.sha; + const currentBaseRef = pullRequest.base?.ref; + const headRepository = pullRequest.head?.repo?.full_name; + const baseRepository = pullRequest.base?.repo?.full_name; + if (pullRequest.state !== "open" || + headRepository !== context.payload.repository.full_name || + baseRepository !== context.payload.repository.full_name || + currentBaseRef !== baseBranch || + !shaPattern.test(currentHeadSha || "") || + (expectedHeadSha !== null && currentHeadSha !== expectedHeadSha)) { + return null; + } + + const mergeableState = typeof pullRequest.mergeable_state === "string" + ? pullRequest.mergeable_state + : pullRequest.mergeable_state === null ? "unknown" : "invalid"; + if (pullRequest.mergeable === false || + mergeableState === "dirty" || + mergeableState === "conflicting") { + core.warning(`Skipping PR #${number}: GitHub reports a merge conflict.`); + return null; + } + if (pullRequest.mergeable === null || mergeableState === "unknown") { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: GitHub did not produce a ready merge tuple.`); + return null; + } + if (pullRequest.mergeable !== true || mergeableState === "invalid") { + core.warning(`Skipping PR #${number}: GitHub returned invalid merge metadata.`); + return null; + } + + const mergeSha = pullRequest.merge_commit_sha; + if (!shaPattern.test(mergeSha || "")) { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: merge SHA is null or invalid.`); + return null; + } + + try { + const commit = await github.rest.repos.getCommit({ + ...context.repo, + ref: mergeSha, + }); + const parents = commit.data.parents?.map((parent) => parent.sha) || []; + if (commit.data.sha !== mergeSha || + parents.length !== 2 || + parents[0] !== baseSha || + parents[1] !== currentHeadSha) { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: merge commit parents do not match the current base/head.`); + return null; + } + } catch (error) { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: exact merge commit could not be read (${error.message}).`); + return null; + } + + return { + tuple: { + prNumber: String(number), + baseRef: baseBranch, + baseSha, + headSha: currentHeadSha, + mergeSha, + }, + pullRequest, + }; + } + return null; + }; + + const loadExistingRuntimeRuns = async () => { + const readInventory = async (createdSince) => { + const inventory = []; + let complete = true; + let incompleteReason = null; + for (const event of runtimeRunEvents) { + const response = await github.rest.actions.listWorkflowRuns({ + ...context.repo, + workflow_id: "runtime-images.yml", + event, + created: `${createdSince}..*`, + per_page: runtimeRunPageSize, + page: 1, + }); + const payload = response?.data; + if (!payload || !Number.isInteger(payload.total_count) || + payload.total_count < 0 || !Array.isArray(payload.workflow_runs)) { + throw new Error(`runtime-images ${event} recent run inventory is malformed`); + } + if (payload.total_count > runtimeRunPageSize) { + complete = false; + incompleteReason ??= `runtime-images ${event} has more than ${runtimeRunPageSize} runs since ${createdSince}`; + } + const expectedPageLength = Math.min(payload.total_count, runtimeRunPageSize); + if (payload.workflow_runs.length !== expectedPageLength) { + throw new Error(`runtime-images ${event} recent run inventory is incomplete`); + } + inventory.push(...payload.workflow_runs); + } + return {complete, runs: inventory, reason: incompleteReason}; + }; + + const createdSince = new Date(Date.now() - runtimeRunLookbackMilliseconds).toISOString(); + const initial = await readInventory(createdSince); + if (initial.complete) { + return initial; + } + + const inFlightStatuses = ["queued", "waiting", "requested", "pending", "in_progress"]; + const inFlightRuns = initial.runs.filter((run) => inFlightStatuses.includes(run?.status)); + if (inFlightRuns.length === 0) { + return initial; + } + + const validTimestamp = (value) => typeof value === "string" && + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(value) && + Number.isFinite(Date.parse(value)); + if (inFlightRuns.some((run) => !runtimeRunEvents.includes(run.event) || + !Number.isSafeInteger(run.id) || run.id <= 0 || !validTimestamp(run.created_at))) { + return { + ...initial, + reason: "truncated recent inventory contains an in-flight run without a valid event, id, or creation timestamp", + }; + } + + const refinementSince = inFlightRuns + .map((run) => run.created_at) + .sort()[0]; + // The inclusive created lower bound makes the refined pages a complete candidate set without relying on API ordering. + const refined = await readInventory(refinementSince); + if (!refined.complete) { + return { + ...refined, + reason: refined.reason || "refined runtime run inventory is incomplete", + }; + } + const refinedIds = new Set(refined.runs.map((run) => `${run?.event}:${run?.id}`)); + if (inFlightRuns.some((run) => !refinedIds.has(`${run.event}:${run.id}`))) { + return { + ...refined, + complete: false, + reason: "refined inventory did not retain every initially observed in-flight run", + }; + } + return refined; + }; + + const findExactExistingProducer = (tuple, inventory) => { + const expectedWorkflowPath = ".github/workflows/runtime-images.yml"; + const workflowPathMatches = (path) => { + if (path === expectedWorkflowPath) { + return true; + } + const prefix = `${expectedWorkflowPath}@`; + if (typeof path !== "string" || !path.startsWith(prefix)) { + return false; + } + const ref = path.slice(prefix.length); + if (ref.length === 0 || ref === "@" || ref.endsWith(".") || + /[\u0000-\u0020\u007f]/.test(ref) || + ["~", "^", ":", "?", "*", "[", "\\"].some((character) => ref.includes(character)) || + ref.includes("..") || ref.includes("@{")) { + return false; + } + return ref.split("/").every((part) => + part.length > 0 && part !== "." && part !== ".." && + !part.startsWith(".") && + !part.endsWith(".lock") + ); + }; + const expectedTitle = + `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} ` + + `base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; + const matching = inventory.runs.filter((run) => + run?.display_title === expectedTitle + ); + const ordered = []; + const matchingIds = new Set(); + for (const run of matching) { + if (!runtimeRunEvents.includes(run.event) || + !Number.isSafeInteger(run.id) || run.id <= 0 || matchingIds.has(run.id) || + typeof run.created_at !== "string" || + !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(run.created_at) || + !Number.isFinite(Date.parse(run.created_at)) || + !workflowPathMatches(run.path) || + !["Build Runtime Images", expectedTitle].includes(run.name) || + run.repository?.full_name !== context.payload.repository.full_name || + run.head_repository?.full_name !== context.payload.repository.full_name) { + throw new Error(`run ${run.id} has the exact tuple title but invalid workflow or repository identity`); + } + matchingIds.add(run.id); + ordered.push(run); + if (run.event === "pull_request") { + if (run.head_sha !== tuple.headSha) { + throw new Error(`run ${run.id} has the exact tuple title but a different PR head SHA`); + } + const pullRequests = run.pull_requests; + if (!Array.isArray(pullRequests) || (pullRequests.length > 0 && !pullRequests.some((pullRequest) => + String(pullRequest?.number) === tuple.prNumber && + pullRequest?.head?.sha === tuple.headSha + ))) { + throw new Error(`run ${run.id} has incomplete or conflicting PR association evidence`); + } + } + } + ordered.sort((left, right) => right.created_at.localeCompare(left.created_at)); + if (ordered.length > 1 && ordered[0].created_at === ordered[1].created_at) { + throw new Error("newest exact runtime producer has an ambiguous created_at timestamp"); + } + const newest = ordered[0]; + if (!newest) { + return []; + } + if (["queued", "waiting", "requested", "pending", "in_progress"].includes(newest.status)) { + if (newest.conclusion !== null && newest.conclusion !== undefined) { + throw new Error(`run ${newest.id} has a conclusion while still ${newest.status}`); + } + return [newest]; + } + if (newest.status === "completed") { + // Completed source success does not prove publication remains usable; preserve recovery dispatch. + return []; + } + throw new Error(`run ${newest.id} has an unknown status and cannot be classified`); + }; + + if (!shaPattern.test(refreshSha) || typeof refreshBranch !== "string" || + refreshBranch.length === 0) { + core.setFailed("Completed CI callback did not identify a branch and lowercase SHA."); + return; + } + let sourcePrNumber = null; + if (workflowRun.event === "pull_request") { + // Completion is a reconcile signal only for a substantive CI attempt. + // Metadata edits also complete CI, but must never reconstruct runtime. + const positiveInteger = (value) => Number.isSafeInteger(value) && value > 0; + const ciPath = ".github/workflows/ci.yml"; + const ciName = "CI — Validation"; + const titleMatch = /^CI — Validation pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40})$/.exec(workflowRun.display_title || ""); + const matchesSource = (run) => + positiveInteger(workflowRun.id) && positiveInteger(workflowRun.run_attempt) && + positiveInteger(workflowRun.workflow_id) && + run.id === workflowRun.id && run.run_attempt === workflowRun.run_attempt && + run.workflow_id === workflowRun.workflow_id && run.event === "pull_request" && + run.status === "completed" && typeof run.conclusion === "string" && run.conclusion.length > 0 && + run.repository?.full_name === context.payload.repository.full_name && + run.head_repository?.full_name === context.payload.repository.full_name && + run.head_branch === refreshBranch && run.head_sha === refreshSha && + run.display_title === workflowRun.display_title && + [ciName, workflowRun.display_title].includes(run.name) && + (run.path === ciPath || (typeof run.path === "string" && + run.path.startsWith(`${ciPath}@`) && run.path.length > ciPath.length + 1)); + if (!titleMatch || titleMatch[3] !== refreshSha) { + core.warning("Skipping PR runtime reconciliation: callback lacks exact CI PR/base/head title metadata."); + return; + } + const {data: ciWorkflow} = await github.rest.actions.getWorkflow({ + ...context.repo, workflow_id: "ci.yml", + }); + const {data: source} = await github.rest.actions.getWorkflowRun({ + ...context.repo, run_id: workflowRun.id, + }); + if (ciWorkflow.id !== workflowRun.workflow_id || ciWorkflow.path !== ciPath || + ciWorkflow.name !== ciName || !matchesSource(source)) { + core.warning("Skipping PR runtime reconciliation: current CI workflow/run identity differs from callback."); + return; + } + const jobs = await github.paginate( + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + {...context.repo, run_id: source.id, attempt_number: source.run_attempt, per_page: 100} + ); + const gates = jobs.filter((job) => job.name === "Validation Gate"); + const gate = gates.length === 1 ? gates[0] : null; + const preservation = gate?.steps?.filter((step) => + step.name === "Preserve successful required gate on metadata-only edit") || []; + const enforcement = gate?.steps?.filter((step) => step.name === "Enforce validation success") || []; + const checkPrefix = `https://api.github.com/repos/${context.payload.repository.full_name}/check-runs/`; + if (!gate || !positiveInteger(gate.id) || gate.run_id !== source.id || + gate.run_attempt !== source.run_attempt || gate.head_sha !== source.head_sha || + ![ciName, source.display_title].includes(gate.workflow_name) || gate.status !== "completed" || + typeof gate.check_run_url !== "string" || !gate.check_run_url.startsWith(checkPrefix) || + !/^[1-9][0-9]*$/.test(gate.check_run_url.slice(checkPrefix.length)) || + preservation.length !== 1 || preservation[0].status !== "completed" || + preservation[0].conclusion !== "skipped" || enforcement.length !== 1 || + enforcement[0].status !== "completed" || !["success", "failure"].includes(enforcement[0].conclusion)) { + core.info("Skipping PR runtime reconciliation: exact CI attempt is metadata-only or lacks substantive native gate evidence."); + return; + } + const {data: latest} = await github.rest.actions.getWorkflowRun({ + ...context.repo, run_id: source.id, + }); + if (!matchesSource(latest)) { + core.warning("Skipping PR runtime reconciliation: CI attempt was superseded during classification."); + return; + } + sourcePrNumber = titleMatch[1]; + } + let currentBranch; + try { + currentBranch = await github.rest.git.getRef({ + ...context.repo, + ref: `heads/${refreshBranch}`, + }); + } catch (error) { + if (error.status !== 404) throw error; + core.info(`Skipping obsolete CI callback: branch ${refreshBranch} no longer exists.`); + return; + } + if (currentBranch.data.object?.sha !== refreshSha) { + core.warning(`Skipping PR base refresh: ${refreshBranch} advanced beyond the completed CI callback ${refreshSha}.`); + return; + } + + // Protected push callbacks own dependent fan-out; PR callbacks for + // those heads still reconcile their own exact source PR below. + const protectedPrHead = workflowRun.event === "pull_request" && + ["main", "develop"].includes(refreshBranch); + const pullRequests = protectedPrHead ? [] : await github.paginate( + github.rest.pulls.list, + { + ...context.repo, + state: "open", + base: refreshBranch, + per_page: 100, + }, + (response) => response.data + ); + const refreshTargets = []; + for (const listedPullRequest of pullRequests) { + if (listedPullRequest.state !== "open" || + listedPullRequest.base?.ref !== refreshBranch || + listedPullRequest.head?.repo?.full_name !== context.payload.repository.full_name || + listedPullRequest.base?.repo?.full_name !== context.payload.repository.full_name) { + continue; + } + const resolved = await resolveExactMerge(listedPullRequest.number); + if (resolved) { + refreshTargets.push(resolved); + } + } + if (workflowRun.event === "pull_request") { + // A retarget/edit can carry an unusable event merge SHA. CI completion + // is only a reconcile signal: re-read its source's current exact tuple. + const sourcePullRequests = await github.paginate( + github.rest.pulls.list, + { + ...context.repo, + state: "open", + head: `${context.repo.owner}:${refreshBranch}`, + per_page: 100, + }, + (response) => response.data + ); + for (const source of sourcePullRequests) { + if (String(source.number) !== sourcePrNumber || + source.state !== "open" || source.head?.sha !== refreshSha || + source.head?.ref !== refreshBranch || + source.head?.repo?.full_name !== context.payload.repository.full_name || + source.base?.repo?.full_name !== context.payload.repository.full_name || + typeof source.base?.ref !== "string" || + source.base.ref.length === 0) { + continue; + } + const sourceBase = await github.rest.git.getRef({ + ...context.repo, + ref: `heads/${source.base.ref}`, + }); + const sourceBaseSha = sourceBase.data.object?.sha; + if (!shaPattern.test(sourceBaseSha || "")) { + core.warning(`Skipping source PR #${source.number}: current base ref SHA is invalid.`); + continue; + } + const resolved = await resolveExactMerge(source.number, source.base.ref, sourceBaseSha, refreshSha); + if (resolved && !refreshTargets.some((target) => target.tuple.prNumber === resolved.tuple.prNumber)) { + refreshTargets.push(resolved); + } + } + } + let runtimeInventoryPromise; + let runtimeInventoryError = null; + for (const resolved of refreshTargets) { + const {tuple, pullRequest} = resolved; + if (await hasRuntimeChange(pullRequest)) { + let existingProducers = []; + let fallbackReason = null; + let inventory; + if (runtimeInventoryError) { + fallbackReason = runtimeInventoryError; + } else { + try { + runtimeInventoryPromise ??= loadExistingRuntimeRuns(); + inventory = await runtimeInventoryPromise; + } catch (error) { + fallbackReason = error.message || String(error); + runtimeInventoryError = fallbackReason; + } + } + if (!fallbackReason) { + try { + existingProducers = findExactExistingProducer(tuple, inventory); + if (!inventory.complete) { + // The REST contract does not specify a sort order, so a truncated page cannot prove omitted runs are older. + existingProducers = []; + fallbackReason = inventory.reason || "recent run inventory is incomplete"; + } + } catch (error) { + fallbackReason = error.message || String(error); + } + } + if (fallbackReason) { + core.warning( + `Cannot verify recent runtime producer evidence for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}); falling back to the required refresh dispatch: ${fallbackReason}` + ); + } + if (existingProducers.length > 0) { + const producer = existingProducers[0]; + core.info( + `Skipping duplicate PR runtime refresh for #${tuple.prNumber}: exact tuple producer ${producer.id} remains ${producer.status}.` + ); + } else { + core.info(`No reusable in-flight exact producer was verified in the bounded recent inventory; dispatching required PR runtime refresh for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); + await github.rest.repos.createDispatchEvent({ + ...context.repo, + event_type: "pr-runtime-base-refresh", + client_payload: { + pr_number: tuple.prNumber, + base_ref: tuple.baseRef, + base_sha: tuple.baseSha, + head_sha: tuple.headSha, + merge_sha: tuple.mergeSha, + }, + }); + } + } else { + core.info(`Skipping PR runtime image refresh for #${tuple.prNumber}: no runtime-changing files.`); + } + if (!isPreviewEligible(pullRequest)) { + core.info(`Skipping preview deploy reconciliation for #${tuple.prNumber}: target is not preview-eligible.`); + continue; + } + core.info(`Dispatching preview deploy reconciliation for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); + await github.rest.repos.createDispatchEvent({ + ...context.repo, + event_type: "preview-deploy", + client_payload: { + action: "deploy", + pr_number: tuple.prNumber, + base_ref: tuple.baseRef, + base_sha: tuple.baseSha, + head_sha: tuple.headSha, + merge_sha: tuple.mergeSha, + preview_domain: "preview.firedevops.net", + }, + }); + } + + build-base-image: + name: Build Runtime Base Image + needs: [image-meta] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + runs-on: ubuntu-latest + outputs: + digest: ${{ steps.select_base_image_digest.outputs.digest }} + permissions: + # This job publishes the shared runtime base image to GHCR. + contents: read + packages: write + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: ⬇️ Checkout Code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Login to GHCR + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push runtime base image + id: build_base_image_first + continue-on-error: true + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: ./docker/base.Dockerfile + push: true + tags: ${{ needs.image-meta.outputs.base_image }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache + type=registry,ref=ghcr.io/benhook1013/firemud-base:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache,mode=max + type=gha,mode=max + + - name: Retry build and push runtime base image + id: build_base_image_retry + if: ${{ steps.build_base_image_first.outcome == 'failure' }} + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: ./docker/base.Dockerfile + push: true + tags: ${{ needs.image-meta.outputs.base_image }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache + type=registry,ref=ghcr.io/benhook1013/firemud-base:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache,mode=max + type=gha,mode=max + + - name: Select exact published runtime base digest + id: select_base_image_digest + if: ${{ !cancelled() }} + env: + FIRST_OUTCOME: ${{ steps.build_base_image_first.outcome }} + FIRST_DIGEST: ${{ steps.build_base_image_first.outputs.digest }} + RETRY_OUTCOME: ${{ steps.build_base_image_retry.outcome }} + RETRY_DIGEST: ${{ steps.build_base_image_retry.outputs.digest }} + run: | + set -euo pipefail + published_digests=() + if [[ "$FIRST_OUTCOME" == "success" ]]; then + published_digests+=("$FIRST_DIGEST") + fi + if [[ "$RETRY_OUTCOME" == "success" ]]; then + published_digests+=("$RETRY_DIGEST") + fi + if ((${#published_digests[@]} != 1)); then + echo "Expected exactly one successful runtime base-image publication digest." >&2 + exit 1 + fi + base_image_digest="${published_digests[0]}" + [[ "$base_image_digest" =~ ^sha256:[0-9a-f]{64}$ ]] || { + echo "Runtime base-image publisher returned an invalid sha256 digest." >&2 + exit 1 + } + echo "digest=$base_image_digest" >> "$GITHUB_OUTPUT" + + build-runtime-images: + name: Build Runtime Images (${{ matrix.service }}) + needs: [image-meta, build-base-image] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + runs-on: ubuntu-latest + permissions: + # This job publishes only unique staging service tags. Canonical aliases + # are written by publish-runtime-images after the exact candidate passes smoke. + contents: read + packages: write + strategy: + fail-fast: false + matrix: + service: + - account-service + - automation-scripting-service + - entity-management-service + - game-design-service + - game-logic-service + - game-session-service + - logging-admin-service + - social-groups-service + - spring-cloud-gateway + - tcp-proxy-service + - world-management-service + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: ⬇️ Checkout Code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: ⚙️ Set Up Java + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: ⚙️ Set Up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: false + + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + + - name: Build service JAR + run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- :${{ matrix.service }}:bootJar + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Login to GHCR + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push runtime service image + id: build_runtime_image_first + continue-on-error: true + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: ./services/${{ matrix.service }}/build/libs + file: ./services/${{ matrix.service }}/Dockerfile + push: true + build-contexts: | + repo_root=. + build-args: | + BASE_IMAGE=ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }} + tags: ghcr.io/benhook1013/${{ matrix.service }}:${{ needs.image-meta.outputs.candidate_tag }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache,mode=max + type=gha,mode=max + + - name: Retry build and push runtime service image + if: ${{ steps.build_runtime_image_first.outcome == 'failure' }} + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: ./services/${{ matrix.service }}/build/libs + file: ./services/${{ matrix.service }}/Dockerfile + push: true + build-contexts: | + repo_root=. + build-args: | + BASE_IMAGE=ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }} + tags: ghcr.io/benhook1013/${{ matrix.service }}:${{ needs.image-meta.outputs.candidate_tag }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache,mode=max + type=gha,mode=max + + build-backup-verifier: + name: Build Backup Verifier Image + needs: [image-meta] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') }} + runs-on: ubuntu-latest + timeout-minutes: 15 + outputs: + image_id: ${{ steps.smoke.outputs.image_id }} + permissions: + contents: read + env: + BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Checkout trusted branch commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Load workflow tool versions + id: workflow-tool-versions + uses: ./.github/actions/load-workflow-tool-versions + + - name: Build backup verifier image + run: | + docker build \ + --file docker/backup-verifier.Dockerfile \ + --tag "$BACKUP_VERIFIER_IMAGE" \ + . + + - name: Smoke backup verifier image + id: smoke + env: + VELERO_VERSION: ${{ steps.workflow-tool-versions.outputs.velero-version }} + run: | + set -euo pipefail + bash ./dev-tools/backups/smoke-backup-verifier-image.sh "$BACKUP_VERIFIER_IMAGE" "$VELERO_VERSION" + image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" + [[ "$image_id" =~ ^sha256:[0-9a-f]{64}$ ]] || { + echo "Backup verifier image did not return an exact image ID." >&2 + exit 1 + } + echo "image_id=$image_id" >> "$GITHUB_OUTPUT" + + - name: Export exact verified backup verifier image artifact + env: + VERIFIED_IMAGE_ID: ${{ steps.smoke.outputs.image_id }} + run: | + set -euo pipefail + current_image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" + [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Backup verifier image changed after its smoke proof; refusing artifact export." >&2 + exit 1 + } + docker save "$BACKUP_VERIFIER_IMAGE" | gzip -1 > "$RUNNER_TEMP/backup-verifier.tar.gz" + + - name: Upload exact verified backup verifier image artifact + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: backup-verifier-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/backup-verifier.tar.gz + if-no-files-found: error + retention-days: 1 + + publish-backup-verifier: + name: Publish Trusted Backup Verifier Image + needs: [image-meta, build-backup-verifier] + if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-backup-verifier.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + packages: write + id-token: write + attestations: write + env: + BACKUP_VERIFIER_IMAGE_NAME: ghcr.io/benhook1013/backup-verifier + BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Checkout trusted publication commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Download exact verified backup verifier image artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: backup-verifier-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/backup-verifier-artifact + + - name: Load and verify exact backup verifier image + env: + BACKUP_VERIFIER_ARCHIVE: ${{ runner.temp }}/backup-verifier-artifact/backup-verifier.tar.gz + VERIFIED_IMAGE_ID: ${{ needs.build-backup-verifier.outputs.image_id }} + run: | + set -euo pipefail + [[ -f "$BACKUP_VERIFIER_ARCHIVE" ]] || { + echo "Verified backup verifier image artifact is missing." >&2 + exit 1 + } + gzip -dc "$BACKUP_VERIFIER_ARCHIVE" | docker load + loaded_image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" + [[ "$loaded_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Loaded backup verifier image does not match the exact verified build image." >&2 + exit 1 + } + + - name: Login to GHCR + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Publish exact verified backup verifier image + id: publish + run: | + set -euo pipefail + bash ./dev-tools/hosted/shared/push-verified-image.sh "$BACKUP_VERIFIER_IMAGE" + + - name: Attest trusted backup verifier image provenance + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-name: ${{ env.BACKUP_VERIFIER_IMAGE_NAME }} + subject-digest: ${{ steps.publish.outputs.digest }} + push-to-registry: true + create-storage-record: false + + build-hosted-identity-controller: + name: Build Trusted Hosted Identity Controller + needs: [image-meta, build-base-image] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-base-image.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 25 + outputs: + image_id: ${{ steps.smoke.outputs.image_id }} + permissions: + contents: read + packages: read + env: + CONTROLLER_IMAGE_NAME: ghcr.io/benhook1013/firemud-hosted-identity-controller + CONTROLLER_IMAGE: ghcr.io/benhook1013/firemud-hosted-identity-controller:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Checkout trusted branch commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up Java + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: false + + - name: Login to GHCR + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + + - name: Build controller JAR and image locally + run: | + set -euo pipefail + bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- :hosted-environment-identity-controller:bootJar + docker build \ + --file services/hosted-environment-identity-controller/Dockerfile \ + --build-arg BASE_IMAGE="ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }}" \ + --tag "$CONTROLLER_IMAGE" \ + services/hosted-environment-identity-controller/build/libs + + - name: Smoke exact controller image + id: smoke + run: | + set -euo pipefail + smoked_image_id="$(bash ./dev-tools/hosted/controller/smoke-paused-controller-image.sh "$CONTROLLER_IMAGE")" + local_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$smoked_image_id" == "$local_image_id" ]] || { + echo "Controller smoke did not execute the exact locally tagged image." >&2 + exit 1 + } + echo "image_id=$local_image_id" >> "$GITHUB_OUTPUT" + + - name: Export exact verified controller image artifact + env: + VERIFIED_IMAGE_ID: ${{ steps.smoke.outputs.image_id }} + run: | + set -euo pipefail + current_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Controller image changed after its smoke proof; refusing artifact export." >&2 + exit 1 + } + docker save "$CONTROLLER_IMAGE" | gzip -1 > "$RUNNER_TEMP/hosted-identity-controller.tar.gz" + + - name: Upload exact verified controller image artifact + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: hosted-identity-controller-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/hosted-identity-controller.tar.gz + if-no-files-found: error + retention-days: 1 + + publish-hosted-identity-controller: + name: Publish Trusted Hosted Identity Controller + needs: [image-meta, build-base-image, build-hosted-identity-controller] + if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-base-image.result == 'success' && needs.build-hosted-identity-controller.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 25 + permissions: + contents: read + packages: write + id-token: write + attestations: write + env: + CONTROLLER_IMAGE_NAME: ghcr.io/benhook1013/firemud-hosted-identity-controller + CONTROLLER_IMAGE: ghcr.io/benhook1013/firemud-hosted-identity-controller:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Checkout trusted publication commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Download exact verified controller image artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: hosted-identity-controller-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/hosted-identity-controller-artifact + + - name: Load and verify exact controller image + env: + CONTROLLER_ARCHIVE: ${{ runner.temp }}/hosted-identity-controller-artifact/hosted-identity-controller.tar.gz + VERIFIED_IMAGE_ID: ${{ needs.build-hosted-identity-controller.outputs.image_id }} + run: | + set -euo pipefail + [[ -f "$CONTROLLER_ARCHIVE" ]] || { + echo "Verified hosted identity controller image artifact is missing." >&2 + exit 1 + } + gzip -dc "$CONTROLLER_ARCHIVE" | docker load + loaded_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$loaded_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Loaded controller image does not match the exact verified build image." >&2 + exit 1 + } + + - name: Login to GHCR + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Publish exact verified controller image + id: publish + env: + VERIFIED_IMAGE_ID: ${{ needs.build-hosted-identity-controller.outputs.image_id }} + run: | + set -euo pipefail + current_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Controller image changed after its verification proof; refusing publication." >&2 + exit 1 + } + bash ./dev-tools/hosted/shared/push-verified-image.sh "$CONTROLLER_IMAGE" + + - name: Attest trusted controller image provenance + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-name: ${{ env.CONTROLLER_IMAGE_NAME }} + subject-digest: ${{ steps.publish.outputs.digest }} + push-to-registry: true + create-storage-record: false + + pr-local-smoke: + outputs: + publishable: ${{ steps.runtime-artifact.outcome == 'success' }} + name: PR Full-Stack Smoke (runtime-required=${{ needs.image-meta.outputs.runtime_smoke_required }}) + needs: [image-meta] + if: ${{ (github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || github.event_name == 'repository_dispatch' }} + runs-on: ubuntu-latest + timeout-minutes: 45 + permissions: + # PR-controlled source receives no registry or repository write credential. + contents: read + env: + COMPOSE_PROJECT_NAME: smoke-full-${{ github.run_id }}-${{ github.run_attempt }} + SMOKE_TIMEOUT_SECONDS: 20 + SMOKE_IMAGE_TAG: ${{ needs.image-meta.outputs.image_tag }} + SMOKE_IMAGE_LOCAL_ONLY: 'true' + SMOKE_MINIO_LOCAL_ONLY: 'true' + SMOKE_MINIO_SERVER_IMAGE: >- + firemud-minio-server-smoke:${{ github.run_id }}-${{ github.run_attempt }} + SMOKE_MINIO_CLIENT_IMAGE: >- + firemud-minio-client-smoke:${{ github.run_id }}-${{ github.run_attempt }} + BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Checkout PR merge + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Load workflow tool versions + id: workflow-tool-versions + uses: ./.github/actions/load-workflow-tool-versions + + - name: Set up canonical Python + if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} + uses: ./.github/actions/setup-python + with: + requirements: smoke + + - name: Set up Java + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: true + + - name: Build local PR runtime images + id: runtime-images-build + env: + MERGE_SHA: ${{ needs.image-meta.outputs.merge_sha }} + run: | + set -euo pipefail + bash ./dev-tools/build-local-smoke-images.sh "$MERGE_SHA" + for service in \ + account-service \ + automation-scripting-service \ + entity-management-service \ + game-design-service \ + game-logic-service \ + game-session-service \ + logging-admin-service \ + social-groups-service \ + spring-cloud-gateway \ + tcp-proxy-service \ + world-management-service; do + docker tag \ + "ghcr.io/benhook1013/${service}:${MERGE_SHA}" \ + "ghcr.io/benhook1013/${service}:${SMOKE_IMAGE_TAG}" + done + + - name: Retain runtime bootJar compile-failure evidence + if: ${{ failure() && steps.runtime-images-build.outcome == 'failure' }} + continue-on-error: true + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: runtime-bootjar-compile-failure-${{ github.run_id }}-attempt-${{ github.run_attempt }} + path: ${{ steps.runtime-images-build.outputs.runtime_compile_failure_path || format('build/reports/compile-failure/runtime-bootjar/unavailable-{0}-{1}', github.run_id, github.run_attempt) }} + if-no-files-found: warn + retention-days: 3 + + - name: Build PR backup verifier image + run: | + docker build \ + --file docker/backup-verifier.Dockerfile \ + --tag "$BACKUP_VERIFIER_IMAGE" \ + . + + - name: Smoke PR backup verifier image + env: + VELERO_VERSION: ${{ steps.workflow-tool-versions.outputs.velero-version }} + run: bash ./dev-tools/backups/smoke-backup-verifier-image.sh "$BACKUP_VERIFIER_IMAGE" "$VELERO_VERSION" + + - name: Build and smoke pinned MinIO sources for PR Compose + id: minio-source + if: >- + ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} + run: | + bash ./dev-tools/minio/build-and-smoke-images.sh \ + "$SMOKE_MINIO_SERVER_IMAGE" "$SMOKE_MINIO_CLIENT_IMAGE" + + - name: Run credential-free full-stack smoke + id: runtime-smoke + # The terminal guard admits only the classified, labeled transition failure. + continue-on-error: true + if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} + env: + FIREMUD_SMOKE_ADMISSION_QUALIFICATION: held + SMOKE_MINIO_SERVER_IMAGE_ID: >- + ${{ steps.minio-source.outputs.server_image_id }} + SMOKE_MINIO_CLIENT_IMAGE_ID: >- + ${{ steps.minio-source.outputs.client_image_id }} + run: bash ./dev-tools/verify-smoke-images.sh --keep-running + + - name: Export fixed-tag preview image artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} + run: | + service_manifest=/tmp/pr-runtime-services.txt + provenance=/tmp/pr-runtime-provenance.json + : > "$service_manifest" + images=() + for service in \ + account-service \ + automation-scripting-service \ + entity-management-service \ + game-design-service \ + game-logic-service \ + game-session-service \ + logging-admin-service \ + social-groups-service \ + spring-cloud-gateway \ + tcp-proxy-service \ + world-management-service; do + printf '%s\n' "$service" >> "$service_manifest" + images+=("ghcr.io/benhook1013/${service}:${SMOKE_IMAGE_TAG}") + done + printf '%s\n' 'backup-verifier' >> "$service_manifest" + images+=("$BACKUP_VERIFIER_IMAGE") + PR_NUMBER="${{ needs.image-meta.outputs.pr_number }}" \ + BASE_SHA="${{ needs.image-meta.outputs.base_sha }}" \ + HEAD_SHA="${{ needs.image-meta.outputs.head_sha }}" \ + MERGE_SHA="${{ needs.image-meta.outputs.merge_sha }}" \ + IMAGE_TAG="${SMOKE_IMAGE_TAG}" \ + SOURCE_RUN_ID="${{ github.run_id }}" \ + REPOSITORY="${GITHUB_REPOSITORY}" \ + PROVENANCE_PATH="$provenance" \ + python3 - <<'PY' + import json + import os + + services = [ + "account-service", + "automation-scripting-service", + "entity-management-service", + "game-design-service", + "game-logic-service", + "game-session-service", + "logging-admin-service", + "social-groups-service", + "spring-cloud-gateway", + "tcp-proxy-service", + "world-management-service", + "backup-verifier", + ] + provenance = { + "repository": os.environ["REPOSITORY"], + "prNumber": int(os.environ["PR_NUMBER"]), + "baseSha": os.environ["BASE_SHA"], + "headSha": os.environ["HEAD_SHA"], + "mergeSha": os.environ["MERGE_SHA"], + "imageTag": os.environ["IMAGE_TAG"], + "sourceRunId": int(os.environ["SOURCE_RUN_ID"]), + "services": services, + } + with open(os.environ["PROVENANCE_PATH"], "w", encoding="utf-8") as output: + json.dump(provenance, output, separators=(",", ":"), sort_keys=True) + output.write("\n") + PY + docker save "${images[@]}" | gzip -1 > /tmp/pr-runtime-images.tar.gz + + - name: Upload preview image artifact + id: runtime-artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: pr-runtime-images-${{ needs.image-meta.outputs.image_tag }} + path: | + /tmp/pr-runtime-images.tar.gz + /tmp/pr-runtime-services.txt + /tmp/pr-runtime-provenance.json + if-no-files-found: error + retention-days: 1 + + - name: Summarize secure PR runtime artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} + env: + PR_NUMBER: ${{ needs.image-meta.outputs.pr_number }} + BASE_SHA: ${{ needs.image-meta.outputs.base_sha }} + HEAD_SHA: ${{ needs.image-meta.outputs.head_sha }} + MERGE_SHA: ${{ needs.image-meta.outputs.merge_sha }} + ARTIFACT_NAME: pr-runtime-images-${{ needs.image-meta.outputs.image_tag }} + run: | + { + echo "### PR runtime images and applicable full-stack smoke" + echo + echo "- Pull request: #${PR_NUMBER}" + echo "- Base SHA: \`${BASE_SHA}\`" + echo "- PR head SHA: \`${HEAD_SHA}\`" + echo "- Built PR merge SHA (full-stack smoke runs when required): \`${MERGE_SHA}\`" + echo "- Merge-scoped publication tag: \`pr-merge-${MERGE_SHA}\`" + echo "- Artifact: \`${ARTIFACT_NAME}\`" + echo + echo "This read-only PR workflow built the PR merge commit and runs full-stack smoke when required by change scope. The trusted default-branch publisher uploads only the exact merge-scoped artifact from this successful run." + } >> "$GITHUB_STEP_SUMMARY" + + - name: Dump Docker Compose logs on failure + if: >- + ${{ always() && steps.runtime-smoke.outcome == 'failure' && + needs.image-meta.outputs.runtime_smoke_required == 'true' && + steps.minio-source.outputs.server_image_id != '' && + steps.minio-source.outputs.client_image_id != '' }} + env: + SMOKE_MINIO_SERVER_IMAGE_ID: >- + ${{ steps.minio-source.outputs.server_image_id }} + SMOKE_MINIO_CLIENT_IMAGE_ID: >- + ${{ steps.minio-source.outputs.client_image_id }} + run: | + docker compose \ + -f docker/docker-compose.yml \ + -f docker/docker-compose.override.yml \ + -f docker/docker-compose.smoke-images.override.yml \ + -f docker/docker-compose.pr-local-minio.override.yml \ + logs || true + + - name: Stop smoke stack + id: runtime-cleanup + if: >- + ${{ always() && + needs.image-meta.outputs.runtime_smoke_required == 'true' && + steps.minio-source.outputs.server_image_id != '' && + steps.minio-source.outputs.client_image_id != '' }} + env: + SMOKE_MINIO_SERVER_IMAGE_ID: >- + ${{ steps.minio-source.outputs.server_image_id }} + SMOKE_MINIO_CLIENT_IMAGE_ID: >- + ${{ steps.minio-source.outputs.client_image_id }} + run: | + source ./dev-tools/smoke/run-owned-compose.sh + if ! stop_run_owned_compose_project \ + -f docker/docker-compose.yml \ + -f docker/docker-compose.override.yml \ + -f docker/docker-compose.smoke-images.override.yml \ + -f docker/docker-compose.pr-local-minio.override.yml; then + echo "Unable to prove or release the smoke Compose project; refusing unowned teardown." >&2 + exit 1 + fi + + # Canonical-transition diagnostic evidence, not runtime qualification. The + # native smoke outcome remains failed; only the bounded CI exception may pass. + - name: Known canonical transition PLAY failure with successful authenticated cleanup + id: canonical-play-transition + if: >- + ${{ always() && + github.repository == 'benhook1013/FireMUD' && + ((github.event_name == 'pull_request' && + contains(github.event.pull_request.labels.*.name, 'canonical-play-transition')) || + (github.event_name == 'repository_dispatch' && + github.event.action == 'pr-runtime-base-refresh' && + needs.image-meta.outputs.canonical_play_transition == 'true')) && + needs.image-meta.outputs.runtime_smoke_required == 'true' && + steps.runtime-smoke.outcome == 'failure' && + steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login' && + steps.runtime-cleanup.outcome == 'success' }} + run: | + echo '### Canonical PLAY transition exception evidence' >> "$GITHUB_STEP_SUMMARY" + echo 'LOGIN succeeded; direct backend PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE. Held-admission qualification and authenticated cleanup passed. No runtime qualification, image export, or publication.' >> "$GITHUB_STEP_SUMMARY" + + - name: Require successful runtime smoke and authenticated cleanup + if: ${{ always() }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + env: + RUNTIME_SMOKE_REQUIRED: ${{ needs.image-meta.outputs.runtime_smoke_required }} + RUNTIME_SMOKE_OUTCOME: ${{ steps.runtime-smoke.outcome }} + RUNTIME_CLEANUP_OUTCOME: ${{ steps.runtime-cleanup.outcome }} + KNOWN_PLAY_EXCEPTION_OUTCOME: ${{ steps.canonical-play-transition.outcome }} + with: + script: | + const required = process.env.RUNTIME_SMOKE_REQUIRED; + if (required !== "true" && required !== "false") { + core.setFailed("Runtime smoke scope is unavailable or invalid."); + } else if (required === "true" && ( + process.env.RUNTIME_CLEANUP_OUTCOME !== "success" || + (process.env.RUNTIME_SMOKE_OUTCOME !== "success" && !( + process.env.RUNTIME_SMOKE_OUTCOME === "failure" && + process.env.KNOWN_PLAY_EXCEPTION_OUTCOME === "success" + )) + )) { + core.setFailed("Required runtime smoke and authenticated cleanup must both execute successfully, unless the exact canonical PLAY transition exception is attested."); + } else if (required === "true" && process.env.RUNTIME_SMOKE_OUTCOME === "failure") { + core.warning("CI passed under the canonical PLAY transition exception. Runtime qualification and image publication remain blocked."); + } + + pr-controller-smoke: + name: PR Hosted Identity Controller Smoke + needs: [image-meta] + if: ${{ ((github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || github.event_name == 'repository_dispatch') && needs.image-meta.outputs.controller_smoke_required == 'true' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + # PR-controlled source receives no registry or repository write credential. + contents: read + env: + BASE_IMAGE: ${{ needs.image-meta.outputs.base_image }} + CONTROLLER_IMAGE: firemud-hosted-identity-controller-local:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Checkout PR merge + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up Java + uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: true + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Build exact local runtime base image + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: docker/base.Dockerfile + push: false + load: true + tags: ${{ env.BASE_IMAGE }} + cache-from: type=gha,scope=pr-controller-smoke + cache-to: type=gha,mode=max,scope=pr-controller-smoke + + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + + - name: Build controller image for credential-free local validation + run: | + set -euo pipefail + bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh \ + --runner ./gradlew -- :hosted-environment-identity-controller:bootJar + docker build \ + --file services/hosted-environment-identity-controller/Dockerfile \ + --build-arg BASE_IMAGE="$BASE_IMAGE" \ + --tag "$CONTROLLER_IMAGE" \ + services/hosted-environment-identity-controller/build/libs + + - name: Smoke controller image entrypoint and paused health + run: | + set -euo pipefail + bash ./dev-tools/hosted/controller/smoke-paused-controller-image.sh "$CONTROLLER_IMAGE" >/dev/null + + dispatch-pr-runtime-publication: + name: Dispatch Trusted PR Runtime Publication + needs: [image-meta, pr-local-smoke, pr-controller-smoke] + if: ${{ always() && !cancelled() && github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && needs.image-meta.result == 'success' && needs.pr-local-smoke.result == 'success' && needs.pr-local-smoke.outputs.publishable == 'true' && (needs.pr-controller-smoke.result == 'success' || (needs.image-meta.outputs.controller_smoke_required == 'false' && needs.pr-controller-smoke.result == 'skipped')) }} + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + # This trusted no-checkout job only sends an exact source-run handoff. + contents: write + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Dispatch exact runtime publication source + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + await github.rest.repos.createDispatchEvent({ + ...context.repo, + event_type: "pr-runtime-image-publication", + client_payload: { source_run_id: String(context.runId) }, + }); + + smoke-full: + name: Published Runtime Full-Stack Smoke + needs: [image-meta, build-runtime-images] + if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.build-runtime-images.result == 'success' }} + permissions: + # The trusted branch smoke workflow only pulls the staged candidate images. + contents: read + packages: read + uses: ./.github/workflows/smoke-full.yml + with: + action: full + head_sha: ${{ needs.image-meta.outputs.head_sha }} + checkout_ref: ${{ needs.image-meta.outputs.checkout_ref }} + image_tag: ${{ needs.image-meta.outputs.candidate_tag }} + secrets: inherit + + publish-runtime-images: + name: Promote Smoke-Tested Runtime Images + needs: [image-meta, build-runtime-images, smoke-full] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.build-runtime-images.result == 'success' && needs.smoke-full.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + packages: write + env: + HEAD_SHA: ${{ needs.image-meta.outputs.head_sha }} + HEAD_BRANCH: ${{ needs.image-meta.outputs.head_branch }} + CANDIDATE_TAG: ${{ needs.image-meta.outputs.candidate_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + + - name: Checkout trusted publication source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up canonical GitHub CLI + uses: ./.github/actions/setup-gh + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Login to GHCR + uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Promote smoke-tested service digests + env: + GH_TOKEN: ${{ github.token }} + GHCR_USERNAME: ${{ github.actor }} + GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + + services=( + account-service + automation-scripting-service + entity-management-service + game-design-service + game-logic-service + game-session-service + logging-admin-service + social-groups-service + spring-cloud-gateway + tcp-proxy-service + world-management-service + ) + + declare -A registry_tokens=() + registry_manifest_state() { + local image="$1" + local image_path="${image#ghcr.io/}" + local repository_path="${image_path%:*}" + local tag="${image_path##*:}" + local manifest_url="https://ghcr.io/v2/${repository_path}/manifests/${tag}" + local registry_token="${registry_tokens[$repository_path]:-}" + local status + + [[ -n "${GHCR_USERNAME:-}" && -n "${GHCR_TOKEN:-}" ]] || { + echo "GHCR credentials are unavailable for authenticated manifest preflight: $image" >&2 + return 1 + } + if [[ -z "$registry_token" ]]; then + if ! registry_token="$(curl --silent --show-error --location --fail \ + --connect-timeout 10 --max-time 30 \ + --user "${GHCR_USERNAME}:${GHCR_TOKEN}" \ + --get \ + --data-urlencode 'service=ghcr.io' \ + --data-urlencode "scope=repository:${repository_path}:pull" \ + --header 'Accept: application/json' \ + 'https://ghcr.io/token' | jq -er '.token // .access_token // empty')"; then + echo "GHCR bearer-token exchange failed for $image; refusing to infer absence." >&2 + return 1 + fi + registry_tokens["$repository_path"]="$registry_token" + fi + # `docker manifest inspect "$image"` conflates a 404 with auth, + # registry, and network failures, so it is never an absence check. + if ! status="$(curl --silent --show-error --location --head \ + --connect-timeout 10 --max-time 30 \ + --header "Authorization: Bearer ${registry_token}" \ + --header 'Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json' \ + --output /dev/null --write-out '%{http_code}' "$manifest_url")"; then + echo "Authenticated OCI manifest HEAD failed for $image; refusing to infer absence." >&2 + return 1 + fi + case "$status" in + 200) printf 'existing\n' ;; + 404) printf 'missing\n' ;; + *) + echo "Authenticated OCI manifest HEAD returned HTTP ${status} for $image; refusing to push." >&2 + return 1 + ;; + esac + } + + registry_digest() { + local image="$1" + local inspect_output inspect_status + local digest + if inspect_output="$(docker buildx imagetools inspect "$image")"; then + : + else + inspect_status=$? + echo "Unable to inspect exact registry digest for $image (imagetools exit $inspect_status); refusing to publish." >&2 + return "$inspect_status" + fi + digest="$(awk '$1 == "Digest:" && $2 ~ /^sha256:[0-9a-f]{64}$/ { print $2; exit }' <<<"$inspect_output")" + [[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]] || { + echo "Registry manifest for $image has no exact digest." >&2 + return 1 + } + printf '%s\n' "$digest" + } + + assert_current_branch_head() { + local current_sha + current_sha="$(gh api \ + "repos/${GITHUB_REPOSITORY}/git/ref/heads/${HEAD_BRANCH}" \ + --jq '.object.sha')" + [[ "$current_sha" == "$HEAD_SHA" ]] || { + echo "Refusing canonical runtime publication: ${HEAD_BRANCH} moved from ${HEAD_SHA} to ${current_sha}." >&2 + exit 1 + } + } + + promote_alias() { + local source="$1" target="$2" fixed="$3" + local source_digest existing_digest target_digest + source_digest="$(registry_digest "$source")" + local target_state + if ! target_state="$(registry_manifest_state "$target")"; then + echo "Immutable target preflight failed for $target; refusing to publish." >&2 + exit 1 + fi + if [[ "$target_state" == missing ]]; then + docker buildx imagetools create --tag "$target" "$source" + else + existing_digest="$(registry_digest "$target")" + if [[ "$fixed" == true && "$existing_digest" != "$source_digest" ]]; then + echo "Refusing to overwrite fixed runtime tag $target: existing digest $existing_digest differs from candidate $source_digest." >&2 + exit 1 + fi + if [[ "$existing_digest" != "$source_digest" ]]; then + docker buildx imagetools create --tag "$target" "$source" + fi + fi + target_digest="$(registry_digest "$target")" + [[ "$target_digest" == "$source_digest" ]] || { + echo "Promoted runtime tag $target does not match candidate digest $source_digest (got $target_digest)." >&2 + exit 1 + } + } + + for service in "${services[@]}"; do + candidate="ghcr.io/benhook1013/${service}:${CANDIDATE_TAG}" + sha_tag="ghcr.io/benhook1013/${service}:${HEAD_SHA}" + branch_tag="ghcr.io/benhook1013/${service}:${HEAD_BRANCH}" + + assert_current_branch_head + promote_alias "$candidate" "$sha_tag" true + assert_current_branch_head + promote_alias "$candidate" "$branch_tag" false + if [[ "$HEAD_BRANCH" == develop ]]; then + assert_current_branch_head + promote_alias "$candidate" "ghcr.io/benhook1013/${service}:latest" false + fi + done diff --git a/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/6b4c33d57a6c44c44258bdbfdae6aa3f59b31ecf.yml b/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/6b4c33d57a6c44c44258bdbfdae6aa3f59b31ecf.yml new file mode 100644 index 0000000000..1e54a955e4 --- /dev/null +++ b/dev-tools/tests/fixtures/trusted-runtime-workflow-definitions/6b4c33d57a6c44c44258bdbfdae6aa3f59b31ecf.yml @@ -0,0 +1,2266 @@ +name: Build Runtime Images + +on: + pull_request: + types: [opened, synchronize, reopened, edited] + paths: + - 'build.gradle.kts' + - 'settings.gradle.kts' + - 'gradle.properties' + - 'gradlew' + - 'gradlew.bat' + - 'buildSrc/**' + - 'gradle/**' + - 'protos/**' + - 'docker/**' + - '.dockerignore' + - '.github/workflows/runtime-images.yml' + - '.github/workflows/publish-pr-runtime-images.yml' + - '.github/workflows/smoke.yml' + - '.github/workflows/smoke-full.yml' + - 'services/**' + - '.github/actions/load-workflow-tool-versions/**' + - '.github/actions/setup-python/**' + - '.python-version' + - 'config/workflow-tool-versions.env' + - 'config/python/smoke-requirements.txt' + - 'config/python/smoke-requirements.in' + - 'dev-tools/build-compose-service-jars.sh' + - 'dev-tools/validation/run-gradle-with-dependency-recovery.sh' + - 'dev-tools/validation/run-locked-gradle.sh' + - 'dev-tools/validation/gradle-run-supervisor.py' + - 'dev-tools/build-local-smoke-images.sh' + - 'dev-tools/backups/verify-backups.sh' + - 'dev-tools/backups/pg-dump-s3-selection.shlib' + - 'dev-tools/backups/smoke-backup-verifier-image.sh' + - 'docker/backup-verifier.Dockerfile' + - 'dev-tools/certs/generate-dev-certs.sh' + - 'dev-tools/minio/**' + - 'dev-tools/hosted/controller/smoke-paused-controller-image.sh' + - 'dev-tools/smoke/**' + - 'dev-tools/verify-compose-health.sh' + - 'dev-tools/verify-fresh-bootstrap.sh' + - 'dev-tools/verify-restart-state.sh' + - 'dev-tools/verify-smoke-images.sh' + workflow_run: + workflows: ["CI — Validation"] + types: [completed] + repository_dispatch: + types: [pr-runtime-base-refresh] + workflow_dispatch: + +run-name: Build Runtime Images ${{ (github.event_name == 'pull_request' || github.event_name == 'repository_dispatch') && format('secure-pr-artifact pr-{0} base-{1} head-{2} merge-{3} mode-{4}', github.event_name == 'pull_request' && github.event.pull_request.number || github.event.client_payload.pr_number, github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.client_payload.base_sha, github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.event.client_payload.head_sha, github.event_name == 'pull_request' && github.sha || github.event.client_payload.merge_sha, github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required') || github.event_name == 'workflow_run' && github.event.workflow_run.conclusion == 'success' && format('trusted-branch branch-{0} sha-{1}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha) || github.event_name == 'workflow_run' && format('base-refresh-only branch-{0} sha-{1} ci-{2}', github.event.workflow_run.head_branch, github.event.workflow_run.head_sha, github.event.workflow_run.conclusion) || github.ref_name }} + +permissions: + contents: read + +concurrency: + group: runtime-images-${{ github.workflow }}-${{ (github.event_name == 'pull_request' && format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.pull_request.number, github.event.pull_request.base.sha, github.event.pull_request.head.sha, github.sha)) || (github.event_name == 'repository_dispatch' && github.event.client_payload.pr_number != '' && github.event.client_payload.base_sha != '' && github.event.client_payload.head_sha != '' && github.event.client_payload.merge_sha != '' && format('pr-{0}-base-{1}-head-{2}-merge-{3}', github.event.client_payload.pr_number, github.event.client_payload.base_sha, github.event.client_payload.head_sha, github.event.client_payload.merge_sha)) || (github.event_name == 'repository_dispatch' && format('repository-dispatch-run-{0}', github.run_id)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && format('ci-pr-run-{0}-attempt-{1}', github.event.workflow_run.id, github.event.workflow_run.run_attempt)) || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && format('branch-{0}', github.event.workflow_run.head_branch)) || github.ref }}-${{ github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'metadata' || 'required' }} + cancel-in-progress: true + +jobs: + image-meta: + name: Derive Runtime Image Metadata + if: ${{ (github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || (github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh') || github.event_name == 'workflow_dispatch' || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'push' && github.event.workflow_run.conclusion == 'success' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop')) }} + runs-on: ubuntu-latest + outputs: + pr_number: ${{ steps.meta.outputs.pr_number }} + base_ref: ${{ steps.meta.outputs.base_ref }} + base_sha: ${{ steps.meta.outputs.base_sha }} + head_sha: ${{ steps.meta.outputs.head_sha }} + merge_sha: ${{ steps.meta.outputs.merge_sha }} + head_branch: ${{ steps.meta.outputs.head_branch }} + checkout_ref: ${{ steps.meta.outputs.checkout_ref }} + image_tag: ${{ steps.meta.outputs.image_tag }} + candidate_tag: ${{ steps.meta.outputs.candidate_tag }} + base_image: ${{ steps.meta.outputs.base_image }} + canonical_play_transition: ${{ steps.meta.outputs.canonical_play_transition }} + runtime_smoke_required: ${{ steps.smoke_scope.outputs.runtime_smoke_required }} + controller_smoke_required: ${{ steps.smoke_scope.outputs.controller_smoke_required }} + permissions: + actions: read + contents: read + pull-requests: read + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Check out trusted workflow helpers + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - name: Set up canonical GitHub CLI + uses: ./.github/actions/setup-gh + + - name: Set up canonical Python + uses: ./.github/actions/setup-python + + - name: Derive image tags + id: meta + env: + GH_TOKEN: ${{ github.token }} + EVENT_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.client_payload.head_sha || '' }} + EVENT_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch || '' }} + EVENT_PR_NUMBER: ${{ github.event.pull_request.number || github.event.client_payload.pr_number || '' }} + EVENT_BASE_REF: ${{ github.event.pull_request.base.ref || github.event.client_payload.base_ref || '' }} + EVENT_BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.client_payload.base_sha || '' }} + EVENT_MERGE_SHA: ${{ github.event.client_payload.merge_sha || '' }} + EVENT_ACTION: ${{ github.event.action || '' }} + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + run: | + set -euo pipefail + EVENT_NAME="${{ github.event_name }}" + PR_NUMBER="" + BASE_REF="" + BASE_SHA="" + MERGE_SHA="" + CANONICAL_PLAY_TRANSITION=false + if [ "$EVENT_NAME" = "pull_request" ]; then + PR_NUMBER="$EVENT_PR_NUMBER" + BASE_REF="$EVENT_BASE_REF" + BASE_SHA="$EVENT_BASE_SHA" + HEAD_SHA="$EVENT_HEAD_SHA" + HEAD_BRANCH="" + MERGE_SHA="${GITHUB_SHA}" + CHECKOUT_REF="$MERGE_SHA" + [[ "$MERGE_SHA" =~ ^[0-9a-f]{40}$ ]] || { + echo "PR merge SHA is not a lowercase 40-character commit SHA." >&2 + exit 1 + } + [[ "$BASE_SHA" =~ ^[0-9a-f]{40}$ && "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]] || { + echo "PR event base/head SHAs are not lowercase 40-character commit SHAs." >&2 + exit 1 + } + merge_commit_json="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${MERGE_SHA}")" + jq -e \ + --arg base_sha "$BASE_SHA" \ + --arg head_sha "$HEAD_SHA" \ + --arg merge_sha "$MERGE_SHA" \ + '.sha == $merge_sha and (.parents | type) == "array" and (.parents | length) == 2 and .parents[0].sha == $base_sha and .parents[1].sha == $head_sha' \ + <<<"$merge_commit_json" >/dev/null || { + echo "PR event merge commit does not have the event's exact base/head parents; refusing a stale PR artifact." >&2 + exit 1 + } + elif [ "$EVENT_NAME" = "repository_dispatch" ]; then + [[ "$EVENT_ACTION" == "pr-runtime-base-refresh" ]] || { + echo "Runtime PR refresh requires the typed pr-runtime-base-refresh dispatch." >&2 + exit 1 + } + [[ "$GITHUB_REF" == "refs/heads/${DEFAULT_BRANCH}" ]] || { + echo "Runtime PR refresh must run from the repository default branch." >&2 + exit 1 + } + PR_NUMBER="$EVENT_PR_NUMBER" + BASE_REF="$EVENT_BASE_REF" + BASE_SHA="$EVENT_BASE_SHA" + MERGE_SHA="$EVENT_MERGE_SHA" + HEAD_SHA="$EVENT_HEAD_SHA" + HEAD_BRANCH="" + CHECKOUT_REF="$MERGE_SHA" + [[ "$PR_NUMBER" =~ ^[1-9][0-9]{0,50}$ ]] || { + echo "Runtime PR refresh payload has an invalid pull request number." >&2 + exit 1 + } + git check-ref-format "refs/heads/${BASE_REF}" >/dev/null || { + echo "Runtime PR refresh payload has an invalid base ref." >&2 + exit 1 + } + for sha_name in BASE_SHA HEAD_SHA MERGE_SHA; do + sha_value="${!sha_name}" + [[ "$sha_value" =~ ^[0-9a-f]{40}$ ]] || { + echo "Runtime PR refresh payload has an invalid ${sha_name}." >&2 + exit 1 + } + done + + encoded_base_ref="$(python3 -c 'import sys; from urllib.parse import quote; print(quote(sys.argv[1], safe="/"))' "$BASE_REF")" + current_base_ref_json="$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/heads/${encoded_base_ref}")" + jq -e \ + --arg base_sha "$BASE_SHA" \ + --arg base_ref "refs/heads/${BASE_REF}" \ + '.ref == $base_ref and .object.sha == $base_sha' \ + <<<"$current_base_ref_json" >/dev/null || { + echo "Runtime PR refresh base SHA is not the current ${BASE_REF} branch ref." >&2 + exit 1 + } + pull_request_json="$(gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}")" + jq -e \ + --arg repository "$GITHUB_REPOSITORY" \ + --arg base_ref "$BASE_REF" \ + --arg head_sha "$HEAD_SHA" \ + --arg merge_sha "$MERGE_SHA" \ + '( + .state == "open" and + .base.ref == $base_ref and + .base.repo.full_name == $repository and + .head.sha == $head_sha and + .head.repo.full_name == $repository and + (.mergeable | type) == "boolean" and + .mergeable == true and + (.mergeable_state | type) == "string" and + .mergeable_state != "dirty" and + .mergeable_state != "conflicting" and + .mergeable_state != "unknown" and + .merge_commit_sha == $merge_sha + )' <<<"$pull_request_json" >/dev/null || { + echo "Runtime PR refresh payload is stale, conflicted, fork-owned, closed, or has an invalid merge tuple." >&2 + exit 1 + } + merge_commit_json="$(gh api "repos/${GITHUB_REPOSITORY}/commits/${MERGE_SHA}")" + jq -e \ + --arg base_sha "$BASE_SHA" \ + --arg head_sha "$HEAD_SHA" \ + --arg merge_sha "$MERGE_SHA" \ + '.sha == $merge_sha and (.parents | type) == "array" and (.parents | length) == 2 and .parents[0].sha == $base_sha and .parents[1].sha == $head_sha' \ + <<<"$merge_commit_json" >/dev/null || { + echo "Runtime PR refresh merge commit does not have the exact current base/head parents." >&2 + exit 1 + } + # Only the verified live same-repository PR can authorize this + # diagnostic marker; dispatch payload labels carry no authority. + if jq -e '(.labels | type) == "array" and any(.labels[]; .name == "canonical-play-transition")' \ + <<<"$pull_request_json" >/dev/null; then + CANONICAL_PLAY_TRANSITION=true + fi + elif [ "${{ github.event_name }}" = "workflow_run" ]; then + [[ "${{ github.event.workflow_run.event }}" == "push" ]] || { + echo "Runtime branch publication requires a CI push workflow run." >&2 + exit 1 + } + [[ "${{ github.event.workflow_run.conclusion }}" == "success" ]] || { + echo "Runtime branch publication requires a successful CI workflow run." >&2 + exit 1 + } + HEAD_SHA="${EVENT_HEAD_SHA:-${{ github.event.workflow_run.head_sha }}}" + HEAD_BRANCH="$EVENT_HEAD_BRANCH" + CHECKOUT_REF="$HEAD_SHA" + else + HEAD_SHA="${GITHUB_SHA}" + CHECKOUT_REF="${GITHUB_SHA}" + HEAD_BRANCH="${GITHUB_REF_NAME}" + fi + + [[ "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]] || { + echo "Runtime publication head SHA is not a lowercase 40-character commit SHA." >&2 + exit 1 + } + if [ "$EVENT_NAME" != "pull_request" ] && [ "$EVENT_NAME" != "repository_dispatch" ]; then + [[ "$HEAD_BRANCH" == main || "$HEAD_BRANCH" == develop ]] || { + echo "Runtime branch publication is restricted to main or develop." >&2 + exit 1 + } + fi + + if [ "$EVENT_NAME" = "pull_request" ] || [ "$EVENT_NAME" = "repository_dispatch" ]; then + IMAGE_TAG="pr-merge-${MERGE_SHA}" + else + IMAGE_TAG="${HEAD_SHA}" + fi + CANDIDATE_TAG="candidate-${HEAD_SHA}-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + if [ "$EVENT_NAME" = "pull_request" ] || [ "$EVENT_NAME" = "repository_dispatch" ]; then + BASE_IMAGE="ghcr.io/benhook1013/firemud-base:${MERGE_SHA}" + else + BASE_IMAGE="ghcr.io/benhook1013/firemud-base:${CANDIDATE_TAG}" + fi + + { + echo "pr_number=${PR_NUMBER}" + echo "base_ref=${BASE_REF}" + echo "base_sha=${BASE_SHA}" + echo "head_sha=${HEAD_SHA}" + echo "merge_sha=${MERGE_SHA}" + echo "head_branch=${HEAD_BRANCH}" + echo "checkout_ref=${CHECKOUT_REF}" + echo "image_tag=${IMAGE_TAG}" + echo "candidate_tag=${CANDIDATE_TAG}" + echo "base_image=${BASE_IMAGE}" + echo "canonical_play_transition=${CANONICAL_PLAY_TRANSITION}" + } >> "$GITHUB_OUTPUT" + + - name: Verify successful CI push for manual publication + if: ${{ github.event_name == 'workflow_dispatch' }} + env: + GH_TOKEN: ${{ github.token }} + EXPECTED_SHA: ${{ steps.meta.outputs.head_sha }} + EXPECTED_BRANCH: ${{ steps.meta.outputs.head_branch }} + run: | + set -euo pipefail + ci_runs="$(gh api --paginate --slurp \ + "repos/${GITHUB_REPOSITORY}/actions/workflows/ci.yml/runs?event=push&head_sha=${EXPECTED_SHA}&per_page=100")" + jq -e \ + --arg expected_sha "$EXPECTED_SHA" \ + --arg expected_branch "$EXPECTED_BRANCH" \ + '[.[].workflow_runs[]?] | any(.[]; .head_sha == $expected_sha and .head_branch == $expected_branch and .event == "push" and .status == "completed" and .conclusion == "success")' \ + <<<"$ci_runs" >/dev/null || { + echo "No successful CI push run exists for manual runtime publication ${EXPECTED_BRANCH}@${EXPECTED_SHA}." >&2 + exit 1 + } + + - name: Detect PR smoke scopes + id: smoke_scope + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + let runtimeSmokeRequired = true; + let controllerSmokeRequired = true; + if (context.eventName === "pull_request" || context.eventName === "repository_dispatch") { + try { + const pullNumber = context.eventName === "pull_request" + ? context.payload.pull_request.number + : context.payload.client_payload.pr_number; + const changedFiles = await github.paginate( + github.rest.pulls.listFiles, + { + ...context.repo, + pull_number: pullNumber, + per_page: 100, + }, + (response) => response.data + ); + const expectedFileCount = context.eventName === "pull_request" + ? context.payload.pull_request.changed_files + : (await github.rest.pulls.get({ + ...context.repo, + pull_number: pullNumber, + })).data.changed_files; + const validFileEntries = changedFiles.every((file) => + file && + typeof file.filename === "string" && + file.filename.length > 0 && + (file.previous_filename === undefined || + (typeof file.previous_filename === "string" && file.previous_filename.length > 0)) + ); + if (!Number.isInteger(expectedFileCount) || changedFiles.length !== expectedFileCount || !validFileEntries) { + core.warning("PR smoke scope detection was incomplete; running both local smokes."); + } else { + const paths = changedFiles.flatMap((file) => + [file.filename, file.previous_filename].filter(Boolean) + ); + const runtimePrefixes = [ + "buildSrc/", + "docker/", + "dev-tools/minio/", + "dev-tools/smoke/", + "gradle/", + "protos/", + ".github/actions/load-workflow-tool-versions/", + ".github/actions/setup-python/", + ]; + const workflowToolAuthorityPath = "config/workflow-tool-versions.env"; + const runtimeFiles = new Set([ + ".dockerignore", + ".github/workflows/publish-pr-runtime-images.yml", + ".github/workflows/runtime-images.yml", + ".github/workflows/smoke-full.yml", + ".github/workflows/smoke.yml", + ".github/actions/load-workflow-tool-versions/action.yml", + ".python-version", + "build.gradle.kts", + "config/python/smoke-requirements.txt", + "config/python/smoke-requirements.in", + "dev-tools/build-compose-service-jars.sh", + "dev-tools/validation/run-gradle-with-dependency-recovery.sh", + "dev-tools/validation/run-locked-gradle.sh", + "dev-tools/validation/gradle-run-supervisor.py", + "dev-tools/build-local-smoke-images.sh", + "dev-tools/backups/verify-backups.sh", + "dev-tools/backups/pg-dump-s3-selection.shlib", + "dev-tools/backups/smoke-backup-verifier-image.sh", + "dev-tools/certs/generate-dev-certs.sh", + "dev-tools/verify-compose-health.sh", + "dev-tools/verify-fresh-bootstrap.sh", + "dev-tools/verify-restart-state.sh", + "dev-tools/verify-smoke-images.sh", + "gradle.properties", + "docker/backup-verifier.Dockerfile", + "gradlew", + "gradlew.bat", + "settings.gradle.kts", + ]); + const controllerPrefixes = [ + "buildSrc/", + "gradle/", + "services/hosted-environment-identity-controller/", + ]; + const controllerFiles = new Set([ + ".dockerignore", + ".github/workflows/runtime-images.yml", + "build.gradle.kts", + "dev-tools/hosted/controller/smoke-paused-controller-image.sh", + "docker/base.Dockerfile", + "gradle.properties", + "gradlew", + "gradlew.bat", + "settings.gradle.kts", + ]); + const authorityChanged = paths.includes(workflowToolAuthorityPath); + const nonAuthorityPaths = paths.filter( + (path) => path !== workflowToolAuthorityPath + ); + runtimeSmokeRequired = nonAuthorityPaths.some( + (path) => + runtimeFiles.has(path) || + runtimePrefixes.some((prefix) => path.startsWith(prefix)) || + (path.startsWith("services/") && + !path.startsWith( + "services/hosted-environment-identity-controller/" + )) + ); + runtimeSmokeRequired = runtimeSmokeRequired || authorityChanged; + controllerSmokeRequired = paths.some( + (path) => + controllerFiles.has(path) || + controllerPrefixes.some((prefix) => path.startsWith(prefix)) + ); + } + } catch (error) { + core.warning( + `PR smoke scope detection failed; running both local smokes: ${error.message}` + ); + } + } + core.setOutput("runtime_smoke_required", String(runtimeSmokeRequired)); + core.setOutput("controller_smoke_required", String(controllerSmokeRequired)); + + dispatch-pr-base-refreshes: + name: Dispatch PR Base Refreshes + concurrency: + group: runtime-pr-refresh-dispatch + queue: max + if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.status == 'completed' && (github.event.workflow_run.event == 'pull_request' || (github.event.workflow_run.event == 'push' && (github.event.workflow_run.head_branch == 'main' || github.event.workflow_run.head_branch == 'develop'))) && github.event.workflow_run.head_repository.full_name == github.repository }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + actions: read + contents: write + pull-requests: read + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Dispatch exact PR runtime refreshes and preview reconciles + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + const workflowRun = context.payload.workflow_run; + const refreshBranch = workflowRun.head_branch; + const refreshSha = workflowRun.head_sha; + const shaPattern = /^[0-9a-f]{40}$/; + const runtimePrefixes = [ + "buildSrc/", + "docker/", + "dev-tools/minio/", + "dev-tools/smoke/", + "gradle/", + "protos/", + ".github/actions/load-workflow-tool-versions/", + ".github/actions/setup-python/", + ]; + const runtimeFiles = new Set([ + ".dockerignore", + ".github/workflows/publish-pr-runtime-images.yml", + ".github/workflows/runtime-images.yml", + ".github/workflows/smoke-full.yml", + ".github/workflows/smoke.yml", + ".github/actions/load-workflow-tool-versions/action.yml", + ".python-version", + "build.gradle.kts", + "config/workflow-tool-versions.env", + "config/python/smoke-requirements.txt", + "config/python/smoke-requirements.in", + "dev-tools/build-compose-service-jars.sh", + "dev-tools/validation/run-gradle-with-dependency-recovery.sh", + "dev-tools/validation/run-locked-gradle.sh", + "dev-tools/validation/gradle-run-supervisor.py", + "dev-tools/build-local-smoke-images.sh", + "dev-tools/backups/verify-backups.sh", + "dev-tools/backups/pg-dump-s3-selection.shlib", + "dev-tools/backups/smoke-backup-verifier-image.sh", + "dev-tools/certs/generate-dev-certs.sh", + "dev-tools/hosted/controller/smoke-paused-controller-image.sh", + "dev-tools/verify-compose-health.sh", + "dev-tools/verify-fresh-bootstrap.sh", + "dev-tools/verify-restart-state.sh", + "dev-tools/verify-smoke-images.sh", + "gradle.properties", + "gradlew", + "gradlew.bat", + "settings.gradle.kts", + ]); + const runtimeRunEvents = ["pull_request", "repository_dispatch"]; + const runtimeRunPageSize = 100; + const runtimeRunLookbackMilliseconds = 7 * 24 * 60 * 60 * 1000; + + const waitForMergeRefresh = async () => { + await new Promise((resolve) => setTimeout(resolve, 2000)); + }; + + const hasRuntimeChange = async (pullRequest) => { + const files = await github.paginate( + github.rest.pulls.listFiles, + { + ...context.repo, + pull_number: pullRequest.number, + per_page: 100, + }, + (response) => response.data + ); + const expectedFileCount = pullRequest.changed_files; + const validFileEntries = Number.isInteger(expectedFileCount) && + files.length === expectedFileCount && + files.every((file) => + file && + typeof file.filename === "string" && + file.filename.length > 0 && + (file.previous_filename === undefined || + (typeof file.previous_filename === "string" && file.previous_filename.length > 0)) + ); + if (!validFileEntries) { + core.warning(`PR #${pullRequest.number} changed-file metadata was incomplete; refreshing its runtime images.`); + return true; + } + return files.flatMap((file) => [file.filename, file.previous_filename].filter(Boolean)).some((path) => + runtimeFiles.has(path) || + runtimePrefixes.some((prefix) => path.startsWith(prefix)) || + path.startsWith("services/") + ); + }; + + const dependencyBotAuthors = new Set([ + "app/dependabot", + "dependabot[bot]", + "app/renovate", + "renovate[bot]", + ]); + + const isPreviewEligible = (pullRequest) => { + const labels = pullRequest.labels; + return typeof pullRequest.user?.login === "string" && + pullRequest.user.login.length > 0 && + !dependencyBotAuthors.has(pullRequest.user.login) && + Array.isArray(labels) && + labels.every((label) => label && typeof label.name === "string") && + (["main", "develop"].includes(pullRequest.base?.ref) || + labels.some((label) => label.name === "preview:priority")); + }; + + const resolveExactMerge = async (number, baseBranch = refreshBranch, baseSha = refreshSha, expectedHeadSha = null) => { + for (let attempt = 1; attempt <= 5; attempt += 1) { + const response = await github.rest.pulls.get({ + ...context.repo, + pull_number: number, + }); + const pullRequest = response.data; + const currentHeadSha = pullRequest.head?.sha; + const currentBaseRef = pullRequest.base?.ref; + const headRepository = pullRequest.head?.repo?.full_name; + const baseRepository = pullRequest.base?.repo?.full_name; + if (pullRequest.state !== "open" || + headRepository !== context.payload.repository.full_name || + baseRepository !== context.payload.repository.full_name || + currentBaseRef !== baseBranch || + !shaPattern.test(currentHeadSha || "") || + (expectedHeadSha !== null && currentHeadSha !== expectedHeadSha)) { + return null; + } + + const mergeableState = typeof pullRequest.mergeable_state === "string" + ? pullRequest.mergeable_state + : pullRequest.mergeable_state === null ? "unknown" : "invalid"; + if (pullRequest.mergeable === false || + mergeableState === "dirty" || + mergeableState === "conflicting") { + core.warning(`Skipping PR #${number}: GitHub reports a merge conflict.`); + return null; + } + if (pullRequest.mergeable === null || mergeableState === "unknown") { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: GitHub did not produce a ready merge tuple.`); + return null; + } + if (pullRequest.mergeable !== true || mergeableState === "invalid") { + core.warning(`Skipping PR #${number}: GitHub returned invalid merge metadata.`); + return null; + } + + const mergeSha = pullRequest.merge_commit_sha; + if (!shaPattern.test(mergeSha || "")) { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: merge SHA is null or invalid.`); + return null; + } + + try { + const commit = await github.rest.repos.getCommit({ + ...context.repo, + ref: mergeSha, + }); + const parents = commit.data.parents?.map((parent) => parent.sha) || []; + if (commit.data.sha !== mergeSha || + parents.length !== 2 || + parents[0] !== baseSha || + parents[1] !== currentHeadSha) { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: merge commit parents do not match the current base/head.`); + return null; + } + } catch (error) { + if (attempt < 5) { + await waitForMergeRefresh(); + continue; + } + core.warning(`Skipping PR #${number}: exact merge commit could not be read (${error.message}).`); + return null; + } + + return { + tuple: { + prNumber: String(number), + baseRef: baseBranch, + baseSha, + headSha: currentHeadSha, + mergeSha, + }, + pullRequest, + }; + } + return null; + }; + + const validTimestamp = (value) => typeof value === "string" && + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(value) && + Number.isFinite(Date.parse(value)); + + const readInventory = async (createdSince, events = runtimeRunEvents) => { + const inventory = []; + let complete = true; + let incompleteReason = null; + for (const event of events) { + let total; + const eventRuns = [], ids = new Set(); + for (let page = 1; page <= 10; page += 1) { + const response = await github.rest.actions.listWorkflowRuns({ + ...context.repo, workflow_id: "runtime-images.yml", event, + created: `${createdSince}..*`, per_page: runtimeRunPageSize, page, + }); + const payload = response?.data; + total ??= payload?.total_count; + if (!Number.isInteger(total) || total < 0 || !Array.isArray(payload?.workflow_runs) || + payload.total_count !== total) throw new Error(`runtime-images ${event} inventory shifted or is malformed`); + if (total >= 1000) { + complete = false; + incompleteReason ??= `runtime-images ${event} exceeds 1000-run bound`; + // Retain this untrusted sample only for the existing conservative in-flight refinement. + // It is never treated as a complete inventory or dispatch authority. + eventRuns.push(...payload.workflow_runs); + break; + } + if (payload.workflow_runs.length !== Math.min(runtimeRunPageSize, total - eventRuns.length)) { + throw new Error(`runtime-images ${event} recent run inventory is incomplete`); + } + for (const run of payload.workflow_runs) { + if (!Number.isSafeInteger(run.id) || run.id <= 0 || ids.has(run.id)) { + throw new Error(`runtime-images ${event} inventory has duplicate or invalid run IDs`); + } + ids.add(run.id); eventRuns.push(run); + } + if (eventRuns.length === total) break; + } + inventory.push(...eventRuns); + } + return {complete, runs: inventory, reason: incompleteReason}; + }; + + + const loadExistingRuntimeRuns = async () => { + const createdSince = new Date(Date.now() - runtimeRunLookbackMilliseconds).toISOString(); + const initial = await readInventory(createdSince); + if (initial.complete) { + return initial; + } + + const inFlightStatuses = ["queued", "waiting", "requested", "pending", "in_progress"]; + const inFlightRuns = initial.runs.filter((run) => inFlightStatuses.includes(run?.status)); + if (inFlightRuns.length === 0) { + return initial; + } + + if (inFlightRuns.some((run) => !runtimeRunEvents.includes(run.event) || + !Number.isSafeInteger(run.id) || run.id <= 0 || !validTimestamp(run.created_at))) { + return { + ...initial, + reason: "truncated recent inventory contains an in-flight run without a valid event, id, or creation timestamp", + }; + } + + const ciCompletedAt = workflowRun.updated_at; + if (!validTimestamp(ciCompletedAt)) return initial; + const refinementSince = [...inFlightRuns.map(run => run.created_at), ciCompletedAt] + .sort((a, b) => Date.parse(a) - Date.parse(b))[0]; + // Refinement can confirm a producer, but cannot prove absence outside its narrower range. + const refined = await readInventory(refinementSince); + if (!refined.complete) { + return { + ...refined, + reason: refined.reason || "refined runtime run inventory is incomplete", + }; + } + const refinedIds = new Set(refined.runs.map((run) => `${run?.event}:${run?.id}`)); + if (inFlightRuns.some((run) => !refinedIds.has(`${run.event}:${run.id}`))) { + return { + ...refined, + complete: false, + reason: "refined inventory did not retain every initially observed in-flight run", + }; + } + return {...refined, absenceProven: false}; + }; + + const findExactExistingProducer = (tuple, inventory) => { + const expectedWorkflowPath = ".github/workflows/runtime-images.yml"; + const workflowPathMatches = (path) => { + if (path === expectedWorkflowPath) { + return true; + } + const prefix = `${expectedWorkflowPath}@`; + if (typeof path !== "string" || !path.startsWith(prefix)) { + return false; + } + const ref = path.slice(prefix.length); + if (ref.length === 0 || ref === "@" || ref.endsWith(".") || + /[\u0000-\u0020\u007f]/.test(ref) || + ["~", "^", ":", "?", "*", "[", "\\"].some((character) => ref.includes(character)) || + ref.includes("..") || ref.includes("@{")) { + return false; + } + return ref.split("/").every((part) => + part.length > 0 && part !== "." && part !== ".." && + !part.startsWith(".") && + !part.endsWith(".lock") + ); + }; + const expectedTitle = + `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} ` + + `base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; + const matching = inventory.runs.filter((run) => + run?.display_title === expectedTitle + ); + const ordered = []; + const matchingIds = new Set(); + for (const run of matching) { + if (!runtimeRunEvents.includes(run.event) || + !Number.isSafeInteger(run.id) || run.id <= 0 || matchingIds.has(run.id) || + typeof run.created_at !== "string" || + !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(run.created_at) || + !Number.isFinite(Date.parse(run.created_at)) || + !workflowPathMatches(run.path) || + !["Build Runtime Images", expectedTitle].includes(run.name) || + run.repository?.full_name !== context.payload.repository.full_name || + run.head_repository?.full_name !== context.payload.repository.full_name) { + throw new Error(`run ${run.id} has the exact tuple title but invalid workflow or repository identity`); + } + matchingIds.add(run.id); + ordered.push(run); + if (run.event === "pull_request") { + if (run.head_sha !== tuple.headSha) { + throw new Error(`run ${run.id} has the exact tuple title but a different PR head SHA`); + } + const pullRequests = run.pull_requests; + if (!Array.isArray(pullRequests) || (pullRequests.length > 0 && !pullRequests.some((pullRequest) => + String(pullRequest?.number) === tuple.prNumber && + pullRequest?.head?.sha === tuple.headSha + ))) { + throw new Error(`run ${run.id} has incomplete or conflicting PR association evidence`); + } + } + } + ordered.sort((left, right) => right.created_at.localeCompare(left.created_at)); + if (ordered.length > 1 && ordered[0].created_at === ordered[1].created_at) { + throw new Error("newest exact runtime producer has an ambiguous created_at timestamp"); + } + const newest = ordered[0]; + if (!newest) { + return []; + } + if (["queued", "waiting", "requested", "pending", "in_progress"].includes(newest.status)) { + if (newest.conclusion !== null && newest.conclusion !== undefined) { + throw new Error(`run ${newest.id} has a conclusion while still ${newest.status}`); + } + return [newest]; + } + if (newest.status === "completed") { + // A refresh created after this CI completed already owns this callback's recovery. + // A later substantive CI signal may still recover publication from an older producer. + const ciCompleted = Date.parse(workflowRun.updated_at || ""); + if (newest.event === "repository_dispatch" && Number.isFinite(ciCompleted) && + Date.parse(newest.created_at) >= ciCompleted) return [newest]; + return []; + } + throw new Error(`run ${newest.id} has an unknown status and cannot be classified`); + }; + + if (!shaPattern.test(refreshSha) || typeof refreshBranch !== "string" || + refreshBranch.length === 0) { + core.setFailed("Completed CI callback did not identify a branch and lowercase SHA."); + return; + } + let sourcePrNumber = null; + if (workflowRun.event === "pull_request") { + // Completion is a reconcile signal only for a substantive CI attempt. + // Metadata edits also complete CI, but must never reconstruct runtime. + const positiveInteger = (value) => Number.isSafeInteger(value) && value > 0; + const ciPath = ".github/workflows/ci.yml"; + const ciName = "CI — Validation"; + const titleMatch = /^CI — Validation pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40})$/.exec(workflowRun.display_title || ""); + const matchesSource = (run) => + positiveInteger(workflowRun.id) && positiveInteger(workflowRun.run_attempt) && + positiveInteger(workflowRun.workflow_id) && + run.id === workflowRun.id && run.run_attempt === workflowRun.run_attempt && + run.workflow_id === workflowRun.workflow_id && run.event === "pull_request" && + run.status === "completed" && typeof run.conclusion === "string" && run.conclusion.length > 0 && + run.repository?.full_name === context.payload.repository.full_name && + run.head_repository?.full_name === context.payload.repository.full_name && + run.head_branch === refreshBranch && run.head_sha === refreshSha && + run.display_title === workflowRun.display_title && + [ciName, workflowRun.display_title].includes(run.name) && + (run.path === ciPath || (typeof run.path === "string" && + run.path.startsWith(`${ciPath}@`) && run.path.length > ciPath.length + 1)); + if (!titleMatch || titleMatch[3] !== refreshSha) { + core.warning("Skipping PR runtime reconciliation: callback lacks exact CI PR/base/head title metadata."); + return; + } + const {data: ciWorkflow} = await github.rest.actions.getWorkflow({ + ...context.repo, workflow_id: "ci.yml", + }); + const {data: source} = await github.rest.actions.getWorkflowRun({ + ...context.repo, run_id: workflowRun.id, + }); + if (ciWorkflow.id !== workflowRun.workflow_id || ciWorkflow.path !== ciPath || + ciWorkflow.name !== ciName || !matchesSource(source)) { + core.warning("Skipping PR runtime reconciliation: current CI workflow/run identity differs from callback."); + return; + } + const jobs = await github.paginate( + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + {...context.repo, run_id: source.id, attempt_number: source.run_attempt, per_page: 100} + ); + const gates = jobs.filter((job) => job.name === "Validation Gate"); + const gate = gates.length === 1 ? gates[0] : null; + const preservation = gate?.steps?.filter((step) => + step.name === "Preserve successful required gate on metadata-only edit") || []; + const enforcement = gate?.steps?.filter((step) => step.name === "Enforce validation success") || []; + const checkPrefix = `https://api.github.com/repos/${context.payload.repository.full_name}/check-runs/`; + if (!gate || !positiveInteger(gate.id) || gate.run_id !== source.id || + gate.run_attempt !== source.run_attempt || gate.head_sha !== source.head_sha || + ![ciName, source.display_title].includes(gate.workflow_name) || gate.status !== "completed" || + typeof gate.check_run_url !== "string" || !gate.check_run_url.startsWith(checkPrefix) || + !/^[1-9][0-9]*$/.test(gate.check_run_url.slice(checkPrefix.length)) || + preservation.length !== 1 || preservation[0].status !== "completed" || + preservation[0].conclusion !== "skipped" || enforcement.length !== 1 || + enforcement[0].status !== "completed" || !["success", "failure"].includes(enforcement[0].conclusion)) { + core.info("Skipping PR runtime reconciliation: exact CI attempt is metadata-only or lacks substantive native gate evidence."); + return; + } + const {data: latest} = await github.rest.actions.getWorkflowRun({ + ...context.repo, run_id: source.id, + }); + if (!matchesSource(latest)) { + core.warning("Skipping PR runtime reconciliation: CI attempt was superseded during classification."); + return; + } + sourcePrNumber = titleMatch[1]; + } + let currentBranch; + try { + currentBranch = await github.rest.git.getRef({ + ...context.repo, + ref: `heads/${refreshBranch}`, + }); + } catch (error) { + if (error.status !== 404) throw error; + core.info(`Skipping obsolete CI callback: branch ${refreshBranch} no longer exists.`); + return; + } + if (currentBranch.data.object?.sha !== refreshSha) { + core.warning(`Skipping PR base refresh: ${refreshBranch} advanced beyond the completed CI callback ${refreshSha}.`); + return; + } + + // Protected push callbacks own dependent fan-out; PR callbacks for + // those heads still reconcile their own exact source PR below. + const protectedPrHead = workflowRun.event === "pull_request" && + ["main", "develop"].includes(refreshBranch); + const pullRequests = protectedPrHead ? [] : await github.paginate( + github.rest.pulls.list, + { + ...context.repo, + state: "open", + base: refreshBranch, + per_page: 100, + }, + (response) => response.data + ); + const refreshTargets = []; + for (const listedPullRequest of pullRequests) { + if (listedPullRequest.state !== "open" || + listedPullRequest.base?.ref !== refreshBranch || + listedPullRequest.head?.repo?.full_name !== context.payload.repository.full_name || + listedPullRequest.base?.repo?.full_name !== context.payload.repository.full_name) { + continue; + } + const resolved = await resolveExactMerge(listedPullRequest.number); + if (resolved) { + refreshTargets.push(resolved); + } + } + if (workflowRun.event === "pull_request") { + // A retarget/edit can carry an unusable event merge SHA. CI completion + // is only a reconcile signal: re-read its source's current exact tuple. + const sourcePullRequests = await github.paginate( + github.rest.pulls.list, + { + ...context.repo, + state: "open", + head: `${context.repo.owner}:${refreshBranch}`, + per_page: 100, + }, + (response) => response.data + ); + for (const source of sourcePullRequests) { + if (String(source.number) !== sourcePrNumber || + source.state !== "open" || source.head?.sha !== refreshSha || + source.head?.ref !== refreshBranch || + source.head?.repo?.full_name !== context.payload.repository.full_name || + source.base?.repo?.full_name !== context.payload.repository.full_name || + typeof source.base?.ref !== "string" || + source.base.ref.length === 0) { + continue; + } + const sourceBase = await github.rest.git.getRef({ + ...context.repo, + ref: `heads/${source.base.ref}`, + }); + const sourceBaseSha = sourceBase.data.object?.sha; + if (!shaPattern.test(sourceBaseSha || "")) { + core.warning(`Skipping source PR #${source.number}: current base ref SHA is invalid.`); + continue; + } + const resolved = await resolveExactMerge(source.number, source.base.ref, sourceBaseSha, refreshSha); + if (resolved && !refreshTargets.some((target) => target.tuple.prNumber === resolved.tuple.prNumber)) { + refreshTargets.push(resolved); + } + } + } + const pendingVisibility = []; + let visibilitySince; + let runtimeInventoryPromise; + let runtimeInventoryError = null; + for (const resolved of refreshTargets) { + const {tuple, pullRequest} = resolved; + let runtimeChanges; + try { + runtimeChanges = await hasRuntimeChange(pullRequest); + } catch (error) { + core.setFailed(`Cannot verify runtime changed files for PR #${tuple.prNumber}; no dispatch issued: ${error.message || error}`); + } + runtimeRefresh: if (runtimeChanges) { + let existingProducers = []; + let fallbackReason = null; + let inventory; + if (runtimeInventoryError) { + fallbackReason = runtimeInventoryError; + } else { + try { + runtimeInventoryPromise ??= loadExistingRuntimeRuns(); + inventory = await runtimeInventoryPromise; + } catch (error) { + fallbackReason = error.message || String(error); + runtimeInventoryError = fallbackReason; + } + } + if (!fallbackReason) { + try { + existingProducers = findExactExistingProducer(tuple, inventory); + if (!inventory.complete) { + // The REST contract does not specify a sort order, so a truncated page cannot prove omitted runs are older. + existingProducers = []; + fallbackReason = inventory.reason || "recent run inventory is incomplete"; + } else if (existingProducers.length === 0 && inventory.absenceProven === false) { + fallbackReason = "truncated initial inventory cannot prove exact producer absence from a narrower refinement"; + } + } catch (error) { + fallbackReason = error.message || String(error); + } + } + if (fallbackReason) { + core.setFailed(`Cannot verify exact runtime producer inventory for PR #${tuple.prNumber}; no dispatch issued: ${fallbackReason}`); + runtimeInventoryPromise = undefined; + runtimeInventoryError = null; + break runtimeRefresh; + } + if (existingProducers.length > 0) { + const producer = existingProducers[0]; + core.info( + `Skipping duplicate PR runtime refresh for #${tuple.prNumber}: exact tuple producer ${producer.id} remains ${producer.status}.` + ); + } else { + core.info(`No reusable in-flight exact producer was verified in the bounded recent inventory; dispatching required PR runtime refresh for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); + // Refresh tuple custody after preceding fan-out/API work under the shared dispatcher lock. + let current; + try { + current = await resolveExactMerge(tuple.prNumber, tuple.baseRef, tuple.baseSha, tuple.headSha); + } catch (error) { + core.setFailed(`Cannot verify runtime tuple for PR #${tuple.prNumber}; no dispatch issued: ${error.message || error}`); + break runtimeRefresh; + } + if (!current || current.tuple.mergeSha !== tuple.mergeSha) { + core.info(`Skipping changed runtime tuple for PR #${tuple.prNumber}.`); + continue; + } + let currentBase; + try { + ({data: currentBase} = await github.rest.git.getRef({...context.repo, ref: `heads/${tuple.baseRef}`})); + } catch (error) { + core.setFailed(`Cannot read current base for PR #${tuple.prNumber}: ${error.message || error}`); + break runtimeRefresh; + } + if (currentBase.object?.sha !== tuple.baseSha) { + core.info(`Skipping changed runtime tuple for PR #${tuple.prNumber}.`); + continue; + } + const previousIds = new Set(inventory?.runs?.map(run => run.id) || []); + const dispatchSince = new Date(Date.now() - 1000).toISOString(); + const pending = {tuple, previousIds, dispatchSince, responseUnknown: false}; + visibilitySince ??= dispatchSince; + pendingVisibility.push(pending); + try { + await github.rest.repos.createDispatchEvent({ + ...context.repo, + event_type: "pr-runtime-base-refresh", + client_payload: { + pr_number: tuple.prNumber, + base_ref: tuple.baseRef, + base_sha: tuple.baseSha, + head_sha: tuple.headSha, + merge_sha: tuple.mergeSha, + }, + }); + } catch (error) { + // Repository dispatch documents 404 and 422 as rejected requests; 401 is invalid authentication. + // A transport error or retryable response is not proof of rejection. + if ([401, 404, 422].includes(error?.status) && error.response?.status === error.status && + !error.response.headers?.["retry-after"] && error.response.headers?.["x-ratelimit-remaining"] !== "0") { + pendingVisibility.pop(); + if (!pendingVisibility.length) visibilitySince = undefined; + core.setFailed(`Runtime refresh POST rejected for PR #${tuple.prNumber}; no retry issued: ${error.message || error}`); + break runtimeRefresh; + } + pending.responseUnknown = true; + core.setFailed(`Runtime refresh handoff for PR #${tuple.prNumber} is uncertain; no retry issued: ${error.message || error}`); + runtimeInventoryPromise = undefined; + break runtimeRefresh; + } + runtimeInventoryPromise = undefined; + } + } else if (runtimeChanges === false) { + core.info(`Skipping PR runtime image refresh for #${tuple.prNumber}: no runtime-changing files.`); + } + // Preview has its own exact-image proof. An uncertain runtime handoff must not suppress it. + let previewCurrent; + try { + previewCurrent = await resolveExactMerge(tuple.prNumber, tuple.baseRef, tuple.baseSha, tuple.headSha); + } catch (error) { + core.setFailed(`Cannot verify preview tuple for PR #${tuple.prNumber}; no dispatch issued: ${error.message || error}`); + continue; + } + if (!previewCurrent || previewCurrent.tuple.mergeSha !== tuple.mergeSha) continue; + if (!isPreviewEligible(previewCurrent.pullRequest)) { + core.info(`Skipping preview deploy reconciliation for #${tuple.prNumber}: target is not preview-eligible.`); + continue; + } + core.info(`Dispatching preview deploy reconciliation for #${tuple.prNumber} (${tuple.baseSha} / ${tuple.headSha} / ${tuple.mergeSha}).`); + try { + await github.rest.repos.createDispatchEvent({ + ...context.repo, + event_type: "preview-deploy", + client_payload: { + action: "deploy", + pr_number: tuple.prNumber, + base_ref: tuple.baseRef, + base_sha: tuple.baseSha, + head_sha: tuple.headSha, + merge_sha: tuple.mergeSha, + preview_domain: "preview.firedevops.net", + }, + }); + } catch (error) { + core.setFailed(`Preview reconciliation handoff for PR #${tuple.prNumber} is uncertain; no retry issued: ${error.message || error}`); + } + } + // One shared bounded observation window, not 120 seconds multiplied by the fan-out size. + // The dispatcher lock remains held; no POST is retried even when visibility is uncertain. + const visibilityDeadline = Date.now() + 120000; + while (pendingVisibility.length > 0) { + try { + const observed = await readInventory(visibilitySince, ["repository_dispatch"]); + if (!observed.complete) throw new Error("Accepted refresh has incomplete visibility; no retry issued"); + for (let index = pendingVisibility.length - 1; index >= 0; index--) { + const {tuple, previousIds, dispatchSince, responseUnknown} = pendingVisibility[index]; + const exactTitle = `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; + if (observed.runs.some(run => run.event === "repository_dispatch" && + run.display_title === exactTitle && !previousIds.has(run.id) && + validTimestamp(run.created_at) && Date.parse(run.created_at) >= Date.parse(dispatchSince))) { + pendingVisibility.splice(index, 1); + if (responseUnknown) core.info(`Runtime refresh for PR #${tuple.prNumber} became visible after an unknown POST response.`); + } + } + } catch (error) { + core.setFailed(`Runtime refresh visibility is uncertain; no retry issued: ${error.message || error}`); + break; + } + if (pendingVisibility.length === 0) break; + if (Date.now() >= visibilityDeadline) { + const dispatchState = pendingVisibility.some(item => item.responseUnknown) ? "attempted" : "accepted"; + core.setFailed(`Refresh dispatch ${dispatchState} but visibility is unknown for PRs ${pendingVisibility.map(item => item.tuple.prNumber).join(", ")}; no retry issued`); + break; + } + await new Promise(resolve => setTimeout(resolve, 5000)); + } + + build-base-image: + name: Build Runtime Base Image + needs: [image-meta] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + runs-on: ubuntu-latest + outputs: + digest: ${{ steps.select_base_image_digest.outputs.digest }} + permissions: + # This job publishes the shared runtime base image to GHCR. + contents: read + packages: write + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: ⬇️ Checkout Code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push runtime base image + id: build_base_image_first + continue-on-error: true + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: ./docker/base.Dockerfile + push: true + tags: ${{ needs.image-meta.outputs.base_image }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache + type=registry,ref=ghcr.io/benhook1013/firemud-base:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache,mode=max + type=gha,mode=max + + - name: Retry build and push runtime base image + id: build_base_image_retry + if: ${{ steps.build_base_image_first.outcome == 'failure' }} + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: ./docker/base.Dockerfile + push: true + tags: ${{ needs.image-meta.outputs.base_image }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache + type=registry,ref=ghcr.io/benhook1013/firemud-base:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/firemud-base:buildcache,mode=max + type=gha,mode=max + + - name: Select exact published runtime base digest + id: select_base_image_digest + if: ${{ !cancelled() }} + env: + FIRST_OUTCOME: ${{ steps.build_base_image_first.outcome }} + FIRST_DIGEST: ${{ steps.build_base_image_first.outputs.digest }} + RETRY_OUTCOME: ${{ steps.build_base_image_retry.outcome }} + RETRY_DIGEST: ${{ steps.build_base_image_retry.outputs.digest }} + run: | + set -euo pipefail + published_digests=() + if [[ "$FIRST_OUTCOME" == "success" ]]; then + published_digests+=("$FIRST_DIGEST") + fi + if [[ "$RETRY_OUTCOME" == "success" ]]; then + published_digests+=("$RETRY_DIGEST") + fi + if ((${#published_digests[@]} != 1)); then + echo "Expected exactly one successful runtime base-image publication digest." >&2 + exit 1 + fi + base_image_digest="${published_digests[0]}" + [[ "$base_image_digest" =~ ^sha256:[0-9a-f]{64}$ ]] || { + echo "Runtime base-image publisher returned an invalid sha256 digest." >&2 + exit 1 + } + echo "digest=$base_image_digest" >> "$GITHUB_OUTPUT" + + build-runtime-images: + name: Build Runtime Images (${{ matrix.service }}) + needs: [image-meta, build-base-image] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + runs-on: ubuntu-latest + permissions: + # This job publishes only unique staging service tags. Canonical aliases + # are written by publish-runtime-images after the exact candidate passes smoke. + contents: read + packages: write + strategy: + fail-fast: false + matrix: + service: + - account-service + - automation-scripting-service + - entity-management-service + - game-design-service + - game-logic-service + - game-session-service + - logging-admin-service + - social-groups-service + - spring-cloud-gateway + - tcp-proxy-service + - world-management-service + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: ⬇️ Checkout Code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: ⚙️ Set Up Java + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: ⚙️ Set Up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: false + + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + + - name: Build service JAR + run: bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- :${{ matrix.service }}:bootJar + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push runtime service image + id: build_runtime_image_first + continue-on-error: true + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: ./services/${{ matrix.service }}/build/libs + file: ./services/${{ matrix.service }}/Dockerfile + push: true + build-contexts: | + repo_root=. + build-args: | + BASE_IMAGE=ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }} + tags: ghcr.io/benhook1013/${{ matrix.service }}:${{ needs.image-meta.outputs.candidate_tag }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache,mode=max + type=gha,mode=max + + - name: Retry build and push runtime service image + if: ${{ steps.build_runtime_image_first.outcome == 'failure' }} + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: ./services/${{ matrix.service }}/build/libs + file: ./services/${{ matrix.service }}/Dockerfile + push: true + build-contexts: | + repo_root=. + build-args: | + BASE_IMAGE=ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }} + tags: ghcr.io/benhook1013/${{ matrix.service }}:${{ needs.image-meta.outputs.candidate_tag }} + cache-from: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:latest + type=gha + cache-to: | + type=registry,ref=ghcr.io/benhook1013/${{ matrix.service }}:buildcache,mode=max + type=gha,mode=max + + build-backup-verifier: + name: Build Backup Verifier Image + needs: [image-meta] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') }} + runs-on: ubuntu-latest + timeout-minutes: 15 + outputs: + image_id: ${{ steps.smoke.outputs.image_id }} + permissions: + contents: read + env: + BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Checkout trusted branch commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Load workflow tool versions + id: workflow-tool-versions + uses: ./.github/actions/load-workflow-tool-versions + + - name: Build backup verifier image + run: | + docker build \ + --file docker/backup-verifier.Dockerfile \ + --tag "$BACKUP_VERIFIER_IMAGE" \ + . + + - name: Smoke backup verifier image + id: smoke + env: + VELERO_VERSION: ${{ steps.workflow-tool-versions.outputs.velero-version }} + run: | + set -euo pipefail + bash ./dev-tools/backups/smoke-backup-verifier-image.sh "$BACKUP_VERIFIER_IMAGE" "$VELERO_VERSION" + image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" + [[ "$image_id" =~ ^sha256:[0-9a-f]{64}$ ]] || { + echo "Backup verifier image did not return an exact image ID." >&2 + exit 1 + } + echo "image_id=$image_id" >> "$GITHUB_OUTPUT" + + - name: Export exact verified backup verifier image artifact + env: + VERIFIED_IMAGE_ID: ${{ steps.smoke.outputs.image_id }} + run: | + set -euo pipefail + current_image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" + [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Backup verifier image changed after its smoke proof; refusing artifact export." >&2 + exit 1 + } + docker save "$BACKUP_VERIFIER_IMAGE" | gzip -1 > "$RUNNER_TEMP/backup-verifier.tar.gz" + + - name: Upload exact verified backup verifier image artifact + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: backup-verifier-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/backup-verifier.tar.gz + if-no-files-found: error + retention-days: 1 + + publish-backup-verifier: + name: Publish Trusted Backup Verifier Image + needs: [image-meta, build-backup-verifier] + if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-backup-verifier.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: read + packages: write + id-token: write + attestations: write + env: + BACKUP_VERIFIER_IMAGE_NAME: ghcr.io/benhook1013/backup-verifier + BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Checkout trusted publication commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Download exact verified backup verifier image artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: backup-verifier-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/backup-verifier-artifact + + - name: Load and verify exact backup verifier image + env: + BACKUP_VERIFIER_ARCHIVE: ${{ runner.temp }}/backup-verifier-artifact/backup-verifier.tar.gz + VERIFIED_IMAGE_ID: ${{ needs.build-backup-verifier.outputs.image_id }} + run: | + set -euo pipefail + [[ -f "$BACKUP_VERIFIER_ARCHIVE" ]] || { + echo "Verified backup verifier image artifact is missing." >&2 + exit 1 + } + gzip -dc "$BACKUP_VERIFIER_ARCHIVE" | docker load + loaded_image_id="$(docker image inspect --format '{{.Id}}' "$BACKUP_VERIFIER_IMAGE")" + [[ "$loaded_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Loaded backup verifier image does not match the exact verified build image." >&2 + exit 1 + } + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Publish exact verified backup verifier image + id: publish + run: | + set -euo pipefail + bash ./dev-tools/hosted/shared/push-verified-image.sh "$BACKUP_VERIFIER_IMAGE" + + - name: Attest trusted backup verifier image provenance + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-name: ${{ env.BACKUP_VERIFIER_IMAGE_NAME }} + subject-digest: ${{ steps.publish.outputs.digest }} + push-to-registry: true + create-storage-record: false + + build-hosted-identity-controller: + name: Build Trusted Hosted Identity Controller + needs: [image-meta, build-base-image] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-base-image.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 25 + outputs: + image_id: ${{ steps.smoke.outputs.image_id }} + permissions: + contents: read + packages: read + env: + CONTROLLER_IMAGE_NAME: ghcr.io/benhook1013/firemud-hosted-identity-controller + CONTROLLER_IMAGE: ghcr.io/benhook1013/firemud-hosted-identity-controller:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Checkout trusted branch commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up Java + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: false + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + + - name: Build controller JAR and image locally + run: | + set -euo pipefail + bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh --runner ./gradlew -- :hosted-environment-identity-controller:bootJar + docker build \ + --file services/hosted-environment-identity-controller/Dockerfile \ + --build-arg BASE_IMAGE="ghcr.io/benhook1013/firemud-base@${{ needs.build-base-image.outputs.digest }}" \ + --tag "$CONTROLLER_IMAGE" \ + services/hosted-environment-identity-controller/build/libs + + - name: Smoke exact controller image + id: smoke + run: | + set -euo pipefail + smoked_image_id="$(bash ./dev-tools/hosted/controller/smoke-paused-controller-image.sh "$CONTROLLER_IMAGE")" + local_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$smoked_image_id" == "$local_image_id" ]] || { + echo "Controller smoke did not execute the exact locally tagged image." >&2 + exit 1 + } + echo "image_id=$local_image_id" >> "$GITHUB_OUTPUT" + + - name: Export exact verified controller image artifact + env: + VERIFIED_IMAGE_ID: ${{ steps.smoke.outputs.image_id }} + run: | + set -euo pipefail + current_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Controller image changed after its smoke proof; refusing artifact export." >&2 + exit 1 + } + docker save "$CONTROLLER_IMAGE" | gzip -1 > "$RUNNER_TEMP/hosted-identity-controller.tar.gz" + + - name: Upload exact verified controller image artifact + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: hosted-identity-controller-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/hosted-identity-controller.tar.gz + if-no-files-found: error + retention-days: 1 + + publish-hosted-identity-controller: + name: Publish Trusted Hosted Identity Controller + needs: [image-meta, build-base-image, build-hosted-identity-controller] + if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && (needs.image-meta.outputs.head_branch == 'develop' || needs.image-meta.outputs.head_branch == 'main') && needs.image-meta.result == 'success' && needs.build-base-image.result == 'success' && needs.build-hosted-identity-controller.result == 'success' }} + runs-on: ubuntu-latest + timeout-minutes: 25 + permissions: + contents: read + packages: write + id-token: write + attestations: write + env: + CONTROLLER_IMAGE_NAME: ghcr.io/benhook1013/firemud-hosted-identity-controller + CONTROLLER_IMAGE: ghcr.io/benhook1013/firemud-hosted-identity-controller:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Checkout trusted publication commit + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Download exact verified controller image artifact + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 + with: + name: hosted-identity-controller-${{ needs.image-meta.outputs.image_tag }} + path: ${{ runner.temp }}/hosted-identity-controller-artifact + + - name: Load and verify exact controller image + env: + CONTROLLER_ARCHIVE: ${{ runner.temp }}/hosted-identity-controller-artifact/hosted-identity-controller.tar.gz + VERIFIED_IMAGE_ID: ${{ needs.build-hosted-identity-controller.outputs.image_id }} + run: | + set -euo pipefail + [[ -f "$CONTROLLER_ARCHIVE" ]] || { + echo "Verified hosted identity controller image artifact is missing." >&2 + exit 1 + } + gzip -dc "$CONTROLLER_ARCHIVE" | docker load + loaded_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$loaded_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Loaded controller image does not match the exact verified build image." >&2 + exit 1 + } + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Publish exact verified controller image + id: publish + env: + VERIFIED_IMAGE_ID: ${{ needs.build-hosted-identity-controller.outputs.image_id }} + run: | + set -euo pipefail + current_image_id="$(docker image inspect --format '{{.Id}}' "$CONTROLLER_IMAGE")" + [[ "$current_image_id" == "$VERIFIED_IMAGE_ID" ]] || { + echo "Controller image changed after its verification proof; refusing publication." >&2 + exit 1 + } + bash ./dev-tools/hosted/shared/push-verified-image.sh "$CONTROLLER_IMAGE" + + - name: Attest trusted controller image provenance + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-name: ${{ env.CONTROLLER_IMAGE_NAME }} + subject-digest: ${{ steps.publish.outputs.digest }} + push-to-registry: true + create-storage-record: false + + pr-local-smoke: + outputs: + publishable: ${{ steps.runtime-artifact.outcome == 'success' }} + name: PR Full-Stack Smoke (runtime-required=${{ needs.image-meta.outputs.runtime_smoke_required }}) + needs: [image-meta] + if: ${{ (github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || github.event_name == 'repository_dispatch' }} + runs-on: ubuntu-latest + timeout-minutes: 45 + permissions: + # PR-controlled source receives no registry or repository write credential. + contents: read + env: + COMPOSE_PROJECT_NAME: smoke-full-${{ github.run_id }}-${{ github.run_attempt }} + SMOKE_TIMEOUT_SECONDS: 20 + SMOKE_IMAGE_TAG: ${{ needs.image-meta.outputs.image_tag }} + SMOKE_IMAGE_LOCAL_ONLY: 'true' + SMOKE_MINIO_LOCAL_ONLY: 'true' + SMOKE_MINIO_SERVER_IMAGE: >- + firemud-minio-server-smoke:${{ github.run_id }}-${{ github.run_attempt }} + SMOKE_MINIO_CLIENT_IMAGE: >- + firemud-minio-client-smoke:${{ github.run_id }}-${{ github.run_attempt }} + BACKUP_VERIFIER_IMAGE: ghcr.io/benhook1013/backup-verifier:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Checkout PR merge + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Load workflow tool versions + id: workflow-tool-versions + uses: ./.github/actions/load-workflow-tool-versions + + - name: Set up canonical Python + if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} + uses: ./.github/actions/setup-python + with: + requirements: smoke + + - name: Set up Java + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: true + + - name: Build local PR runtime images + id: runtime-images-build + env: + MERGE_SHA: ${{ needs.image-meta.outputs.merge_sha }} + run: | + set -euo pipefail + bash ./dev-tools/build-local-smoke-images.sh "$MERGE_SHA" + for service in \ + account-service \ + automation-scripting-service \ + entity-management-service \ + game-design-service \ + game-logic-service \ + game-session-service \ + logging-admin-service \ + social-groups-service \ + spring-cloud-gateway \ + tcp-proxy-service \ + world-management-service; do + docker tag \ + "ghcr.io/benhook1013/${service}:${MERGE_SHA}" \ + "ghcr.io/benhook1013/${service}:${SMOKE_IMAGE_TAG}" + done + + - name: Retain runtime bootJar compile-failure evidence + if: ${{ failure() && steps.runtime-images-build.outcome == 'failure' }} + continue-on-error: true + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: runtime-bootjar-compile-failure-${{ github.run_id }}-attempt-${{ github.run_attempt }} + path: ${{ steps.runtime-images-build.outputs.runtime_compile_failure_path || format('build/reports/compile-failure/runtime-bootjar/unavailable-{0}-{1}', github.run_id, github.run_attempt) }} + if-no-files-found: warn + retention-days: 3 + + - name: Build PR backup verifier image + run: | + docker build \ + --file docker/backup-verifier.Dockerfile \ + --tag "$BACKUP_VERIFIER_IMAGE" \ + . + + - name: Smoke PR backup verifier image + env: + VELERO_VERSION: ${{ steps.workflow-tool-versions.outputs.velero-version }} + run: bash ./dev-tools/backups/smoke-backup-verifier-image.sh "$BACKUP_VERIFIER_IMAGE" "$VELERO_VERSION" + + - name: Build and smoke pinned MinIO sources for PR Compose + id: minio-source + if: >- + ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} + run: | + bash ./dev-tools/minio/build-and-smoke-images.sh \ + "$SMOKE_MINIO_SERVER_IMAGE" "$SMOKE_MINIO_CLIENT_IMAGE" + + - name: Run credential-free full-stack smoke + id: runtime-smoke + # The terminal guard admits only the classified, labeled transition failure. + continue-on-error: true + if: ${{ needs.image-meta.outputs.runtime_smoke_required == 'true' }} + env: + FIREMUD_SMOKE_ADMISSION_QUALIFICATION: held + SMOKE_MINIO_SERVER_IMAGE_ID: >- + ${{ steps.minio-source.outputs.server_image_id }} + SMOKE_MINIO_CLIENT_IMAGE_ID: >- + ${{ steps.minio-source.outputs.client_image_id }} + run: bash ./dev-tools/verify-smoke-images.sh --keep-running + + - name: Export fixed-tag preview image artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} + run: | + service_manifest=/tmp/pr-runtime-services.txt + provenance=/tmp/pr-runtime-provenance.json + : > "$service_manifest" + images=() + for service in \ + account-service \ + automation-scripting-service \ + entity-management-service \ + game-design-service \ + game-logic-service \ + game-session-service \ + logging-admin-service \ + social-groups-service \ + spring-cloud-gateway \ + tcp-proxy-service \ + world-management-service; do + printf '%s\n' "$service" >> "$service_manifest" + images+=("ghcr.io/benhook1013/${service}:${SMOKE_IMAGE_TAG}") + done + printf '%s\n' 'backup-verifier' >> "$service_manifest" + images+=("$BACKUP_VERIFIER_IMAGE") + PR_NUMBER="${{ needs.image-meta.outputs.pr_number }}" \ + BASE_SHA="${{ needs.image-meta.outputs.base_sha }}" \ + HEAD_SHA="${{ needs.image-meta.outputs.head_sha }}" \ + MERGE_SHA="${{ needs.image-meta.outputs.merge_sha }}" \ + IMAGE_TAG="${SMOKE_IMAGE_TAG}" \ + SOURCE_RUN_ID="${{ github.run_id }}" \ + REPOSITORY="${GITHUB_REPOSITORY}" \ + PROVENANCE_PATH="$provenance" \ + python3 - <<'PY' + import json + import os + + services = [ + "account-service", + "automation-scripting-service", + "entity-management-service", + "game-design-service", + "game-logic-service", + "game-session-service", + "logging-admin-service", + "social-groups-service", + "spring-cloud-gateway", + "tcp-proxy-service", + "world-management-service", + "backup-verifier", + ] + provenance = { + "repository": os.environ["REPOSITORY"], + "prNumber": int(os.environ["PR_NUMBER"]), + "baseSha": os.environ["BASE_SHA"], + "headSha": os.environ["HEAD_SHA"], + "mergeSha": os.environ["MERGE_SHA"], + "imageTag": os.environ["IMAGE_TAG"], + "sourceRunId": int(os.environ["SOURCE_RUN_ID"]), + "services": services, + } + with open(os.environ["PROVENANCE_PATH"], "w", encoding="utf-8") as output: + json.dump(provenance, output, separators=(",", ":"), sort_keys=True) + output.write("\n") + PY + docker save "${images[@]}" | gzip -1 > /tmp/pr-runtime-images.tar.gz + + - name: Upload preview image artifact + id: runtime-artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: pr-runtime-images-${{ needs.image-meta.outputs.image_tag }} + path: | + /tmp/pr-runtime-images.tar.gz + /tmp/pr-runtime-services.txt + /tmp/pr-runtime-provenance.json + if-no-files-found: error + retention-days: 1 + + - name: Summarize secure PR runtime artifact + if: ${{ success() && (needs.image-meta.outputs.runtime_smoke_required == 'false' || steps.runtime-smoke.outcome == 'success') }} + env: + PR_NUMBER: ${{ needs.image-meta.outputs.pr_number }} + BASE_SHA: ${{ needs.image-meta.outputs.base_sha }} + HEAD_SHA: ${{ needs.image-meta.outputs.head_sha }} + MERGE_SHA: ${{ needs.image-meta.outputs.merge_sha }} + ARTIFACT_NAME: pr-runtime-images-${{ needs.image-meta.outputs.image_tag }} + run: | + { + echo "### PR runtime images and applicable full-stack smoke" + echo + echo "- Pull request: #${PR_NUMBER}" + echo "- Base SHA: \`${BASE_SHA}\`" + echo "- PR head SHA: \`${HEAD_SHA}\`" + echo "- Built PR merge SHA (full-stack smoke runs when required): \`${MERGE_SHA}\`" + echo "- Merge-scoped publication tag: \`pr-merge-${MERGE_SHA}\`" + echo "- Artifact: \`${ARTIFACT_NAME}\`" + echo + echo "This read-only PR workflow built the PR merge commit and runs full-stack smoke when required by change scope. The trusted default-branch publisher uploads only the exact merge-scoped artifact from this successful run." + } >> "$GITHUB_STEP_SUMMARY" + + - name: Dump Docker Compose logs on failure + if: >- + ${{ always() && steps.runtime-smoke.outcome == 'failure' && + needs.image-meta.outputs.runtime_smoke_required == 'true' && + steps.minio-source.outputs.server_image_id != '' && + steps.minio-source.outputs.client_image_id != '' }} + env: + SMOKE_MINIO_SERVER_IMAGE_ID: >- + ${{ steps.minio-source.outputs.server_image_id }} + SMOKE_MINIO_CLIENT_IMAGE_ID: >- + ${{ steps.minio-source.outputs.client_image_id }} + run: | + docker compose \ + -f docker/docker-compose.yml \ + -f docker/docker-compose.override.yml \ + -f docker/docker-compose.smoke-images.override.yml \ + -f docker/docker-compose.pr-local-minio.override.yml \ + logs || true + + - name: Stop smoke stack + id: runtime-cleanup + if: >- + ${{ always() && + needs.image-meta.outputs.runtime_smoke_required == 'true' && + steps.minio-source.outputs.server_image_id != '' && + steps.minio-source.outputs.client_image_id != '' }} + env: + SMOKE_MINIO_SERVER_IMAGE_ID: >- + ${{ steps.minio-source.outputs.server_image_id }} + SMOKE_MINIO_CLIENT_IMAGE_ID: >- + ${{ steps.minio-source.outputs.client_image_id }} + run: | + source ./dev-tools/smoke/run-owned-compose.sh + if ! stop_run_owned_compose_project \ + -f docker/docker-compose.yml \ + -f docker/docker-compose.override.yml \ + -f docker/docker-compose.smoke-images.override.yml \ + -f docker/docker-compose.pr-local-minio.override.yml; then + echo "Unable to prove or release the smoke Compose project; refusing unowned teardown." >&2 + exit 1 + fi + + # Canonical-transition diagnostic evidence, not runtime qualification. The + # native smoke outcome remains failed; only the bounded CI exception may pass. + - name: Known canonical transition PLAY failure with successful authenticated cleanup + id: canonical-play-transition + if: >- + ${{ always() && + github.repository == 'benhook1013/FireMUD' && + ((github.event_name == 'pull_request' && + contains(github.event.pull_request.labels.*.name, 'canonical-play-transition')) || + (github.event_name == 'repository_dispatch' && + github.event.action == 'pr-runtime-base-refresh' && + needs.image-meta.outputs.canonical_play_transition == 'true')) && + needs.image-meta.outputs.runtime_smoke_required == 'true' && + steps.runtime-smoke.outcome == 'failure' && + steps.runtime-smoke.outputs.known_play_failure == 'direct-backend-play-entitlement-unavailable-after-login' && + steps.runtime-cleanup.outcome == 'success' }} + run: | + echo '### Canonical PLAY transition exception evidence' >> "$GITHUB_STEP_SUMMARY" + echo 'LOGIN succeeded; direct backend PLAY failed: ERROR ENTITLEMENT_UNAVAILABLE. Held-admission qualification and authenticated cleanup passed. No runtime qualification, image export, or publication.' >> "$GITHUB_STEP_SUMMARY" + + - name: Require successful runtime smoke and authenticated cleanup + if: ${{ always() }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + env: + RUNTIME_SMOKE_REQUIRED: ${{ needs.image-meta.outputs.runtime_smoke_required }} + RUNTIME_SMOKE_OUTCOME: ${{ steps.runtime-smoke.outcome }} + RUNTIME_CLEANUP_OUTCOME: ${{ steps.runtime-cleanup.outcome }} + KNOWN_PLAY_EXCEPTION_OUTCOME: ${{ steps.canonical-play-transition.outcome }} + with: + script: | + const required = process.env.RUNTIME_SMOKE_REQUIRED; + if (required !== "true" && required !== "false") { + core.setFailed("Runtime smoke scope is unavailable or invalid."); + } else if (required === "true" && ( + process.env.RUNTIME_CLEANUP_OUTCOME !== "success" || + (process.env.RUNTIME_SMOKE_OUTCOME !== "success" && !( + process.env.RUNTIME_SMOKE_OUTCOME === "failure" && + process.env.KNOWN_PLAY_EXCEPTION_OUTCOME === "success" + )) + )) { + core.setFailed("Required runtime smoke and authenticated cleanup must both execute successfully, unless the exact canonical PLAY transition exception is attested."); + } else if (required === "true" && process.env.RUNTIME_SMOKE_OUTCOME === "failure") { + core.warning("CI passed under the canonical PLAY transition exception. Runtime qualification and image publication remain blocked."); + } + + pr-controller-smoke: + name: PR Hosted Identity Controller Smoke + needs: [image-meta] + if: ${{ ((github.event_name == 'pull_request' && (github.event.action != 'edited' || github.event.changes.base.ref != null)) || github.event_name == 'repository_dispatch') && needs.image-meta.outputs.controller_smoke_required == 'true' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + # PR-controlled source receives no registry or repository write credential. + contents: read + env: + BASE_IMAGE: ${{ needs.image-meta.outputs.base_image }} + CONTROLLER_IMAGE: firemud-hosted-identity-controller-local:${{ needs.image-meta.outputs.image_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Checkout PR merge + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up Java + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + with: + distribution: 'temurin' + java-version: '25' + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + build-scan-publish: true + build-scan-terms-of-use-url: 'https://gradle.com/help/legal-terms-of-use' + build-scan-terms-of-use-agree: 'yes' + cache-read-only: true + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Build exact local runtime base image + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: docker/base.Dockerfile + push: false + load: true + tags: ${{ env.BASE_IMAGE }} + cache-from: type=gha,scope=pr-controller-smoke + cache-to: type=gha,mode=max,scope=pr-controller-smoke + + - name: Set up Python for Gradle recovery + uses: ./.github/actions/setup-python + with: + requirements: none + + - name: Build controller image for credential-free local validation + run: | + set -euo pipefail + bash ./dev-tools/validation/run-gradle-with-dependency-recovery.sh \ + --runner ./gradlew -- :hosted-environment-identity-controller:bootJar + docker build \ + --file services/hosted-environment-identity-controller/Dockerfile \ + --build-arg BASE_IMAGE="$BASE_IMAGE" \ + --tag "$CONTROLLER_IMAGE" \ + services/hosted-environment-identity-controller/build/libs + + - name: Smoke controller image entrypoint and paused health + run: | + set -euo pipefail + bash ./dev-tools/hosted/controller/smoke-paused-controller-image.sh "$CONTROLLER_IMAGE" >/dev/null + + dispatch-pr-runtime-publication: + name: Dispatch Trusted PR Runtime Publication + needs: [image-meta, pr-local-smoke, pr-controller-smoke] + if: ${{ always() && !cancelled() && github.event_name == 'repository_dispatch' && github.event.action == 'pr-runtime-base-refresh' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && needs.image-meta.result == 'success' && needs.pr-local-smoke.result == 'success' && needs.pr-local-smoke.outputs.publishable == 'true' && (needs.pr-controller-smoke.result == 'success' || (needs.image-meta.outputs.controller_smoke_required == 'false' && needs.pr-controller-smoke.result == 'skipped')) }} + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + # This trusted no-checkout job only sends an exact source-run handoff. + contents: write + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Dispatch exact runtime publication source + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 + with: + script: | + await github.rest.repos.createDispatchEvent({ + ...context.repo, + event_type: "pr-runtime-image-publication", + client_payload: { source_run_id: String(context.runId) }, + }); + + smoke-full: + name: Published Runtime Full-Stack Smoke + needs: [image-meta, build-runtime-images] + if: ${{ always() && github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.build-runtime-images.result == 'success' }} + permissions: + # The trusted branch smoke workflow only pulls the staged candidate images. + contents: read + packages: read + uses: ./.github/workflows/smoke-full.yml + with: + action: full + head_sha: ${{ needs.image-meta.outputs.head_sha }} + checkout_ref: ${{ needs.image-meta.outputs.checkout_ref }} + image_tag: ${{ needs.image-meta.outputs.candidate_tag }} + secrets: inherit + + publish-runtime-images: + name: Promote Smoke-Tested Runtime Images + needs: [image-meta, build-runtime-images, smoke-full] + if: ${{ github.event_name != 'pull_request' && github.event_name != 'repository_dispatch' && needs.image-meta.result == 'success' && needs.build-runtime-images.result == 'success' && needs.smoke-full.result == 'success' && (needs.image-meta.outputs.head_branch == 'main' || needs.image-meta.outputs.head_branch == 'develop') }} + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + packages: write + env: + HEAD_SHA: ${{ needs.image-meta.outputs.head_sha }} + HEAD_BRANCH: ${{ needs.image-meta.outputs.head_branch }} + CANDIDATE_TAG: ${{ needs.image-meta.outputs.candidate_tag }} + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + + - name: Checkout trusted publication source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.image-meta.outputs.checkout_ref }} + persist-credentials: false + + - name: Set up canonical GitHub CLI + uses: ./.github/actions/setup-gh + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Login to GHCR + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Promote smoke-tested service digests + env: + GH_TOKEN: ${{ github.token }} + GHCR_USERNAME: ${{ github.actor }} + GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + + services=( + account-service + automation-scripting-service + entity-management-service + game-design-service + game-logic-service + game-session-service + logging-admin-service + social-groups-service + spring-cloud-gateway + tcp-proxy-service + world-management-service + ) + + declare -A registry_tokens=() + registry_manifest_state() { + local image="$1" + local image_path="${image#ghcr.io/}" + local repository_path="${image_path%:*}" + local tag="${image_path##*:}" + local manifest_url="https://ghcr.io/v2/${repository_path}/manifests/${tag}" + local registry_token="${registry_tokens[$repository_path]:-}" + local status + + [[ -n "${GHCR_USERNAME:-}" && -n "${GHCR_TOKEN:-}" ]] || { + echo "GHCR credentials are unavailable for authenticated manifest preflight: $image" >&2 + return 1 + } + if [[ -z "$registry_token" ]]; then + if ! registry_token="$(curl --silent --show-error --location --fail \ + --connect-timeout 10 --max-time 30 \ + --user "${GHCR_USERNAME}:${GHCR_TOKEN}" \ + --get \ + --data-urlencode 'service=ghcr.io' \ + --data-urlencode "scope=repository:${repository_path}:pull" \ + --header 'Accept: application/json' \ + 'https://ghcr.io/token' | jq -er '.token // .access_token // empty')"; then + echo "GHCR bearer-token exchange failed for $image; refusing to infer absence." >&2 + return 1 + fi + registry_tokens["$repository_path"]="$registry_token" + fi + # `docker manifest inspect "$image"` conflates a 404 with auth, + # registry, and network failures, so it is never an absence check. + if ! status="$(curl --silent --show-error --location --head \ + --connect-timeout 10 --max-time 30 \ + --header "Authorization: Bearer ${registry_token}" \ + --header 'Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json' \ + --output /dev/null --write-out '%{http_code}' "$manifest_url")"; then + echo "Authenticated OCI manifest HEAD failed for $image; refusing to infer absence." >&2 + return 1 + fi + case "$status" in + 200) printf 'existing\n' ;; + 404) printf 'missing\n' ;; + *) + echo "Authenticated OCI manifest HEAD returned HTTP ${status} for $image; refusing to push." >&2 + return 1 + ;; + esac + } + + registry_digest() { + local image="$1" + local inspect_output inspect_status + local digest + if inspect_output="$(docker buildx imagetools inspect "$image")"; then + : + else + inspect_status=$? + echo "Unable to inspect exact registry digest for $image (imagetools exit $inspect_status); refusing to publish." >&2 + return "$inspect_status" + fi + digest="$(awk '$1 == "Digest:" && $2 ~ /^sha256:[0-9a-f]{64}$/ { print $2; exit }' <<<"$inspect_output")" + [[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]] || { + echo "Registry manifest for $image has no exact digest." >&2 + return 1 + } + printf '%s\n' "$digest" + } + + assert_current_branch_head() { + local current_sha + current_sha="$(gh api \ + "repos/${GITHUB_REPOSITORY}/git/ref/heads/${HEAD_BRANCH}" \ + --jq '.object.sha')" + [[ "$current_sha" == "$HEAD_SHA" ]] || { + echo "Refusing canonical runtime publication: ${HEAD_BRANCH} moved from ${HEAD_SHA} to ${current_sha}." >&2 + exit 1 + } + } + + promote_alias() { + local source="$1" target="$2" fixed="$3" + local source_digest existing_digest target_digest + source_digest="$(registry_digest "$source")" + local target_state + if ! target_state="$(registry_manifest_state "$target")"; then + echo "Immutable target preflight failed for $target; refusing to publish." >&2 + exit 1 + fi + if [[ "$target_state" == missing ]]; then + docker buildx imagetools create --tag "$target" "$source" + else + existing_digest="$(registry_digest "$target")" + if [[ "$fixed" == true && "$existing_digest" != "$source_digest" ]]; then + echo "Refusing to overwrite fixed runtime tag $target: existing digest $existing_digest differs from candidate $source_digest." >&2 + exit 1 + fi + if [[ "$existing_digest" != "$source_digest" ]]; then + docker buildx imagetools create --tag "$target" "$source" + fi + fi + target_digest="$(registry_digest "$target")" + [[ "$target_digest" == "$source_digest" ]] || { + echo "Promoted runtime tag $target does not match candidate digest $source_digest (got $target_digest)." >&2 + exit 1 + } + } + + for service in "${services[@]}"; do + candidate="ghcr.io/benhook1013/${service}:${CANDIDATE_TAG}" + sha_tag="ghcr.io/benhook1013/${service}:${HEAD_SHA}" + branch_tag="ghcr.io/benhook1013/${service}:${HEAD_BRANCH}" + + assert_current_branch_head + promote_alias "$candidate" "$sha_tag" true + assert_current_branch_head + promote_alias "$candidate" "$branch_tag" false + if [[ "$HEAD_BRANCH" == develop ]]; then + assert_current_branch_head + promote_alias "$candidate" "ghcr.io/benhook1013/${service}:latest" false + fi + done diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index da38e93d1b..b22951c554 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -497,11 +497,9 @@ python3 - "$ROOT_DIR" "$smoke_clock_fixture" <<'PY' from pathlib import Path import base64 import hashlib -import io import json import re import sys -import tarfile import yaml root = Path(sys.argv[1]) @@ -618,15 +616,11 @@ retained_refs = ( "3f19ad85ad2fa867b978ec009b078eb950ae1b97", "2c5bfc6129723cff130081a66a25986cf18555bc", ) -fixture = root / "dev-tools/tests/fixtures/trusted-runtime-workflow-definitions.txt" -retained_archive = io.BytesIO(base64.b64decode(fixture.read_bytes())) -with tarfile.open(fileobj=retained_archive, mode="r:xz") as archive: - retained_definitions = [] - for ref in retained_refs: - entry = archive.getmember(f"{ref}.yml") - if not entry.isfile(): - raise SystemExit(f"Historical runtime workflow bytes are absent for {ref}") - retained_definitions.append(base64.b64encode(archive.extractfile(entry).read()).decode("ascii")) +fixture = root / "dev-tools/tests/fixtures/trusted-runtime-workflow-definitions" +retained_definitions = [ + base64.b64encode((fixture / f"{ref}.yml").read_bytes()).decode("ascii") + for ref in retained_refs +] Path(sys.argv[2] + ".retained-producers.json").write_text(json.dumps(retained_definitions)) Path(sys.argv[2]).write_text(script) PY @@ -963,6 +957,7 @@ const repository = "example/firemud"; const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; async function scenario(kind, event = "pull_request") { let now = 1000, snapshots = 0, reads = 0; + let qualifiedAttemptReads = 0, observedBaseMove = false, waitedMillis = 0; const failures = [], refs = []; const context = {repo: {owner: "example", repo: "firemud"}, sha: merge, payload: { repository: {default_branch: "develop"}, @@ -1007,12 +1002,8 @@ async function scenario(kind, event = "pull_request") { if (kind === "not-required") job.name = "PR Full-Stack Smoke (runtime-required=false)"; if (kind === "step-skipped") job.steps = [{name: "Run credential-free full-stack smoke", status: "completed", conclusion: "skipped"}]; if (kind === "legacy-positive") job.steps = [{name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]; - if (kind === "failed-smoke-step") { - source.conclusion = job.conclusion = job.steps[1].conclusion = "failure"; - job.steps[1].conclusion = "failure"; - job.steps[3].conclusion = job.steps[4].conclusion = job.steps[5].conclusion = "skipped"; - job.steps[6].conclusion = "failure"; - } + if (kind === "failed-smoke-step") job.steps[1].conclusion = "failure"; + if (kind === "failed-run") source.conclusion = "failure"; const sourceMutations = { "wrong-repository": {repository: {full_name: "other/repo"}}, "wrong-workflow": {workflow_id: 8}, "wrong-path": {path: ".github/workflows/fake.yml"}, @@ -1025,7 +1016,9 @@ async function scenario(kind, event = "pull_request") { const github = {rest: { pulls: {get: async () => { reads += 1; - return {data: {state: "open", head: {sha: head}, base: {ref: kind === "stale-final" && reads > 3 ? "other" : "develop", sha: base}, merge_commit_sha: merge}}; + const moved = kind === "drift-during-final-attempt" && qualifiedAttemptReads >= 2; + observedBaseMove ||= moved; + return {data: {state: "open", head: {sha: head}, base: {ref: moved || kind === "stale-final" && reads > 3 ? "other" : "develop", sha: base}, merge_commit_sha: merge}}; }}, git: {getRef: async () => ({data: {ref: "refs/heads/develop", object: {sha: base}}})}, repos: { @@ -1041,7 +1034,10 @@ async function scenario(kind, event = "pull_request") { actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs, getWorkflow: async () => ({data: {id: 7, path: source.path, name: "Build Runtime Images"}}), - getWorkflowRun: async () => ({data: {...source, run_attempt: kind === "newer-attempt" ? 2 : 1}}), + getWorkflowRun: async () => { + if (refs.length) qualifiedAttemptReads++; + return {data: {...source, run_attempt: kind === "newer-attempt" ? 2 : 1}}; + }, }, }, request: async (route, input) => { assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"); @@ -1051,6 +1047,14 @@ async function scenario(kind, event = "pull_request") { if (method === listJobs) { snapshots += 1; return kind === "duplicate-jobs" ? [job, {...job, id: 101}] : [job]; } assert.equal(method, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); assert.equal(input.run_id, 42); assert.equal(input.attempt_number, 1); + snapshots++; + if (kind === "lagging-cleanup" && snapshots <= 2) { + return [{...job, steps: job.steps.filter(step => step.name !== "Stop smoke stack")}]; + } + if (kind === "lagging-terminal-guard" && snapshots <= 2) { + return [{...job, steps: job.steps.map(step => step.name === "Require successful runtime smoke and authenticated cleanup" + ? {...step, status: "in_progress", conclusion: null} : step)}]; + } const mutations = { "wrong-job": {id: 101}, "wrong-job-run": {run_id: 43}, "wrong-job-attempt": {run_attempt: 2}, "wrong-job-head": {head_sha: "e".repeat(40)}, "wrong-check-url": {check_run_url: "https://example.com/check"}, @@ -1068,8 +1072,8 @@ async function scenario(kind, event = "pull_request") { }; const clock = {now: () => now, parse: Date.parse}; await execute(github, context, {info: () => {}, warning: () => {}, setFailed: message => failures.push(message)}, - clock, (callback, duration) => {now += duration; queueMicrotask(callback);}, require); - return {failures, refs, snapshots}; + clock, (callback, duration) => {now += duration; waitedMillis += duration; queueMicrotask(callback);}, require); + return {failures, refs, snapshots, observedBaseMove, waitedMillis}; } (async () => { for (const event of ["pull_request", "repository_dispatch"]) { @@ -1080,7 +1084,7 @@ async function scenario(kind, event = "pull_request") { } assert.deepEqual((await scenario("legacy-positive")).failures, []); for (const kind of ["marker-missing", "marker-success", "legacy-missing", "not-required", "step-skipped", "wrong-repository", "wrong-workflow", - "wrong-path", "wrong-event", "wrong-head", "wrong-head-repository", "wrong-title", "wrong-source-attempt", "failed-smoke-step", + "wrong-path", "wrong-event", "wrong-head", "wrong-head-repository", "wrong-title", "wrong-source-attempt", "failed-smoke-step", "failed-run", "changed-definition", "unavailable-definition", "wrong-job", "wrong-job-run", "wrong-job-attempt", "wrong-job-head", "wrong-check-url", "failed-job", "pending-job", "duplicate-jobs", "duplicate-attempt-jobs", "newer-attempt", "bad-parents"]) { assert.equal((await scenario(kind, "repository_dispatch")).failures.length, 1, @@ -1089,6 +1093,13 @@ async function scenario(kind, event = "pull_request") { assert.equal((await scenario("wrong-dispatch-branch", "repository_dispatch")).failures.length, 1); const stale = await scenario("stale-final"); assert.deepEqual(stale.failures, [], "obsolete gate exits without publishing proof for changed base ref"); + for (const kind of ["lagging-cleanup", "lagging-terminal-guard"]) { + const result = await scenario(kind, "repository_dispatch"); + assert.deepEqual(result.failures, [], `${kind} must wait for exact terminal step evidence to converge`); + assert(result.snapshots >= 4 && result.waitedMillis > 0, `${kind} retries only after a bounded pause`); + } + const moved = await scenario("drift-during-final-attempt", "repository_dispatch"); + assert(moved.observedBaseMove, "typed acceptance must re-read the live base after the final attempt lookup"); console.log("Smoke producer contract passed: native outcomes, exact immutable definition/attempt, legacy proof and fail-closed cases"); })().catch(error => {console.error(error); process.exitCode = 1;}); NODE @@ -3704,6 +3715,10 @@ const fn = script.slice(start, end); const workflowPath = ".github/workflows/runtime-images.yml"; const isRuntimeSourceWorkflowPath = new Function("workflowPath", `${script.slice(start, script.indexOf("function isSuccessfulRuntimeWorkflowDefinition(", start))}; return isRuntimeSourceWorkflowPath;`)(workflowPath); +const evidencePendingStart = script.indexOf("function hasPendingCanonicalSmokeTerminalEvidence("); +const evidencePendingEnd = script.indexOf("// Canonical-transition diagnostic acceptance", evidencePendingStart); +const hasPendingCanonicalSmokeTerminalEvidence = new Function( + `${script.slice(evidencePendingStart, evidencePendingEnd)}; return hasPendingCanonicalSmokeTerminalEvidence;`)(); const repositoryName = "benhook1013/FireMUD"; const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; const canonicalRuntimeWorkflowSha256 = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); @@ -3970,7 +3985,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { const original = {...source, id: 98, event: "pull_request", status: "completed", conclusion: options.originalConclusion || "failure"}; const execute = new Function("repositoryName", "workflowPath", "isRuntimeSourceWorkflowPath", "github", "owner", "repo", "canonicalSmokeJobName", "withTransientGitHubRetry", "verifyKnownPlayFailure", - "verifyCanonicalSmokeProducer", "isTransientGitHubFailure", + "verifyCanonicalSmokeProducer", "isTransientGitHubFailure", "hasPendingCanonicalSmokeTerminalEvidence", "verifyFailedPullCanonicalRefresh", "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", "core", "resolveCurrentIdentity", "identityKey", "setTimeout", "sleepMs", "Date", "started", "timeoutMs", "pullRequestCheckInterval", "findMatchingRuntimeImagesRun", @@ -4003,7 +4018,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { assert.equal(required, true); return Boolean(options.ordinaryAfterDrift && proofIdentity.baseSha === options.finalIdentity.baseSha && proofIdentity.mergeSha === options.finalIdentity.mergeSha); - }, isTransientGitHubFailure, + }, isTransientGitHubFailure, hasPendingCanonicalSmokeTerminalEvidence, async (selectedRun, selectedIdentity) => { if (options.directSnapshots && selectedRun.event === "repository_dispatch") return false; assert.equal(selectedRun.id, original.id); @@ -4011,6 +4026,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { assert.equal(selectedIdentity.baseSha, identity.baseSha); assert.equal(selectedIdentity.mergeSha, identity.mergeSha); const status = statuses[Math.min(polls++, statuses.length - 1)]; + if (options.transientNested && polls === 1) throw Object.assign(new Error("temporary nested proof lookup"), {status: 502}); if (options.rejectedObject) return {status: "rejected", run: {id: 99, run_attempt: 2}}; if (options.proofDrift) { const result = await recoveredFailure({mutateProof(data) { @@ -4233,6 +4249,7 @@ function markerAccepted(overrides = {}) { const missing = Object.assign(new Error("missing"), {status: 404}); await assert.rejects(finalAttemptCheck(null, missing), error => error === missing); await pendingRefreshCaller(["completed", "completed"], false, {transientFinal: true}); + await pendingRefreshCaller(["completed", "completed"], false, {transientNested: true}); await movedCancellation(true); await movedCancellation(false); await movedCancellation(true, true); @@ -4342,10 +4359,10 @@ function markerAccepted(overrides = {}) { data.definitions[workflowPath].content = Buffer.from("wrong immutable producer").toString("base64"); data.definitions[workflowPath].size = Buffer.byteLength("wrong immutable producer"); }})).accepted, false, "an untrusted typed run must fail before waiting for omitted jobs"); - for (const suffix of ["@develop", "@refs/heads/develop"]) { + for (const suffix of ["@develop", "@refs/heads/develop", "@feature+metadata", "@feature@metadata", "@refs/heads/feature./test", "@feature/ā"]) { assert.equal(await verify(data => { data.source.path = workflowPath + suffix; }, "repository_dispatch", false), true); } - for (const path of [workflowPath + "@refs/heads/a..b", workflowPath + "@refs/tags/develop", ".github/workflows/other.yml@develop"]) { + for (const path of [workflowPath + "@refs/heads/a..b", workflowPath + "@refs/heads/trailing.", workflowPath + "@@", workflowPath + "@refs/tags/develop", ".github/workflows/other.yml@develop"]) { assert.equal(await verify(data => { data.source.path = path; }, "repository_dispatch", false), false); } const marker = "Known canonical transition PLAY failure with successful authenticated cleanup"; @@ -4666,7 +4683,8 @@ async function run(kind, shared = {visible: false, posts: 0}) { if (kind === "fork") event.head_repository.full_name = "fork/repo"; if (kind === "success") event.conclusion = "success"; const startClock = Date.parse(source.created_at); - let clock = startClock, tupleReads = 0, sourceReads = 0, metadataReads = 0, ciInventoryReads = 0, refreshInventoryReads = 0; + const sameSecond = ["same-second", "ambiguous-same-second"].includes(kind); + let clock = startClock + (sameSecond ? 200 : 0), tupleReads = 0, sourceReads = 0, metadataReads = 0, ciInventoryReads = 0, refreshInventoryReads = 0; const github = {rest: { actions: { getWorkflow: async ({workflow_id}) => ({data: workflow_id === "ci.yml" @@ -4716,6 +4734,7 @@ async function run(kind, shared = {visible: false, posts: 0}) { } if (kind === "post-read-forbidden") throw Object.assign(new Error("visibility forbidden"), {status: 403}); if (kind === "post-read-incomplete") return {data: {total_count: 1, workflow_runs: []}}; + if (kind === "ambiguous-same-second") runs = [refresh, {...refresh, id: refresh.id + 1}]; if (kind === "ambiguous-visible" && clock - startClock >= 5000) { shared.visible = true; runs = [refresh]; @@ -4748,7 +4767,8 @@ async function run(kind, shared = {visible: false, posts: 0}) { assert.deepEqual(payload, {owner: "example", repo: "firemud", event_type: "pr-runtime-base-refresh", client_payload: {pr_number: "42", base_ref: "develop", base_sha: base, head_sha: head, merge_sha: merge}}); shared.posts++; - shared.refreshCreatedAt = refresh.created_at = new Date(clock + 1000).toISOString(); + const createdTime = sameSecond ? Math.floor(clock / 1000) * 1000 : clock + 1000; + shared.refreshCreatedAt = refresh.created_at = new Date(createdTime).toISOString(); if (["ambiguous-post", "ambiguous-visible"].includes(kind)) throw new Error("unknown POST outcome"); if (kind === "rejected-post") throw Object.assign(new Error("validation rejected"), {status: 422, response: {status: 422}}); if (kind !== "invisible") shared.visible = true; @@ -4830,6 +4850,12 @@ async function run(kind, shared = {visible: false, posts: 0}) { } (async () => { assert.equal(await run("valid"), 1); + const sameSecondHandoff = {visible: false, posts: 0}; + assert.equal(await run("same-second", sameSecondHandoff), 1); + assert.equal(sameSecondHandoff.observations, 1, "a unique new exact run is visible in the POST's own timestamp second"); + const ambiguousSameSecond = {visible: false, posts: 0}; + await assert.rejects(run("ambiguous-same-second", ambiguousSameSecond), /dispatch outcome is ambiguous/); + assert.equal(ambiguousSameSecond.posts, 1, "ambiguous visibility must never repeat the POST"); assert.equal(await run("cancel-before-enforcement"), 1); assert.equal(await run("qualified-runtime"), 1); assert.equal(await run("wake-cancel-qualified"), 1); diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 81098068f0..ad8462a755 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -898,6 +898,7 @@ async function runDispatcher({ hideDispatchVisibility = false, filesByPr = {}, postFailurePr = null, previewFailurePr = null, visibilityResponse = null, filesFailurePr = null, postFailureVisible = false, postFailureStatus = null, fanoutCutoffAfterInventory = false, fanoutCutoffAfterPreviewPr = null, expireAfterFirstApiRequest = false, + initialTime = "2026-01-08T00:00:00Z", }) { const dispatches = []; const postedRuns = []; @@ -911,7 +912,7 @@ async function runDispatcher({ const deadlineSignals = []; const apiRequestRecords = []; let waitedMillis = 0; - let fakeNow = Date.parse("2026-01-08T00:00:00Z"); + let fakeNow = Date.parse(initialTime); let expireOnFirstRequest = expireAfterFirstApiRequest; const currentBaseSha = tuples[0]?.baseSha ?? baseSha; const allTuples = [...tuples, ...sourceTuples]; @@ -1368,6 +1369,7 @@ async function runDispatcher({ for (const event of ["pull_request", "repository_dispatch"]) { const completedSuccess = await runDispatcher({ tuples: [tuple], + callback: {updated_at: "2026-01-02T00:00:00Z"}, inventories: { [event]: [producer(tuple, event, "completed", "success")] }, }); assert.equal(completedSuccess.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 1, @@ -1378,6 +1380,7 @@ async function runDispatcher({ "main", "refs/heads/feature]/test", "refs/heads/feature/@/test", + "refs/heads/feature./test", ]) { const refSuffixedPath = await runDispatcher({ tuples: [tuple], @@ -1388,7 +1391,7 @@ async function runDispatcher({ assert.equal(refSuffixedPath.dispatches.filter((item) => item.event_type === "pr-runtime-base-refresh").length, 0, `the exact owning workflow path with valid Git ref ${validRef} must remain eligible`); } - for (const invalidRef of ["@", "refs/heads/trailing.", "refs/heads/feature./test", "refs/heads/feature[/test"]) { + for (const invalidRef of ["@", "refs/heads/trailing.", "refs/heads/feature/.hidden", "refs/heads/feature[/test"]) { const invalidRefPath = await runDispatcher({ tuples: [tuple], inventories: { pull_request: [producer(tuple, "pull_request", "in_progress", null, { @@ -1649,14 +1652,14 @@ async function runDispatcher({ "unknown inventory must be an explicit error, not apparent success"); } - for (const [signalAt, expected] of [["2026-01-02T00:00:00Z", 0], ["2026-01-04T00:00:00Z", 1]]) { + for (const [signalAt, expected] of [["2026-01-02T00:00:00Z", 0], ["2026-01-03T00:00:00.200Z", 0], ["2026-01-04T00:00:00Z", 1]]) { const result = await runDispatcher({ tuples: [tuple], callback: { updated_at: signalAt }, inventories: { repository_dispatch: [producer(tuple, "repository_dispatch", "completed", "success", { created_at: "2026-01-03T00:00:00Z", })] }, }); - assert.equal(numbers(result).length, expected, "completed refresh suppresses only an earlier signal"); + assert.equal(numbers(result).length, expected, "completed refresh suppresses an earlier or same-second signal"); } const invisible = await runDispatcher({ tuples: [tuple], hideDispatchVisibility: true }); assert.deepEqual(numbers(invisible), ["101"], "accepted invisible POST must never be repeated"); @@ -1678,6 +1681,21 @@ async function runDispatcher({ "broad preflight still checks native producers"); assert(manyInvisible.inventoryCalls.some(request => request.event === "repository_dispatch" && request.created !== visibilityFloor), "broad preflight still checks existing dispatch producers"); + const sameSecond = await runDispatcher({tuples: [tuple], initialTime: "2026-01-08T00:00:00.200Z", + visibilityResponse: (_request, [posted]) => ({total_count: 1, + workflow_runs: [{...posted, created_at: "2026-01-08T00:00:00Z"}]}), + }); + assert.deepEqual(numbers(sameSecond), ["101"]); + assert.deepEqual(sameSecond.errors, [], "a unique new exact run in the POST's timestamp second is visible"); + assert.equal(sameSecond.waitedMillis, 0); + const ambiguousSameSecond = await runDispatcher({tuples: [tuple], initialTime: "2026-01-08T00:00:00.200Z", + visibilityResponse: (_request, [posted]) => ({total_count: 2, workflow_runs: [ + {...posted, created_at: "2026-01-08T00:00:00Z"}, + {...posted, id: posted.id + 1, created_at: "2026-01-08T00:00:00Z"}, + ]}), + }); + assert.deepEqual(numbers(ambiguousSameSecond), ["101"], "ambiguous handoff never repeats the POST"); + assert(ambiguousSameSecond.errors.some(error => error.includes("multiple new exact runtime handoffs"))); const transientTuples = [tuple, tupleFor(102, "a", "c")]; let transientReads = 0; const transient = await runDispatcher({tuples: transientTuples, visibilityResponse: (_request, posted) => { @@ -3086,9 +3104,10 @@ const quota = (reset, remaining = "0") => ({ status: 403, response: { headers: { }); NODE -node - "$smoke_gate_script" <<'NODE' +node - "$smoke_gate_script" "$runtime_images_path" <<'NODE' const fs = require("node:fs"); const script = fs.readFileSync(process.argv[2], "utf8"); +const runtimeImagesPath = process.argv[3]; const headSha = "a".repeat(40); const baseSha = "b".repeat(40); const mergeSha = "c".repeat(40); @@ -3204,7 +3223,7 @@ const github = { if (path !== ".github/workflows/runtime-images.yml" || !availableRuns.some(row => row.event === "repository_dispatch" && row.head_sha === ref)) { throw new Error("typed runtime proof must pin its executed workflow definition"); } - const bytes = fs.readFileSync(path); + const bytes = fs.readFileSync(runtimeImagesPath); return {data: {type: "file", path, size: bytes.length, encoding: "base64", content: bytes.toString("base64")}}; }, getCommit: async ({ ref }) => { diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index d91dc8c98d..513ad38ee5 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -996,6 +996,7 @@ for valid_ref in \ "refs/heads/develop" \ "refs/heads/feature]/test" \ "refs/heads/feature/@/test" \ + "refs/heads/feature./test" \ "$head_sha"; do set_source_run_path ".github/workflows/runtime-images.yml@$valid_ref" run_validation || { @@ -1011,7 +1012,7 @@ for invalid_path in \ '.github/workflows/runtime-images.yml@@' \ '.github/workflows/runtime-images.yml@refs/heads/trailing.' \ '.github/workflows/runtime-images.yml@refs/heads/feature[/test' \ - '.github/workflows/runtime-images.yml@refs/heads/feature./test' \ + '.github/workflows/runtime-images.yml@refs/heads/feature/.hidden' \ '.github/workflows/runtime-images.yml@.hidden' \ '.github/workflows/runtime-images.yml@feature/.lock'; do set_source_run_path "$invalid_path" diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index 57901229bd..8d64011910 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -162,6 +162,8 @@ Result rearm(Request prior, Request next, UUID recoveryOwner, long claimFence) { || row.get("owner_readback", byte[].class) == null) throw conflict(); current(next); requireSupportedShape(next); + // Match the fresh reservation/refusal path before arbitrating the attempt UUID. + capacity.usage(next); originDecisions.accept(next); requireClaim(row, recoveryOwner, claimFence, clock.instant()); requireCurrentLifetime(next.evidence(), clock.instant()); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreatorBootstrapIntegrationFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreatorBootstrapIntegrationFixture.java new file mode 100644 index 0000000000..81891652b8 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountTenantCreatorBootstrapIntegrationFixture.java @@ -0,0 +1,89 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.UUID; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Completion; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; + +public final class AccountTenantCreatorBootstrapIntegrationFixture { + private AccountTenantCreatorBootstrapIntegrationFixture() {} + + public static StoredOperation claimBootstrap( + AccountTenantCreationBootstrapOperationRepository operations, + Account creator, + FreshTenantCreationEvidence creation) { + UUID accountId = creator.getAccountUuid(); + UUID authorizationId = UUID.randomUUID(); + String authorizationDigest = + AccountTenantCreationBootstrapDigest.sha256( + "fixture authorization".getBytes(StandardCharsets.UTF_8)); + var evidence = + new FreshTenantCreatorEvidence( + 1, + creation, + accountId, + authorizationId, + authorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, accountId, authorizationId, authorizationDigest)); + byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence); + byte[] sourcePayload = "fixture source snapshot".getBytes(StandardCharsets.UTF_8); + byte[] requestPayload = + AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, sourcePayload); + var claim = + operations.claim( + evidence, + creatorPayload, + sourcePayload, + AccountTenantCreationBootstrapDigest.sha256(sourcePayload), + requestPayload, + AccountTenantCreationBootstrapDigest.sha256(requestPayload), + 1, + 1); + assertThat(claim.claimed()).isTrue(); + return claim.operation(); + } + + public static Completion completion(StoredOperation operation) { + // Controlled completion receipts exercise the real storage owner's guarded transition. + byte[] event = "fixture membership event".getBytes(StandardCharsets.UTF_8); + byte[] audit = "fixture bootstrap audit".getBytes(StandardCharsets.UTF_8); + byte[] result = "fixture bootstrap result".getBytes(StandardCharsets.UTF_8); + return new Completion( + 1, + operation.baselineMembershipVersion() + 1, + operation.baselineMembershipAuthorityGeneration(), + "ACTIVE", + false, + "[\"tenantAdmin\"]".getBytes(StandardCharsets.UTF_8), + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + operation.initiatingAccountUuid() + + "/" + + operation.tenantUuid(), + operation.requestId().toString(), + 1, + "fixture-membership-event", + AccountTenantCreationBootstrapDigest.sha256(event), + false, + event, + UUID.randomUUID(), + "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED", + Instant.now().truncatedTo(ChronoUnit.MICROS), + AccountTenantCreationBootstrapDigest.sha256(audit), + audit, + result, + AccountTenantCreationBootstrapDigest.sha256(result)); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index 027fbd0216..45715fac90 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import integration.net.firedevops.firemud.accountservice.AccountTenantCreatorBootstrapIntegrationFixture; import java.nio.charset.StandardCharsets; import java.time.Instant; import java.time.temporal.ChronoUnit; @@ -13,15 +14,9 @@ import net.firedevops.firemud.accountservice.repository.AccountCapacityRefusalBudgetRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest; import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Completion; -import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; -import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; -import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.flywaydb.core.Flyway; import org.jooq.SQLDialect; @@ -259,7 +254,7 @@ void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { Objects.requireNonNull( transaction.execute(status -> { repository.importVerified(existing); - return claimBootstrap( + return AccountTenantCreatorBootstrapIntegrationFixture.claimBootstrap( operations, new AccountRepository(dsl).save(creator()), existing); })); assertThat(historical.status()).isEqualTo("IN_PROGRESS"); @@ -287,7 +282,9 @@ void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { assertThat(operation.status()).isEqualTo("IN_PROGRESS"); assertThat(operation.creationOperationId()).isEqualTo(existing.operationId()); assertThat(operation.requestPayload()).isEqualTo(historical.requestPayload()); - return operations.complete(operation.requestId(), completion(operation)); + return operations.complete( + operation.requestId(), + AccountTenantCreatorBootstrapIntegrationFixture.completion(operation)); })); assertThat(completed.status()).isEqualTo("COMMITTED"); assertThat(completed.tenantUuid()).isEqualTo(existing.canonicalTenantId()); @@ -645,10 +642,13 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { transaction.executeWithoutResult(status -> { new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(acceptedTenant); var claimed = - claimBootstrap(operations, new AccountRepository(dsl).save(creator()), acceptedTenant); + AccountTenantCreatorBootstrapIntegrationFixture.claimBootstrap( + operations, new AccountRepository(dsl).save(creator()), acceptedTenant); var current = operations.findForUpdate(claimed.requestId()).orElseThrow(); assertThat(current.status()).isEqualTo("IN_PROGRESS"); - operations.complete(current.requestId(), completion(current)); + operations.complete( + current.requestId(), + AccountTenantCreatorBootstrapIntegrationFixture.completion(current)); }); UUID acceptedRequest = UUID.randomUUID(); @@ -791,7 +791,8 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { assertTenantCapacityInventoryMatches(dsl, acceptedTenant.canonicalTenantId()); var acceptedOriginsBeforeReplay = originRows(dsl, acceptedTenant.canonicalTenantId()); - var acceptedReservationsBeforeReplay = reservationRows(dsl, acceptedTenant.canonicalTenantId()); + var acceptedReservationsBeforeReplay = + reservationRows(dsl, acceptedTenant.canonicalTenantId()); var acceptedUsageBeforeReplay = usageRows(dsl, acceptedTenant.canonicalTenantId()); assertThat(acceptedOriginsBeforeReplay) .anySatisfy(row -> @@ -802,7 +803,8 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { .containsEntry("mutation_digest", acceptedAfterMigration.digest()) .containsEntry("decision", "ACCEPTED") .containsEntry( - "payload", java.util.HexFormat.of().formatHex(acceptedAfterMigration.payload()))); + "payload", + java.util.HexFormat.of().formatHex(acceptedAfterMigration.payload()))); assertThat(acceptedReservationsBeforeReplay) .anySatisfy(row -> assertThat(row) @@ -812,7 +814,8 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { .containsEntry("mutation_digest", acceptedAfterMigration.digest()) .containsEntry("capacity_delta", 1L) .containsEntry( - "payload", java.util.HexFormat.of().formatHex(acceptedAfterMigration.payload()))); + "payload", + java.util.HexFormat.of().formatHex(acceptedAfterMigration.payload()))); assertThat( dsl.execute( @@ -1129,8 +1132,8 @@ private static void assertTenantCapacityInventoryMatches( org.jooq.DSLContext dsl, UUID tenantUuid) { var rows = dsl.fetch( - "SELECT u.owner_service, u.held_units, u.used_units, COALESCE(sum(r.capacity_delta) FILTER (WHERE r.state IN ('RESERVED', 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION')), 0) AS reservation_held_units, COALESCE(sum(r.capacity_delta) FILTER (WHERE r.state = 'FINALIZED'), 0) AS reservation_used_units FROM account_tenant_capacity_usage u LEFT JOIN account_tenant_capacity_reservations r ON r.tenant_uuid = u.tenant_uuid AND r.owner_service = u.owner_service WHERE u.tenant_uuid = ? GROUP BY u.owner_service, u.held_units, u.used_units ORDER BY u.owner_service", - tenantUuid) + "SELECT u.owner_service, u.held_units, u.used_units, COALESCE(sum(r.capacity_delta) FILTER (WHERE r.state IN ('RESERVED', 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION')), 0) AS reservation_held_units, COALESCE(sum(r.capacity_delta) FILTER (WHERE r.state = 'FINALIZED'), 0) AS reservation_used_units FROM account_tenant_capacity_usage u LEFT JOIN account_tenant_capacity_reservations r ON r.tenant_uuid = u.tenant_uuid AND r.owner_service = u.owner_service WHERE u.tenant_uuid = ? GROUP BY u.owner_service, u.held_units, u.used_units ORDER BY u.owner_service", + tenantUuid) .intoMaps(); assertThat(rows).hasSize(2); for (var row : rows) { @@ -1168,74 +1171,6 @@ private static Account creator() { return account; } - private static StoredOperation claimBootstrap( - AccountTenantCreationBootstrapOperationRepository operations, - Account creator, - FreshTenantCreationEvidence creation) { - UUID accountId = creator.getAccountUuid(); - UUID authorizationId = UUID.randomUUID(); - String authorizationDigest = - AccountTenantCreationBootstrapDigest.sha256( - "fixture authorization".getBytes(StandardCharsets.UTF_8)); - var evidence = - new FreshTenantCreatorEvidence( - 1, - creation, - accountId, - authorizationId, - authorizationDigest, - FreshTenantCreatorDigest.evidenceDigest( - 1, creation, accountId, authorizationId, authorizationDigest)); - byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence); - byte[] sourcePayload = "fixture source snapshot".getBytes(StandardCharsets.UTF_8); - byte[] requestPayload = - AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, sourcePayload); - var claim = - operations.claim( - evidence, - creatorPayload, - sourcePayload, - AccountTenantCreationBootstrapDigest.sha256(sourcePayload), - requestPayload, - AccountTenantCreationBootstrapDigest.sha256(requestPayload), - 1, - 1); - assertThat(claim.claimed()).isTrue(); - return claim.operation(); - } - - private static Completion completion(StoredOperation operation) { - // Controlled completion receipts exercise the real storage owner's guarded transition. - byte[] event = "fixture membership event".getBytes(StandardCharsets.UTF_8); - byte[] audit = "fixture bootstrap audit".getBytes(StandardCharsets.UTF_8); - byte[] result = "fixture bootstrap result".getBytes(StandardCharsets.UTF_8); - return new Completion( - 1, - operation.baselineMembershipVersion() + 1, - operation.baselineMembershipAuthorityGeneration(), - "ACTIVE", - false, - "[\"tenantAdmin\"]".getBytes(StandardCharsets.UTF_8), - MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX - + "membership/" - + operation.initiatingAccountUuid() - + "/" - + operation.tenantUuid(), - operation.requestId().toString(), - 1, - "fixture-membership-event", - AccountTenantCreationBootstrapDigest.sha256(event), - false, - event, - UUID.randomUUID(), - "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED", - Instant.now().truncatedTo(ChronoUnit.MICROS), - AccountTenantCreationBootstrapDigest.sha256(audit), - audit, - result, - AccountTenantCreationBootstrapDigest.sha256(result)); - } - private static FreshTenantCreationEvidence source() { UUID request = UUID.randomUUID(), operation = UUID.randomUUID(), tenant = UUID.randomUUID(); String slug = "capacity-" + UUID.randomUUID().toString().substring(0, 8); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index dc1cc902e6..26fff3de37 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -9,6 +9,7 @@ import static org.mockito.Mockito.when; import com.google.protobuf.ByteString; +import integration.net.firedevops.firemud.accountservice.AccountTenantCreatorBootstrapIntegrationFixture; import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; import java.nio.charset.StandardCharsets; import java.nio.file.Path; @@ -55,10 +56,7 @@ import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.CapacityException; -import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapDigest; import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; -import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.Completion; -import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation; import net.firedevops.firemud.accountservice.repository.AccountTenantEntitlementOutboxRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantIdentityResolver; import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; @@ -70,7 +68,6 @@ import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence; -import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; @@ -83,8 +80,6 @@ import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; import net.firedevops.firemud.common.security.GatewayFirstPartyConnectContextEnvelope.ContextClaims; import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; -import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; -import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; @@ -820,8 +815,11 @@ private Fixture(DriverManagerDataSource dataSource, boolean join, boolean initia tenants.importVerified(tenantSource); if (initializeCapacity) { var bootstrap = new AccountTenantCreationBootstrapOperationRepository(dsl); - var claim = claimBootstrap(bootstrap, account, tenantSource); - bootstrap.complete(claim.requestId(), completion(claim)); + var claim = + AccountTenantCreatorBootstrapIntegrationFixture.claimBootstrap( + bootstrap, account, tenantSource); + bootstrap.complete( + claim.requestId(), AccountTenantCreatorBootstrapIntegrationFixture.completion(claim)); new AccountCapacityRefusalBudgetRepository(dsl).provision(tenantId, 1); } sources.initializeIssuerIfAbsent(ISSUER); @@ -987,74 +985,6 @@ private void setInstant(Instant instant) { } } - private static StoredOperation claimBootstrap( - AccountTenantCreationBootstrapOperationRepository operations, - Account creator, - FreshTenantCreationEvidence creation) { - UUID accountId = creator.getAccountUuid(); - UUID authorizationId = UUID.randomUUID(); - String authorizationDigest = - AccountTenantCreationBootstrapDigest.sha256( - "fixture authorization".getBytes(StandardCharsets.UTF_8)); - var evidence = - new FreshTenantCreatorEvidence( - 1, - creation, - accountId, - authorizationId, - authorizationDigest, - FreshTenantCreatorDigest.evidenceDigest( - 1, creation, accountId, authorizationId, authorizationDigest)); - byte[] creatorPayload = AccountTenantCreationBootstrapDigest.creatorEvidencePayload(evidence); - byte[] sourcePayload = "fixture source snapshot".getBytes(StandardCharsets.UTF_8); - byte[] requestPayload = - AccountTenantCreationBootstrapDigest.requestPayload(creatorPayload, sourcePayload); - var claim = - operations.claim( - evidence, - creatorPayload, - sourcePayload, - AccountTenantCreationBootstrapDigest.sha256(sourcePayload), - requestPayload, - AccountTenantCreationBootstrapDigest.sha256(requestPayload), - 1, - 1); - assertThat(claim.claimed()).isTrue(); - return claim.operation(); - } - - private static Completion completion(StoredOperation operation) { - // Controlled completion receipts exercise the real storage owner's guarded transition. - byte[] event = "fixture membership event".getBytes(StandardCharsets.UTF_8); - byte[] audit = "fixture bootstrap audit".getBytes(StandardCharsets.UTF_8); - byte[] result = "fixture bootstrap result".getBytes(StandardCharsets.UTF_8); - return new Completion( - 1, - operation.baselineMembershipVersion() + 1, - operation.baselineMembershipAuthorityGeneration(), - "ACTIVE", - false, - "[\"tenantAdmin\"]".getBytes(StandardCharsets.UTF_8), - MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX - + "membership/" - + operation.initiatingAccountUuid() - + "/" - + operation.tenantUuid(), - operation.requestId().toString(), - 1, - "fixture-membership-event", - AccountTenantCreationBootstrapDigest.sha256(event), - false, - event, - UUID.randomUUID(), - "ACCOUNT_TENANT_CREATOR_BOOTSTRAPPED", - Instant.now().truncatedTo(ChronoUnit.MICROS), - AccountTenantCreationBootstrapDigest.sha256(audit), - audit, - result, - AccountTenantCreationBootstrapDigest.sha256(result)); - } - private static FreshTenantCreationEvidence tenantSource(UUID tenantId) { UUID requestId = UUID.randomUUID(); UUID operationId = UUID.randomUUID(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index d99bc2e29b..539842aed0 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -293,6 +293,11 @@ void claimExpiryDuringRearmAcceptanceRollsBackBeforeHistoryOrFenceMutation() thr .thenReturn(AccountTenantCapacityRepository.at(claimExpiry)); when(row.get("execution_status", String.class)).thenReturn("NOT_EXECUTED_AFTER_AUTHORIZATION"); when(row.get("owner_readback", byte[].class)).thenReturn(new byte[] {1}); + String usageLock = + "SELECT * FROM account_tenant_capacity_usage WHERE tenant_uuid = ? AND owner_service = ? FOR UPDATE"; + org.mockito.Mockito.doReturn(mock(Record.class)) + .when(f.dsl) + .fetchOne(startsWith(usageLock), any(Object[].class)); retainOriginThenAdvanceClock(f, next, "ACCEPTED", claimExpiry); var rearm = AccountTenantCapacityOwner.class.getDeclaredMethod( @@ -301,7 +306,10 @@ void claimExpiryDuringRearmAcceptanceRollsBackBeforeHistoryOrFenceMutation() thr assertThatThrownBy(() -> rearm.invoke(f.owner, f.request, next, claimOwner, 7L)) .hasCauseInstanceOf(AccountTenantCapacityRepository.CapacityException.class) .hasRootCauseMessage("IDEMPOTENCY_CONFLICT"); - verify(f.dsl) + var lockOrder = org.mockito.Mockito.inOrder(f.dsl); + lockOrder.verify(f.dsl).fetchOne(startsWith(usageLock), any(Object[].class)); + lockOrder + .verify(f.dsl) .execute(startsWith("INSERT INTO account_capacity_origin_decisions "), any(Object[].class)); verify(f.dsl, never()) .execute( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java index 7709b82477..de52902641 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java @@ -193,7 +193,8 @@ public void ping(PingRequest request, StreamObserver observer) { assertThat(stub.getChannel()).isSameAs(previous); selected.countDown(); try { - assertThat(ready.await(5, TimeUnit.SECONDS)) + // The second call also waits for stub selection and the first RPC. + assertThat(ready.await(30, TimeUnit.SECONDS)) .as("the selected call must be released before its bounded wait") .isTrue(); } catch (InterruptedException interrupted) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index 2663f96d3b..5a9edec24a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -3,9 +3,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.grpc.CallOptions; +import io.grpc.ClientCall; +import io.grpc.ConnectivityState; import io.grpc.Context; import io.grpc.Deadline; import io.grpc.ManagedChannel; +import io.grpc.MethodDescriptor; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.Status; @@ -255,14 +259,17 @@ void successfulRpcPropagatesMinimumOfExplicitIncomingAndMaximumDeadline( long explicitMillis, long incomingMillis, long expectedMaximumMillis) throws Exception { AtomicInteger calls = new AtomicInteger(); AtomicLong observedNanos = new AtomicLong(); + var channelFactory = new CallOptionsCapturingChannelFactory(); // Warm the channel, then reset the sample before the measured RPC. Server server = server("account", calls, false, observedNanos, new AtomicBoolean(true)); var scheduler = Executors.newSingleThreadScheduledExecutor(); - try (var client = client(server)) { + try (var client = + client(server, pki.clientProperties(directory, pki.identity("client")), channelFactory)) { client.init(); var request = CapacityAdmissionTestFixture.playerRequest(); client.commit(request, deadline()); observedNanos.set(0); + channelFactory.resetCapturedDeadline(); try (var context = Context.current().withDeadlineAfter(incomingMillis, TimeUnit.MILLISECONDS, scheduler)) { var result = @@ -276,6 +283,11 @@ void successfulRpcPropagatesMinimumOfExplicitIncomingAndMaximumDeadline( assertThat(observedNanos.get()) .isPositive() .isLessThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(expectedMaximumMillis)); + // This is sampled at newCall, before the RPC is handed to the network. The broad one-second + // tolerance permits local call setup, while a fixed one-second client deadline cannot pass. + assertThat(channelFactory.capturedDeadlineNanos.get()) + .isGreaterThan(TimeUnit.MILLISECONDS.toNanos(expectedMaximumMillis - 1_000)) + .isLessThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(expectedMaximumMillis)); } finally { scheduler.shutdownNow(); stop(server); @@ -705,4 +717,92 @@ public ManagedChannel buildChannel( return super.buildChannel(target, defaultPort, properties, keepAlive); } } + + private static final class CallOptionsCapturingChannelFactory extends GrpcChannelFactory { + private final AtomicLong capturedDeadlineNanos = new AtomicLong(-1); + + @Override + public ManagedChannel buildChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + return new CallOptionsCapturingManagedChannel( + super.buildChannel(target, defaultPort, properties, keepAlive), capturedDeadlineNanos); + } + + private void resetCapturedDeadline() { + capturedDeadlineNanos.set(-1); + } + } + + private static final class CallOptionsCapturingManagedChannel extends ManagedChannel { + private final ManagedChannel delegate; + private final AtomicLong capturedDeadlineNanos; + + private CallOptionsCapturingManagedChannel( + ManagedChannel delegate, AtomicLong capturedDeadlineNanos) { + this.delegate = delegate; + this.capturedDeadlineNanos = capturedDeadlineNanos; + } + + @Override + public ClientCall newCall( + MethodDescriptor methodDescriptor, CallOptions callOptions) { + Deadline deadline = callOptions.getDeadline(); + capturedDeadlineNanos.set( + deadline == null ? 0 : deadline.timeRemaining(TimeUnit.NANOSECONDS)); + return delegate.newCall(methodDescriptor, callOptions); + } + + @Override + public String authority() { + return delegate.authority(); + } + + @Override + public ManagedChannel shutdown() { + delegate.shutdown(); + return this; + } + + @Override + public boolean isShutdown() { + return delegate.isShutdown(); + } + + @Override + public boolean isTerminated() { + return delegate.isTerminated(); + } + + @Override + public ManagedChannel shutdownNow() { + delegate.shutdownNow(); + return this; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { + return delegate.awaitTermination(timeout, unit); + } + + @Override + public ConnectivityState getState(boolean requestConnection) { + return delegate.getState(requestConnection); + } + + @Override + public void notifyWhenStateChanged(ConnectivityState source, Runnable callback) { + delegate.notifyWhenStateChanged(source, callback); + } + + @Override + public void resetConnectBackoff() { + delegate.resetConnectBackoff(); + } + + @Override + public void enterIdle() { + delegate.enterIdle(); + } + } } From ff2b4d523404a4e1e876078e6069fc8fdf7dd3db Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 16:31:24 +1300 Subject: [PATCH 35/96] Resolve FireMUD #3451 review findings and Validation failures --- .github/workflows/runtime-images.yml | 75 ++- .github/workflows/smoke.yml | 599 ++++++++++++++---- .../account-service/runtime-and-data.md | 4 +- .../architecture/system-architecture-cicd.md | 4 +- .../pr-required-gate-context-contract.sh | 153 ++++- .../tests/pr-retarget-workflow-contract.sh | 89 ++- .../pr-runtime-image-publication-contract.sh | 98 ++- ...ccountCapacityRefusalBudgetRepository.java | 16 +- ...acityMigrationPostgresIntegrationTest.java | 23 +- .../AccountTenantCapacityOwnerTest.java | 60 +- .../AccountTenantCapacityClientMtlsTest.java | 160 ++++- ...alGameplayRosterReferenceGrpcMtlsTest.java | 3 +- ...tSessionOwnerEvidenceReadGrpcMtlsTest.java | 3 +- .../stubs/EntityManagementStubServerTest.java | 13 +- .../test/stubs/GameDesignStubServerTest.java | 3 +- .../stubs/WorldManagementStubServerTest.java | 8 +- 16 files changed, 1077 insertions(+), 234 deletions(-) diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 4930f5c5ac..c0cd85890a 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -942,14 +942,33 @@ jobs: (response) => response.data ); const refreshTargets = []; - for (const listedPullRequest of pullRequests) { + for (let pullRequestIndex = 0; pullRequestIndex < pullRequests.length; pullRequestIndex += 1) { + const listedPullRequest = pullRequests[pullRequestIndex]; if (listedPullRequest.state !== "open" || listedPullRequest.base?.ref !== refreshBranch || listedPullRequest.head?.repo?.full_name !== context.payload.repository.full_name || listedPullRequest.base?.repo?.full_name !== context.payload.repository.full_name) { continue; } - const resolved = await resolveExactMerge(listedPullRequest.number); + let resolved; + try { + resolved = await resolveExactMerge(listedPullRequest.number); + } catch (error) { + if (Date.now() >= fanoutDeadline) { + const incompleteTargets = pullRequests.slice(pullRequestIndex) + .map(({number}) => `#${number}`).join(", "); + core.setFailed( + `Runtime fan-out cutoff reached during initial PR target merge resolution; ` + + `PR targets ${incompleteTargets} remain incomplete: ${error.message || error}` + ); + break; + } + core.setFailed( + `Cannot verify runtime target tuple for PR #${listedPullRequest.number}; ` + + `no dispatch issued: ${error.message || error}` + ); + continue; + } if (resolved) { refreshTargets.push(resolved); } @@ -1025,6 +1044,7 @@ jobs: let existingProducers = []; let fallbackReason = null; let inventory; + const reusingInventory = runtimeInventoryPromise !== undefined; if (runtimeInventoryError) { fallbackReason = runtimeInventoryError; } else { @@ -1039,6 +1059,13 @@ jobs: if (!fallbackReason) { try { existingProducers = findExactExistingProducer(tuple, inventory); + // A cache hit can prove that an exact producer exists. Refresh + // a miss after earlier targets so it cannot hide a new producer. + if (reusingInventory && inventory.complete && existingProducers.length === 0) { + runtimeInventoryPromise = loadExistingRuntimeRuns(); + inventory = await runtimeInventoryPromise; + existingProducers = findExactExistingProducer(tuple, inventory); + } if (!inventory.complete) { // The REST contract does not specify a sort order, so a truncated page cannot prove omitted runs are older. existingProducers = []; @@ -1104,7 +1131,7 @@ jobs: reportFanoutCutoff(targetIndex, `before the runtime POST for PR #${tuple.prNumber}`); break; } - const previousIds = new Set(inventory?.runs?.map(run => run.id) || []); + const previousIds = new Set(inventory.runs.map(run => run.id)); // Actions run timestamps may omit sub-second precision. Inventory // from the start of this second so a handoff created in the POST's // timestamp second remains observable. @@ -1202,20 +1229,40 @@ jobs: const expectedRepository = `${context.repo.owner}/${context.repo.repo}`; const defaultBranch = context.payload.repository?.default_branch; let runtimeWorkflow = null; + const isTransientVisibilityError = error => { + const status = error?.status ?? error?.response?.status; + const code = error?.code ?? error?.cause?.code; + return [408, 425, 429, 500, 502, 503, 504].includes(status) || + (status == null && (["ABORT_ERR", "ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", + "ENETUNREACH", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"].includes(code) || + ["AbortError", "TimeoutError"].includes(error?.name))); + }; if (pendingVisibility.length > 0) { try { if (context.payload.repository?.full_name !== expectedRepository || typeof defaultBranch !== "string" || !defaultBranch) { throw new Error("Repository identity or default branch is unavailable"); } - const {data: workflow} = await github.rest.actions.getWorkflow(withRequestDeadline({ - ...context.repo, workflow_id: "runtime-images.yml", - }, visibilityDeadline, "Runtime visibility observation")); - if (!Number.isSafeInteger(workflow?.id) || workflow.id <= 0 || - workflow.path !== expectedWorkflowPath || workflow.name !== "Build Runtime Images") { - throw new Error("Current runtime workflow identity is not trusted"); + while (!runtimeWorkflow && Date.now() < visibilityDeadline) { + try { + const {data: workflow} = await github.rest.actions.getWorkflow(withRequestDeadline({ + ...context.repo, workflow_id: "runtime-images.yml", + }, visibilityDeadline, "Runtime visibility observation")); + if (!Number.isSafeInteger(workflow?.id) || workflow.id <= 0 || + workflow.path !== expectedWorkflowPath || workflow.name !== "Build Runtime Images") { + throw new Error("Current runtime workflow identity is not trusted"); + } + runtimeWorkflow = workflow; + } catch (error) { + if (!isTransientVisibilityError(error)) throw error; + core.warning("Producer workflow identity lookup is temporarily unavailable; retrying within the existing visibility deadline without retrying any POST."); + const remaining = visibilityDeadline - Date.now(); + if (remaining > 0) await new Promise(resolve => setTimeout(resolve, Math.min(5000, remaining))); + } + } + if (!runtimeWorkflow) { + throw new Error("Producer workflow identity remained unavailable until the visibility deadline"); } - runtimeWorkflow = workflow; } catch (error) { core.setFailed(`Runtime refresh visibility is unconfirmed because the producer workflow identity could not be trusted; no retry issued: ${error.message || error}`); } @@ -1264,13 +1311,7 @@ jobs: } } } catch (error) { - const status = error?.status ?? error?.response?.status; - const code = error?.code ?? error?.cause?.code; - const transient = [408, 425, 429, 500, 502, 503, 504].includes(status) || - (status == null && (["ABORT_ERR", "ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", - "ENETUNREACH", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"].includes(code) || - ["AbortError", "TimeoutError"].includes(error?.name))); - if (!transient) { + if (!isTransientVisibilityError(error)) { core.setFailed(`Runtime refresh visibility is uncertain; no retry issued: ${error.message || error}`); break; } diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 73e4976816..7a2e4f4956 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -632,7 +632,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "e86f75e3220be624f1644b8368c66b7165b98fba9905142f107819d926db8055"; + const canonicalRuntimeWorkflowSha256 = "a29d15fa877ccf53e6677c3ccd60e2fbed7e817fd776a0fc8093ca24c2462a7e"; // Only authenticated default-branch refreshes may use retained successful definitions. // Keep the pre-rollout default and predecessor definitions for mixed-version runs. const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set([ @@ -773,6 +773,23 @@ jobs: ref.split("/").every(part => part && !part.startsWith(".") && !part.endsWith(".lock")); } + const immutableDefinitionHashes = new Map(); + async function immutableDefinitionHash(path, ref, label) { + const key = `${ref}:${path}`; + if (immutableDefinitionHashes.has(key)) return immutableDefinitionHashes.get(key); + const { data: definition } = await withTransientGitHubRetry( + label, + () => github.rest.repos.getContent({ owner, repo, path, ref }) + ); + if (definition.type !== "file" || definition.path !== path || + definition.encoding !== "base64" || typeof definition.content !== "string") return null; + const bytes = Buffer.from(definition.content, "base64"); + if (definition.size !== bytes.length) return null; + const hash = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); + immutableDefinitionHashes.set(key, hash); + return hash; + } + function isSuccessfulRuntimeWorkflowDefinition(definitionHash, sourceEvent) { return definitionHash === canonicalRuntimeWorkflowSha256 || (sourceEvent === "repository_dispatch" && @@ -781,6 +798,8 @@ jobs: async function verifyCanonicalSmokeProducer(run, candidate, identity, requireTerminalSmokeProof = false) { if (!positiveInteger(run.id) || !positiveInteger(run.run_attempt)) return false; + const exactSnapshotPending = requireTerminalSmokeProof && run.event === "repository_dispatch"; + const pendingExactSnapshot = () => exactSnapshotPending ? "snapshot-pending" : false; const { data: source } = await withTransientGitHubRetry( "exact runtime workflow attempt lookup", () => github.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}", { @@ -789,19 +808,45 @@ jobs: ); const expectedTitle = `Build Runtime Images secure-pr-artifact pr-${prNumber} ` + `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; + if ((source.id != null && source.id !== run.id) || + (source.run_attempt != null && source.run_attempt !== run.run_attempt)) return false; + if ((source.path != null && !isRuntimeSourceWorkflowPath(source.path)) || + (source.repository?.full_name != null && source.repository.full_name !== repositoryName) || + (source.workflow_id != null && !positiveInteger(source.workflow_id)) || + (source.display_title != null && source.display_title !== expectedTitle) || + (source.event != null && (source.event !== run.event || + !["pull_request", "repository_dispatch"].includes(source.event)))) return false; + if ([source.id, source.run_attempt, source.path, source.repository?.full_name, + source.workflow_id, source.display_title, source.event].some(value => value == null)) { + return pendingExactSnapshot(); + } if ( - source.id !== run.id || source.run_attempt !== run.run_attempt || - source.status !== "completed" || source.conclusion !== "success" || !isRuntimeSourceWorkflowPath(source.path) || source.repository?.full_name !== repositoryName || !positiveInteger(source.workflow_id) || source.display_title !== expectedTitle || source.event !== run.event || !["pull_request", "repository_dispatch"].includes(source.event) ) return false; + if (source.status !== "completed" || source.conclusion == null) { + if (exactSnapshotPending && source.status == null && source.conclusion === run.conclusion) { + return pendingExactSnapshot(); + } + if (exactSnapshotPending && (source.status == null || ["queued", "in_progress", "waiting", "pending", "requested"].includes(source.status)) && + source.conclusion == null) return pendingExactSnapshot(); + if (exactSnapshotPending && source.status === "completed" && source.conclusion == null) { + return pendingExactSnapshot(); + } + return false; + } + if (source.conclusion !== "success") return false; const expectedHeadRepository = source.event === "pull_request" ? context.payload.pull_request.head.repo?.full_name : repositoryName; - if (typeof expectedHeadRepository !== "string" || - source.head_repository?.full_name !== expectedHeadRepository) return false; + if (typeof expectedHeadRepository !== "string") return false; + if (source.head_repository?.full_name == null) return pendingExactSnapshot(); + if (source.head_repository.full_name !== expectedHeadRepository) return false; + if (source.event === "pull_request" && source.head_sha == null) return pendingExactSnapshot(); if (source.event === "pull_request" && source.head_sha !== identity.headSha) return false; + if (source.event === "repository_dispatch" && + (source.head_branch == null || source.head_sha == null)) return pendingExactSnapshot(); if (source.event === "repository_dispatch" && ( source.head_branch !== context.payload.repository.default_branch || !/^[0-9a-f]{40}$/.test(source.head_sha ?? "") @@ -812,6 +857,13 @@ jobs: ); if (workflow.id !== source.workflow_id || workflow.path !== workflowPath || workflow.name !== "Build Runtime Images") return false; + // PR workflows execute their test merge definition; typed refreshes execute the + // immutable default-branch revision recorded by their native run attempt. + const workflowSha = source.event === "pull_request" ? identity.mergeSha : source.head_sha; + const definitionHash = await immutableDefinitionHash( + workflowPath, workflowSha, "immutable runtime workflow definition lookup"); + const currentDefinition = isSuccessfulRuntimeWorkflowDefinition(definitionHash, source.event); + if (!currentDefinition && definitionHash !== canonicalLegacyRuntimeWorkflowSha256) return false; const jobs = await withTransientGitHubRetry( "exact runtime attempt jobs lookup", () => github.paginate( @@ -821,62 +873,96 @@ jobs: ); if (!Array.isArray(jobs)) return false; const producers = jobs.filter((job) => job.name === canonicalSmokeJobName); - if (producers.length !== 1) return false; + if (producers.length > 1) return false; + if (producers.length === 0) return pendingExactSnapshot(); const job = producers[0]; - if ( - !positiveInteger(job.id) || (candidate && job.id !== candidate.id) || - job.run_id !== source.id || job.run_attempt !== source.run_attempt || - job.head_sha !== source.head_sha || job.status !== "completed" || job.conclusion !== "success" || - job.check_run_url !== `https://api.github.com/repos/${repositoryName}/check-runs/${job.id}` - ) return false; + if ((job.id != null && !positiveInteger(job.id)) || + (candidate?.id != null && job.id != null && job.id !== candidate.id) || + (job.run_id != null && job.run_id !== source.id) || + (job.run_attempt != null && job.run_attempt !== source.run_attempt) || + (job.head_sha != null && job.head_sha !== source.head_sha) || + (job.check_run_url != null && job.id != null && + job.check_run_url !== `https://api.github.com/repos/${repositoryName}/check-runs/${job.id}`)) return false; + if (job.id == null || job.run_id == null || job.run_attempt == null || + job.head_sha == null || job.check_run_url == null) return pendingExactSnapshot(); + if (!positiveInteger(job.id) || job.run_id !== source.id || + job.run_attempt !== source.run_attempt || job.head_sha !== source.head_sha || + job.check_run_url !== `https://api.github.com/repos/${repositoryName}/check-runs/${job.id}`) return false; + if (job.status == null) { + if (exactSnapshotPending && (job.conclusion == null || job.conclusion === "success")) { + return pendingExactSnapshot(); + } + return false; + } + if (job.status !== "completed" || job.conclusion == null) { + if (exactSnapshotPending && (job.status == null || ["queued", "in_progress", "waiting", "pending", "requested"].includes(job.status)) && + job.conclusion == null) return pendingExactSnapshot(); + if (exactSnapshotPending && job.status === "completed" && job.conclusion == null) { + return pendingExactSnapshot(); + } + return false; + } + if (job.conclusion !== "success") return false; const markers = (job.steps ?? []).filter((step) => step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" ); - // PR workflows execute their test merge definition; typed refreshes execute the - // immutable default-branch revision recorded by their native run attempt. - const workflowSha = source.event === "pull_request" ? identity.mergeSha : source.head_sha; - const { data: definition } = await withTransientGitHubRetry( - "immutable runtime workflow definition lookup", - () => github.rest.repos.getContent({ owner, repo, path: workflowPath, ref: workflowSha }) - ); - if (definition.type !== "file" || definition.path !== workflowPath || - definition.encoding !== "base64" || typeof definition.content !== "string") return false; - const bytes = Buffer.from(definition.content, "base64"); - if (definition.size !== bytes.length) return false; - const definitionHash = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); - if (isSuccessfulRuntimeWorkflowDefinition(definitionHash, source.event)) { - if (markers.length !== 1 || markers[0].status !== "completed" || - markers[0].conclusion !== "skipped") return false; - } else if (definitionHash !== canonicalLegacyRuntimeWorkflowSha256) return false; + if (currentDefinition) { + if (markers.length > 1) return false; + if (markers.length === 0 || markers[0].status !== "completed" || + markers[0].conclusion == null) return pendingExactSnapshot(); + if (markers[0].conclusion !== "skipped") return false; + } if (requireTerminalSmokeProof) { - if (source.workflow_id !== run.workflow_id || run.repository?.full_name !== repositoryName || - run.head_sha !== source.head_sha || - run.status !== "completed" || run.conclusion !== "success") return false; + if ((run.workflow_id != null && source.workflow_id !== run.workflow_id) || + (run.repository?.full_name != null && run.repository.full_name !== repositoryName) || + (run.head_sha != null && run.head_sha !== source.head_sha) || + (run.status != null && run.status !== "completed") || + (run.conclusion != null && run.conclusion !== "success")) return false; + if (run.workflow_id == null || run.repository?.full_name == null || run.head_sha == null || + run.status == null || run.conclusion == null) return pendingExactSnapshot(); if (markers.length !== 1 || markers[0].status !== "completed" || markers[0].conclusion !== "skipped") return false; if (!Array.isArray(job.steps)) return false; const smokeSteps = job.steps.filter((step) => step.name === "Run credential-free full-stack smoke" ); - if (smokeSteps.length > 1 || (smokeSteps.length === 1 && - (smokeSteps[0].status !== "completed" || smokeSteps[0].conclusion !== "success"))) return false; + if (smokeSteps.length > 1) return false; + if (smokeSteps.length === 1 && (smokeSteps[0].status !== "completed" || + smokeSteps[0].conclusion == null)) return pendingExactSnapshot(); + if (smokeSteps.length === 1 && smokeSteps[0].conclusion !== "success") return false; for (const name of [ "Stop smoke stack", "Require successful runtime smoke and authenticated cleanup", ]) { const matches = job.steps.filter((step) => step.name === name); - if (matches.length !== 1 || matches[0].status !== "completed" || - matches[0].conclusion !== "success") return false; + if (matches.length > 1) return false; + if (matches.length === 0 || matches[0].status !== "completed" || + matches[0].conclusion == null) return pendingExactSnapshot(); + if (matches[0].conclusion !== "success") return false; } - if (job.steps.some((step) => step.status !== "completed" || - !["success", "skipped"].includes(step.conclusion))) return false; + if (job.steps.some((step) => step.status !== "completed" || step.conclusion == null)) { + return pendingExactSnapshot(); + } + if (job.steps.some((step) => !["success", "skipped"].includes(step.conclusion))) return false; } const { data: latest } = await withTransientGitHubRetry( "current runtime attempt lookup", () => github.rest.actions.getWorkflowRun({ owner, repo, run_id: source.id }) ); - return latest.id === source.id && latest.run_attempt === source.run_attempt && - latest.status === "completed" && latest.conclusion === "success"; + if (source.event === "repository_dispatch" && latest.id === source.id && + positiveInteger(latest.run_attempt) && latest.run_attempt > source.run_attempt) { + return "attempt-superseded"; + } + if (latest.id == null || latest.run_attempt == null) return pendingExactSnapshot(); + if (latest.id !== source.id || latest.run_attempt !== source.run_attempt) return false; + if (latest.status !== "completed" || latest.conclusion == null) { + if (exactSnapshotPending && latest.status == null && latest.conclusion === source.conclusion) { + return pendingExactSnapshot(); + } + if (exactSnapshotPending && latest.conclusion == null) return pendingExactSnapshot(); + return false; + } + return latest.conclusion === "success"; } function hasPendingCanonicalSmokeTerminalEvidence(job) { @@ -884,23 +970,26 @@ jobs: const markerName = "Known canonical transition PLAY failure with successful authenticated cleanup"; const markerMatches = job.steps.filter((step) => step.name === markerName); if (markerMatches.length > 1) return false; + if (markerMatches.length === 0 || markerMatches[0].status !== "completed" || + markerMatches[0].conclusion == null) return true; + if (!["success", "skipped"].includes(markerMatches[0].conclusion)) return false; for (const name of [ "Stop smoke stack", "Require successful runtime smoke and authenticated cleanup", ]) { const matches = job.steps.filter((step) => step.name === name); if (matches.length > 1) return false; - if (matches.length === 0 || matches[0].status !== "completed") return true; + if (matches.length === 0 || matches[0].status !== "completed" || matches[0].conclusion == null) return true; if (matches[0].conclusion !== "success") return false; } const smokeSteps = job.steps.filter((step) => step.name === "Run credential-free full-stack smoke" ); if (smokeSteps.length > 1) return false; - if (smokeSteps.length === 1 && smokeSteps[0].status !== "completed") return true; - return job.steps.some((step) => - step.name !== markerName && step.status !== "completed" - ); + if (smokeSteps.length === 1 && (smokeSteps[0].status !== "completed" || + smokeSteps[0].conclusion == null)) return true; + return job.steps.some((step) => step.name !== markerName && + (step.status !== "completed" || step.conclusion == null)); } // Canonical-transition diagnostic acceptance never becomes passing producer proof. @@ -916,18 +1005,49 @@ jobs: ); const expectedTitle = `Build Runtime Images secure-pr-artifact pr-${prNumber} ` + `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; + if ((source.id != null && source.id !== run.id) || + (source.run_attempt != null && source.run_attempt !== run.run_attempt)) return false; + if ((source.path != null && !isRuntimeSourceWorkflowPath(source.path)) || + (source.repository?.full_name != null && source.repository.full_name !== repositoryName) || + (source.workflow_id != null && !positiveInteger(source.workflow_id)) || + (source.display_title != null && source.display_title !== expectedTitle) || + (source.event != null && (source.event !== run.event || + !["pull_request", "repository_dispatch"].includes(source.event)))) return false; + if ([source.id, source.run_attempt, source.path, source.repository?.full_name, + source.workflow_id, source.display_title, source.event].some(value => value == null)) { + return allowIncompleteSteps ? "snapshot-pending" : false; + } if ( - source.id !== run.id || source.run_attempt !== run.run_attempt || - source.status !== "completed" || source.conclusion !== run.conclusion || !["success", "failure"].includes(source.conclusion) || !isRuntimeSourceWorkflowPath(source.path) || source.repository?.full_name !== repositoryName || !positiveInteger(source.workflow_id) || source.display_title !== expectedTitle || source.event !== run.event ) return false; + if (source.status !== "completed" || source.conclusion == null) { + if (allowIncompleteSteps && source.status == null && source.conclusion === run.conclusion) { + return "snapshot-pending"; + } + if (allowIncompleteSteps && source.conclusion == null && + (source.status == null || ["queued", "in_progress", "waiting", "pending", "requested"].includes(source.status) || + source.status === "completed")) return "snapshot-pending"; + return false; + } + if (source.conclusion !== run.conclusion || !["success", "failure"].includes(source.conclusion)) return false; const expectedHeadRepository = context.payload.pull_request.head.repo?.full_name; - if (typeof expectedHeadRepository !== "string" || - expectedHeadRepository !== repositoryName || - source.head_repository?.full_name !== expectedHeadRepository) return false; + if (typeof expectedHeadRepository !== "string" || expectedHeadRepository !== repositoryName) return false; + if (source.head_repository?.full_name == null) { + if (allowIncompleteSteps) return "snapshot-pending"; + return false; + } + if (source.head_repository.full_name !== expectedHeadRepository) return false; + if (source.event === "pull_request" && source.head_sha == null) { + if (allowIncompleteSteps) return "snapshot-pending"; + return false; + } if (source.event === "pull_request" && source.head_sha !== identity.headSha) return false; + if (source.event === "repository_dispatch" && (source.head_branch == null || source.head_sha == null)) { + if (allowIncompleteSteps) return "snapshot-pending"; + return false; + } if (source.event === "repository_dispatch" && ( source.head_branch !== context.payload.repository.default_branch || !/^[0-9a-f]{40}$/.test(source.head_sha ?? "") @@ -938,6 +1058,12 @@ jobs: ); if (workflow.id !== source.workflow_id || workflow.path !== workflowPath || workflow.name !== "Build Runtime Images") return false; + const workflowSha = source.event === "pull_request" ? identity.mergeSha : source.head_sha; + const workflowHash = await immutableDefinitionHash( + workflowPath, workflowSha, "immutable PLAY runtime workflow lookup"); + if (source.conclusion === "success" + ? !isSuccessfulRuntimeWorkflowDefinition(workflowHash, source.event) + : workflowHash !== canonicalLegacyRuntimeWorkflowSha256) return false; const jobs = await withTransientGitHubRetry( "exact runtime attempt jobs lookup", () => github.paginate( @@ -945,20 +1071,35 @@ jobs: { owner, repo, run_id: source.id, attempt_number: source.run_attempt, per_page: 100 } ) ); + if (!Array.isArray(jobs)) return false; const producers = jobs.filter((job) => job.name === canonicalSmokeJobName); - if (producers.length > 1 || (producers.length === 0 && !allowIncompleteSteps)) return false; + if (producers.length > 1 || (!allowIncompleteSteps && producers.length === 0)) return false; const job = producers[0]; - let incompleteSteps = !job || job.status !== "completed"; + if (job && ((job.id != null && !positiveInteger(job.id)) || + (candidate?.id != null && job.id != null && job.id !== candidate.id) || + (job.run_id != null && job.run_id !== source.id) || + (job.run_attempt != null && job.run_attempt !== source.run_attempt) || + (job.head_sha != null && job.head_sha !== source.head_sha) || + (job.check_run_url != null && job.id != null && + job.check_run_url !== `https://api.github.com/repos/${repositoryName}/check-runs/${job.id}`))) return false; + let incompleteSteps = job?.status !== "completed"; if (job) { - if (!positiveInteger(job.id) || (candidate && job.id !== candidate.id) || - job.run_id !== source.id || job.run_attempt !== source.run_attempt || - job.head_sha !== source.head_sha || - job.check_run_url !== `https://api.github.com/repos/${repositoryName}/check-runs/${job.id}`) return false; - if (job.status === "completed") { - if (job.conclusion !== source.conclusion) return false; + if (job.id == null || job.run_id == null || job.run_attempt == null || + job.head_sha == null || job.check_run_url == null) { + if (!allowIncompleteSteps) return false; + incompleteSteps = true; + } + if (job.status == null) { + if (!allowIncompleteSteps || + (job.conclusion != null && job.conclusion !== source.conclusion)) return false; + incompleteSteps = true; + } else if (job.status === "completed") { + if (job.conclusion == null) incompleteSteps = true; + else if (job.conclusion !== source.conclusion) return false; } else if (!allowIncompleteSteps || - !["queued", "in_progress", "waiting", "pending", "requested"].includes(job.status) || + !(job.status == null || ["queued", "in_progress", "waiting", "pending", "requested"].includes(job.status)) || job.conclusion != null) return false; + if (job.steps != null && !Array.isArray(job.steps)) return false; } const expectedSuccessfulSteps = [ "Run credential-free full-stack smoke", @@ -973,7 +1114,7 @@ jobs: const ordinary = ordinaryCandidate && markers[0]?.status === "completed" && markers[0].conclusion === "skipped"; const unknownDisposition = ordinaryCandidate && - (!markers.length || markers[0].status !== "completed"); + (!markers.length || markers[0].status !== "completed" || markers[0].conclusion == null); const requiredSteps = new Map([ [markerName, ordinary ? "skipped" : "success"], ["Stop smoke stack", "success"], ...expectedSuccessfulSteps.map((name) => [name, source.conclusion]), @@ -985,12 +1126,13 @@ jobs: for (const [name, conclusion] of requiredSteps) { const matches = steps.filter((step) => step.name === name); if (matches.length > 1) return false; - if (matches.length === 0 || matches[0].status !== "completed") { + if (matches.length === 0 || matches[0].status !== "completed" || matches[0].conclusion == null) { incompleteSteps = true; } else if (matches[0].conclusion !== conclusion) return false; } for (const step of steps) { if (step.status !== "completed") incompleteSteps = true; + else if (step.conclusion == null) incompleteSteps = true; else if (!["success", "skipped", "failure"].includes(step.conclusion) || (step.conclusion === "failure" && !(source.conclusion === "failure" && expectedSuccessfulSteps.includes(step.name)))) return false; @@ -1000,31 +1142,13 @@ jobs: if (["queued", "in_progress", "waiting", "pending", "requested"].includes(other.status)) incompleteSteps = true; else if (other.status !== "completed" || !["success", "skipped"].includes(other.conclusion)) return false; } - // Typed refresh workflow authority is its native default-branch revision; - // the executed classifier source still belongs to the verified PR merge. - const workflowSha = source.event === "pull_request" ? identity.mergeSha : source.head_sha; - // Only the exception relies on the historical PLAY classifier. - // An unpublished marker stays pending until its disposition is known. - const definitionPaths = ordinary || unknownDisposition - ? [workflowPath] : [workflowPath, ...Object.keys(canonicalPlayClassifierSha256)]; - for (const path of definitionPaths) { - const { data: definition } = await withTransientGitHubRetry( - `immutable PLAY classifier definition lookup: ${path}`, - () => github.rest.repos.getContent({ - owner, repo, path, ref: path === workflowPath ? workflowSha : identity.mergeSha, - }) - ); - if (definition.type !== "file" || definition.path !== path || - definition.encoding !== "base64" || typeof definition.content !== "string") return false; - const bytes = Buffer.from(definition.content, "base64"); - if (definition.size !== bytes.length) return false; - const definitionHash = require("node:crypto").createHash("sha256").update(bytes).digest("hex"); - const expectedSha256 = path === workflowPath - ? canonicalLegacyRuntimeWorkflowSha256 : canonicalPlayClassifierSha256[path]; - const matches = path === workflowPath && source.conclusion === "success" - ? isSuccessfulRuntimeWorkflowDefinition(definitionHash, source.event) - : definitionHash === expectedSha256; - if (!matches) return false; + // Only the exception relies on the classifier from the verified PR merge. + if (!ordinary && !unknownDisposition) { + for (const [path, expectedHash] of Object.entries(canonicalPlayClassifierSha256)) { + const definitionHash = await immutableDefinitionHash( + path, identity.mergeSha, `immutable PLAY classifier definition lookup: ${path}`); + if (definitionHash !== expectedHash) return false; + } } const { data: latest } = await withTransientGitHubRetry( "current runtime attempt lookup", @@ -1034,8 +1158,21 @@ jobs: positiveInteger(latest.run_attempt) && latest.run_attempt > source.run_attempt) { return "attempt-superseded"; } - if (latest.id !== source.id || latest.run_attempt !== source.run_attempt || - latest.status !== "completed" || latest.conclusion !== source.conclusion) return false; + if (latest.id == null || latest.run_attempt == null) { + if (allowIncompleteSteps) return "snapshot-pending"; + return false; + } + if (latest.id !== source.id || latest.run_attempt !== source.run_attempt) return false; + if (latest.status !== "completed" || latest.conclusion == null) { + if (allowIncompleteSteps && latest.status == null && latest.conclusion === source.conclusion) { + return "snapshot-pending"; + } + if (allowIncompleteSteps && latest.conclusion == null && + (latest.status == null || ["queued", "in_progress", "waiting", "pending", "requested"].includes(latest.status) || + latest.status === "completed")) return "snapshot-pending"; + return false; + } + if (latest.conclusion !== source.conclusion) return false; // The fingerprinted marker attests the PR event label or the typed // refresh's verified live PR label. Removal closes either exception. const { data: currentPullRequest } = await withTransientGitHubRetry( @@ -1107,17 +1244,22 @@ jobs: const candidate = jobs.find((job) => job.name === canonicalSmokeJobName); const proofRun = {id: replacement.id, run_attempt: replacement.run_attempt, conclusion: replacement.conclusion}; - if (replacement.conclusion === "success" && - await verifyCanonicalSmokeProducer(replacement, candidate, identity, true)) { + const canonicalProof = replacement.conclusion === "success" + ? await verifyCanonicalSmokeProducer(replacement, candidate, identity, true) : false; + if (canonicalProof === true) { return {status: "ordinary", run: proofRun}; } const proof = await verifyKnownPlayFailure(replacement, candidate, identity, true, true); if (proof === "attempt-superseded") return "pending"; if (proof === "ordinary") { - if (!await verifyCanonicalSmokeProducer(replacement, candidate, identity, true)) return false; + const ordinaryProof = await verifyCanonicalSmokeProducer(replacement, candidate, identity, true); + if (ordinaryProof === "snapshot-pending") return {status: "snapshot-pending", run: proofRun}; + if (ordinaryProof !== true) return false; return {status: "ordinary", run: proofRun}; } - if (proof === "snapshot-pending") return {status: "snapshot-pending", run: proofRun}; + if (proof === "snapshot-pending" || canonicalProof === "snapshot-pending") { + return {status: "snapshot-pending", run: proofRun}; + } if (proof === true) return {status: "verified", run: proofRun}; // A new attempt can start between list/proof reads. Invalid current proof // is terminal; only a verified newer attempt warrants bounded reselection. @@ -1363,6 +1505,56 @@ jobs: let cancelledRunId = null; let cancelledRunObservedAt = null; let cancelledRecoveryMoved = false; + async function verifySameTupleReplacementProof(replacement, identity) { + if (replacement.event !== "repository_dispatch" || + !positiveInteger(replacement.id) || !positiveInteger(replacement.run_attempt) || + replacement.status !== "completed" || !["success", "failure"].includes(replacement.conclusion)) { + return false; + } + const jobs = await withTransientGitHubRetry("same-tuple replacement exact jobs lookup", () => + github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", { + owner, repo, run_id: replacement.id, attempt_number: replacement.run_attempt, per_page: 100, + }) + ); + if (!Array.isArray(jobs)) return false; + const producers = jobs.filter((job) => job.name === canonicalSmokeJobName); + if (producers.length > 1) return false; + if (producers.length === 0) return "snapshot-pending"; + const candidate = producers[0]; + if ((candidate.id != null && !positiveInteger(candidate.id)) || + (candidate.run_id != null && candidate.run_id !== replacement.id) || + (candidate.run_attempt != null && candidate.run_attempt !== replacement.run_attempt) || + (candidate.head_sha != null && replacement.head_sha != null && + candidate.head_sha !== replacement.head_sha) || + (candidate.check_run_url != null && candidate.id != null && + candidate.check_run_url !== `https://api.github.com/repos/${repositoryName}/check-runs/${candidate.id}`)) { + return false; + } + if (candidate.id == null || candidate.run_id == null || candidate.run_attempt == null || + candidate.head_sha == null || candidate.check_run_url == null) return "snapshot-pending"; + if (candidate.status == null) { + if (candidate.conclusion == null || candidate.conclusion === replacement.conclusion) { + return "snapshot-pending"; + } + return false; + } + if (candidate.status !== "completed" || candidate.conclusion == null) { + if ((["queued", "in_progress", "waiting", "pending", "requested"].includes(candidate.status) || + candidate.status === "completed") && candidate.conclusion == null) return "snapshot-pending"; + return false; + } + if (candidate.conclusion !== replacement.conclusion) return false; + if (candidate.steps != null && !Array.isArray(candidate.steps)) return false; + if (replacement.conclusion === "success") { + // Ordinary success has one canonical proof path. A contradictory + // snapshot cannot be retried through the diagnostic exception path. + return await verifyCanonicalSmokeProducer(replacement, candidate, identity, true); + } + const playProof = await verifyKnownPlayFailure(replacement, candidate, identity, true, true); + if (playProof === true) return true; + if (["snapshot-pending", "attempt-superseded"].includes(playProof)) return playProof; + return false; + } smokeGatePolling: while (Date.now() - started < timeoutMs) { if (pollIteration % pullRequestCheckInterval === 0 || !currentIdentity) { const resolvedIdentity = await resolveCurrentIdentity( @@ -1474,11 +1666,108 @@ jobs: currentIdentity = liveIdentity; continue smokeGatePolling; } - // Continue polling the original event until this replacement - // supplies proof or the comparison actually moves. + // A listed same-tuple refresh is only speculative. Keep the + // cancelled original authoritative until the exact typed attempt + // and its terminal smoke proof have been freshly verified. sameTupleCancellationDeadline = cancelledRunObservedAt + cancellationDiscoveryMs; + if (replacement.status !== "completed") { + const knownNonterminal = ["queued", "in_progress", "waiting", "pending", "requested"] + .includes(replacement.status); + if (replacement.status != null && (!knownNonterminal || replacement.conclusion != null)) { + core.setFailed("Cancelled runtime replacement has an invalid nonterminal identity."); + return; + } + if (Date.now() >= sameTupleCancellationDeadline) { + core.setFailed( + `Cancelled runtime-images run ${cancelledRunId} has no freshly proven exact replacement ` + + `after ${cancellationDiscoveryMs / 60000} minutes` + ); + return; + } + core.info(`Exact repository_dispatch run ${replacement.id} has incomplete/nonterminal status; ` + + `retaining cancelled pull_request run ${cancelledRunId} until replacement proof is complete.`); + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + if (replacement.run_attempt == null || replacement.conclusion == null) { + if (Date.now() >= sameTupleCancellationDeadline) { + core.setFailed( + `Cancelled runtime-images run ${cancelledRunId} has no freshly proven exact replacement ` + + `after ${cancellationDiscoveryMs / 60000} minutes` + ); + return; + } + core.info(`Exact repository_dispatch run ${replacement.id} has sparse terminal metadata; retaining the cancelled original.`); + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + if (!positiveInteger(replacement.run_attempt) || !["success", "failure"].includes(replacement.conclusion)) { + core.setFailed("Cancelled runtime replacement has an invalid terminal conclusion."); + return; + } + const replacementProofKey = + `same-tuple-replacement:${identityKey(currentIdentity)}:${replacement.id}:${replacement.run_attempt}`; + let replacementProof; + try { + replacementProof = await verifySameTupleReplacementProof(replacement, currentIdentity); + } catch (error) { + if (error instanceof TerminalGitHubRequestError) throw error; + if (error?.status === 404) { + replacementProof = false; + } else { + if (!isTransientGitHubFailure(error)) throw error; + core.warning(`Exact cancelled-run replacement proof is temporarily unavailable: ${error.message ?? String(error)}`); + replacementProof = "transient-pending"; + } + } + if (replacementProof === "snapshot-pending") { + if (incompleteRefreshKey !== replacementProofKey) { + incompleteRefreshKey = replacementProofKey; + incompleteRefreshObservedAt = Date.now(); + } + if (Date.now() - incompleteRefreshObservedAt >= completedSnapshotTimeoutMs && + Date.now() >= sameTupleCancellationDeadline) { + core.setFailed("Cancelled runtime replacement did not expose complete exact smoke proof before its existing discovery deadline."); + return; + } + } else { + incompleteRefreshKey = null; + incompleteRefreshObservedAt = null; + } + if (replacementProof === "transient-pending" || replacementProof === "snapshot-pending" || + replacementProof === "attempt-superseded") { + if (Date.now() >= sameTupleCancellationDeadline) { + core.setFailed( + `Cancelled runtime-images run ${cancelledRunId} has no freshly proven exact replacement ` + + `after ${cancellationDiscoveryMs / 60000} minutes` + ); + return; + } + core.info(`Exact repository_dispatch run ${replacement.id} is not yet freshly proven; retaining the cancelled original.`); + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + if (replacementProof !== "ordinary" && replacementProof !== true) { + // A disproven speculative replacement cannot settle the gate. + // The original attempt may still recover within its existing window. + if (replacement.conclusion === "success" || Date.now() >= sameTupleCancellationDeadline) { + core.setFailed("Cancelled runtime replacement has contradictory identity or invalid terminal smoke proof. The original did not expose a terminal PR Full-Stack Smoke job and smoke step."); + return; + } + core.warning(`Rejecting exact repository_dispatch run ${replacement.id}/${replacement.run_attempt}; retaining the original until its recovery deadline.`); + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + if (Date.now() >= sameTupleCancellationDeadline) { + core.setFailed( + `Cancelled runtime-images run ${cancelledRunId} has no freshly proven exact replacement ` + + `after ${cancellationDiscoveryMs / 60000} minutes` + ); + return; + } core.info( - `Exact pull_request runtime-images run ${matching.id} was cancelled; checking exact repository_dispatch replacement ${replacement.id}.` + `Exact pull_request runtime-images run ${matching.id} was cancelled; exact repository_dispatch ` + + `replacement ${replacement.id}/${replacement.run_attempt} passed a fresh terminal proof.` ); matching = replacement; } @@ -1719,12 +2008,15 @@ jobs: let proof; try { const ordinaryProducerVerified = matching.conclusion === "success" && - await verifyCanonicalSmokeProducer(matching, null, currentIdentity, true); + (await verifyCanonicalSmokeProducer(matching, null, currentIdentity, true)) === true; proof = ordinaryProducerVerified ? "ordinary" : await verifyKnownPlayFailure(matching, null, currentIdentity, true, true); - if (proof === "ordinary" && !ordinaryProducerVerified && - !await verifyCanonicalSmokeProducer(matching, null, currentIdentity, true)) { - proof = false; + if (proof === "ordinary" && !ordinaryProducerVerified) { + const ordinaryProof = await verifyCanonicalSmokeProducer(matching, null, currentIdentity, true); + if (ordinaryProof !== true) { + proof = ["snapshot-pending", "attempt-superseded"].includes(ordinaryProof) + ? ordinaryProof : false; + } } } catch (error) { if (error instanceof TerminalGitHubRequestError) throw error; @@ -1807,21 +2099,30 @@ jobs: await failNonTerminalSnapshot("before the workflow deadline"); return; } - const jobs = await withTransientGitHubRetry( - "runtime-images job lookup", - () => github.paginate( - typedRuntimeProof - ? "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" - : github.rest.actions.listJobsForWorkflowRun, - { - owner, - repo, - run_id: matching.id, - ...(typedRuntimeProof ? {attempt_number: matching.run_attempt} : {}), - per_page: 100, - } - ) - ); + let jobs; + try { + jobs = await withTransientGitHubRetry( + "runtime-images job lookup", + () => github.paginate( + typedRuntimeProof + ? "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" + : github.rest.actions.listJobsForWorkflowRun, + { + owner, + repo, + run_id: matching.id, + ...(typedRuntimeProof ? {attempt_number: matching.run_attempt} : {}), + per_page: 100, + } + ) + ); + } catch (error) { + if (error instanceof TerminalGitHubRequestError) throw error; + if (!isTransientGitHubFailure(error)) throw error; + core.warning(`Runtime job snapshot is temporarily unavailable: ${error.message ?? String(error)}`); + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } if (await isCurrentPullRequestObsolete("Stopping obsolete completed smoke gate for")) { return; } @@ -1834,33 +2135,53 @@ jobs: return; } fullSmokeJob = producerJobs[0] ?? null; - if (typedRuntimeProof && fullSmokeJob && - (fullSmokeJob.run_id !== matching.id || + let attemptIdentityPending = false; + if (typedRuntimeProof && fullSmokeJob) { + const identityFields = [fullSmokeJob.run_id, fullSmokeJob.run_attempt, fullSmokeJob.head_sha]; + if (identityFields.some(value => value == null)) { + attemptIdentityPending = true; + } else if (fullSmokeJob.run_id !== matching.id || fullSmokeJob.run_attempt !== matching.run_attempt || - fullSmokeJob.head_sha !== matching.head_sha)) { - await failNonTerminalSnapshot("with a producer from a different runtime attempt"); - return; + fullSmokeJob.head_sha !== matching.head_sha) { + await failNonTerminalSnapshot("with a producer from a different runtime attempt"); + return; + } } fullSmokeStep = fullSmokeJob?.steps?.find( (step) => step.name === "Run credential-free full-stack smoke" ) ?? null; - if (fullSmokeJob?.status === "completed") { + if (fullSmokeJob?.status === "completed" && !attemptIdentityPending) { // Typed success is ordinary proof only through the complete canonical producer. if (typedRuntimeProof && fullSmokeJob.name === canonicalSmokeJobName && fullSmokeJob.conclusion === "success") { + let canonicalProof = false; try { - canonicalProducerVerified = await verifyCanonicalSmokeProducer( + canonicalProof = await verifyCanonicalSmokeProducer( matching, fullSmokeJob, currentIdentity, true ); } catch (error) { if (error instanceof TerminalGitHubRequestError) throw error; + if (isTransientGitHubFailure(error)) { + core.warning(`Canonical smoke producer proof is temporarily unavailable: ${error.message ?? String(error)}`); + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } core.warning(`Canonical smoke producer proof is unavailable: ${error.message}`); } + if (canonicalProof === "attempt-superseded") { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + canonicalProducerVerified = canonicalProof === true; if (canonicalProducerVerified) break; // Marker-only lag retains its dedicated exact-attempt proof below. // Other missing terminal evidence keeps this typed snapshot pending. - if (!hasPendingCanonicalSmokeTerminalEvidence(fullSmokeJob) && - fullSmokeStep?.status === "completed") break; + const markerNeedsVerification = !(fullSmokeJob.steps ?? []).some((step) => + step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" && + step.status === "completed" && step.conclusion != null); + if (fullSmokeStep?.status === "completed" && (markerNeedsVerification || + (canonicalProof !== "snapshot-pending" && + !hasPendingCanonicalSmokeTerminalEvidence(fullSmokeJob)))) break; } else if (fullSmokeStep?.status === "completed") { // The native pull_request path keeps its existing step-proof behavior. break; @@ -1868,9 +2189,9 @@ jobs: if (!typedRuntimeProof && fullSmokeJob.name === canonicalSmokeJobName && fullSmokeJob.conclusion === "success") { try { - canonicalProducerVerified = await verifyCanonicalSmokeProducer( + canonicalProducerVerified = (await verifyCanonicalSmokeProducer( matching, fullSmokeJob, currentIdentity - ); + )) === true; } catch (error) { if (error instanceof TerminalGitHubRequestError) throw error; core.warning(`Canonical smoke producer proof is unavailable: ${error.message}`); @@ -1912,19 +2233,38 @@ jobs: let markerProof = false; if (matching.event === "repository_dispatch" && (markers.length === 0 || (markers.length === 1 && markers[0].status !== "completed"))) { - markerProof = await verifyKnownPlayFailure( - matching, fullSmokeJob, currentIdentity, true, true); + try { + markerProof = await verifyKnownPlayFailure( + matching, fullSmokeJob, currentIdentity, true, true); + } catch (error) { + if (error instanceof TerminalGitHubRequestError) throw error; + if (!isTransientGitHubFailure(error)) throw error; + core.warning(`Canonical PLAY marker proof is temporarily unavailable: ${error?.message ?? String(error)}`); + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } if (markerProof === "attempt-superseded") { await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } if (markerProof === "ordinary") { try { - canonicalProducerVerified = await verifyCanonicalSmokeProducer( + const ordinaryProof = await verifyCanonicalSmokeProducer( matching, fullSmokeJob, currentIdentity, true ); + if (ordinaryProof === "attempt-superseded") { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + if (ordinaryProof === "snapshot-pending") markerProof = "snapshot-pending"; + canonicalProducerVerified = ordinaryProof === true; } catch (error) { if (error instanceof TerminalGitHubRequestError) throw error; + if (isTransientGitHubFailure(error)) { + core.warning(`Canonical ordinary smoke proof is temporarily unavailable: ${error?.message ?? String(error)}`); + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } core.warning(`Canonical ordinary smoke proof is unavailable: ${error?.message ?? String(error)}`); } } @@ -1948,6 +2288,11 @@ jobs: matching, fullSmokeJob, currentIdentity, matching.event === "repository_dispatch"); } catch (error) { if (error instanceof TerminalGitHubRequestError) throw error; + if (isTransientGitHubFailure(error)) { + core.warning(`Canonical PLAY transition proof is temporarily unavailable: ${error?.message ?? String(error)}`); + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); } if (knownPlayVerified === "attempt-superseded") { diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 7cf51b2666..0ba850e3ce 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -90,7 +90,9 @@ Strict capacity follows the canonical [capacity-attempt proof obligations](../.. V1040.1 serializes the exact Account `ACCEPTED` and `NO_ACCEPT` origin decisions against reservation creation and rearm. A pre-V1040.1 writer cannot create a reservation after the guard applies. The [database migration compatibility and writer-quiescence policy](../../system-architecture-database-migrations.md#version-aware-migration-checklist) governs deployment. A reset must preserve results for still-eligible retries and may proceed only once external-action outcomes are known and any receipts to be discarded have passed their retry and reconciliation window. V1040.2 retains an exact quota denial under an explicitly installed finite tenant refusal limit. The same serializable owner transaction checks quota and chooses between a reservation and a denial. The denial carries no reservation and permanently excludes acceptance for the exact original. Exact replay returns the same decision even after capacity becomes available. An unavailable refusal budget or uncertain outcome leaves Game Session's reserve active. Account neither frees nor rearms an accepted reservation through this path. Before enabling any admission producer, the Account operator must provision every supported canonical tenant through `AccountCapacityRefusalBudgetRepository.provision` and call `requireReady` with the same explicit lifetime limit and the bounded admission cohort headroom in one writable owner transaction while producers remain quiescent. Commit only after both succeed; otherwise roll back the undersized installation so it does not permanently bind an unusable limit. Sizing is explicit: the finite lifetime limit must cover retained denials plus the planned denial cohort; it is not the gameplay capacity quota or an automatically replenished rate limit. Exact provisioning retries preserve the row and its historical evidence; a different limit conflicts. Missing, mismatched or insufficient budgets fail readiness. Readiness is a local observation, not a reservation or authority to admit, and the SQL trigger remains the runtime concurrency authority. Exhaustion requires stopping new admission and an independently designed retention-safe lifecycle, never deleting denials or resetting/increasing this immutable budget. No exhaustion detector or admission-producer stop control is implemented by these private repositories: the positive reservation path does not consult refusal headroom. Qualifying that stop, including last-slot consumption followed by available capacity, is an unmet activation prerequisite; provisioning readiness alone cannot satisfy it. These private methods do not register an endpoint, seed tenants automatically or activate the default-off capacity component. -V1040.6 backfills one immutable refusal slot per retained `NO_ACCEPT` decision. After origin identity arbitration, a fresh refusal takes the existing tenant budget lock, reads the highest slot through the tenant-slot index, and appends the next slot in the same transaction. Replay, conflict, and failed inserts leave the inventory unchanged. The migration preserves origin rows and provisioned limits. +Pre-v1 Account reset or deletion remains only the proposal in [ADR 0185](../../decisions/adr-0185-no-data-carry-over-before-v1.md), whose status is **Proposed - Pending Human Review**; this capacity implementation adds no reset, budget-reset, or refusal-receipt deletion operation. If ADR 0185 is later accepted, the reset must follow the [database migration compatibility and writer-quiescence policy](../../system-architecture-database-migrations.md#version-aware-migration-checklist) and keep every still-eligible exact retry or reconciliation read able to recover its original durable owner result, including a committed external action whose response was lost. Otherwise, discard a receipt only after the action family's documented retry and reconciliation window is proved ended and delayed requests are fenced from executing again. Uncertain action outcomes or retry eligibility block reset, and a provider reset or replay rejection does not replace recovery of the original result. + +V1040.6 backfills one immutable refusal slot per retained `NO_ACCEPT` decision as the contiguous sequence `1..N`. After origin identity arbitration, a fresh refusal takes the existing tenant budget lock, reads the highest slot through the tenant-slot index, and appends `N+1` in the same transaction. `requireReady` uses that indexed highest slot as the retained refusal count under this invariant to compute bounded headroom; the missing or mismatched budget and insufficient headroom remain fail-closed. Replay, conflict, and failed inserts leave the inventory unchanged. The migration preserves origin rows and provisioned limits. The unregistered capacity owner requires exact retained evidence and current Account membership/issuance/scope source equality before creating a new positive player-binding reservation. Exact attempt retries replay before fresh-source or usage work; changed complete payloads conflict. The Account recovery component alone can finalize, release or rearm under its current durable claim and exact selected-owner readback; an ambiguous observation records only the bounded retry/deadline and retains the hold. No runtime readback producer or recovery client is registered. World lifecycle, authoritative prior-shape/zero-delta recovery, current selected-owner activation and complete end-to-end qualification remain held as detailed in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 6706d69bb9..4c7b9f3828 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -88,9 +88,11 @@ The trust split is deliberate: PR-controlled source can build and execute withou A typed runtime refresh hands off publication explicitly after its required credential-free image and smoke jobs succeed and its image artifact upload succeeds; an exception pass with no uploaded artifact cannot dispatch publication. Its separate trusted default-ref job checks out no source and receives only job-scoped `contents: write` to send `pr-runtime-image-publication` with the sole `source_run_id` field. PR build jobs retain read-only repository permissions. The publisher accepts this fixed repository-dispatch type and ordinary successful runtime workflow-run callbacks, both using the trusted default-branch definition. It exposes no branch-selectable manual publication entrypoint and requires no additional credential. +For typed publication, `source_run_id` selects a native Actions run for lookup; neither the payload nor its title is source authority. The no-checkout resolver binds the returned native `run.id` to that supplied ID and its `workflow_id` to the separately resolved runtime workflow identity (`Build Runtime Images` at `.github/workflows/runtime-images.yml`). The native run path must be that workflow path or its validated ref-suffixed form, and its name must be the owner workflow name or exact canonical display title. It requires native `event=repository_dispatch`, the current repository in both `repository` and `head_repository`, `head_branch` equal to the repository default branch, a lowercase 40-character native `head_sha` for that default-branch source revision, and the canonical runtime title carrying the exact PR number/base/head/merge tuple and `mode-required`. The type and default-branch ref are also checked at the handoff boundary. This trusted typed source identity comes from GitHub's Actions run and workflow records, not from caller-supplied tuple fields. + The publisher's no-checkout, Actions-read-only resolver reads only the supplied exact source run and owning runtime workflow identity. A dispatch can arrive before its source workflow finishes, so the resolver waits for actual terminal success within a two-minute budget; malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. The resolver never substitutes a successful status. Both trigger paths retain the same exact source, current PR/base/head/merge, artifact provenance, and immutable-tag validation. Publishing jobs serialize on the verified merge-bound source title across both paths; duplicate publication preserves identical existing images and rejects conflicting image bytes. Explicit dispatch avoids relying on a workflow-run callback from a token-origin refresh without weakening the source or registry boundary. -The trusted publisher also reconciles a failed, cancelled, or timed-out original same-repository PR runtime run when substantive Validation already completed. This API-only job has `contents: write` solely to request an exact typed refresh; it never checks out PR code. It verifies current native source and CI attempts, the live base/head/merge tuple, and absence of a newer original or typed refresh before dispatch. Typed-refresh and nested workflow callbacks cannot recursively invoke this recovery. The CI dispatcher and completion reconciler share an API-job concurrency group with `queue: max`; runtime builds remain parallel. Unknown inventory fails closed, and an uncertain dispatch is not blindly repeated. Accepted handoffs share one 120-second visibility window after fan-out rather than delaying each later target in turn. Preview reconciliation checks its own current tuple independently of runtime handoff uncertainty; a failed target does not automatically suppress independent later targets. This is bounded coordination, not exactly-once delivery or an unbounded no-starvation guarantee: GitHub admits at most 100 pending jobs in the group, inventories and job durations are bounded, and existing superseding base callbacks can cancel obsolete work. Remaining unknown outcomes require fresh evidence rather than presumed success. +The trusted publisher also reconciles a failed, cancelled, or timed-out original same-repository PR runtime run when substantive Validation already completed. This API-only job has `contents: write` solely to request an exact typed refresh; it never checks out PR code. It verifies current native source and CI attempts, the live base/head/merge tuple, and absence of a newer original or typed refresh before dispatch. Typed-refresh and nested workflow callbacks cannot recursively invoke this recovery. The CI dispatcher and completion reconciler share an API-job concurrency group with `queue: max`; runtime builds remain parallel. Unknown or incomplete producer inventory fails closed. Before each candidate runtime POST, the dispatcher refreshes the complete producer inventory, suppresses a newly reusable exact producer, and rechecks the current PR tuple and base ref; each handoff remains a single non-retried POST. An uncertain dispatch is not blindly repeated. Accepted handoffs share one 120-second visibility window after fan-out rather than delaying each later target in turn. The dispatcher resolves the current native runtime workflow identity before classifying observed producers and retries only transient identity lookup failures within that existing visibility deadline; it never retries a POST. Visibility requires a complete native producer inventory, the exact tuple title and current workflow/repository identity, a new run ID absent from the complete pre-POST snapshot, and a creation timestamp no earlier than the dispatch timestamp second. Preview reconciliation checks its own current tuple independently of runtime handoff uncertainty; a failed target does not automatically suppress independent later targets. This is bounded coordination, not exactly-once delivery or an unbounded no-starvation guarantee: GitHub admits at most 100 pending jobs in the group, inventories and job durations are bounded, and existing superseding base callbacks can cancel obsolete work. Remaining unknown outcomes require fresh evidence rather than presumed success. Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard. Ordinary runtime qualification requires both Actions-native outcomes to be `success` and the transition-exception marker to be explicitly skipped. Missing marker metadata cannot use the native-job fallback: a successful job alone may instead represent the bounded exception described below. Skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify as real runtime proof. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. A separate, temporary diagnostic exception lets the required Smoke Gate succeed for a same-repository `benhook1013/FireMUD` pull request whose current live PR carries the `canonical-play-transition` label. A `pull_request` producer also requires the source event label and exact verified PR-event base/head/merge tuple. A typed `pr-runtime-base-refresh` producer instead derives label authority from its verified live same-repository PR, never dispatch payload labels, and requires the exact current base/head/merge tuple again at consumption. Both paths require the latest successful CI attempt with its explicit exception marker while the PR head and base branch remain current. During the default-branch workflow rollout, the exact previous fail-red producer fingerprint remains accepted only with its original failed smoke and terminal guard plus successful marker and cleanup; it supplies the same diagnostic exception and no runtime qualification. The smoke invocation retains its failed Actions-native outcome through step-level continuation; only the exact label, classifier and successful authenticated cleanup can make the mandatory final guard accept that failed probe. Every other probe failure still fails CI. GitHub reports the continued step conclusion as success, so the consumer verifies the immutable marker rather than treating that conclusion as runtime proof. The fingerprinted producer must attest the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, with successful authenticated cleanup. The executing workflow is fingerprinted at the PR merge revision or typed refresh's native default-branch revision, respectively; classifiers, held-admission qualification, authenticated cleanup, certificate setup, and their checked-in environment and Compose inputs are always fingerprinted at the tested PR merge. Its original smoke failure remains visible in the probe logs, summary and Actions-native outcome; unrelated failures still block, and image export and upload must be skipped. The typed publication handoff also requires a real successful image upload. A trusted workflow-run publisher detects the exception marker before exposing a publication source and skips its privileged job; a successful CI conclusion under exception does not authorize registry access or preview images. This is gate acceptance for the nonproduction canonical cutover, not successful smoke, runtime qualification, branch-image promotion, hosted preview eligibility, or production activation. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception; after the cutover merges, branch images remain on hold until the Account entitlement path is repaired. Remove the label-based marker and consumer exception when fresh-image backend `LOGIN` → `PLAY` → `LOOK` passes, then remove this transitional contract. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index b22951c554..a830f6a07e 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -833,6 +833,12 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single", t ]}; return; } + if (selectionCase === "wrong-base-only") { + const staleBase = makeRun(43, "2026-09-01T00:00:01Z", "completed", "failure"); + staleBase.display_title = title.replace(base, "f".repeat(40)); + yield {data: [staleBase, makeRun(42, "2026-09-01T00:00:00Z", "completed", "success")]}; + return; + } if (["cancelled-executed", "cancelled-partial-inventory", "cancelled-empty-inventory", "cancelled-unknown-outcome", "cancelled-changed-attempt", "cancelled-older-success"].includes(selectionCase)) { yield {data: [ @@ -888,6 +894,8 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single", t assert.deepEqual(olderSuccess.failures, [], "only a complete no-step cancellation may be excluded from authority"); const ignoredDistractors = await scenario("success", 0, "wrong-tuple-event"); assert.deepEqual(ignoredDistractors.failures, [], "wrong-event and wrong-head runs must not displace the exact run"); + const baseOnlyDistractor = await scenario("success", 0, "wrong-base-only"); + assert.deepEqual(baseOnlyDistractor.failures, [], "a same-event, same-head stale base tuple must not displace exact-base proof"); const cancelled = await scenario("cancelled", 0); assert.equal(cancelled.failures.length, 1); assert.match(cancelled.failures[0], /cancelled/i); @@ -1013,6 +1021,7 @@ async function scenario(kind, event = "pull_request") { "wrong-dispatch-branch": {head_branch: "feature"}, }; const listRuns = async () => {}, listJobs = async () => {}; + let exactAttemptReads = 0; const github = {rest: { pulls: {get: async () => { reads += 1; @@ -1042,6 +1051,16 @@ async function scenario(kind, event = "pull_request") { }, request: async (route, input) => { assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"); assert.equal(input.run_id, 42); assert.equal(input.attempt_number, 1); + exactAttemptReads++; + if (kind === "transient-exact-attempt" && exactAttemptReads <= 4) { + throw Object.assign(new Error("temporary exact-attempt lookup"), {status: 502}); + } + if (kind === "sparse-exact-attempt-source" && exactAttemptReads === 3) { + return {data: {...source, run_attempt: undefined}}; + } + if (kind === "sparse-exact-attempt-status" && exactAttemptReads === 3) { + return {data: {...source, status: undefined}}; + } return {data: {...source, ...(sourceMutations[kind] || {})}}; }, paginate: async (method, input) => { if (method === listJobs) { snapshots += 1; return kind === "duplicate-jobs" ? [job, {...job, id: 101}] : [job]; } @@ -1055,6 +1074,24 @@ async function scenario(kind, event = "pull_request") { return [{...job, steps: job.steps.map(step => step.name === "Require successful runtime smoke and authenticated cleanup" ? {...step, status: "in_progress", conclusion: null} : step)}]; } + if (kind === "transient-exact-job-list" && snapshots <= 4) { + throw Object.assign(new Error("temporary exact-attempt jobs lookup"), {status: 502}); + } + if (kind === "transient-canonical-job-list" && snapshots >= 2 && snapshots <= 5) { + throw Object.assign(new Error("temporary canonical attempt jobs lookup"), {status: 502}); + } + if (kind === "sparse-exact-job-snapshots" && snapshots === 2) { + return [{...job, steps: job.steps.filter(step => + step.name !== "Known canonical transition PLAY failure with successful authenticated cleanup")}]; + } + if (kind === "sparse-exact-job-identity" && snapshots === 2) { + return [{...job, run_id: undefined}]; + } + if (kind === "cross-snapshot-changed-job-id" && snapshots === 2) { + const changed = {...job, id: job.id + 1}; + changed.check_run_url = `https://api.github.com/repos/${repository}/check-runs/${changed.id}`; + return [changed]; + } const mutations = { "wrong-job": {id: 101}, "wrong-job-run": {run_id: 43}, "wrong-job-attempt": {run_attempt: 2}, "wrong-job-head": {head_sha: "e".repeat(40)}, "wrong-check-url": {check_run_url: "https://example.com/check"}, @@ -1098,6 +1135,17 @@ async function scenario(kind, event = "pull_request") { assert.deepEqual(result.failures, [], `${kind} must wait for exact terminal step evidence to converge`); assert(result.snapshots >= 4 && result.waitedMillis > 0, `${kind} retries only after a bounded pause`); } + for (const kind of ["transient-exact-attempt", "transient-exact-job-list", + "transient-canonical-job-list", "sparse-exact-attempt-source", "sparse-exact-attempt-status", + "sparse-exact-job-snapshots", "sparse-exact-job-identity"]) { + const result = await scenario(kind, "repository_dispatch"); + assert.deepEqual(result.failures, [], `${kind} remains pending until fresh exact-attempt proof is available`); + assert(result.snapshots >= 3 && result.waitedMillis > 0, `${kind} retries within the existing proof budget`); + } + const changedJobId = await scenario("cross-snapshot-changed-job-id", "repository_dispatch"); + assert.equal(changedJobId.failures.length, 1, + "a job ID that changes between exact-attempt snapshots is contradictory, not a successful proof"); + assert.match(changedJobId.failures[0], /Cancelled runtime replacement has contradictory identity/); const moved = await scenario("drift-during-final-attempt", "repository_dispatch"); assert(moved.observedBaseMove, "typed acceptance must re-read the live base after the final attempt lookup"); console.log("Smoke producer contract passed: native outcomes, exact immutable definition/attempt, legacy proof and fail-closed cases"); @@ -3798,12 +3846,13 @@ async function verify(mutate = () => {}, event = "pull_request", knownPlay = tru value => Number.isSafeInteger(value) && value > 0, (_label, call) => call(), {payload: {repository: {default_branch: "develop"}, pull_request: {head: {repo: {full_name: data.eventHeadRepository}}}}}, "benhook1013", "FireMUD", require, data); - const pendingMarker = accepted === "snapshot-pending" && allowOrdinary && - event === "repository_dispatch" && data.source.conclusion === "success" && - !data.jobs.some(job => job.steps.some(step => step.name.startsWith("Known canonical") && step.status === "completed")); - if (accepted) assert.deepEqual(contentRequests, - knownPlay && accepted !== "ordinary" && !pendingMarker - ? [workflowPath, ...Object.keys(classifierDefinitions)] : [workflowPath]); + const proofPaths = knownPlay && accepted !== "ordinary" + ? [workflowPath, ...Object.keys(classifierDefinitions)] : [workflowPath]; + if (accepted === "snapshot-pending") { + assert.deepEqual(contentRequests, proofPaths.slice(0, contentRequests.length)); + } else if (accepted) { + assert.deepEqual(contentRequests, proofPaths); + } return accepted; } // Final attempt authority remains separate from PR identity and label authority. @@ -3973,7 +4022,10 @@ async function failedLegacyProof(stage, error, event = "pull_request") { } // Run the production polling loop and timeout handler with a fake clock. const loopStart = script.indexOf("let currentIdentity = null;"); -const actualPollingLoop = script.slice(loopStart); +const replacementVerifier = script.indexOf("async function verifySameTupleReplacementProof(", loopStart); +const pollStart = script.indexOf("smokeGatePolling: while", replacementVerifier); +assert.ok(loopStart >= 0 && replacementVerifier > loopStart && pollStart > replacementVerifier); +const actualPollingLoop = script.slice(loopStart, replacementVerifier) + script.slice(pollStart); async function pendingRefreshCaller(statuses, expires = false, options = {}) { const failures = [], outputs = []; let sleeps = 0, polls = 0, writes = 0, now = 0, currentChecks = 0, finalChecks = 0, nullReads = 0, directReads = 0; @@ -3991,6 +4043,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { "Date", "started", "timeoutMs", "pullRequestCheckInterval", "findMatchingRuntimeImagesRun", "prNumber", "identityDiagnostic", "cancelledReplacementTimeoutMs", "context", "refreshDiscoveryTimeoutMs", "completedSnapshotTimeoutMs", "snapshotSleepMs", "positiveInteger", "isCurrentCanonicalAttempt", + "verifySameTupleReplacementProof", `return (async () => { let pollIteration = 0; ${actualPollingLoop} })();`); await execute(repositoryName, workflowPath, isRuntimeSourceWorkflowPath, {rest: {actions: {listJobsForWorkflowRun: "jobs"}}, paginate: async () => { if (options.originalError) throw options.originalError; @@ -4080,7 +4133,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { return finalAttemptCheck(null, Object.assign(new Error("temporary"), {status: 502})); } return !options.rerunFinal || finalChecks > 1; - }); + }, async () => "ordinary"); if (options.ordinaryAfterDrift) { assert.deepEqual(failures, []); assert.deepEqual(outputs, []); assert.equal(writes, 0); } else if (options.directInvalid) { @@ -4150,6 +4203,7 @@ async function movedCancellation(ordinaryProof, listedOldReplacement = false) { "setTimeout", "sleepMs", "Date", "started", "timeoutMs", "pullRequestCheckInterval", "findMatchingRuntimeImagesRun", "prNumber", "identityDiagnostic", "cancelledReplacementTimeoutMs", "context", "refreshDiscoveryTimeoutMs", "completedSnapshotTimeoutMs", "positiveInteger", "isCurrentCanonicalAttempt", + "verifySameTupleReplacementProof", `return (async () => { let pollIteration = 0; ${actualPollingLoop} })();`); await execute(repositoryName, workflowPath, isRuntimeSourceWorkflowPath, canonicalSmokeJobName, (_label, call) => call(), async (run, candidate, selected, incomplete, ordinary) => { @@ -4171,11 +4225,62 @@ async function movedCancellation(ordinaryProof, listedOldReplacement = false) { {payload: {pull_request: {head: {ref: "feature", repo: {full_name: repositoryName}}}}}, 60, 30, value => Number.isSafeInteger(value) && value > 0, async run => { finalReads++; assert.equal(run, refresh); return true; - }); + }, async () => "ordinary"); assert.equal(typedReads, 2); assert.equal(proofReads, 1); assert.equal(finalReads, ordinaryProof ? 1 : 0); assert.deepEqual(outputs, [], "ordinary proof never publishes an exception output"); assert.deepEqual(failures, ordinaryProof ? [] : ["Moved cancelled-run recovery did not supply authenticated smoke proof."]); } +async function sameTupleCancellation(replacementStatus, proofSequence = [], sparseAttempt = false) { + let now = 0, proofReads = 0, runtimeJobReads = 0, sleeps = 0; + const sameIdentity = {...identity, sourceEvent: "pull_request"}; + const old = {...source, id: 98, event: "pull_request", status: "completed", conclusion: "cancelled", + head_sha: identity.headSha, head_branch: "feature", repository: {full_name: "other/repo"}, + display_title: `Build Runtime Images secure-pr-artifact pr-3390 base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`}; + const replacement = {...source, id: 99, event: "repository_dispatch", status: replacementStatus, + conclusion: replacementStatus === "completed" ? "success" : null, head_sha: workflowSha, + ...(sparseAttempt ? {run_attempt: undefined} : {})}; + const smokeJob = {...candidate, id: 123, run_id: replacement.id, run_attempt: replacement.run_attempt, + head_sha: replacement.head_sha, name: canonicalSmokeJobName, conclusion: "success", + status: "completed", check_run_url: `https://api.github.com/repos/${repositoryName}/check-runs/123`, + steps: [ + step("Known canonical transition PLAY failure with successful authenticated cleanup", "skipped"), + step("Run credential-free full-stack smoke", "success"), + step("Stop smoke stack", "success"), + step("Require successful runtime smoke and authenticated cleanup", "success"), + ]}; + const failures = [], outputs = []; + const core = {info() {}, warning() {}, setFailed: value => failures.push(value), setOutput: (...value) => outputs.push(value)}; + const execute = new Function("repositoryName", "workflowPath", "isRuntimeSourceWorkflowPath", "github", "owner", "repo", + "canonicalSmokeJobName", "withTransientGitHubRetry", "verifyKnownPlayFailure", "verifyCanonicalSmokeProducer", + "isTransientGitHubFailure", "hasPendingCanonicalSmokeTerminalEvidence", "verifyFailedPullCanonicalRefresh", + "isCurrentPullRequestObsolete", "TerminalGitHubRequestError", "core", "resolveCurrentIdentity", "identityKey", + "setTimeout", "sleepMs", "Date", "started", "timeoutMs", "pullRequestCheckInterval", "findMatchingRuntimeImagesRun", + "prNumber", "identityDiagnostic", "cancelledReplacementTimeoutMs", "context", "refreshDiscoveryTimeoutMs", + "completedSnapshotTimeoutMs", "snapshotSleepMs", "positiveInteger", "isCurrentCanonicalAttempt", + "verifySameTupleReplacementProof", + `return (async () => { let pollIteration = 0; ${actualPollingLoop} })();`); + await execute(repositoryName, workflowPath, isRuntimeSourceWorkflowPath, {rest: {actions: {listJobsForWorkflowRun: "jobs"}}, + paginate: async (route, input) => { + assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); + assert.equal(input.run_id, replacement.id); assert.equal(input.attempt_number, replacement.run_attempt); + runtimeJobReads++; + return [smokeJob]; + }}, "benhook1013", "FireMUD", canonicalSmokeJobName, (_label, call) => call(), async () => false, + async () => true, isTransientGitHubFailure, hasPendingCanonicalSmokeTerminalEvidence, async () => false, + async () => false, TerminalGitHubRequestError, core, async () => sameIdentity, + selected => JSON.stringify(selected), resolve => {sleeps++; now += 10; resolve();}, 10, + {now: () => now}, 0, 1000, 1, async event => event === "pull_request" ? old : replacement, + "3390", "test identity", 50, + {payload: {pull_request: {head: {ref: "feature", repo: {full_name: repositoryName}}}}}, + 200, 100, 10, value => Number.isSafeInteger(value) && value > 0, async () => true, + async (run, selected) => { + proofReads++; + assert.equal(run, replacement); + assert.deepEqual(selected, sameIdentity); + return proofSequence[Math.min(proofReads - 1, proofSequence.length - 1)] ?? false; + }); + return {failures, outputs, now, proofReads, runtimeJobReads, sleeps}; +} // Exercise the real resolver, not merely a stub that honors requireCurrent. async function refreshFinalIdentity(eventUnavailable = false) { const start = script.indexOf("async function resolveCurrentIdentity("); @@ -4254,6 +4359,36 @@ function markerAccepted(overrides = {}) { await movedCancellation(false); await movedCancellation(true, true); await movedCancellation(false, true); + const unprovenInProgressReplacement = await sameTupleCancellation("in_progress"); + assert.equal(unprovenInProgressReplacement.failures.length, 1); + assert.match(unprovenInProgressReplacement.failures[0], /no freshly proven exact replacement/); + assert.equal(unprovenInProgressReplacement.now, 50, + "an in-progress speculative replacement cannot extend the original cancellation deadline"); + assert.equal(unprovenInProgressReplacement.proofReads, 0); + assert.equal(unprovenInProgressReplacement.runtimeJobReads, 0, + "an unproven replacement does not take over the cancelled original"); + const sparseReplacement = await sameTupleCancellation("completed", ["snapshot-pending"]); + assert.equal(sparseReplacement.failures.length, 1); + assert.equal(sparseReplacement.now, 50, + "sparse exact replacement snapshots remain bounded by the original cancellation deadline"); + assert.equal(sparseReplacement.runtimeJobReads, 0); + const sparseReplacementAttempt = await sameTupleCancellation("completed", [], true); + assert.equal(sparseReplacementAttempt.failures.length, 1); + assert.equal(sparseReplacementAttempt.now, 50, + "missing replacement attempt identity remains pending only until the original cancellation deadline"); + assert.equal(sparseReplacementAttempt.proofReads, 0); + assert.equal(sparseReplacementAttempt.runtimeJobReads, 0); + const sequencedReplacement = await sameTupleCancellation("completed", ["snapshot-pending", "ordinary"]); + assert.deepEqual(sequencedReplacement.failures, []); + assert.equal(sequencedReplacement.proofReads, 2, + "a same-tuple replacement becomes authoritative only after a fresh complete exact proof"); + assert.equal(sequencedReplacement.runtimeJobReads, 1); + assert.equal(sequencedReplacement.now, 10); + const invalidReplacement = await sameTupleCancellation("completed", [false]); + assert.equal(invalidReplacement.failures.length, 1); + assert.match(invalidReplacement.failures[0], /contradictory identity or invalid terminal smoke proof/); + assert.equal(invalidReplacement.runtimeJobReads, 0, + "invalid terminal replacement proof remains fail-closed rather than falling back to unverified jobs"); assert.equal((await recoveredFailure({original: {conclusion: "timed_out"}})).accepted, true); await pendingRefreshCaller(["queued", "completed"], false, {originalConclusion: "timed_out"}); for (const siblingStatus of ["in_progress", "queued"]) { diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index ad8462a755..5101829b86 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -898,6 +898,7 @@ async function runDispatcher({ hideDispatchVisibility = false, filesByPr = {}, postFailurePr = null, previewFailurePr = null, visibilityResponse = null, filesFailurePr = null, postFailureVisible = false, postFailureStatus = null, fanoutCutoffAfterInventory = false, fanoutCutoffAfterPreviewPr = null, expireAfterFirstApiRequest = false, + pullGetFailures = {}, lateProducer = null, runtimeWorkflowLookupFailures = [], initialTime = "2026-01-08T00:00:00Z", }) { const dispatches = []; @@ -911,6 +912,9 @@ async function runDispatcher({ const timerPostCounts = []; const deadlineSignals = []; const apiRequestRecords = []; + const lateProducers = []; + let lateProducerAdded = false; + let runtimeWorkflowLookupCount = 0; let waitedMillis = 0; let fakeNow = Date.parse(initialTime); let expireOnFirstRequest = expireAfterFirstApiRequest; @@ -1007,6 +1011,12 @@ async function runDispatcher({ const number = String(pull_number); const reads = (pullReads.get(number) ?? 0) + 1; pullReads.set(number, reads); + const pullGetFailure = typeof pullGetFailures[number] === "function" + ? pullGetFailures[number](reads) + : pullGetFailures[number]; + if (pullGetFailure) { + throw Object.assign(new Error("fixture initial pull request lookup failed"), {status: pullGetFailure}); + } const override = pullOverrides[number]; return { data: { ...pullRequestFor(tupleByNumber.get(number)), @@ -1061,9 +1071,13 @@ async function runDispatcher({ getWorkflow: async (request) => { recordApiRequest("actions.getWorkflow", request); const {workflow_id} = request; - return { data: workflow_id === "runtime-images.yml" - ? {id: 701, path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images"} - : {id: ciRun.workflow_id, path: ".github/workflows/ci.yml", name: "CI — Validation", ...(ciEvidence.workflow ?? {})} }; + if (workflow_id === "runtime-images.yml") { + runtimeWorkflowLookupCount += 1; + const failure = runtimeWorkflowLookupFailures[runtimeWorkflowLookupCount - 1]; + if (failure) throw Object.assign(new Error("fixture producer workflow lookup failed"), {status: failure}); + return {data: {id: 701, path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images"}}; + } + return {data: {id: ciRun.workflow_id, path: ".github/workflows/ci.yml", name: "CI — Validation", ...(ciEvidence.workflow ?? {})}}; }, getWorkflowRun: async (request) => { recordApiRequest("actions.getWorkflowRun", request); @@ -1091,7 +1105,9 @@ async function runDispatcher({ const suppliedRuns = Array.isArray(inventory) ? inventory : refinement ? inventory.refined : inventory.initial ?? inventory.runs ?? []; - const runs = [...suppliedRuns, ...(request.event === "repository_dispatch" ? postedRuns : [])]; + const runs = [...suppliedRuns, + ...(request.event === "repository_dispatch" ? lateProducers : []), + ...(request.event === "repository_dispatch" ? postedRuns : [])]; const createdMatch = /^(.+)\.\.\*$/.exec(request.created ?? ""); const createdFloor = createdMatch ? Date.parse(createdMatch[1]) : Number.NaN; const filteredRuns = Number.isFinite(createdFloor) @@ -1109,6 +1125,13 @@ async function runDispatcher({ ? inventory.refinedTotalCount ?? filteredRuns.length : inventory.initialPageTotals?.[request.page] ?? inventory.initialTotalCount ?? inventory.total_count ?? filteredRuns.length; const response = { data: { total_count: filteredTotalCount, workflow_runs: filteredRuns.slice((request.page - 1) * 100, request.page * 100) } }; + const broadRuntimeInventoryCalls = inventoryCalls.filter(call => + call.created !== "2026-01-08T00:00:00.000Z..*" + ).length; + if (lateProducer && !lateProducerAdded && broadRuntimeInventoryCalls === 2) { + lateProducerAdded = true; + lateProducers.push(lateProducer); + } if (fanoutCutoffAfterInventory && request.event === "repository_dispatch") { fakeNow += 12 * 60 * 1000; } @@ -1171,7 +1194,8 @@ async function runDispatcher({ global.setTimeout = originalSetTimeout; } return { dispatches, errors, infos, warnings, inventoryCalls, observationPostCounts, timerPostCounts, waitedMillis, - ciJobRequests, pullListRequests, refRequests, deadlineSignals, apiRequestRecords, fatalError }; + ciJobRequests, pullListRequests, pullReads, refRequests, deadlineSignals, apiRequestRecords, + runtimeWorkflowLookupCount, fatalError }; } (async () => { @@ -1494,6 +1518,34 @@ async function runDispatcher({ }); assert.deepEqual(numbers(existingFirst), ["102"], "existing first PR must not starve second"); assert.equal(existingFirst.errors.length, 0, existingFirst.errors.join("\n")); + const initialTargetReadFailure = await runDispatcher({ + tuples: [tuple, sibling], pullGetFailures: {"101": 502}, + }); + assert.deepEqual(numbers(initialTargetReadFailure), ["102"], + "a failed first pulls.get while resolving listed PR #101 must not prevent PR #102 from progressing"); + assert.equal(initialTargetReadFailure.pullReads.get("101"), 1, + "the isolated failure is the initial native PR lookup for listed PR #101"); + assert(initialTargetReadFailure.pullReads.get("102") > 0, + "later exact target discovery continues after the initial PR #101 read fails"); + assert(initialTargetReadFailure.errors.some(message => + message.includes("Cannot verify runtime target tuple for PR #101") && message.includes("no dispatch issued")), + "the unavailable PR #101 tuple remains an explicit failed target rather than silent success"); + const lateSiblingProducer = producer(sibling, "repository_dispatch", "in_progress", null, { + id: 90202, created_at: "2026-01-03T00:00:00Z", + }); + const refreshedAfterReuse = await runDispatcher({ + tuples: [tuple, sibling], + inventories: {pull_request: [producer(tuple, "pull_request", "in_progress")]}, + lateProducer: lateSiblingProducer, + }); + assert.deepEqual(numbers(refreshedAfterReuse), [], + "a full fresh producer inventory before the second candidate POST must find a producer hidden from the reused cache"); + assert.equal(refreshedAfterReuse.inventoryCalls.filter(request => + request.created !== "2026-01-08T00:00:00.000Z..*" + ).length, 4, "a cached initial snapshot is refreshed across both event kinds before a later candidate POST"); + assert.equal(previewDispatches(refreshedAfterReuse).length, 2, + "the last-minute producer discovery must not suppress independent preview reconciliation"); + assert.equal(refreshedAfterReuse.errors.length, 0, refreshedAfterReuse.errors.join("\n")); const skippedFirst = await runDispatcher({ tuples: [tuple, sibling], filesByPr: { "101": [{ filename: "README.md" }] }, }); @@ -1706,6 +1758,33 @@ async function runDispatcher({ assert.equal(transientReads, 2); assert.equal(transient.waitedMillis, 5000); assert.deepEqual(transient.errors, []); + const transientProducerIdentity = await runDispatcher({ + tuples: [tuple], runtimeWorkflowLookupFailures: [503], + }); + assert.deepEqual(numbers(transientProducerIdentity), ["101"], + "a transient post-dispatch producer identity lookup retries observation, never the handoff"); + assert.equal(transientProducerIdentity.runtimeWorkflowLookupCount, 2); + assert.equal(transientProducerIdentity.waitedMillis, 5000); + assert.equal(transientProducerIdentity.errors.length, 0, transientProducerIdentity.errors.join("\n")); + assertRequestContracts(transientProducerIdentity); + const deniedProducerIdentity = await runDispatcher({ + tuples: [tuple], runtimeWorkflowLookupFailures: [403], + }); + assert.deepEqual(numbers(deniedProducerIdentity), ["101"], + "a non-transient producer identity lookup failure cannot retransmit the one-shot handoff"); + assert.equal(deniedProducerIdentity.runtimeWorkflowLookupCount, 1, + "only transient producer identity lookup failures are retried"); + assert.equal(deniedProducerIdentity.waitedMillis, 0); + assert(deniedProducerIdentity.errors.some(message => message.includes("producer workflow identity could not be trusted"))); + const expiredProducerIdentity = await runDispatcher({ + tuples: [tuple], runtimeWorkflowLookupFailures: Array(30).fill(503), + }); + assert.deepEqual(numbers(expiredProducerIdentity), ["101"]); + assert.equal(expiredProducerIdentity.runtimeWorkflowLookupCount, 24, + "transient producer identity lookup retries stop at the existing two-minute observation deadline"); + assert.equal(expiredProducerIdentity.waitedMillis, 120000); + assert(expiredProducerIdentity.errors.some(message => message.includes("visibility deadline"))); + assertRequestContracts(expiredProducerIdentity); for (const [failure, reason] of [ [() => { throw Object.assign(new Error("visibility forbidden"), {status: 403}); }, "visibility forbidden"], [() => ({total_count: 1, workflow_runs: []}), "recent run inventory is incomplete"], diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 513ad38ee5..0e57e9eac5 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -409,12 +409,18 @@ const gate = { ], }; -async function runReconcile({ambiguousPost = true, expireFirstRequest = false} = {}) { +async function runReconcile({ + ambiguousPost = true, expireFirstRequest = false, initialDiscoveryUnavailable = false, + ciRuns = [ciRun], ciNativeRuns = {}, ciJobsByRun = {}, postVisibilityRuns = null, +} = {}) { let now = Date.parse("2026-01-08T00:00:00Z"); let expire = expireFirstRequest; + let failInitialDiscovery = initialDiscoveryUnavailable; let visibleRun = null; let postAttempts = 0; const requests = []; + const inventoryRequests = []; + const nativeJobRunIds = []; const signals = []; const dispatchRequests = []; const warnings = []; @@ -476,7 +482,7 @@ async function runReconcile({ambiguousPost = true, expireFirstRequest = false} = }, getWorkflowRun: async options => { record("actions.getWorkflowRun", options, {owner, repo, run_id: options.run_id}); - return {data: options.run_id === source.id ? source : ciRun}; + return {data: options.run_id === source.id ? source : ciNativeRuns[options.run_id] ?? ciRun}; }, listWorkflowRuns: async options => { const {workflow_id: workflowId, event, head_sha: requestedHead, created, per_page, page} = options; @@ -484,9 +490,17 @@ async function runReconcile({ambiguousPost = true, expireFirstRequest = false} = if (requestedHead !== undefined) normal.head_sha = requestedHead; if (created !== undefined) normal.created = created; record("actions.listWorkflowRuns", options, normal); + inventoryRequests.push(options); + if (failInitialDiscovery && workflowId === "runtime-images.yml" && + event === "pull_request" && created === undefined) { + failInitialDiscovery = false; + throw Object.assign(new Error("fixture initial runtime discovery unavailable"), {status: 503}); + } let runs = []; - if (workflowId === "ci.yml") runs = [ciRun]; - if (workflowId === "runtime-images.yml" && event === "repository_dispatch" && visibleRun) runs = [visibleRun]; + if (workflowId === "ci.yml") runs = ciRuns; + if (workflowId === "runtime-images.yml" && event === "repository_dispatch" && visibleRun) { + runs = postVisibilityRuns ?? [visibleRun]; + } return {data: {total_count: runs.length, workflow_runs: runs}}; }, }, @@ -528,8 +542,11 @@ async function runReconcile({ambiguousPost = true, expireFirstRequest = false} = }, paginate: async (route, options) => { assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); - record("paginate.jobs", options, {owner, repo, run_id: ciRun.id, attempt_number: 1, per_page: 100}); - return [gate]; + record("paginate.jobs", options, { + owner, repo, run_id: options.run_id, attempt_number: options.attempt_number, per_page: 100, + }); + nativeJobRunIds.push(options.run_id); + return ciJobsByRun[options.run_id] ?? [gate]; }, }; let failure = null; @@ -539,7 +556,8 @@ async function runReconcile({ambiguousPost = true, expireFirstRequest = false} = } catch (error) { failure = error; } - return {failure, now, requests, signals, dispatchRequests, postAttempts, warnings, infos}; + return {failure, now, requests, signals, inventoryRequests, nativeJobRunIds, + dispatchRequests, postAttempts, warnings, infos}; } (async () => { @@ -553,8 +571,74 @@ async function runReconcile({ambiguousPost = true, expireFirstRequest = false} = assert(uncertainPost.infos.some(message => message.includes("exact refresh is visible"))); assert(uncertainPost.requests.some(({name}) => name === "actions.listWorkflowRuns"), "the one-shot handoff must be followed by source-derived visibility observation"); + const postVisibilityFloor = "2026-01-08T00:00:00.000Z..*"; + const assertExactPostVisibilityFilter = result => { + const observationReads = result.inventoryRequests.filter(request => request.created === postVisibilityFloor); + assert(observationReads.length > 0, "post-POST observation must query from the dispatch timestamp second"); + for (const request of observationReads) { + const {request: requestOptions, ...normalOptions} = request; + assert.deepEqual(normalOptions, { + owner, repo, workflow_id: "runtime-images.yml", event: "repository_dispatch", + created: postVisibilityFloor, per_page: 100, page: 1, + }, "visibility must be a complete bounded native producer query on the exact post-POST time filter"); + assert.deepEqual(Object.keys(requestOptions).sort(), ["signal"], + "post-POST visibility query carries only its source-derived deadline signal"); + } + assert.equal(result.postAttempts, 1, "post-POST visibility must never retransmit a dispatch"); + }; + assertExactPostVisibilityFilter(uncertainPost); assert(uncertainPost.requests.every(({signal}) => signal.timeoutMs > 0), "every mocked GitHub request receives a positive wall-clock AbortSignal budget"); + const sameSecondVisible = await runReconcile({ + postVisibilityRuns: [{ + id: 9001, workflow_id: 777, run_attempt: 1, + path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images", + display_title: sourceTitle, event: "repository_dispatch", status: "queued", conclusion: null, + repository: {full_name: repository}, head_repository: {full_name: repository}, + head_branch: "develop", head_sha: base, created_at: "2026-01-08T00:00:00Z", + }], + }); + assert.equal(sameSecondVisible.failure, null, + "a unique exact native producer created in the POST's timestamp second is visible"); + assert.equal(sameSecondVisible.postAttempts, 1); + assertExactPostVisibilityFilter(sameSecondVisible); + const stalePostVisibility = await runReconcile({ + postVisibilityRuns: [{ + id: 9001, workflow_id: 777, run_attempt: 1, + path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images", + display_title: sourceTitle, event: "repository_dispatch", status: "queued", conclusion: null, + repository: {full_name: repository}, head_repository: {full_name: repository}, + head_branch: "develop", head_sha: base, created_at: "2026-01-07T23:59:59Z", + }], + }); + assert.match(stalePostVisibility.failure?.message ?? "", /visibility is unknown/, + "an otherwise exact native run created before the dispatch second cannot confirm the POST"); + assert.equal(stalePostVisibility.postAttempts, 1); + assert.equal(stalePostVisibility.inventoryRequests.filter(request => + request.created === postVisibilityFloor + ).length, 24, "out-of-filter stale evidence remains unaccepted throughout the bounded observation window"); + assertExactPostVisibilityFilter(stalePostVisibility); + const unavailableInitialDiscovery = await runReconcile({initialDiscoveryUnavailable: true}); + assert.match(unavailableInitialDiscovery.failure?.message ?? "", /initial runtime discovery unavailable/); + assert.equal(unavailableInitialDiscovery.postAttempts, 0, + "unavailable initial source inventory is not treated as absence or permission to dispatch"); + assert.equal(unavailableInitialDiscovery.inventoryRequests[0].event, "pull_request"); + assert.equal(unavailableInitialDiscovery.inventoryRequests[0].workflow_id, "runtime-images.yml"); + const newestCancelledCi = { + ...ciRun, id: 7002, status: "completed", conclusion: "cancelled", + }; + const olderSuccessfulCi = {...ciRun, id: 7001, status: "completed", conclusion: "success"}; + const cancelledNewestMissingEvidence = await runReconcile({ + ciRuns: [newestCancelledCi, olderSuccessfulCi], + ciNativeRuns: {[newestCancelledCi.id]: newestCancelledCi, [olderSuccessfulCi.id]: olderSuccessfulCi}, + ciJobsByRun: {[newestCancelledCi.id]: [], [olderSuccessfulCi.id]: [gate]}, + }); + assert.equal(cancelledNewestMissingEvidence.failure, null); + assert.equal(cancelledNewestMissingEvidence.postAttempts, 0, + "a cancelled newest CI candidate with missing native jobs cannot reveal older success or authorize refresh"); + assert.deepEqual(cancelledNewestMissingEvidence.nativeJobRunIds, + [newestCancelledCi.id, newestCancelledCi.id, newestCancelledCi.id], + "classification retries only the newest cancelled attempt and never falls back to older CI evidence"); const expiredRequest = await runReconcile({expireFirstRequest: true}); assert.equal(expiredRequest.failure?.name, "TimeoutError", "request abortion at the wall-clock deadline remains visible"); assert.equal(expiredRequest.requests.length, 1, "deadline abortion prevents subsequent GitHub API requests"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityRefusalBudgetRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityRefusalBudgetRepository.java index 64b3262ca0..25507db672 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityRefusalBudgetRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityRefusalBudgetRepository.java @@ -61,14 +61,16 @@ public long requireReady(UUID tenantId, int maximumRefusals, int requiredHeadroo tenantId); if (row == null) throw unavailable(); if (!Integer.valueOf(maximumRefusals).equals(row.get(0, Integer.class))) throw conflict(); - var count = + var lastSlot = dsl.fetchOne( - "SELECT count(*) FROM (SELECT 1 FROM account_capacity_origin_decisions WHERE tenant_uuid=? AND decision='NO_ACCEPT' LIMIT ?) retained", - tenantId, - (long) maximumRefusals + 1); - Long retained = count == null ? null : count.get(0, Long.class); - if (retained == null || retained < 0 || retained > maximumRefusals) throw unavailable(); - long remaining = maximumRefusals - retained; + "SELECT slot FROM account_capacity_origin_refusal_slots WHERE tenant_uuid = ? ORDER BY slot DESC LIMIT 1", + tenantId); + // V1040.6 backfills immutable contiguous slots and fresh refusals append lastSlot + 1. + // The indexed highest slot is therefore the retained refusal count without scanning origins. + Long highestSlot = lastSlot == null ? Long.valueOf(0L) : lastSlot.get("slot", Long.class); + if (highestSlot == null || highestSlot < 0 || highestSlot > maximumRefusals) + throw unavailable(); + long remaining = maximumRefusals - highestSlot; if (remaining < requiredHeadroom) throw unavailable(); return remaining; } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index 45715fac90..706f844959 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -594,6 +594,7 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { .migrate(); var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); + var budgets = new AccountCapacityRefusalBudgetRepository(dsl); var historicalTenant = source(); transaction.executeWithoutResult(status -> new FreshTenantIdentityAssociationRepository(dsl, "prod") @@ -713,6 +714,13 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { .target("1040.5") .load() .migrate(); + transaction.executeWithoutResult( + status -> budgets.provision(historicalTenant.canonicalTenantId(), 3)); + var provisionedBudgetAtV1040_5 = + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", + historicalTenant.canonicalTenantId()) + .intoMap(); var originalDecisions = dsl.fetch( "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM account_capacity_origin_decisions ORDER BY decision_id") @@ -729,6 +737,16 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { .load() .migrate(); + assertThat( + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", + historicalTenant.canonicalTenantId()) + .intoMap()) + .isEqualTo(provisionedBudgetAtV1040_5); + Long remainingHeadroom = + transaction.execute( + status -> budgets.requireReady(historicalTenant.canonicalTenantId(), 3, 1)); + assertThat(remainingHeadroom).isEqualTo(1L); assertThat( dsl.fetch( "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM account_capacity_origin_decisions ORDER BY decision_id") @@ -741,7 +759,7 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { assertThat( dsl.fetchOne( "SELECT 1 FROM account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", - historicalTenant.canonicalTenantId())) + acceptedTenant.canonicalTenantId())) .isNull(); assertThat( dsl.fetchOne( @@ -900,9 +918,6 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { .isEqualTo(acceptedUsageBeforeReplay); assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); - transaction.executeWithoutResult(status -> - new AccountCapacityRefusalBudgetRepository(dsl) - .provision(historicalTenant.canonicalTenantId(), 3)); UUID freshRequest = UUID.randomUUID(); UUID freshAdmission = UUID.randomUUID(); UUID freshAttempt = UUID.randomUUID(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index 539842aed0..9472cf7084 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -2,8 +2,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.startsWith; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -166,6 +168,28 @@ void durableQuotaDenialReplaysWithoutConsultingMutableCapacity() throws Exceptio f.existing = false; Record genericRefusal = mock(Record.class); UUID decisionId = UUID.randomUUID(); + String originLookupSql = + "SELECT * FROM account_capacity_origin_decisions WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND capacity_rearm_fence = ?"; + String originInsertSql = + "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, refusal_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING"; + Object[] originKey = { + f.request.identity().tenantId(), + f.request.identity().requestId(), + f.request.identity().admissionId(), + f.request.capacityRearmFence() + }; + doAnswer( + invocation -> { + Object[] arguments = (Object[]) invocation.getRawArguments()[1]; + assertThat(arguments).hasSize(4); + assertThat(arguments[0]).isEqualTo(f.request.identity().tenantId()); + assertThat(arguments[1]).isEqualTo(f.request.identity().requestId()); + assertThat(arguments[2]).isEqualTo(f.request.identity().admissionId()); + assertThat(arguments[3]).isEqualTo(f.request.capacityRearmFence()); + return f.pendingOriginDecision != null ? f.pendingOriginDecision : f.originDecision; + }) + .when(f.dsl) + .fetchOne(eq(originLookupSql), any(Object[].class)); when(genericRefusal.get("tenant_uuid", UUID.class)).thenReturn(f.request.identity().tenantId()); when(genericRefusal.get("request_id", UUID.class)).thenReturn(f.request.identity().requestId()); when(genericRefusal.get("admission_id", UUID.class)) @@ -185,16 +209,29 @@ void durableQuotaDenialReplaysWithoutConsultingMutableCapacity() throws Exceptio org.mockito.Mockito.doReturn(usage) .when(f.dsl) .fetchOne(startsWith("SELECT * FROM account_tenant_capacity_usage "), any(Object[].class)); - when(f.dsl.execute( - startsWith("INSERT INTO account_capacity_origin_decisions "), any(Object[].class))) - .thenAnswer(invocation -> { - Object[] arguments = (Object[]) invocation.getRawArguments()[1]; - assertThat(arguments[7]).isEqualTo("NO_ACCEPT"); - assertThat(arguments[9]).isEqualTo("CAPACITY_QUOTA_EXCEEDED"); - when(genericRefusal.get("decision_id", UUID.class)).thenReturn((UUID) arguments[8]); - f.pendingOriginDecision = genericRefusal; - return 1; - }); + doAnswer( + invocation -> { + Object[] arguments = (Object[]) invocation.getRawArguments()[1]; + assertThat(arguments).hasSize(10); + assertThat(arguments[0]).isEqualTo(f.request.identity().tenantId()); + assertThat(arguments[1]).isEqualTo(f.request.identity().requestId()); + assertThat(arguments[2]).isEqualTo(f.request.identity().admissionId()); + assertThat(arguments[3]).isEqualTo(f.request.capacityRearmFence()); + assertThat(arguments[4]).isEqualTo(f.request.admissionAttemptId()); + assertThat(arguments[5]).isEqualTo(f.request.mutationDigest()); + assertThat( + java.util.Arrays.equals( + (byte[]) arguments[6], CapacityAdmissionDigest.preimage(f.request))) + .isTrue(); + assertThat(arguments[7]).isEqualTo("NO_ACCEPT"); + assertThat(arguments[8]).isInstanceOf(UUID.class); + assertThat(arguments[9]).isEqualTo("CAPACITY_QUOTA_EXCEEDED"); + when(genericRefusal.get("decision_id", UUID.class)).thenReturn((UUID) arguments[8]); + f.pendingOriginDecision = genericRefusal; + return 1; + }) + .when(f.dsl) + .execute(eq(originInsertSql), any(Object[].class)); f.retained = true; qualifySources(f); assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) @@ -209,6 +246,8 @@ void durableQuotaDenialReplaysWithoutConsultingMutableCapacity() throws Exceptio assertThat(f.originDecision).isSameAs(genericRefusal); assertThat(f.pendingOriginDecision).isNull(); UUID committedId = genericRefusal.get("decision_id", UUID.class); + verify(f.dsl, times(1)).execute(eq(originInsertSql), any(Object[].class)); + verify(f.dsl, times(3)).fetchOne(eq(originLookupSql), aryEq(originKey)); when(usage.get("held_units", Long.class)).thenReturn(0L); org.mockito.Mockito.clearInvocations(f.dsl, f.accounts, f.memberships, f.issuances, f.scopes); @@ -223,6 +262,7 @@ void durableQuotaDenialReplaysWithoutConsultingMutableCapacity() throws Exceptio }); } verifyNoInteractions(f.accounts, f.memberships, f.issuances, f.scopes); + verify(f.dsl, times(2)).fetchOne(eq(originLookupSql), aryEq(originKey)); verify(f.dsl, never()).execute(anyString(), any(Object[].class)); verify(f.dsl, never()) .fetchOne(startsWith("SELECT * FROM account_tenant_capacity_usage "), any(Object[].class)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index 5a9edec24a..2e25905c17 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -9,9 +9,11 @@ import io.grpc.Context; import io.grpc.Deadline; import io.grpc.ManagedChannel; +import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.Server; import io.grpc.ServerInterceptors; +import io.grpc.ServerStreamTracer; import io.grpc.Status; import io.grpc.StatusRuntimeException; import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; @@ -61,6 +63,8 @@ @Timeout(90) class AccountTenantCapacityClientMtlsTest { private static final String TLS_RELOAD_PROPERTY = "firemud.grpc.tls-reload.enabled"; + private static final UUID ACCOUNT_RESERVATION_ID = + UUID.fromString("a0577a29-9be2-42a0-9770-4c2a90581358"); @TempDir static Path directory; private static LoopbackMtlsTestPki.Pki pki; @@ -102,14 +106,57 @@ void blankEndpointIsUnsetAndExplicitAccountEndpointIsPreserved() throws Exceptio @Test void exactAccountPeerReceivesCompleteRequestAndExactRetryKeepsReservation() throws Exception { AtomicInteger calls = new AtomicInteger(); - Server server = server("account", calls, false); + AtomicInteger messages = new AtomicInteger(); + Server server = + server( + "account", + calls, + false, + new AtomicLong(), + new AtomicBoolean(true), + null, + null, + messages); try (var client = client(server)) { client.init(); var request = CapacityAdmissionTestFixture.playerRequest(); var first = client.commit(request, deadline()); - assertThat(client.commit(request, deadline())).isEqualTo(first); + var replay = client.commit(request, deadline()); + assertThat(first.reservationId()).isEqualTo(ACCOUNT_RESERVATION_ID); + assertThat(replay).isEqualTo(first); assertThat(first.identity()).isEqualTo(request.identity()); assertThat(calls).hasValue(2); + assertThat(messages).hasValue(2); + } finally { + stop(server); + } + } + + @Test + void unavailableAfterAccountReceivedRequestDoesNotRetryCommit() throws Exception { + AtomicInteger calls = new AtomicInteger(); + Server server = + startServer( + "account", + new AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + observer.onError( + Status.UNAVAILABLE.withDescription("Response lost").asRuntimeException()); + } + }); + try (var client = client(server)) { + client.init(); + assertThatThrownBy( + () -> client.commit(CapacityAdmissionTestFixture.playerRequest(), deadline())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(calls).hasValue(1); } finally { stop(server); } @@ -213,7 +260,10 @@ void mismatchedTypedRefusalDoesNotBecomeAnAccountDecision() throws Exception { @Test void wrongAccountPeerIsRejectedBeforeRequestBodyRelease() throws Exception { AtomicInteger calls = new AtomicInteger(); - Server server = server("wrong", calls, false); + AtomicInteger messages = new AtomicInteger(); + Server server = + server( + "wrong", calls, false, new AtomicLong(), new AtomicBoolean(true), null, null, messages); try (var client = client(server)) { client.init(); assertThatThrownBy( @@ -225,6 +275,7 @@ void wrongAccountPeerIsRejectedBeforeRequestBodyRelease() throws Exception { assertThat(failure.getStatus().getDescription()) .isEqualTo("Request requires the exact authenticated server workload identity"); }); + assertThat(messages).hasValue(0); assertThat(calls).hasValue(0); } finally { stop(server); @@ -270,6 +321,7 @@ void successfulRpcPropagatesMinimumOfExplicitIncomingAndMaximumDeadline( client.commit(request, deadline()); observedNanos.set(0); channelFactory.resetCapturedDeadline(); + var earliest = Deadline.after(expectedMaximumMillis, TimeUnit.MILLISECONDS); try (var context = Context.current().withDeadlineAfter(incomingMillis, TimeUnit.MILLISECONDS, scheduler)) { var result = @@ -283,11 +335,11 @@ void successfulRpcPropagatesMinimumOfExplicitIncomingAndMaximumDeadline( assertThat(observedNanos.get()) .isPositive() .isLessThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(expectedMaximumMillis)); - // This is sampled at newCall, before the RPC is handed to the network. The broad one-second - // tolerance permits local call setup, while a fixed one-second client deadline cannot pass. - assertThat(channelFactory.capturedDeadlineNanos.get()) - .isGreaterThan(TimeUnit.MILLISECONDS.toNanos(expectedMaximumMillis - 1_000)) - .isLessThanOrEqualTo(TimeUnit.MILLISECONDS.toNanos(expectedMaximumMillis)); + var latest = Deadline.after(expectedMaximumMillis, TimeUnit.MILLISECONDS); + var captured = channelFactory.capturedDeadline.get(); + assertThat(captured).isNotNull(); + assertThat(captured.isBefore(earliest)).isFalse(); + assertThat(latest.isBefore(captured)).isFalse(); } finally { scheduler.shutdownNow(); stop(server); @@ -503,8 +555,10 @@ void incomingDeadlineBoundsAStalledAccountCall() throws Exception { @Test void expiredExplicitBudgetSendsNoAccountRequest() throws Exception { AtomicInteger calls = new AtomicInteger(); + var channelFactory = new CallOptionsCapturingChannelFactory(); Server server = server("account", calls, false); - try (var client = client(server)) { + try (var client = + client(server, pki.clientProperties(directory, pki.identity("client")), channelFactory)) { client.init(); assertThatThrownBy(() -> client.commit( @@ -514,6 +568,7 @@ void expiredExplicitBudgetSendsNoAccountRequest() throws Exception { .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()) .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + assertThat(channelFactory.callsCreated).hasValue(0); assertThat(calls).hasValue(0); } finally { stop(server); @@ -598,7 +653,28 @@ private static Server server( AtomicReference serverFailure, CountDownLatch measuredSecondInvocationEntered) throws Exception { - UUID reservationId = UUID.randomUUID(); + return server( + identity, + calls, + wrongFence, + observedNanos, + respond, + serverFailure, + measuredSecondInvocationEntered, + null); + } + + private static Server server( + String identity, + AtomicInteger calls, + boolean wrongFence, + AtomicLong observedNanos, + AtomicBoolean respond, + AtomicReference serverFailure, + CountDownLatch measuredSecondInvocationEntered, + AtomicInteger messages) + throws Exception { + UUID reservationId = ACCOUNT_RESERVATION_ID; var service = new AccountServiceGrpc.AccountServiceImplBase() { @Override @@ -663,22 +739,42 @@ public void commitTenantCapacityAdmission( observer.onCompleted(); } }; - return startServer(identity, service); + return startServer(identity, service, messages); } private static Server startServer( String identity, AccountServiceGrpc.AccountServiceImplBase service) throws Exception { + return startServer(identity, service, null); + } + + private static Server startServer( + String identity, AccountServiceGrpc.AccountServiceImplBase service, AtomicInteger messages) + throws Exception { var peer = pki.identity(identity); - return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) - .sslContext( - GrpcSslContexts.configure( - SslContextBuilder.forServer(peer.privateKey(), peer.certificate())) - .trustManager(pki.caCertificate()) - .clientAuth(ClientAuth.REQUIRE) - .build()) - .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) - .build() - .start(); + var builder = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(peer.privateKey(), peer.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())); + if (messages != null) { + builder.addStreamTracerFactory( + new ServerStreamTracer.Factory() { + @Override + public ServerStreamTracer newServerStreamTracer(String method, Metadata headers) { + return new ServerStreamTracer() { + @Override + public void inboundMessage(int sequence) { + messages.incrementAndGet(); + } + }; + } + }); + } + return builder.build().start(); } private static void assertServerSide( @@ -719,37 +815,37 @@ public ManagedChannel buildChannel( } private static final class CallOptionsCapturingChannelFactory extends GrpcChannelFactory { - private final AtomicLong capturedDeadlineNanos = new AtomicLong(-1); + private final AtomicReference capturedDeadline = new AtomicReference<>(); + private final AtomicInteger callsCreated = new AtomicInteger(); @Override public ManagedChannel buildChannel( String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) throws SSLException { return new CallOptionsCapturingManagedChannel( - super.buildChannel(target, defaultPort, properties, keepAlive), capturedDeadlineNanos); + super.buildChannel(target, defaultPort, properties, keepAlive), this); } private void resetCapturedDeadline() { - capturedDeadlineNanos.set(-1); + capturedDeadline.set(null); } } private static final class CallOptionsCapturingManagedChannel extends ManagedChannel { private final ManagedChannel delegate; - private final AtomicLong capturedDeadlineNanos; + private final CallOptionsCapturingChannelFactory capture; private CallOptionsCapturingManagedChannel( - ManagedChannel delegate, AtomicLong capturedDeadlineNanos) { + ManagedChannel delegate, CallOptionsCapturingChannelFactory capture) { this.delegate = delegate; - this.capturedDeadlineNanos = capturedDeadlineNanos; + this.capture = capture; } @Override public ClientCall newCall( MethodDescriptor methodDescriptor, CallOptions callOptions) { - Deadline deadline = callOptions.getDeadline(); - capturedDeadlineNanos.set( - deadline == null ? 0 : deadline.timeRemaining(TimeUnit.NANOSECONDS)); + capture.callsCreated.incrementAndGet(); + capture.capturedDeadline.set(callOptions.getDeadline()); return delegate.newCall(methodDescriptor, callOptions); } @@ -760,7 +856,7 @@ public String authority() { @Override public ManagedChannel shutdown() { - delegate.shutdown(); + assertThat(delegate.shutdown()).isNotNull(); return this; } @@ -776,7 +872,7 @@ public boolean isTerminated() { @Override public ManagedChannel shutdownNow() { - delegate.shutdownNow(); + assertThat(delegate.shutdownNow()).isNotNull(); return this; } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java index ddb98af268..51e42d6a5d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java @@ -604,8 +604,7 @@ private Channel channel(String alias) throws Exception { private record Channel(ManagedChannel channel) implements AutoCloseable { @Override public void close() throws Exception { - channel.shutdownNow(); - assertThat(channel.awaitTermination(2L, TimeUnit.SECONDS)).isTrue(); + assertThat(channel.shutdownNow().awaitTermination(2L, TimeUnit.SECONDS)).isTrue(); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java index 8672b58dba..f99010e974 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java @@ -89,8 +89,7 @@ static void createTestPki() throws Exception { @AfterEach void stopTransportAndClearAuthContext() throws Exception { if (noCertificateChannel != null) { - noCertificateChannel.shutdownNow(); - assertThat(noCertificateChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + assertThat(noCertificateChannel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue(); noCertificateChannel = null; } if (server != null) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java index 1d022d7f9e..9b3a44c515 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java @@ -5,6 +5,7 @@ import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import java.util.List; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.entitymanagement.v1.Character; import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc; import net.firedevops.firemud.entitymanagement.v1.ListCharactersByAccountRequest; @@ -32,7 +33,7 @@ void returnsPongToPingOverLoopbackGrpc() throws Exception { assertThat(response.getMessage()).isEqualTo("pong"); assertThat(response.hasError()).isFalse(); } finally { - channel.shutdownNow(); + assertThat(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue(); } } } @@ -59,7 +60,7 @@ void listsOnlyThePersistedSharedCharacterForTheRequestedTenantAndAccount() throw assertThat(response.getCharactersList()).containsExactly(sharedCharacter(fixture.name())); } } finally { - channel.shutdownNow(); + assertThat(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue(); } } } @@ -88,7 +89,7 @@ void resetCharactersRestoresDefaultSharedCharactersAfterAnEmptyOverride() throws assertThat(resetResponse.hasError()).isFalse(); assertThat(resetResponse.getCharactersList()).containsExactly(sharedCharacter("Emberline")); } finally { - channel.shutdownNow(); + assertThat(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue(); } } } @@ -143,7 +144,7 @@ void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { .getCharactersList()) .isEmpty(); } finally { - channel.shutdownNow(); + assertThat(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue(); } } } @@ -171,7 +172,7 @@ void unknownOrMismatchedTenantAndAccountReturnNoCharacters() throws Exception { .getCharactersList()) .isEmpty(); } finally { - channel.shutdownNow(); + assertThat(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue(); } } } @@ -202,7 +203,7 @@ void unsupportedPlayableStateScopesReturnNoCharacters() throws Exception { .getCharactersList()) .isEmpty(); } finally { - channel.shutdownNow(); + assertThat(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue(); } } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/GameDesignStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/GameDesignStubServerTest.java index 59ea0c6b3e..4467e90052 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/GameDesignStubServerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/GameDesignStubServerTest.java @@ -4,6 +4,7 @@ import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.gamedesign.v1.GameDesignServiceGrpc; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleRequest; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; @@ -32,7 +33,7 @@ void returnsTheReleaseBundleIdentityUsedByGameplayFixtures() throws Exception { assertThat(response.getBundle().getCommandDefinitionsList()).isEmpty(); assertThat(server.publishedReleaseBundleRequests()).isEqualTo(1); } finally { - channel.shutdownNow(); + assertThat(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue(); } } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java index be0d8f8d68..fca0de9698 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServerTest.java @@ -2,10 +2,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.StatusRuntimeException; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.gamesession.test.LookTestFixtures; import net.firedevops.firemud.shared.v1.RoomInstanceRef; import net.firedevops.firemud.worldmanagement.v1.GetRoomSnapshotRequest; @@ -52,7 +54,7 @@ void returnsRoomSnapshotForRequestedRoomInstanceId() throws Exception { LookTestFixtures.DESTINATION_ROOM_NAME, destination.getSnapshot().getRoomName()); assertEquals("SOUTH", destination.getSnapshot().getExits(0).getDirection()); } finally { - channel.shutdownNow(); + assertTrue(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)); } } } @@ -84,7 +86,7 @@ void returnsRoomSnapshotInTheRequestedRuntimeScope() throws Exception { assertEquals("42", response.getSnapshot().getGameInstanceId()); assertEquals(LookTestFixtures.ROOM_INSTANCE_ID, response.getSnapshot().getRoomInstanceId()); } finally { - channel.shutdownNow(); + assertTrue(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)); } } } @@ -109,7 +111,7 @@ void unknownRoomInstanceIdReturnsNotFound() throws Exception { RoomInstanceRef.newBuilder().setRoomInstanceId("unknown-room").build()) .build())); } finally { - channel.shutdownNow(); + assertTrue(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)); } } } From f03051b9bd85c677ca1238181c282b8433c3bfe8 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 22 Nov 2026 17:09:07 +1300 Subject: [PATCH 36/96] Keep retarget and smoke proof contracts aligned --- .github/workflows/smoke.yml | 35 +++++++++++++++---- .../pr-required-gate-context-contract.sh | 19 ++++++---- .../tests/pr-retarget-workflow-contract.sh | 2 +- dev-tools/tests/smoke-transport-contract.sh | 34 ++++++++++-------- 4 files changed, 62 insertions(+), 28 deletions(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 7a2e4f4956..07c6c25fc3 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -1548,7 +1548,8 @@ jobs: if (replacement.conclusion === "success") { // Ordinary success has one canonical proof path. A contradictory // snapshot cannot be retried through the diagnostic exception path. - return await verifyCanonicalSmokeProducer(replacement, candidate, identity, true); + const proof = await verifyCanonicalSmokeProducer(replacement, candidate, identity, true); + return proof === true ? "ordinary" : proof; } const playProof = await verifyKnownPlayFailure(replacement, candidate, identity, true, true); if (playProof === true) return true; @@ -1765,11 +1766,33 @@ jobs: ); return; } - core.info( - `Exact pull_request runtime-images run ${matching.id} was cancelled; exact repository_dispatch ` + - `replacement ${replacement.id}/${replacement.run_attempt} passed a fresh terminal proof.` - ); - matching = replacement; + if (!await isCurrentCanonicalAttempt(replacement)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + const finalIdentity = await resolveCurrentIdentity("Fencing proven cancelled-run replacement", true); + if (finalIdentity?.obsolete) return; + if (!finalIdentity || identityKey({...finalIdentity, sourceEvent: currentIdentity.sourceEvent}) !== + identityKey(currentIdentity)) { + if (finalIdentity) { + cancelledRecoveryMoved = true; + requireCurrentIdentity = true; + currentIdentity = finalIdentity; + } + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } + if (replacementProof === "ordinary") { + core.info(`Exact repository_dispatch replacement ${replacement.id}/${replacement.run_attempt} passed full-stack smoke and authenticated cleanup.`); + return; + } + if (!finalIdentity.canonicalPlayEligible) { + core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); + return; + } + core.setOutput("known_play_exception", "true"); + core.warning("Canonical PLAY transition exception accepted; no runtime qualification or image publication."); + return; } if (matching) { core.info(`Found runtime-images run ${matching.id} with status=${matching.status} conclusion=${matching.conclusion}`); diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index a830f6a07e..34ff9f76ed 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -1055,10 +1055,11 @@ async function scenario(kind, event = "pull_request") { if (kind === "transient-exact-attempt" && exactAttemptReads <= 4) { throw Object.assign(new Error("temporary exact-attempt lookup"), {status: 502}); } - if (kind === "sparse-exact-attempt-source" && exactAttemptReads === 3) { + // The first exact-attempt read classifies the cancelled original. + if (kind === "sparse-exact-attempt-source" && exactAttemptReads === 2) { return {data: {...source, run_attempt: undefined}}; } - if (kind === "sparse-exact-attempt-status" && exactAttemptReads === 3) { + if (kind === "sparse-exact-attempt-status" && exactAttemptReads === 2) { return {data: {...source, status: undefined}}; } return {data: {...source, ...(sourceMutations[kind] || {})}}; @@ -1084,6 +1085,9 @@ async function scenario(kind, event = "pull_request") { return [{...job, steps: job.steps.filter(step => step.name !== "Known canonical transition PLAY failure with successful authenticated cleanup")}]; } + if (kind === "sparse-exact-cleanup" && snapshots === 2) { + return [{...job, steps: job.steps.filter(step => step.name !== "Stop smoke stack")}]; + } if (kind === "sparse-exact-job-identity" && snapshots === 2) { return [{...job, run_id: undefined}]; } @@ -1110,7 +1114,7 @@ async function scenario(kind, event = "pull_request") { const clock = {now: () => now, parse: Date.parse}; await execute(github, context, {info: () => {}, warning: () => {}, setFailed: message => failures.push(message)}, clock, (callback, duration) => {now += duration; waitedMillis += duration; queueMicrotask(callback);}, require); - return {failures, refs, snapshots, observedBaseMove, waitedMillis}; + return {failures, refs, snapshots, exactAttemptReads, observedBaseMove, waitedMillis}; } (async () => { for (const event of ["pull_request", "repository_dispatch"]) { @@ -1137,10 +1141,12 @@ async function scenario(kind, event = "pull_request") { } for (const kind of ["transient-exact-attempt", "transient-exact-job-list", "transient-canonical-job-list", "sparse-exact-attempt-source", "sparse-exact-attempt-status", - "sparse-exact-job-snapshots", "sparse-exact-job-identity"]) { + "sparse-exact-job-snapshots", "sparse-exact-cleanup", "sparse-exact-job-identity"]) { const result = await scenario(kind, "repository_dispatch"); assert.deepEqual(result.failures, [], `${kind} remains pending until fresh exact-attempt proof is available`); - assert(result.snapshots >= 3 && result.waitedMillis > 0, `${kind} retries within the existing proof budget`); + assert(result.snapshots >= 2 && result.waitedMillis > 0, `${kind} retries within the existing proof budget`); + if (kind === "transient-exact-attempt") assert(result.exactAttemptReads >= 5); + if (kind.startsWith("sparse-exact-attempt-")) assert(result.exactAttemptReads >= 3); } const changedJobId = await scenario("cross-snapshot-changed-job-id", "repository_dispatch"); assert.equal(changedJobId.failures.length, 1, @@ -4382,7 +4388,8 @@ function markerAccepted(overrides = {}) { assert.deepEqual(sequencedReplacement.failures, []); assert.equal(sequencedReplacement.proofReads, 2, "a same-tuple replacement becomes authoritative only after a fresh complete exact proof"); - assert.equal(sequencedReplacement.runtimeJobReads, 1); + assert.equal(sequencedReplacement.runtimeJobReads, 0, + "a freshly proved replacement needs only the final currentness fences, without rereading its job inventory"); assert.equal(sequencedReplacement.now, 10); const invalidReplacement = await sameTupleCancellation("completed", [false]); assert.equal(invalidReplacement.failures.length, 1); diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 5101829b86..deaba4e965 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -2706,7 +2706,7 @@ require_contains "$smoke_path" 'fullSmokeStep?.conclusion !== "success"' require_contains "$smoke_path" 'credential-free full-stack smoke step did not pass' require_ordered_sequence \ "$smoke_path" \ - 'if (fullSmokeJob?.status === "completed") {' \ + 'if (fullSmokeJob?.status === "completed" && !attemptIdentityPending) {' \ 'if (fullSmokeJob?.conclusion !== "success") {' \ 'PR Full-Stack Smoke job did not complete successfully:' # shellcheck disable=SC2016 # Assert literal GitHub expression syntax. diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index 14dea193c2..8b61472fbf 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -1150,21 +1150,25 @@ discovery_session = CommandResponseSession( ] ) discovery_results = [] -discovery_responses = run_telnet_smoke_session( - "example.test", - 2323, - [ - ("WORLDS", ["OK WORLDS"], "WORLDS"), - ("LOGIN demo swordfish", ["OK LOGIN"], "LOGIN"), - ("PLAY demo", ["OK PLAY"], "PLAY"), - ("LOOK", ["OK LOOK"], "LOOK"), - ], - 1, - open_session=lambda: discovery_session, - step_results=discovery_results, - tls_enabled=False, - discovery_selector="demo", -) +# The fixture controls the responses. Avoid spending its one-second deadline +# on scheduler-dependent sleep while checking that the discovery poll retries. +with patch("smoke_common.time.sleep") as discovery_sleep: + discovery_responses = run_telnet_smoke_session( + "example.test", + 2323, + [ + ("WORLDS", ["OK WORLDS"], "WORLDS"), + ("LOGIN demo swordfish", ["OK LOGIN"], "LOGIN"), + ("PLAY demo", ["OK PLAY"], "PLAY"), + ("LOOK", ["OK LOOK"], "LOOK"), + ], + 1, + open_session=lambda: discovery_session, + step_results=discovery_results, + tls_enabled=False, + discovery_selector="demo", + ) +discovery_sleep.assert_called() assert discovery_session.sent == [ "WORLDS\r\n", "WORLDS\r\n", From 80c263a3976155a2b69b0d9b7edeb6de3642bbc4 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:08:43 +1300 Subject: [PATCH 37/96] Revalidate runtime and smoke proof after recovery --- .../workflows/publish-pr-runtime-images.yml | 9 +- .github/workflows/runtime-images.yml | 6 +- .github/workflows/smoke.yml | 78 +++++++----- .../pr-required-gate-context-contract.sh | 114 +++++++++++++----- .../tests/pr-retarget-workflow-contract.sh | 37 +++++- .../pr-runtime-image-publication-contract.sh | 13 +- 6 files changed, 185 insertions(+), 72 deletions(-) diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 3986eac19a..09b930df47 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -544,7 +544,8 @@ jobs: if (run.id !== sourceId || run.workflow_id !== workflow.id || !isTrustedWorkflowPath(run.path) || !title || !["Build Runtime Images", run.display_title].includes(run.name) || - !["pull_request", "repository_dispatch"].includes(run.event) || + !(callback ? ["pull_request", "repository_dispatch"].includes(run.event) + : run.event === "repository_dispatch") || run.repository?.full_name !== repository || run.head_repository?.full_name !== repository || typeof run.head_branch !== "string" || !run.head_branch || typeof run.head_sha !== "string" || !/^[0-9a-f]{40}$/.test(run.head_sha) || @@ -631,6 +632,7 @@ jobs: - name: Validate exact PR source and artifact before registry login env: CURRENT_REPOSITORY: ${{ github.repository }} + PUBLICATION_TRIGGER: ${{ github.event_name }} SOURCE_RUN_ID: ${{ fromJSON(needs.source.outputs.source).id }} SOURCE_RUN_URL: ${{ fromJSON(needs.source.outputs.source).html_url }} SOURCE_RUN_TITLE: ${{ fromJSON(needs.source.outputs.source).display_title }} @@ -765,6 +767,11 @@ jobs: source_event = required_environment("SOURCE_RUN_EVENT") if source_event not in {"pull_request", "repository_dispatch"}: fail("source event is not an allowed PR image source") + publication_trigger = required_environment("PUBLICATION_TRIGGER") + if publication_trigger not in {"workflow_run", "repository_dispatch"}: + fail("publication trigger is not allowed") + if publication_trigger == "repository_dispatch" and source_event != "repository_dispatch": + fail("typed publication requires a repository_dispatch source run") if required_environment("SOURCE_RUN_CONCLUSION") != "success": fail("source workflow did not succeed") if required_environment("SOURCE_HEAD_REPOSITORY") != repository: diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index c0cd85890a..96cd246311 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -1106,7 +1106,11 @@ jobs: core.setFailed(`Cannot verify runtime tuple for PR #${tuple.prNumber}; no dispatch issued: ${error.message || error}`); break runtimeRefresh; } - if (!current || current.tuple.mergeSha !== tuple.mergeSha) { + if (!current) { + core.info(`Skipping unverified runtime tuple for PR #${tuple.prNumber}.`); + break runtimeRefresh; + } + if (current.tuple.mergeSha !== tuple.mergeSha) { core.info(`Skipping changed runtime tuple for PR #${tuple.prNumber}.`); continue; } diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 07c6c25fc3..687d59aac8 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -632,7 +632,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "a29d15fa877ccf53e6677c3ccd60e2fbed7e817fd776a0fc8093ca24c2462a7e"; + const canonicalRuntimeWorkflowSha256 = "da1e6c06adfa8fb26aad72dd5a613f2d55e5339c382f713888623e4f542e0a70"; // Only authenticated default-branch refreshes may use retained successful definitions. // Keep the pre-rollout default and predecessor definitions for mixed-version runs. const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set([ @@ -1546,10 +1546,16 @@ jobs: if (candidate.conclusion !== replacement.conclusion) return false; if (candidate.steps != null && !Array.isArray(candidate.steps)) return false; if (replacement.conclusion === "success") { - // Ordinary success has one canonical proof path. A contradictory - // snapshot cannot be retried through the diagnostic exception path. - const proof = await verifyCanonicalSmokeProducer(replacement, candidate, identity, true); - return proof === true ? "ordinary" : proof; + const markers = (candidate.steps ?? []).filter((step) => + step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" + ); + if (markers.length > 1) return false; + const exceptionMarked = markers[0]?.status === "completed" && markers[0].conclusion === "success"; + if (!exceptionMarked) { + // Contradictory ordinary proof cannot use the exception verifier. + const proof = await verifyCanonicalSmokeProducer(replacement, candidate, identity, true); + return proof === true ? "ordinary" : proof; + } } const playProof = await verifyKnownPlayFailure(replacement, candidate, identity, true, true); if (playProof === true) return true; @@ -1766,10 +1772,6 @@ jobs: ); return; } - if (!await isCurrentCanonicalAttempt(replacement)) { - await new Promise((resolve) => setTimeout(resolve, sleepMs)); - continue smokeGatePolling; - } const finalIdentity = await resolveCurrentIdentity("Fencing proven cancelled-run replacement", true); if (finalIdentity?.obsolete) return; if (!finalIdentity || identityKey({...finalIdentity, sourceEvent: currentIdentity.sourceEvent}) !== @@ -1782,6 +1784,10 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } + if (!await isCurrentCanonicalAttempt(replacement)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } if (replacementProof === "ordinary") { core.info(`Exact repository_dispatch replacement ${replacement.id}/${replacement.run_attempt} passed full-stack smoke and authenticated cleanup.`); return; @@ -1926,10 +1932,6 @@ jobs: } } if (refreshProof?.status === "ordinary") { - if (!await isCurrentCanonicalAttempt(refreshProof.run)) { - await new Promise((resolve) => setTimeout(resolve, sleepMs)); - continue smokeGatePolling; - } const freshIdentity = await resolveCurrentIdentity("Fencing exact passing typed smoke recovery", true); if (freshIdentity?.obsolete) return; if (!freshIdentity || identityKey({...freshIdentity, sourceEvent: currentIdentity.sourceEvent}) !== @@ -1940,6 +1942,10 @@ jobs: } continue smokeGatePolling; } + if (!await isCurrentCanonicalAttempt(refreshProof.run)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } return; } knownPlayVerified = refreshProof?.status === "verified" && @@ -1960,10 +1966,6 @@ jobs: if (knownPlayVerified) { const selectedProofRun = verifiedRefreshRun ?? matching; const needsLiveTuple = refreshVerified || matching.event === "repository_dispatch"; - if (!await isCurrentCanonicalAttempt(selectedProofRun)) { - await new Promise((resolve) => setTimeout(resolve, sleepMs)); - continue smokeGatePolling; - } const freshIdentity = await resolveCurrentIdentity( "Stopping stale canonical transition PLAY exception", requireCurrentIdentity || needsLiveTuple); // Original event proof keeps its immutable tuple semantics. Refreshed @@ -1986,6 +1988,10 @@ jobs: core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); return; } + if (!await isCurrentCanonicalAttempt(selectedProofRun)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } core.setOutput("known_play_exception", "true"); core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); await core.summary.addHeading("Canonical PLAY transition exception accepted") @@ -2071,10 +2077,6 @@ jobs: core.setFailed("Moved cancelled-run recovery did not supply authenticated smoke proof."); return; } - if (!await isCurrentCanonicalAttempt(matching)) { - await new Promise((resolve) => setTimeout(resolve, sleepMs)); - continue smokeGatePolling; - } const freshIdentity = await resolveCurrentIdentity("Fencing moved cancelled-run recovery", true); if (freshIdentity?.obsolete) return; if (!freshIdentity || identityKey(freshIdentity) !== identityKey(currentIdentity)) { @@ -2082,6 +2084,10 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } + if (!await isCurrentCanonicalAttempt(matching)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } if (proof === "ordinary") return; if (!freshIdentity.canonicalPlayEligible) { core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); @@ -2111,6 +2117,20 @@ jobs: `step=${fullSmokeStep?.status ?? "missing"}/${fullSmokeStep?.conclusion ?? "unknown"}` ); } + if (typedRuntimeProof && matching.head_sha == null) { + // Retrying the jobs lookup cannot fill a sparse run-list row. + const snapshotKey = `typed-list-head:${matching.id}:${matching.run_attempt}:${identityKey(currentIdentity)}`; + if (incompleteRefreshKey !== snapshotKey) { + incompleteRefreshKey = snapshotKey; + incompleteRefreshObservedAt = Date.now(); + } + if (Date.now() - incompleteRefreshObservedAt >= completedSnapshotTimeoutMs) { + await failNonTerminalSnapshot("without the typed run-list head SHA"); + return; + } + await new Promise((resolve) => setTimeout(resolve, snapshotSleepMs)); + continue smokeGatePolling; + } const maxCompletedJobSnapshotRetries = 8; for ( let completedJobSnapshotAttempt = 0; @@ -2340,10 +2360,6 @@ jobs: return; } const needsLiveTuple = matching.event === "repository_dispatch"; - if (!await isCurrentCanonicalAttempt(matching)) { - await new Promise((resolve) => setTimeout(resolve, sleepMs)); - continue smokeGatePolling; - } const freshIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception", requireCurrentIdentity || needsLiveTuple); const comparableFreshIdentity = needsLiveTuple && freshIdentity ? {...freshIdentity, sourceEvent: currentIdentity.sourceEvent} @@ -2358,6 +2374,10 @@ jobs: core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); return; } + if (!await isCurrentCanonicalAttempt(matching)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } core.setOutput("known_play_exception", "true"); core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); await core.summary.addHeading("Canonical PLAY transition exception accepted") @@ -2402,10 +2422,6 @@ jobs: ); return; } - if (typedRuntimeProof && !await isCurrentCanonicalAttempt(matching)) { - await new Promise((resolve) => setTimeout(resolve, sleepMs)); - continue smokeGatePolling; - } const finalIdentity = await fenceCompletedRuntimeIdentity("Stopping stale smoke gate before accepting full-stack proof"); if (finalIdentity?.obsolete) { return; @@ -2417,6 +2433,10 @@ jobs: ); continue smokeGatePolling; } + if (typedRuntimeProof && !await isCurrentCanonicalAttempt(matching)) { + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } return; } diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 34ff9f76ed..985bbc1d02 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -646,6 +646,7 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single", t const start = now; const failures = []; let typedCurrentChecks = 0; + const typedJobAttempts = []; const listRuns = async () => {}, listJobs = async () => {}; const cancelledSource = runId => ({id: runId, workflow_id: 7, run_attempt: 1, event: "pull_request", status: "completed", conclusion: "cancelled", path: ".github/workflows/runtime-images.yml", @@ -668,11 +669,12 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single", t pull_requests: [], }); const smokeJob = (runId, runAttempt, smokeConclusion) => { + const jobConclusion = runId === 44 ? "success" : smokeConclusion; const jobId = runId === 44 ? 144 : runId * 100 + 1; return {id: jobId, run_id: runId, run_attempt: runAttempt, head_sha: runId === 44 ? "d".repeat(40) : head, workflow_name: "Build Runtime Images", name: "PR Full-Stack Smoke (runtime-required=true)", - status: "completed", conclusion: smokeConclusion === "success" ? "success" : "failure", + status: "completed", conclusion: jobConclusion, created_at: "2026-09-01T00:00:01Z", started_at: "2026-09-01T00:00:02Z", completed_at: "2026-09-01T00:30:02Z", url: `https://api.github.com/repos/example/firemud/actions/jobs/${jobId}`, @@ -688,19 +690,19 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single", t {name: "Known canonical transition PLAY failure with successful authenticated cleanup", number: 4, status: "completed", conclusion: "skipped", started_at: null, completed_at: null}, {name: "Export fixed-tag preview image artifact", number: 5, status: "completed", - conclusion: smokeConclusion === "success" ? "success" : "skipped", - started_at: smokeConclusion === "success" ? "2026-09-01T00:29:00Z" : null, - completed_at: smokeConclusion === "success" ? "2026-09-01T00:29:30Z" : null}, + conclusion: jobConclusion === "success" ? "success" : "skipped", + started_at: jobConclusion === "success" ? "2026-09-01T00:29:00Z" : null, + completed_at: jobConclusion === "success" ? "2026-09-01T00:29:30Z" : null}, {name: "Upload preview image artifact", number: 6, status: "completed", - conclusion: smokeConclusion === "success" ? "success" : "skipped", - started_at: smokeConclusion === "success" ? "2026-09-01T00:29:30Z" : null, - completed_at: smokeConclusion === "success" ? "2026-09-01T00:29:45Z" : null}, + conclusion: jobConclusion === "success" ? "success" : "skipped", + started_at: jobConclusion === "success" ? "2026-09-01T00:29:30Z" : null, + completed_at: jobConclusion === "success" ? "2026-09-01T00:29:45Z" : null}, {name: "Summarize secure PR runtime artifact", number: 7, status: "completed", - conclusion: smokeConclusion === "success" ? "success" : "skipped", - started_at: smokeConclusion === "success" ? "2026-09-01T00:29:45Z" : null, - completed_at: smokeConclusion === "success" ? "2026-09-01T00:29:55Z" : null}, + conclusion: jobConclusion === "success" ? "success" : "skipped", + started_at: jobConclusion === "success" ? "2026-09-01T00:29:45Z" : null, + completed_at: jobConclusion === "success" ? "2026-09-01T00:29:55Z" : null}, {name: "Require successful runtime smoke and authenticated cleanup", number: 8, - status: "completed", conclusion: smokeConclusion === "success" ? "success" : "failure", + status: "completed", conclusion: jobConclusion, started_at: "2026-09-01T00:30:00Z", completed_at: "2026-09-01T00:30:01Z"}, ]}; }; @@ -749,7 +751,7 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single", t const rerunning = selectionCase === "recoverable-replacement-rerun" && typedCurrentChecks === 1; const attempt = rerunning || selectionCase === "recoverable-replacement-rerun" ? 2 : 1; return {data: refreshSource(attempt, rerunning ? "in_progress" : "completed", - rerunning ? null : typedSmokeConclusion)}; + rerunning ? null : "success")}; } if (run_id === 42 && originalRerunComplete()) { return {data: currentPullRun(42, 2, "completed", "success")}; @@ -762,7 +764,7 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single", t if (input.run_id === 44) { const attempt = selectionCase === "recoverable-replacement-rerun" && typedCurrentChecks > 0 ? 2 : 1; assert.equal(input.attempt_number, attempt); - return {data: refreshSource(attempt, "completed", typedSmokeConclusion)}; + return {data: refreshSource(attempt)}; } if (input.run_id === 42 && originalRerunComplete()) { assert.equal(input.attempt_number, 2); @@ -781,7 +783,8 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single", t assert.equal(method, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); if (input.run_id === 44) { assert.equal(input.attempt_number, selectionCase === "recoverable-replacement-rerun" && typedCurrentChecks > 0 ? 2 : 1); - return [smokeJob(44, input.attempt_number, typedSmokeConclusion)]; + typedJobAttempts.push(input.attempt_number); + return [smokeJob(44, input.attempt_number, input.attempt_number === 1 ? "success" : typedSmokeConclusion)]; } return cancellationJobs(input.run_id); } }; @@ -794,7 +797,7 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single", t const ready = originalRerun || replacementRerun || selectionCase === "recoverable-delayed" && now - start >= 6 * 60 * 1000; const waiting = originalRerun && now === start; yield {data: ready ? [refreshSource(replacementRerun && typedCurrentChecks > 0 ? 2 : 1, - waiting ? "queued" : "completed", waiting ? null : originalRerun ? "failure" : typedSmokeConclusion)] : []}; + waiting ? "queued" : "completed", waiting ? null : originalRerun ? "failure" : "success")] : []}; return; } assert.equal(input.head_sha, head); @@ -862,7 +865,7 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single", t const clock = { now: () => now, parse: Date.parse }; const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; await execute(github, context, core, clock, sleep); - return { failures, minutes: (now - start) / 60000 }; + return { failures, minutes: (now - start) / 60000, typedJobAttempts }; } (async () => { const success = await scenario("success", 30); @@ -915,7 +918,9 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single", t const failedCurrentTypedSmoke = await scenario("cancelled", 0, "recoverable-replacement-rerun", "failure"); assert.equal(failedCurrentTypedSmoke.failures.length, 1, "a current typed refresh with a failed full-stack smoke step must not be accepted as ordinary proof"); - assert.match(failedCurrentTypedSmoke.failures[0], /did not complete successfully|did not expose a terminal PR Full-Stack Smoke job and smoke step/); + assert.deepEqual([...new Set(failedCurrentTypedSmoke.typedJobAttempts)], [1, 2], + "read passing attempt 1 evidence before rejecting the failed smoke step on attempt 2"); + assert.match(failedCurrentTypedSmoke.failures[0], /contradictory identity or invalid terminal smoke proof/); const lateCancellation = await scenario("cancelled", 80, "recoverable-missing"); assert.equal(lateCancellation.minutes, 90, "late cancellation cannot extend global deadline"); assert.match(lateCancellation.failures[0], /Timed out waiting for the exact/); @@ -965,9 +970,12 @@ const repository = "example/firemud"; const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; async function scenario(kind, event = "pull_request") { let now = 1000, snapshots = 0, reads = 0; - let qualifiedAttemptReads = 0, observedBaseMove = false, waitedMillis = 0; + let qualifiedAttemptReads = 0, observedBaseMove = false, observedAttemptMove = false, waitedMillis = 0; + let typedListReads = 0; + const ordinary = kind.startsWith("ordinary-"); + const movedBase = "e".repeat(40), movedMerge = "f".repeat(40); const failures = [], refs = []; - const context = {repo: {owner: "example", repo: "firemud"}, sha: merge, payload: { + const context = {repo: {owner: "example", repo: "firemud"}, sha: ordinary ? null : merge, payload: { repository: {default_branch: "develop"}, pull_request: {number: 42, head: {sha: head, repo: {full_name: repository}}, base: {ref: "develop", sha: base}, created_at: "2026-09-01T00:00:00Z"}, @@ -1025,13 +1033,17 @@ async function scenario(kind, event = "pull_request") { const github = {rest: { pulls: {get: async () => { reads += 1; - const moved = kind === "drift-during-final-attempt" && qualifiedAttemptReads >= 2; + const moved = kind === "ordinary-final-base-drift" && qualifiedAttemptReads > 0; observedBaseMove ||= moved; - return {data: {state: "open", head: {sha: head}, base: {ref: moved || kind === "stale-final" && reads > 3 ? "other" : "develop", sha: base}, merge_commit_sha: merge}}; + observedAttemptMove ||= kind === "ordinary-final-attempt-drift" && qualifiedAttemptReads > 0; + return {data: {state: "open", head: {sha: head}, + base: {ref: kind === "stale-final" && reads > 3 ? "other" : "develop", sha: moved ? movedBase : base}, + merge_commit_sha: moved ? movedMerge : merge}}; }}, - git: {getRef: async () => ({data: {ref: "refs/heads/develop", object: {sha: base}}})}, + git: {getRef: async () => ({data: {ref: "refs/heads/develop", object: {sha: observedBaseMove ? movedBase : base}}})}, repos: { - getCommit: async ({ref}) => ({data: {sha: ref, parents: [{sha: kind === "bad-parents" ? defaultSha : base}, {sha: head}]}}), + getCommit: async ({ref}) => ({data: {sha: ref, parents: [ + {sha: kind === "bad-parents" ? defaultSha : ref === movedMerge ? movedBase : base}, {sha: head}]}}), getContent: async ({ref, path}) => { refs.push(ref); assert.equal(path, source.path); @@ -1045,7 +1057,7 @@ async function scenario(kind, event = "pull_request") { getWorkflow: async () => ({data: {id: 7, path: source.path, name: "Build Runtime Images"}}), getWorkflowRun: async () => { if (refs.length) qualifiedAttemptReads++; - return {data: {...source, run_attempt: kind === "newer-attempt" ? 2 : 1}}; + return {data: {...source, run_attempt: kind === "newer-attempt" || observedAttemptMove ? 2 : 1}}; }, }, }, request: async (route, input) => { @@ -1106,6 +1118,9 @@ async function scenario(kind, event = "pull_request") { }}; github.paginate.iterator = async function* (method, input) { assert.equal(method, listRuns); + if (ordinary && ++typedListReads === 1 && kind === "ordinary-sparse-head") { + yield {data: [{...source, head_sha: undefined}]}; return; + } if (event === "repository_dispatch" && input.event === "pull_request") { yield {data: [{...source, event: "pull_request", head_sha: head, conclusion: "cancelled"}]}; return; } @@ -1114,7 +1129,7 @@ async function scenario(kind, event = "pull_request") { const clock = {now: () => now, parse: Date.parse}; await execute(github, context, {info: () => {}, warning: () => {}, setFailed: message => failures.push(message)}, clock, (callback, duration) => {now += duration; waitedMillis += duration; queueMicrotask(callback);}, require); - return {failures, refs, snapshots, exactAttemptReads, observedBaseMove, waitedMillis}; + return {failures, refs, snapshots, exactAttemptReads, observedBaseMove, observedAttemptMove, waitedMillis}; } (async () => { for (const event of ["pull_request", "repository_dispatch"]) { @@ -1152,8 +1167,18 @@ async function scenario(kind, event = "pull_request") { assert.equal(changedJobId.failures.length, 1, "a job ID that changes between exact-attempt snapshots is contradictory, not a successful proof"); assert.match(changedJobId.failures[0], /Cancelled runtime replacement has contradictory identity/); - const moved = await scenario("drift-during-final-attempt", "repository_dispatch"); - assert(moved.observedBaseMove, "typed acceptance must re-read the live base after the final attempt lookup"); + const ordinary = await scenario("ordinary-stable", "repository_dispatch"); + assert.deepEqual(ordinary.failures, [], "unchanged ordinary typed proof passes"); + assert.equal(ordinary.waitedMillis, 0); + const sparseHead = await scenario("ordinary-sparse-head", "repository_dispatch"); + assert.deepEqual(sparseHead.failures, [], "a temporarily missing typed list head waits for a complete run row"); + assert(sparseHead.waitedMillis > 0); + for (const kind of ["ordinary-final-base-drift", "ordinary-final-attempt-drift"]) { + const moved = await scenario(kind, "repository_dispatch"); + assert(kind.endsWith("base-drift") ? moved.observedBaseMove : moved.observedAttemptMove); + assert.equal(moved.failures.length, 1); + assert.match(moved.failures[0], /^Timed out waiting for the exact runtime-images/); + } console.log("Smoke producer contract passed: native outcomes, exact immutable definition/attempt, legacy proof and fail-closed cases"); })().catch(error => {console.error(error); process.exitCode = 1;}); NODE @@ -3972,9 +3997,9 @@ async function failedProof(error, event = "pull_request") { assert.match(warnings[0], /^Canonical PLAY transition exception proof is unavailable:/); assert.deepEqual(outputs, []); } -async function selectedProducerFinalFence(event, moved = false, superseded = false) { +async function selectedProducerFinalFence(event, moved = false, superseded = false, rerunDuringIdentity = false) { const outputs = [], failures = [], required = []; - let proofs = 0, sleeps = 0; + let proofs = 0, sleeps = 0, attemptChanged = false; const core = {warning: () => {}, setFailed: x => failures.push(x), setOutput: (...x) => outputs.push(x)}; core.summary = {addHeading() {return this;}, addRaw() {return this;}, async write() {}}; const execute = new Function("fullSmokeJob", "matching", "canonicalSmokeJobName", "currentIdentity", @@ -3986,17 +4011,18 @@ async function selectedProducerFinalFence(event, moved = false, superseded = fal ++proofs === 1 && superseded ? "attempt-superseded" : true, TerminalGitHubRequestError, core, async (_label, current) => { required.push(current); + attemptChanged = rerunDuringIdentity; return {...identity, canonicalPlayEligible: true, ...(current ? {sourceEvent: "repository_dispatch"} : {}), ...(current && moved ? {baseSha: "e".repeat(40), mergeSha: "f".repeat(40)} : {})}; }, selected => { const {canonicalPlayEligible, ...tuple} = selected; return JSON.stringify(tuple); }, - async () => true, resolve => {sleeps++; resolve();}, 0); + async () => !attemptChanged, resolve => {sleeps++; resolve();}, 0); assert.equal(proofs, superseded ? 2 : 1); - assert.equal(sleeps, superseded ? 1 : 0); + assert.equal(sleeps, superseded || rerunDuringIdentity ? 1 : 0); assert.deepEqual(required, Array(proofs - (superseded ? 1 : 0)).fill(event === "repository_dispatch")); assert.deepEqual(failures, []); - assert.equal(outputs.length, event === "repository_dispatch" && moved ? 0 : 1, - "selected typed producer must reject base movement after proof, original retains immutable event semantics"); + assert.equal(outputs.length, (event === "repository_dispatch" && moved) || rerunDuringIdentity ? 0 : 1, + "an exception must retain its exact attempt through the final live identity read"); } // Execute the failed-run branch so proof errors retain the deterministic failure diagnostic. const legacyFailedStart = script.indexOf('if (matching.conclusion !== "success")'); @@ -4032,6 +4058,23 @@ const replacementVerifier = script.indexOf("async function verifySameTupleReplac const pollStart = script.indexOf("smokeGatePolling: while", replacementVerifier); assert.ok(loopStart >= 0 && replacementVerifier > loopStart && pollStart > replacementVerifier); const actualPollingLoop = script.slice(loopStart, replacementVerifier) + script.slice(pollStart); +async function sameTupleProof(marker, ordinaryProof, exceptionProof) { + const replacement = {...source, event: "repository_dispatch", head_sha: workflowSha}; + const job = {...candidate, head_sha: workflowSha, steps: candidate.steps.map(value => + value.name.startsWith("Known canonical transition") ? {...value, conclusion: marker} : value)}; + const verifiers = []; + const proof = new Function("positiveInteger", "withTransientGitHubRetry", "github", "owner", "repo", + "repositoryName", "canonicalSmokeJobName", "verifyCanonicalSmokeProducer", "verifyKnownPlayFailure", + `${script.slice(replacementVerifier, pollStart)}; return verifySameTupleReplacementProof;`)( + Number.isSafeInteger, (_label, call) => call(), {paginate: async (_route, input) => { + assert.equal(input.run_id, replacement.id); + assert.equal(input.attempt_number, replacement.run_attempt); + return [job]; + }}, "benhook1013", "FireMUD", repositoryName, canonicalSmokeJobName, + async () => {verifiers.push("ordinary"); return ordinaryProof;}, + async () => {verifiers.push("exception"); return exceptionProof;}); + return {result: await proof(replacement, identity), verifiers}; +} async function pendingRefreshCaller(statuses, expires = false, options = {}) { const failures = [], outputs = []; let sleeps = 0, polls = 0, writes = 0, now = 0, currentChecks = 0, finalChecks = 0, nullReads = 0, directReads = 0; @@ -4365,6 +4408,10 @@ function markerAccepted(overrides = {}) { await movedCancellation(false); await movedCancellation(true, true); await movedCancellation(false, true); + assert.deepEqual(await sameTupleProof("success", false, true), {result: true, verifiers: ["exception"]}); + assert.deepEqual(await sameTupleProof("success", true, false), {result: false, verifiers: ["exception"]}); + assert.deepEqual(await sameTupleProof("skipped", true, false), {result: "ordinary", verifiers: ["ordinary"]}); + assert.deepEqual(await sameTupleProof("skipped", false, true), {result: false, verifiers: ["ordinary"]}); const unprovenInProgressReplacement = await sameTupleCancellation("in_progress"); assert.equal(unprovenInProgressReplacement.failures.length, 1); assert.match(unprovenInProgressReplacement.failures[0], /no freshly proven exact replacement/); @@ -4556,6 +4603,7 @@ function markerAccepted(overrides = {}) { await selectedProducerFinalFence(event, true); } await selectedProducerFinalFence("repository_dispatch", false, true); + await selectedProducerFinalFence("repository_dispatch", false, false, true); await pendingRefreshCaller(["completed"], true, {finalIdentity: {baseSha: "d".repeat(40)}}); await pendingRefreshCaller(["completed"], true, {finalIdentity: {mergeSha: "e".repeat(40)}}); await pendingRefreshCaller(["completed", "completed"], false, { diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index deaba4e965..138e2aa700 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -894,7 +894,7 @@ const runsDescending = (event, firstCreatedAt) => Array.from({ length: 100 }, (_ })); async function runDispatcher({ tuples, inventories = {}, apiFailure = null, sourceTuples = [], callback = {}, - branchHeads = {}, branchErrors = {}, pullOverrides = {}, mergeParents = {}, ciEvidence = {}, + branchHeads = {}, branchErrors = {}, pullOverrides = {}, mergeParents = {}, mergeReadFailures = {}, ciEvidence = {}, hideDispatchVisibility = false, filesByPr = {}, postFailurePr = null, previewFailurePr = null, visibilityResponse = null, filesFailurePr = null, postFailureVisible = false, postFailureStatus = null, fanoutCutoffAfterInventory = false, fanoutCutoffAfterPreviewPr = null, expireAfterFirstApiRequest = false, @@ -904,6 +904,7 @@ async function runDispatcher({ const dispatches = []; const postedRuns = []; const pullReads = new Map(); + const mergeReads = new Map(); const errors = []; const infos = []; const warnings = []; @@ -1034,6 +1035,11 @@ async function runDispatcher({ getCommit: async (request) => { recordApiRequest("repos.getCommit", request); const {ref} = request; + const reads = (mergeReads.get(ref) ?? 0) + 1; + mergeReads.set(ref, reads); + if (mergeReadFailures[ref]?.(reads)) { + throw Object.assign(new Error("fixture exact merge commit lookup failed"), {status: 502}); + } const tuple = allTuples.find((candidate) => candidate.mergeSha === ref); return { data: { sha: ref, parents: (mergeParents[ref] ?? [tuple.baseSha, tuple.headSha]) .map((parent) => ({ sha: parent })) } }; @@ -1616,7 +1622,9 @@ async function runDispatcher({ pullOverrides: { "101": reads => reads > 1 ? { state: "closed" } : {} }, }); assert.deepEqual(numbers(changedFirst), ["102"], "changed first PR must not starve second"); - assert(changedFirst.infos.some(message => message.includes("Skipping changed runtime tuple"))); + assert(changedFirst.infos.some(message => message.includes("Skipping unverified runtime tuple for PR #101"))); + assert(!previewDispatches(changedFirst).some(item => item.client_payload.pr_number === "101"), + "independent preview proof must still exclude a now-closed PR"); const vanishedBase = await runDispatcher({ tuples: [tuple, sibling], branchErrors: {"heads/develop": count => count === 2 ? 404 : null}, }); @@ -1655,18 +1663,23 @@ async function runDispatcher({ assert(refinedBound.inventoryCalls.some(request => request.created === "2026-01-02T00:00:00Z..*")); const unrelatedInflight = producer(sibling, "pull_request", "in_progress", null, {created_at: "2026-01-02T00:00:00Z"}); + const completedRefresh = producer(tuple, "repository_dispatch", "completed", "success", { + created_at: "2026-01-01T12:00:00Z", + }); const refinedCompleted = await runDispatcher({ tuples: [tuple], callback: {updated_at: "2026-01-01T06:00:00Z"}, inventories: { pull_request: {total_count: 1001, runs: [unrelatedInflight], refinedCreated: "2026-01-01T06:00:00Z..*", refined: [unrelatedInflight], refinedTotalCount: 1}, - repository_dispatch: [producer(tuple, "repository_dispatch", "completed", "success", { - created_at: "2026-01-01T12:00:00Z", - })], + repository_dispatch: [completedRefresh], }, }); assert.deepEqual(numbers(refinedCompleted), [], "refinement must retain completed refresh between CI completion and sampled inflight floor"); assert(refinedCompleted.inventoryCalls.some(request => request.created === "2026-01-01T06:00:00Z..*")); + assert.deepEqual(refinedCompleted.errors, [], "refinement must reuse proof rather than fail closed"); + assert(refinedCompleted.infos.some(message => message.includes( + `Skipping duplicate PR runtime refresh for #101: exact tuple producer ${completedRefresh.id} remains completed.` + )), "refinement must report reuse of the completed producer"); const narrowedAbsence = await runDispatcher({ tuples: [tuple], callback: {updated_at: "2026-01-03T00:00:00Z"}, @@ -1871,6 +1884,20 @@ async function runDispatcher({ "accepted handoffs are observed after target lookup failure"); assert(!lookupFailure.errors.some(message => message.includes("visibility is unknown"))); } + for (const previewHeadMoved of [false, true]) { + const runtimeMergeUnavailable = await runDispatcher({ + tuples: [previewTuple], + mergeReadFailures: {[previewTuple.mergeSha]: reads => reads >= 2 && reads <= 6}, + pullOverrides: {"101": reads => previewHeadMoved && reads > 6 + ? {head: {sha: sha("f"), repo: {full_name: repository}}} + : {}}, + }); + assert.equal(runtimeDispatches(runtimeMergeUnavailable).length, 0); + assert(runtimeMergeUnavailable.warnings.some(message => message.includes("exact merge commit could not be read"))); + assert.deepEqual(previewDispatches(runtimeMergeUnavailable).map(item => item.client_payload.merge_sha), + previewHeadMoved ? [] : [previewTuple.mergeSha], + "the independent preview lookup must verify the exact tuple after all runtime merge reads fail"); + } const previewInvisible = await runDispatcher({tuples: [previewTuple], hideDispatchVisibility: true}); assert.equal(previewDispatches(previewInvisible).length, 1, "invisible accepted runtime handoff must preserve preview reconciliation"); process.stdout.write("runtime refresh deduplication fixtures passed\n"); diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 0e57e9eac5..f571822507 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -318,7 +318,7 @@ for (const publishable of ["false", "", undefined]) { assert.equal(callback.output.artifact_name, direct.output.artifact_name); const prSource = {...source, event: "pull_request", head_sha: sha("a"), head_branch: "feature/ci"}; const prCallback = {...callbackContext, payload: {repository, workflow_run: prSource}}; - assert.equal((await resolve({runs: [prSource]})).output.artifact_name, direct.output.artifact_name); + await assert.rejects(resolve({runs: [prSource]}), /publication source run provenance is not trusted/); assert.equal((await resolve({runs: [prSource], context: prCallback})).output.artifact_name, direct.output.artifact_name); const publisherWorkflow = fs.readFileSync(process.argv[5], "utf8"); assert.ok(publisherWorkflow.includes("if: ${{ needs.source.outputs.source != '' }}"), "no source must skip privileged publication"); @@ -1033,6 +1033,7 @@ run_validation() { local source_event="${1:-pull_request}" local source_branch="${2:-feature/ci}" local source_sha="${3:-$head_sha}" + local publication_trigger="${4:-workflow_run}" local environment_file="$fixture_dir/github-env" : > "$environment_file" if [[ -n "${PULL_REQUEST_SEQUENCE_DIR:-}" ]]; then @@ -1044,6 +1045,7 @@ run_validation() { REGISTRY_MARKER="$fixture_dir/registry-marker" \ PR_RUNTIME_ARTIFACT_ROOT="$artifact_root" \ CURRENT_REPOSITORY="$repository" \ + PUBLICATION_TRIGGER="$publication_trigger" \ SOURCE_RUN_ID="$source_run_id" \ SOURCE_RUN_URL="https://example.test/runs/$source_run_id" \ SOURCE_RUN_TITLE="$source_title" \ @@ -1074,6 +1076,11 @@ PY } run_validation +if run_validation pull_request feature/ci "$head_sha" repository_dispatch 2>"$fixture_dir/typed-source-error"; then + echo "typed publication accepted a pull-request producer" >&2 + exit 1 +fi +grep -Fq 'typed publication requires a repository_dispatch source run' "$fixture_dir/typed-source-error" for valid_ref in \ "main" \ "feature+metadata" \ @@ -1260,7 +1267,7 @@ payload = json.loads(path.read_text(encoding="utf-8")) payload.update({"event": "repository_dispatch", "head_sha": sys.argv[2], "head_branch": "develop"}) path.write_text(json.dumps(payload), encoding="utf-8") PY -run_validation repository_dispatch develop "$default_branch_sha" +run_validation repository_dispatch develop "$default_branch_sha" repository_dispatch grep -Fxq "IMAGE_TAG=pr-merge-$merge_sha" "$fixture_dir/github-env" if [[ -e "$fixture_dir/registry-marker" ]]; then echo "typed refresh source validation reached a registry operation" >&2 @@ -1277,7 +1284,7 @@ payload = json.loads(path.read_text(encoding="utf-8")) payload["event"] = "workflow_dispatch" path.write_text(json.dumps(payload), encoding="utf-8") PY -if run_validation repository_dispatch develop "$default_branch_sha"; then +if run_validation repository_dispatch develop "$default_branch_sha" repository_dispatch; then echo "typed refresh validation accepted a source run with the wrong API event" >&2 exit 1 fi From a4db30b0259f798545c4a8a7e2e4be7d35c88df2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:00:36 +1300 Subject: [PATCH 38/96] Resolve retained runtime CI and capacity review findings --- .../workflows/publish-pr-runtime-images.yml | 95 +++- .github/workflows/runtime-images.yml | 84 ++- .github/workflows/smoke.yml | 192 +++++-- .../account-service/api-contracts.md | 2 +- .../account-service/runtime-and-data.md | 2 +- .../architecture/system-architecture-cicd.md | 4 +- ...system-architecture-database-migrations.md | 2 +- .../player-access-and-session.md | 10 +- .../detect-hosted-v2-migration-activation.sh | 9 +- ...hosted-v2-migration-activation-contract.sh | 31 ++ .../pr-required-gate-context-contract.sh | 499 +++++++++++++++++- .../tests/pr-retarget-workflow-contract.sh | 13 +- .../pr-runtime-image-publication-contract.sh | 8 +- ...acityMigrationPostgresIntegrationTest.java | 80 ++- ...titlementOwnerPostgresIntegrationTest.java | 2 +- .../AccountTenantCapacityOwnerTest.java | 2 +- ...stractReloadingBlockingGrpcClientTest.java | 4 +- .../TenantCapacityAdmissionGrpcCodec.java | 2 + .../TenantCapacityAdmissionGrpcCodecTest.java | 167 +++--- 19 files changed, 994 insertions(+), 214 deletions(-) diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 09b930df47..59530c91e0 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -14,7 +14,7 @@ permissions: {} jobs: reconcile-failed-pr-runtime: name: Reconcile Failed Original PR Runtime - if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && (((github.event.workflow_run.path == '.github/workflows/runtime-images.yml' || startsWith(github.event.workflow_run.path, '.github/workflows/runtime-images.yml@')) && contains(fromJSON('["failure","cancelled","timed_out"]'), github.event.workflow_run.conclusion)) || ((github.event.workflow_run.path == '.github/workflows/ci.yml' || startsWith(github.event.workflow_run.path, '.github/workflows/ci.yml@')) && github.event.workflow_run.conclusion == 'cancelled')) && github.event.workflow_run.head_repository.full_name == github.repository }} + if: ${{ github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request' && (((github.event.workflow_run.path == '.github/workflows/runtime-images.yml' || startsWith(github.event.workflow_run.path, '.github/workflows/runtime-images.yml@')) && contains(fromJSON('["failure","cancelled","timed_out"]'), github.event.workflow_run.conclusion)) || ((github.event.workflow_run.path == '.github/workflows/ci.yml' || startsWith(github.event.workflow_run.path, '.github/workflows/ci.yml@')) && contains(fromJSON('["success","cancelled"]'), github.event.workflow_run.conclusion))) && github.event.workflow_run.head_repository.full_name == github.repository }} runs-on: ubuntu-latest timeout-minutes: 5 concurrency: @@ -56,8 +56,11 @@ jobs: const positive = value => Number.isSafeInteger(value) && value > 0; const sha = value => typeof value === "string" && /^[0-9a-f]{40}$/.test(value); const titlePattern = /^Build Runtime Images secure-pr-artifact pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40}) merge-([0-9a-f]{40}) mode-required$/; + const validationTitle = /^CI — Validation pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40})$/; + const validationWake = validationTitle.exec(callback?.display_title || ""); if (context.eventName !== "workflow_run" || event?.event !== "pull_request" || - event.status !== "completed" || !["failure", "cancelled", "timed_out"].includes(event.conclusion) || + event.status !== "completed" || + !(["failure", "cancelled", "timed_out"].includes(event.conclusion) || validationWake && event.conclusion === "success") || event.repository?.full_name !== repository || event.head_repository?.full_name !== repository || !positive(event.id) || !positive(event.run_attempt)) return; const {data: workflow} = await github.rest.actions.getWorkflow(prePostOptions({...context.repo, workflow_id: "runtime-images.yml"})); @@ -85,33 +88,47 @@ jobs: run.repository?.full_name === repository && run.head_repository?.full_name === repository && [workflow.name, run.display_title].includes(run.name) && positive(run.id) && positive(run.run_attempt); // Inventory incompleteness is unknown, never permission to dispatch duplicates. - const inventory = async (workflowId, filter, deadline = prePostDeadline, phase = "Pre-dispatch") => { - const runs = [], ids = new Set(); + const inventory = async (workflowId, filter, deadline = prePostDeadline, phase = "Pre-dispatch", validateVisibilityRun = null) => { + const runs = [], ids = new Map(); let total; for (let page = 1; page <= 10; page++) { const {data} = await github.rest.actions.listWorkflowRuns(withRequestDeadline({ ...context.repo, workflow_id: workflowId, per_page: 100, page, ...filter, }, deadline, phase)); - total ??= data?.total_count; - if (!Number.isInteger(total) || total < 0 || total >= 1000 || data?.total_count !== total || - !Array.isArray(data.workflow_runs) || data.workflow_runs.length !== Math.min(100, total - runs.length)) { + if (!Number.isInteger(data?.total_count) || data.total_count < 0 || data.total_count >= 1000 || + !Array.isArray(data.workflow_runs) || data.workflow_runs.length !== Math.min(100, Math.max(0, data.total_count - (page - 1) * 100))) { throw new Error("Reconciliation inventory is incomplete; no dispatch issued"); } + total ??= data.total_count; + let shifted = data.total_count !== total; + const pageIds = new Set(); for (const run of data.workflow_runs) { - if (!positive(run.id) || ids.has(run.id)) throw new Error("Reconciliation inventory shifted; no dispatch issued"); - ids.add(run.id); runs.push(run); + if (!positive(run?.id) || pageIds.has(run.id)) throw new Error("Reconciliation inventory has invalid or duplicate page IDs"); + pageIds.add(run.id); + if (validateVisibilityRun) validateVisibilityRun(run); + if (ids.has(run.id)) { + if (JSON.stringify(ids.get(run.id)) !== JSON.stringify(run)) { + throw new Error("Reconciliation inventory has contradictory duplicate run evidence"); + } + shifted = true; + } + ids.set(run.id, run); runs.push(run); + } + if (shifted) { + // Only POST visibility may restart this complete inventory; preflight stays terminal. + const error = new Error("Reconciliation inventory shifted; discard the whole snapshot"); + if (validateVisibilityRun) error.code = "VISIBILITY_PAGINATION_DRIFT"; + throw error; } if (runs.length === total) return runs; } throw new Error("Reconciliation inventory exceeds bounded pagination"); }; - const validationTitle = /^CI — Validation pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40})$/; - const validationWake = validationTitle.exec(callback.display_title || ""); let ciWorkflow = null; let wakeCurrent = async () => true; if (validationWake) { const [, wakeNumber, wakeBase, wakeHead] = validationWake; - if (callback.conclusion !== "cancelled" || callback.head_sha !== wakeHead || + if (!["cancelled", "success"].includes(callback.conclusion) || callback.head_sha !== wakeHead || typeof callback.head_branch !== "string" || !callback.head_branch || !positive(Number(wakeNumber))) return; ({data: ciWorkflow} = await github.rest.actions.getWorkflow(prePostOptions({...context.repo, workflow_id: "ci.yml"}))); @@ -119,7 +136,7 @@ jobs: ciWorkflow.name !== "CI — Validation") throw new Error("Untrusted CI workflow identity"); const matchesWake = run => run?.id === callback.id && run.run_attempt === callback.run_attempt && run.workflow_id === ciWorkflow.id && matchesPath(run.path, ciWorkflow.path) && - run.event === "pull_request" && run.status === "completed" && run.conclusion === "cancelled" && + run.event === "pull_request" && run.status === "completed" && run.conclusion === callback.conclusion && run.repository?.full_name === repository && run.head_repository?.full_name === repository && run.head_sha === wakeHead && run.head_branch === callback.head_branch && run.display_title === callback.display_title && run.path === callback.path && @@ -198,10 +215,21 @@ jobs: const matchesCi = run => matchesCiIdentity(run, ci) && run.status === "completed"; const selectCi = async () => { ci = null; + if (!await wakeCurrent()) return null; const ciRuns = (await inventory("ci.yml", {event: "pull_request", head_sha: head})) .filter(run => run.display_title === ciTitle).sort((a, b) => b.id - a.id); let skippedPreEnforcementCancellation = false; let skippedExactWake = false; + // A successful callback is only a wake after this same native attempt + // is positively classified as metadata, never from its conclusion alone. + const recordMetadataWake = () => { + if (validationWake && callback.conclusion === "success" && ci.id === callback.id) { + if (ci.run_attempt !== callback.run_attempt || ci.path !== callback.path || + ci.conclusion !== callback.conclusion) return false; + skippedExactWake = true; + } + return true; + }; // Metadata-only completions cannot conceal an earlier substantive attempt for this exact tuple. for (const candidate of ciRuns) { ci = candidate; @@ -265,6 +293,7 @@ jobs: if (await retryClassification()) continue; return null; } + if (!recordMetadataWake()) return null; ci = null; skippedCandidate = true; break; @@ -285,7 +314,7 @@ jobs: // inventory without failures or unexplained work may reveal older proof. const seenJobIds = new Set(); const seenChecks = new Set(); - let coherentCancellation = true; + let coherentCancellation = jobs.length > 1; for (const job of jobs) { if (!nativeJob(job) || seenJobIds.has(job.id) || seenChecks.has(job.check_run_url) || !["success", "skipped", "cancelled"].includes(job.conclusion) || !Array.isArray(job.steps)) { @@ -308,6 +337,19 @@ jobs: if (await retryClassification()) continue; return null; } + // The paginated adapter omits the provider's total. Recheck + // that the terminal attempt inventory is still complete and + // agrees with the first native page before revealing older CI. + const {data: confirmedJobs} = await github.rest.actions.listJobsForWorkflowRunAttempt( + prePostOptions({...context.repo, run_id: ci.id, attempt_number: ci.run_attempt, per_page: 100, page: 1}) + ); + if (confirmedJobs?.total_count !== jobs.length || !Array.isArray(confirmedJobs.jobs) || + confirmedJobs.jobs.length !== Math.min(jobs.length, 100) || + confirmedJobs.jobs.some((job, index) => !nativeJob(job) || job.id !== jobs[index].id || + job.conclusion !== jobs[index].conclusion)) { + if (await retryClassification()) continue; + return null; + } const {data: latestCancelled} = await github.rest.actions.getWorkflowRun( prePostOptions({...context.repo, run_id: ci.id}) ); @@ -316,7 +358,7 @@ jobs: return null; } skippedPreEnforcementCancellation = true; - if (validationWake && !skippedExactWake) { + if (validationWake && callback.conclusion === "cancelled" && !skippedExactWake) { if (ci.id !== callback.id || ci.run_attempt !== callback.run_attempt) return null; skippedExactWake = true; } @@ -349,6 +391,7 @@ jobs: if (await retryClassification()) continue; return null; } + if (!recordMetadataWake()) return null; ci = null; skippedCandidate = true; break; @@ -382,7 +425,16 @@ jobs: "runtime-images.yml", {event: "repository_dispatch", created: `${createdSince}..*`}, deadline, - phase + phase, + strictlyAfter === null ? null : run => { + if (run.display_title !== event.display_title) return; + if (!trusted(run) || run.event !== "repository_dispatch" || + run.head_branch !== context.payload.repository.default_branch || !sha(run.head_sha) || + typeof run.created_at !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(run.created_at) || + !Number.isFinite(Date.parse(run.created_at))) { + throw new Error("Exact refresh has conflicting native provenance or creation timestamp"); + } + } ); const exact = runs.filter(run => run.display_title === event.display_title && run.id > event.id); for (const run of exact) { @@ -461,7 +513,8 @@ jobs: if (error?.code === "REQUEST_DEADLINE_EXPIRED") break; const status = error?.status ?? error?.response?.status; const code = error?.code ?? error?.cause?.code; - const transient = [408, 425, 429, 500, 502, 503, 504].includes(status) || + const transient = code === "VISIBILITY_PAGINATION_DRIFT" || + [408, 425, 429, 500, 502, 503, 504].includes(status) || (status == null && (["ABORT_ERR", "ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"].includes(code) || ["AbortError", "TimeoutError"].includes(error?.name))); @@ -542,6 +595,7 @@ jobs: }); const title = typeof run.display_title === "string" && run.display_title.match(titlePattern); if (run.id !== sourceId || run.workflow_id !== workflow.id || + !Number.isSafeInteger(run.run_attempt) || run.run_attempt <= 0 || !isTrustedWorkflowPath(run.path) || !title || !["Build Runtime Images", run.display_title].includes(run.name) || !(callback ? ["pull_request", "repository_dispatch"].includes(run.event) @@ -634,6 +688,7 @@ jobs: CURRENT_REPOSITORY: ${{ github.repository }} PUBLICATION_TRIGGER: ${{ github.event_name }} SOURCE_RUN_ID: ${{ fromJSON(needs.source.outputs.source).id }} + SOURCE_RUN_ATTEMPT: ${{ fromJSON(needs.source.outputs.source).run_attempt }} SOURCE_RUN_URL: ${{ fromJSON(needs.source.outputs.source).html_url }} SOURCE_RUN_TITLE: ${{ fromJSON(needs.source.outputs.source).display_title }} SOURCE_RUN_EVENT: ${{ fromJSON(needs.source.outputs.source).event }} @@ -754,6 +809,10 @@ jobs: if not source_run_id_text.isdigit() or int(source_run_id_text) <= 0: fail("source workflow run id is not a positive integer") source_run_id = int(source_run_id_text) + source_run_attempt_text = required_environment("SOURCE_RUN_ATTEMPT") + if not source_run_attempt_text.isdigit() or int(source_run_attempt_text) <= 0: + fail("source workflow attempt is not a positive integer") + source_run_attempt = int(source_run_attempt_text) source_title = required_environment("SOURCE_RUN_TITLE") title_match = TITLE_PATTERN.fullmatch(source_title) if title_match is None: @@ -785,6 +844,8 @@ jobs: source_run = gh_json(f"repos/{repository}/actions/runs/{source_run_id}") if source_run.get("id") != source_run_id: fail("source workflow run API id does not match the event") + if type(source_run.get("run_attempt")) is not int or source_run["run_attempt"] != source_run_attempt: + fail("source workflow attempt changed before artifact validation") if source_run.get("workflow_id") != int(workflow_id_text): fail("source workflow identity changed between event and API") if source_run.get("name") not in {"Build Runtime Images", source_title}: diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 96cd246311..82c606d4fa 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -668,22 +668,23 @@ jobs: /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(value) && Number.isFinite(Date.parse(value)); - const readInventory = async (createdSince, events = runtimeRunEvents, deadline = fanoutDeadline, phase = "Runtime fan-out") => { + const readInventory = async (createdSince, events = runtimeRunEvents, deadline = fanoutDeadline, phase = "Runtime fan-out", validateVisibilityRun = null) => { const inventory = []; let complete = true; let incompleteReason = null; for (const event of events) { let total; - const eventRuns = [], ids = new Set(); + const eventRuns = [], ids = new Map(); for (let page = 1; page <= 10; page += 1) { const response = await github.rest.actions.listWorkflowRuns(withRequestDeadline({ ...context.repo, workflow_id: "runtime-images.yml", event, created: `${createdSince}..*`, per_page: runtimeRunPageSize, page, }, deadline, phase)); const payload = response?.data; - total ??= payload?.total_count; - if (!Number.isInteger(total) || total < 0 || !Array.isArray(payload?.workflow_runs) || - payload.total_count !== total) throw new Error(`runtime-images ${event} inventory shifted or is malformed`); + if (!Number.isInteger(payload?.total_count) || payload.total_count < 0 || !Array.isArray(payload?.workflow_runs)) { + throw new Error(`runtime-images ${event} inventory is malformed`); + } + total ??= payload.total_count; if (total >= 1000) { complete = false; incompleteReason ??= `runtime-images ${event} exceeds 1000-run bound`; @@ -692,14 +693,31 @@ jobs: eventRuns.push(...payload.workflow_runs); break; } - if (payload.workflow_runs.length !== Math.min(runtimeRunPageSize, total - eventRuns.length)) { + if (payload.total_count >= 1000 || + payload.workflow_runs.length !== Math.min(runtimeRunPageSize, Math.max(0, payload.total_count - (page - 1) * runtimeRunPageSize))) { throw new Error(`runtime-images ${event} recent run inventory is incomplete`); } + let shifted = payload.total_count !== total; + const pageIds = new Set(); for (const run of payload.workflow_runs) { - if (!Number.isSafeInteger(run.id) || run.id <= 0 || ids.has(run.id)) { + if (!Number.isSafeInteger(run?.id) || run.id <= 0 || pageIds.has(run.id)) { throw new Error(`runtime-images ${event} inventory has duplicate or invalid run IDs`); } - ids.add(run.id); eventRuns.push(run); + pageIds.add(run.id); + if (validateVisibilityRun) validateVisibilityRun(run); + if (ids.has(run.id)) { + if (JSON.stringify(ids.get(run.id)) !== JSON.stringify(run)) { + throw new Error(`runtime-images ${event} inventory has contradictory duplicate run evidence`); + } + shifted = true; + } + ids.set(run.id, run); eventRuns.push(run); + } + if (shifted) { + // Only POST visibility may restart this complete inventory; preflight stays terminal. + const error = new Error(`runtime-images ${event} inventory shifted; discard the whole snapshot`); + if (validateVisibilityRun) error.code = "VISIBILITY_PAGINATION_DRIFT"; + throw error; } if (eventRuns.length === total) break; } @@ -1044,7 +1062,6 @@ jobs: let existingProducers = []; let fallbackReason = null; let inventory; - const reusingInventory = runtimeInventoryPromise !== undefined; if (runtimeInventoryError) { fallbackReason = runtimeInventoryError; } else { @@ -1059,13 +1076,6 @@ jobs: if (!fallbackReason) { try { existingProducers = findExactExistingProducer(tuple, inventory); - // A cache hit can prove that an exact producer exists. Refresh - // a miss after earlier targets so it cannot hide a new producer. - if (reusingInventory && inventory.complete && existingProducers.length === 0) { - runtimeInventoryPromise = loadExistingRuntimeRuns(); - inventory = await runtimeInventoryPromise; - existingProducers = findExactExistingProducer(tuple, inventory); - } if (!inventory.complete) { // The REST contract does not specify a sort order, so a truncated page cannot prove omitted runs are older. existingProducers = []; @@ -1131,6 +1141,30 @@ jobs: core.info(`Skipping changed runtime tuple for PR #${tuple.prNumber}.`); continue; } + // Native PR producers do not share this dispatch lock. Fence + // both duplicate suppression and the visibility baseline after + // the potentially slow live comparison checks. + try { + runtimeInventoryPromise = loadExistingRuntimeRuns(); + inventory = await runtimeInventoryPromise; + const latestProducers = findExactExistingProducer(tuple, inventory); + if (!inventory.complete || !latestProducers.length && inventory.absenceProven === false) { + throw new Error(inventory.reason || "the final producer inventory cannot prove absence"); + } + if (latestProducers.length) { + core.info(`Skipping duplicate PR runtime refresh for #${tuple.prNumber}: exact tuple producer ${latestProducers[0].id} appeared during tuple verification.`); + break runtimeRefresh; + } + } catch (error) { + if (Date.now() >= fanoutDeadline) { + reportFanoutCutoff(targetIndex, "during final runtime inventory"); + break; + } + core.setFailed(`Cannot verify final runtime producer inventory for PR #${tuple.prNumber}; no dispatch issued: ${error.message || error}`); + runtimeInventoryPromise = undefined; + runtimeInventoryError = null; + break runtimeRefresh; + } if (Date.now() >= fanoutDeadline) { reportFanoutCutoff(targetIndex, `before the runtime POST for PR #${tuple.prNumber}`); break; @@ -1236,7 +1270,8 @@ jobs: const isTransientVisibilityError = error => { const status = error?.status ?? error?.response?.status; const code = error?.code ?? error?.cause?.code; - return [408, 425, 429, 500, 502, 503, 504].includes(status) || + return code === "VISIBILITY_PAGINATION_DRIFT" || + [408, 425, 429, 500, 502, 503, 504].includes(status) || (status == null && (["ABORT_ERR", "ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"].includes(code) || ["AbortError", "TimeoutError"].includes(error?.name))); @@ -1282,7 +1317,20 @@ jobs: visibilitySince, ["repository_dispatch"], visibilityDeadline, - "Runtime visibility observation" + "Runtime visibility observation", + run => { + for (const {tuple} of pendingVisibility) { + const exactTitle = `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; + if (run.display_title !== exactTitle) continue; + if (run.event !== "repository_dispatch" || run.workflow_id !== runtimeWorkflow.id || + !workflowPathMatches(run.path) || ![runtimeWorkflow.name, exactTitle].includes(run.name) || + run.repository?.full_name !== expectedRepository || run.head_repository?.full_name !== expectedRepository || + run.head_branch !== defaultBranch || typeof run.head_sha !== "string" || + !/^[0-9a-f]{40}$/.test(run.head_sha) || !validTimestamp(run.created_at)) { + throw new Error(`run ${run.id} has the exact PR tuple title but untrusted native workflow identity`); + } + } + } ); if (!observed.complete) throw new Error("Accepted refresh has incomplete visibility; no retry issued"); for (let index = pendingVisibility.length - 1; index >= 0; index--) { diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 687d59aac8..5d424fdb76 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -632,7 +632,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "da1e6c06adfa8fb26aad72dd5a613f2d55e5339c382f713888623e4f542e0a70"; + const canonicalRuntimeWorkflowSha256 = "a10e3434165cc6b150e380a75bcf5b4298c8895121017e36238a04f503b3ec2b"; // Only authenticated default-branch refreshes may use retained successful definitions. // Keep the pre-rollout default and predecessor definitions for mixed-version runs. const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set([ @@ -1227,23 +1227,29 @@ jobs: `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; const replacement = await findMatchingRuntimeImagesRun("repository_dispatch", title, identity); if (!replacement) return "absent"; - if (!positiveInteger(replacement.id) || !positiveInteger(replacement.run_attempt) || + if (!positiveInteger(replacement.id) || + (replacement.run_attempt != null && !positiveInteger(replacement.run_attempt)) || replacement.event !== "repository_dispatch") return false; if (replacement.id <= run.id) return "absent"; // Pending exact refreshes are not proof, but must not fail the caller // before the asynchronous producer can finish within its existing deadline. if (["queued", "in_progress", "waiting", "pending", "requested"].includes(replacement.status)) { - return "pending"; + return replacement.conclusion == null ? "pending" : false; + } + if (replacement.status !== "completed" || + (replacement.conclusion != null && !["success", "failure"].includes(replacement.conclusion))) return false; + const proofRun = {id: replacement.id, run_attempt: replacement.run_attempt, + conclusion: replacement.conclusion}; + // Re-list sparse native identity before reading any attempt-bound proof. + if (replacement.run_attempt == null || replacement.conclusion == null) { + return {status: "snapshot-pending", run: proofRun}; } - if (replacement.status !== "completed" || !["success", "failure"].includes(replacement.conclusion)) return false; const jobs = await withTransientGitHubRetry("canonical transition refresh jobs lookup", () => github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", { owner, repo, run_id: replacement.id, attempt_number: replacement.run_attempt, per_page: 100, }) ); const candidate = jobs.find((job) => job.name === canonicalSmokeJobName); - const proofRun = {id: replacement.id, run_attempt: replacement.run_attempt, - conclusion: replacement.conclusion}; const canonicalProof = replacement.conclusion === "success" ? await verifyCanonicalSmokeProducer(replacement, candidate, identity, true) : false; if (canonicalProof === true) { @@ -1504,6 +1510,7 @@ jobs: let requireCurrentIdentity = false; let cancelledRunId = null; let cancelledRunObservedAt = null; + let cancelledReplacement = null; let cancelledRecoveryMoved = false; async function verifySameTupleReplacementProof(replacement, identity) { if (replacement.event !== "repository_dispatch" || @@ -1598,6 +1605,7 @@ jobs: ) { cancelledRunId = null; cancelledRunObservedAt = null; + cancelledReplacement = null; } if ( currentIdentity.sourceEvent === "pull_request" && @@ -1607,6 +1615,7 @@ jobs: if (cancelledRunId !== matching.id) { cancelledRunId = matching.id; cancelledRunObservedAt = Date.now(); + cancelledReplacement = null; } const replacement = await findMatchingRuntimeImagesRun( "repository_dispatch", @@ -1625,6 +1634,16 @@ jobs: matching.head_branch === context.payload.pull_request.head.ref; const cancellationDiscoveryMs = recoverableCancellation ? refreshDiscoveryTimeoutMs : cancelledReplacementTimeoutMs; + const supersedingReplacement = cancelledReplacement && replacement && + positiveInteger(replacement.run_attempt) && + (replacement.id > cancelledReplacement.id || + (replacement.id === cancelledReplacement.id && + replacement.run_attempt > cancelledReplacement.run_attempt)); + if (cancelledReplacement?.terminalObservedAt != null && !supersedingReplacement && + Date.now() - cancelledReplacement.terminalObservedAt >= completedSnapshotTimeoutMs) { + core.setFailed("Cancelled runtime replacement did not expose complete exact smoke proof within the snapshot convergence allowance."); + return; + } if (!replacement) { if (recoverableCancellation && (pollIteration === 1 || pollIteration % pullRequestCheckInterval === 0)) { const liveIdentity = await resolveCurrentIdentity("Resolving live cancelled-run recovery tuple", true); @@ -1637,7 +1656,7 @@ jobs: continue smokeGatePolling; } } - if (Date.now() - cancelledRunObservedAt >= cancellationDiscoveryMs) { + if (!cancelledReplacement && Date.now() - cancelledRunObservedAt >= cancellationDiscoveryMs) { if (await isCurrentPullRequestObsolete("Stopping obsolete cancelled-run smoke gate for")) { return; } @@ -1659,7 +1678,7 @@ jobs: const liveIdentity = await resolveCurrentIdentity("Fencing listed cancelled-run replacement", true); if (liveIdentity?.obsolete) return; if (!liveIdentity) { - if (Date.now() - cancelledRunObservedAt >= cancellationDiscoveryMs) { + if (!cancelledReplacement && Date.now() - cancelledRunObservedAt >= cancellationDiscoveryMs) { core.setFailed("Cancelled runtime replacement lacks a verified live PR tuple."); return; } @@ -1676,11 +1695,51 @@ jobs: // A listed same-tuple refresh is only speculative. Keep the // cancelled original authoritative until the exact typed attempt // and its terminal smoke proof have been freshly verified. - sameTupleCancellationDeadline = cancelledRunObservedAt + cancellationDiscoveryMs; + if (!positiveInteger(replacement.id) || replacement.event !== "repository_dispatch" || + replacement.display_title !== expectedDisplayTitle || + (replacement.run_attempt != null && !positiveInteger(replacement.run_attempt))) { + core.setFailed("Cancelled runtime replacement has an invalid exact attempt identity."); + return; + } + if (cancelledReplacement && (replacement.id < cancelledReplacement.id || + (replacement.id === cancelledReplacement.id && positiveInteger(replacement.run_attempt) && + replacement.run_attempt < cancelledReplacement.run_attempt))) { + core.setFailed("Cancelled runtime replacement regressed to an older run or attempt; refusing stale proof."); + return; + } + if (positiveInteger(replacement.run_attempt) && (!cancelledReplacement || + replacement.id !== cancelledReplacement.id || + replacement.run_attempt !== cancelledReplacement.run_attempt)) { + cancelledReplacement = {id: replacement.id, run_attempt: replacement.run_attempt, terminalObservedAt: null}; + } + if (cancelledReplacement?.id === replacement.id && + (replacement.status === "completed" || replacement.status == null)) { + cancelledReplacement.terminalObservedAt ??= Date.now(); + } + // Discovery bounds absence, not execution of an identified replacement. + // Its completion still shares the unchanged overall Smoke deadline. + sameTupleCancellationDeadline = cancelledReplacement + ? started + timeoutMs : cancelledRunObservedAt + cancellationDiscoveryMs; + const snapshotAttempt = replacement.run_attempt ?? + (cancelledReplacement?.id === replacement.id ? cancelledReplacement.run_attempt : "missing"); + const replacementProofKey = + `same-tuple-replacement:${identityKey(currentIdentity)}:${replacement.id}:${snapshotAttempt}`; + if ((replacement.status === "completed" || replacement.status == null) && + incompleteRefreshKey !== replacementProofKey) { + incompleteRefreshKey = replacementProofKey; + incompleteRefreshObservedAt = Date.now(); + } + if (incompleteRefreshKey === replacementProofKey && + Date.now() - incompleteRefreshObservedAt >= completedSnapshotTimeoutMs) { + core.setFailed("Cancelled runtime replacement did not expose complete exact smoke proof within the snapshot convergence allowance."); + return; + } if (replacement.status !== "completed") { const knownNonterminal = ["queued", "in_progress", "waiting", "pending", "requested"] .includes(replacement.status); - if (replacement.status != null && (!knownNonterminal || replacement.conclusion != null)) { + if ((replacement.status != null && !knownNonterminal) || + (knownNonterminal && replacement.conclusion != null) || + (replacement.conclusion != null && !["success", "failure"].includes(replacement.conclusion))) { core.setFailed("Cancelled runtime replacement has an invalid nonterminal identity."); return; } @@ -1696,6 +1755,10 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } + if (replacement.conclusion != null && !["success", "failure"].includes(replacement.conclusion)) { + core.setFailed("Cancelled runtime replacement has an invalid terminal conclusion."); + return; + } if (replacement.run_attempt == null || replacement.conclusion == null) { if (Date.now() >= sameTupleCancellationDeadline) { core.setFailed( @@ -1708,12 +1771,6 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } - if (!positiveInteger(replacement.run_attempt) || !["success", "failure"].includes(replacement.conclusion)) { - core.setFailed("Cancelled runtime replacement has an invalid terminal conclusion."); - return; - } - const replacementProofKey = - `same-tuple-replacement:${identityKey(currentIdentity)}:${replacement.id}:${replacement.run_attempt}`; let replacementProof; try { replacementProof = await verifySameTupleReplacementProof(replacement, currentIdentity); @@ -1727,20 +1784,6 @@ jobs: replacementProof = "transient-pending"; } } - if (replacementProof === "snapshot-pending") { - if (incompleteRefreshKey !== replacementProofKey) { - incompleteRefreshKey = replacementProofKey; - incompleteRefreshObservedAt = Date.now(); - } - if (Date.now() - incompleteRefreshObservedAt >= completedSnapshotTimeoutMs && - Date.now() >= sameTupleCancellationDeadline) { - core.setFailed("Cancelled runtime replacement did not expose complete exact smoke proof before its existing discovery deadline."); - return; - } - } else { - incompleteRefreshKey = null; - incompleteRefreshObservedAt = null; - } if (replacementProof === "transient-pending" || replacementProof === "snapshot-pending" || replacementProof === "attempt-superseded") { if (Date.now() >= sameTupleCancellationDeadline) { @@ -1756,12 +1799,12 @@ jobs: } if (replacementProof !== "ordinary" && replacementProof !== true) { // A disproven speculative replacement cannot settle the gate. - // The original attempt may still recover within its existing window. + // Only a fresh original rerun or converged exact proof can recover. if (replacement.conclusion === "success" || Date.now() >= sameTupleCancellationDeadline) { core.setFailed("Cancelled runtime replacement has contradictory identity or invalid terminal smoke proof. The original did not expose a terminal PR Full-Stack Smoke job and smoke step."); return; } - core.warning(`Rejecting exact repository_dispatch run ${replacement.id}/${replacement.run_attempt}; retaining the original until its recovery deadline.`); + core.warning(`Rejecting exact repository_dispatch run ${replacement.id}/${replacement.run_attempt}; retaining the original within the terminal snapshot allowance.`); await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } @@ -1772,7 +1815,7 @@ jobs: ); return; } - const finalIdentity = await resolveCurrentIdentity("Fencing proven cancelled-run replacement", true); + let finalIdentity = await resolveCurrentIdentity("Fencing proven cancelled-run replacement", true); if (finalIdentity?.obsolete) return; if (!finalIdentity || identityKey({...finalIdentity, sourceEvent: currentIdentity.sourceEvent}) !== identityKey(currentIdentity)) { @@ -1788,6 +1831,18 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } + finalIdentity = await resolveCurrentIdentity("Fencing proven cancelled-run replacement", true); + if (finalIdentity?.obsolete) return; + if (!finalIdentity || identityKey({...finalIdentity, sourceEvent: currentIdentity.sourceEvent}) !== + identityKey(currentIdentity)) { + if (finalIdentity) { + cancelledRecoveryMoved = true; + requireCurrentIdentity = true; + currentIdentity = finalIdentity; + } + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } if (replacementProof === "ordinary") { core.info(`Exact repository_dispatch replacement ${replacement.id}/${replacement.run_attempt} passed full-stack smoke and authenticated cleanup.`); return; @@ -1895,7 +1950,7 @@ jobs: } const snapshotPending = refreshProof?.status === "snapshot-pending"; if (snapshotPending) { - const snapshotKey = `${refreshKey}:${refreshProof.run.id}:${refreshProof.run.run_attempt}`; + const snapshotKey = `${refreshKey}:${refreshProof.run.id}:${refreshProof.run.run_attempt ?? "missing"}`; if (incompleteRefreshKey !== snapshotKey) { incompleteRefreshKey = snapshotKey; incompleteRefreshObservedAt = Date.now(); @@ -1946,6 +2001,16 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } + const finalIdentity = await resolveCurrentIdentity("Fencing exact passing typed smoke recovery", true); + if (finalIdentity?.obsolete) return; + if (!finalIdentity || identityKey({...finalIdentity, sourceEvent: currentIdentity.sourceEvent}) !== + identityKey(currentIdentity)) { + if (finalIdentity) { + requireCurrentIdentity = true; + currentIdentity = finalIdentity; + } + continue smokeGatePolling; + } return; } knownPlayVerified = refreshProof?.status === "verified" && @@ -1992,6 +2057,22 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } + if (needsLiveTuple) { + const finalIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception", true); + if (finalIdentity?.obsolete) return; + if (!finalIdentity || identityKey({...finalIdentity, sourceEvent: currentIdentity.sourceEvent}) !== + identityKey(currentIdentity)) { + if (finalIdentity) { + requireCurrentIdentity = true; + currentIdentity = finalIdentity; + } + continue smokeGatePolling; + } + if (!finalIdentity.canonicalPlayEligible) { + core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); + return; + } + } core.setOutput("known_play_exception", "true"); core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); await core.summary.addHeading("Canonical PLAY transition exception accepted") @@ -2077,7 +2158,7 @@ jobs: core.setFailed("Moved cancelled-run recovery did not supply authenticated smoke proof."); return; } - const freshIdentity = await resolveCurrentIdentity("Fencing moved cancelled-run recovery", true); + let freshIdentity = await resolveCurrentIdentity("Fencing moved cancelled-run recovery", true); if (freshIdentity?.obsolete) return; if (!freshIdentity || identityKey(freshIdentity) !== identityKey(currentIdentity)) { if (freshIdentity) currentIdentity = freshIdentity; @@ -2088,6 +2169,13 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } + freshIdentity = await resolveCurrentIdentity("Fencing moved cancelled-run recovery", true); + if (freshIdentity?.obsolete) return; + if (!freshIdentity || identityKey(freshIdentity) !== identityKey(currentIdentity)) { + if (freshIdentity) currentIdentity = freshIdentity; + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } if (proof === "ordinary") return; if (!freshIdentity.canonicalPlayEligible) { core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); @@ -2102,7 +2190,7 @@ jobs: let fullSmokeStep = null; let canonicalProducerVerified = false; const typedRuntimeProof = matching.event === "repository_dispatch"; - if (typedRuntimeProof && !positiveInteger(matching.run_attempt)) { + if (typedRuntimeProof && matching.run_attempt != null && !positiveInteger(matching.run_attempt)) { core.setFailed("Typed runtime smoke producer lacks an exact attempt."); return; } @@ -2117,15 +2205,15 @@ jobs: `step=${fullSmokeStep?.status ?? "missing"}/${fullSmokeStep?.conclusion ?? "unknown"}` ); } - if (typedRuntimeProof && matching.head_sha == null) { + if (typedRuntimeProof && (matching.run_attempt == null || matching.head_sha == null)) { // Retrying the jobs lookup cannot fill a sparse run-list row. - const snapshotKey = `typed-list-head:${matching.id}:${matching.run_attempt}:${identityKey(currentIdentity)}`; + const snapshotKey = `typed-list-identity:${matching.id}:${matching.run_attempt ?? "missing"}:${identityKey(currentIdentity)}`; if (incompleteRefreshKey !== snapshotKey) { incompleteRefreshKey = snapshotKey; incompleteRefreshObservedAt = Date.now(); } if (Date.now() - incompleteRefreshObservedAt >= completedSnapshotTimeoutMs) { - await failNonTerminalSnapshot("without the typed run-list head SHA"); + await failNonTerminalSnapshot("without the typed run-list attempt or head SHA"); return; } await new Promise((resolve) => setTimeout(resolve, snapshotSleepMs)); @@ -2378,6 +2466,22 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } + if (needsLiveTuple) { + const finalIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception", true); + if (finalIdentity?.obsolete) return; + if (!finalIdentity || identityKey({...finalIdentity, sourceEvent: currentIdentity.sourceEvent}) !== + identityKey(currentIdentity)) { + if (finalIdentity) { + requireCurrentIdentity = true; + currentIdentity = finalIdentity; + } + continue smokeGatePolling; + } + if (!finalIdentity.canonicalPlayEligible) { + core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); + return; + } + } core.setOutput("known_play_exception", "true"); core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); await core.summary.addHeading("Canonical PLAY transition exception accepted") @@ -2437,6 +2541,16 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } + if (typedRuntimeProof) { + // The final attempt GET can itself overlap PR/base movement. + const fencedIdentity = await fenceCompletedRuntimeIdentity("Stopping stale smoke gate before accepting full-stack proof"); + if (fencedIdentity?.obsolete) return; + if (!fencedIdentity || identityKey(fencedIdentity) !== identityKey(currentIdentity)) { + currentIdentity = fencedIdentity; + core.info(`Runtime images run ${matching.id} was not accepted because its PR identity changed during the final attempt lookup.`); + continue smokeGatePolling; + } + } return; } diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index d7243e2afb..ea7bec95ef 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -233,7 +233,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 canonical Account UUIDs. Account resolves known subjects through one local UUID batch query with the same persisted provenance and source-row checks as scalar identity reads, then returns policies keyed by UUID. Unknown or unproven entries are intentionally omitted so Social applies complete `PRIVATE` redaction. - `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current gRPC adapter returns `FAILED_PRECONDITION` before selector parsing or owner reads; this does not implement the target export operation. -- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns the typed `TENANT_BILLING_BLOCKED` response. This billing refusal does not consume the quota-refusal budget or create a durable decision receipt; it remains available when no refusal-budget row exists. Fresh creation-eligible evidence with checked insufficient capacity returns the typed `CAPACITY_QUOTA_EXCEEDED` response only after the exact durable `NO_ACCEPT` decision commits. If its refusal budget is missing or exhausted, Account returns non-OK `ENTITLEMENT_UNAVAILABLE` instead; no quota receipt or settlement authority is issued. Each refusal is bound to the exact original attempt, mutation digest, snapshot and evaluation. A quota refusal includes the immutable Account decision UUID only after an exact durable `NO_ACCEPT` commits. A matching exact retry returns the retained receipt. A quota refusal without that receipt grants no evidence settlement authority. The response contains exactly one commitment or one typed refusal. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a changed exact retry. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays. A request outside the proof-backed rearm contract that changes a bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest returns an idempotency conflict before usage mutation. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns the typed `TENANT_BILLING_BLOCKED` response. This billing refusal does not consume the quota-refusal budget or create a durable decision receipt; it remains available when no refusal-budget row exists. Fresh creation-eligible evidence with checked insufficient capacity returns the typed `CAPACITY_QUOTA_EXCEEDED` response only after the exact durable `NO_ACCEPT` decision commits. If its refusal budget is missing or exhausted, Account returns non-OK `ENTITLEMENT_UNAVAILABLE` instead; no quota receipt or settlement authority is issued. Each refusal is bound to the exact original attempt, mutation digest, snapshot and evaluation. A quota refusal includes the immutable Account decision UUID only after an exact durable `NO_ACCEPT` commits. A matching exact retry returns the retained receipt. A quota refusal without that receipt grants no evidence settlement authority. The response contains exactly one commitment or one typed refusal. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a changed exact retry. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact attempt-and-fence retries replay; a changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. Exact replay is guaranteed only for outcomes Account durably retained. A billing or non-creating entitlement refusal that did not retain a decision receipt is not a replayable outcome; a later retry rechecks current evidence freshness before deciding and cannot treat the earlier refusal as a retained result. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 0ba850e3ce..847e13f2e8 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -8,7 +8,7 @@ Account owns platform identity, hosted Creator Party/operator and terms currentn ### Finalized capacity usage retirement -After [Game Session supplies authenticated terminal proof](../game-session-service/runtime-and-data.md#finalized-capacity-usage-retirement) for the exact finalized binding and reservation, Account retains a unique retirement receipt and decrements used units in the same owner transaction. Exact retirement retries replay that receipt. Account preserves the original `FINALIZED` result and its replay evidence. +After [Game Session supplies authenticated terminal proof](../game-session-service/runtime-and-data.md#finalized-capacity-usage-retirement) for the exact finalized binding and reservation, Account retains a unique retirement receipt and subtracts only the units covered by that exact receipt from used units in the same owner transaction, leaving unrelated used units unchanged. Exact retirement retries replay that receipt without a second decrement. Account preserves the original `FINALIZED` reservation, result and replay evidence. ## Implementation Status diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 4c7b9f3828..97900635be 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -90,9 +90,9 @@ A typed runtime refresh hands off publication explicitly after its required cred For typed publication, `source_run_id` selects a native Actions run for lookup; neither the payload nor its title is source authority. The no-checkout resolver binds the returned native `run.id` to that supplied ID and its `workflow_id` to the separately resolved runtime workflow identity (`Build Runtime Images` at `.github/workflows/runtime-images.yml`). The native run path must be that workflow path or its validated ref-suffixed form, and its name must be the owner workflow name or exact canonical display title. It requires native `event=repository_dispatch`, the current repository in both `repository` and `head_repository`, `head_branch` equal to the repository default branch, a lowercase 40-character native `head_sha` for that default-branch source revision, and the canonical runtime title carrying the exact PR number/base/head/merge tuple and `mode-required`. The type and default-branch ref are also checked at the handoff boundary. This trusted typed source identity comes from GitHub's Actions run and workflow records, not from caller-supplied tuple fields. -The publisher's no-checkout, Actions-read-only resolver reads only the supplied exact source run and owning runtime workflow identity. A dispatch can arrive before its source workflow finishes, so the resolver waits for actual terminal success within a two-minute budget; malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. The resolver never substitutes a successful status. Both trigger paths retain the same exact source, current PR/base/head/merge, artifact provenance, and immutable-tag validation. Publishing jobs serialize on the verified merge-bound source title across both paths; duplicate publication preserves identical existing images and rejects conflicting image bytes. Explicit dispatch avoids relying on a workflow-run callback from a token-origin refresh without weakening the source or registry boundary. +The publisher's no-checkout, Actions-read-only resolver reads only the supplied exact source run and owning runtime workflow identity. A dispatch can arrive before its source workflow finishes, so the resolver waits for actual terminal success within a two-minute budget; malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. The resolver never substitutes a successful status. Both trigger paths retain the same exact source, current PR/base/head/merge, artifact provenance, and immutable-tag validation. The publisher checks the resolved native source attempt again after download and refuses a superseded attempt before registry access. Publishing jobs serialize on the verified merge-bound source title across both paths; duplicate publication preserves identical existing images and rejects conflicting image bytes. Explicit dispatch avoids relying on a workflow-run callback from a token-origin refresh without weakening the source or registry boundary. -The trusted publisher also reconciles a failed, cancelled, or timed-out original same-repository PR runtime run when substantive Validation already completed. This API-only job has `contents: write` solely to request an exact typed refresh; it never checks out PR code. It verifies current native source and CI attempts, the live base/head/merge tuple, and absence of a newer original or typed refresh before dispatch. Typed-refresh and nested workflow callbacks cannot recursively invoke this recovery. The CI dispatcher and completion reconciler share an API-job concurrency group with `queue: max`; runtime builds remain parallel. Unknown or incomplete producer inventory fails closed. Before each candidate runtime POST, the dispatcher refreshes the complete producer inventory, suppresses a newly reusable exact producer, and rechecks the current PR tuple and base ref; each handoff remains a single non-retried POST. An uncertain dispatch is not blindly repeated. Accepted handoffs share one 120-second visibility window after fan-out rather than delaying each later target in turn. The dispatcher resolves the current native runtime workflow identity before classifying observed producers and retries only transient identity lookup failures within that existing visibility deadline; it never retries a POST. Visibility requires a complete native producer inventory, the exact tuple title and current workflow/repository identity, a new run ID absent from the complete pre-POST snapshot, and a creation timestamp no earlier than the dispatch timestamp second. Preview reconciliation checks its own current tuple independently of runtime handoff uncertainty; a failed target does not automatically suppress independent later targets. This is bounded coordination, not exactly-once delivery or an unbounded no-starvation guarantee: GitHub admits at most 100 pending jobs in the group, inventories and job durations are bounded, and existing superseding base callbacks can cancel obsolete work. Remaining unknown outcomes require fresh evidence rather than presumed success. +The trusted publisher also reconciles a failed, cancelled, or timed-out original same-repository PR runtime run when substantive Validation already completed. This API-only job has `contents: write` solely to request an exact typed refresh; it never checks out PR code. It verifies current native source and CI attempts, the live base/head/merge tuple, and absence of a newer original or typed refresh before dispatch. A cancelled Validation callback can also wake recovery. The exact cancelled attempt must prove that enforcement never started and that none of its prerequisite jobs failed. An exact terminal metadata-only Validation attempt can also wake the reconciler once its native jobs positively identify it as metadata-only. The reconciler skips that attempt as proof. Recovery past a cancelled Validation attempt requires an earlier successful substantive attempt for the same comparison. Typed-refresh and nested workflow callbacks cannot recursively invoke this recovery. The CI dispatcher and completion reconciler share an API-job concurrency group with `queue: max`; runtime builds remain parallel. Unknown or incomplete producer inventory fails closed. Before each candidate runtime POST, the dispatcher rechecks the current PR tuple and base ref, then refreshes the complete producer inventory to suppress any newly reusable exact producer. Each handoff sends one POST. An uncertain dispatch is not blindly repeated. Accepted handoffs share one 120-second visibility window after fan-out rather than delaying each later target in turn. The dispatcher resolves the current native runtime workflow identity before classifying observed producers and retries only transient identity lookup failures within that existing visibility deadline; it never retries a POST. Visibility requires a complete native producer inventory, the exact tuple title and current workflow/repository identity, a new run ID absent from the complete pre-POST snapshot, and a creation timestamp no earlier than the dispatch timestamp second. Preview reconciliation checks its own current tuple independently of runtime handoff uncertainty; a failed target does not automatically suppress independent later targets. This is bounded coordination, not exactly-once delivery or an unbounded no-starvation guarantee: GitHub admits at most 100 pending jobs in the group, inventories and job durations are bounded, and existing superseding base callbacks can cancel obsolete work. Remaining unknown outcomes require fresh evidence rather than presumed success. Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard. Ordinary runtime qualification requires both Actions-native outcomes to be `success` and the transition-exception marker to be explicitly skipped. Missing marker metadata cannot use the native-job fallback: a successful job alone may instead represent the bounded exception described below. Skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify as real runtime proof. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. A separate, temporary diagnostic exception lets the required Smoke Gate succeed for a same-repository `benhook1013/FireMUD` pull request whose current live PR carries the `canonical-play-transition` label. A `pull_request` producer also requires the source event label and exact verified PR-event base/head/merge tuple. A typed `pr-runtime-base-refresh` producer instead derives label authority from its verified live same-repository PR, never dispatch payload labels, and requires the exact current base/head/merge tuple again at consumption. Both paths require the latest successful CI attempt with its explicit exception marker while the PR head and base branch remain current. During the default-branch workflow rollout, the exact previous fail-red producer fingerprint remains accepted only with its original failed smoke and terminal guard plus successful marker and cleanup; it supplies the same diagnostic exception and no runtime qualification. The smoke invocation retains its failed Actions-native outcome through step-level continuation; only the exact label, classifier and successful authenticated cleanup can make the mandatory final guard accept that failed probe. Every other probe failure still fails CI. GitHub reports the continued step conclusion as success, so the consumer verifies the immutable marker rather than treating that conclusion as runtime proof. The fingerprinted producer must attest the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, with successful authenticated cleanup. The executing workflow is fingerprinted at the PR merge revision or typed refresh's native default-branch revision, respectively; classifiers, held-admission qualification, authenticated cleanup, certificate setup, and their checked-in environment and Compose inputs are always fingerprinted at the tested PR merge. Its original smoke failure remains visible in the probe logs, summary and Actions-native outcome; unrelated failures still block, and image export and upload must be skipped. The typed publication handoff also requires a real successful image upload. A trusted workflow-run publisher detects the exception marker before exposing a publication source and skips its privileged job; a successful CI conclusion under exception does not authorize registry access or preview images. This is gate acceptance for the nonproduction canonical cutover, not successful smoke, runtime qualification, branch-image promotion, hosted preview eligibility, or production activation. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception; after the cutover merges, branch images remain on hold until the Account entitlement path is repaired. Remove the label-based marker and consumer exception when fresh-image backend `LOGIN` → `PLAY` → `LOOK` passes, then remove this transitional contract. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. diff --git a/design/architecture/system-architecture-database-migrations.md b/design/architecture/system-architecture-database-migrations.md index 2224fb528b..bf7ce003ff 100644 --- a/design/architecture/system-architecture-database-migrations.md +++ b/design/architecture/system-architecture-database-migrations.md @@ -244,7 +244,7 @@ ORDER BY conrelid::regclass::text, conname; This catalog query identifies enforced references, not all domain-level reachability; the owner must also check release bundles, launch descriptors, remap sets, publish attempts, and asset workflows for the exact candidate IDs. If the draft cannot be proved disposable, the migration remains blocked for owner adjudication. After correction or approved draft removal, rerun both queries and require zero rows before retrying the same release. Never broaden the migration to rewrite or delete retained rows to make V27 pass. -The trusted dev-demo workflow preserves its existing clean namespace reset for ordinary pushes. A push that first adds the Game Session or Automation V2 Flyway migration, or Account V25 profile-identity migration, in the trusted deployed-to-target range instead preserves the runtime database and uses the quiesced activation path. That path first proves the reserved nonmatching selector does not match a Pod, replaces each canonical Account, Game Session, and Automation Service selector, verifies each readback, and waits until all matching EndpointSlices contain no endpoints. It then scales all three writers to zero and proves their Deployments and writer Pods are quiescent before restoring the canonical Service selectors. If selector mutation, endpoint observation, scaling, or drain proof fails, the helper aborts before migration activation and attempts to leave the canonical Services closed. If closure cannot be verified or reapplied, an operator must verify and repair admission before retrying. This includes Account because its V25 tenant-scoped uniqueness constraint must not overlap an old Account writer. Edits or deletions of an existing supported migration fail before namespace mutation because retained-database and Flyway checksum state are uncertain. Other Flyway migrations in the exact deployed-to-target Git range fail detection before namespace mutation until explicit trusted support exists; non-migration pushes retain the clean reset. Both pushes and redispatches use only the exact deployed-head annotation from the owned `dev` namespace as the classification base and require valid Git ancestry to the target. A supplied push before-SHA can add an ancestry check but never replaces that deployed-head base. Missing or ambiguous namespace evidence stops the workflow before namespace mutation. This narrow exception avoids using namespace deletion as a substitute for proving the retained V1 data prerequisites. +The trusted dev-demo workflow preserves its existing clean namespace reset for ordinary pushes. A push that first adds the Game Session or Automation V2 Flyway migration, Account V25 profile-identity migration, or one of the explicitly listed Account V1040.1–V1040.6 capacity-origin migrations, in the trusted deployed-to-target range instead preserves the runtime database and uses the quiesced activation path. That path first proves the reserved nonmatching selector does not match a Pod, replaces each canonical Account, Game Session, and Automation Service selector, verifies each readback, and waits until all matching EndpointSlices contain no endpoints. It then scales all three writers to zero and proves their Deployments and writer Pods are quiescent before restoring the canonical Service selectors. If selector mutation, endpoint observation, scaling, or drain proof fails, the helper aborts before migration activation and attempts to leave the canonical Services closed. If closure cannot be verified or reapplied, an operator must verify and repair admission before retrying. Account writer quiescence also protects V25 profile uniqueness and the capacity-origin uniqueness, refusal guards and slot backfill. Edits or deletions of an existing supported migration fail before namespace mutation because retained-database and Flyway checksum state are uncertain. Other Flyway migrations in the exact deployed-to-target Git range fail detection before namespace mutation until explicit trusted support exists; non-migration pushes retain the clean reset. Both pushes and redispatches use only the exact deployed-head annotation from the owned `dev` namespace as the classification base and require valid Git ancestry to the target. A supplied push before-SHA can add an ancestry check but never replaces that deployed-head base. Missing or ambiguous namespace evidence stops the workflow before namespace mutation. This narrow exception avoids using namespace deletion as a substitute for proving the retained V1 data prerequisites. Hosted candidate previews may activate a migration only when the trusted path independently proves both an isolated fresh database and absence of old writers. A newly recreated namespace or a manifest value is not database provenance when backing storage may be retained. If the preview credential cannot verify that proof, skip or fail the candidate activation before modifying its namespace; use the trusted post-merge quiesce path instead. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 87dd792aa8..778d226957 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -32,9 +32,17 @@ The [shared capacity-admission/v1 schema](../../../services/common-platform-core The unregistered Account owner prepares exact initial reservation, replay and conflict. The recovery worker uses an exact selected-owner observation to finalize, release or rearm the original reservation. Missing and ambiguous observations retain the hold through bounded quarantine. Focused Account proof covers the ledger, fresh and historical bootstrap, exact replay, refusal and controlled recovery. The default Account runtime refuses the legacy numeric entitlement route and has no registered capacity receiver or recovery worker. +The staged [Game Session capacity client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java) is manually composed and unregistered. It requires the exact same-namespace Account mTLS peer before releasing the request body, carries the complete typed request and verifies the exact response binding. Its call uses the minimum of the remaining absolute admission budget, incoming deadline and five-second cap, with bounded request/response sizes and no automatic mutation retry. A timeout, transport failure or inexact response leaves the original commitment indeterminate; the client neither admits gameplay nor performs an owner activation CAS. + +After exact replay/conflict and retained/current source qualification, the Account owner returns `TENANT_BILLING_BLOCKED` only when the bound evidence does not permit creation. This refusal carries no durable decision receipt and is not a retained replayable outcome; a later retry must recheck current evidence. A creating request denied by quota instead commits an exact `NO_ACCEPT` decision under the finite tenant refusal budget before returning `CAPACITY_QUOTA_EXCEEDED` with its durable denial ID. That retained denial has no reservation or usage mutation, excludes acceptance for the same original and replays even after headroom returns or the evaluation expires. The client preserves the typed distinction and exposes a durable denial ID only when supplied by the authenticated Account response; a refusal without that receipt supplies no durable settlement proof. + +Account [V1040.6](../../../services/account-service/src/main/resources/db/migration/V1040.6__index_retained_capacity_refusal_slots.sql) backfills immutable contiguous per-tenant refusal slots for retained `NO_ACCEPT` decisions without rewriting the original decisions or provisioned limits. After origin identity arbitration, each fresh refusal appends one slot under the existing tenant budget lock; replay, conflict and failed insertion do not spend a slot. Refusal admission and readiness headroom use the indexed highest slot rather than scanning lifetime origin history. Missing or mismatched budgets and exhausted headroom remain fail-closed; this adds no replenishment, reset or receipt-deletion authority. + +Existing focused proof anchors include the [Account owner units](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java), [creation/ledger/recovery PostgreSQL cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java), [player-owner retained-denial case](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java), [migration/refusal-slot cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java), [shared codec cases](../../../services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java) and [Game Session client mTLS cases](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java). These cover controlled owner/storage, exact refusal/replay and separate loopback transport boundaries, not a genuine cross-owner runtime-admission chain. The codec cases now prepare contradictory billing-refusal rejection on both encode and decode while preserving valid non-creating billing evidence and quota-denial invariants. This bounded correction runs only the four-file `git diff --check`; canonical Gradle formatting and focused test execution remain delegated to the parent, with no new compilation, test-pass or physical-execution claim here. + The Account owner can retry a rolled-back PostgreSQL serialization failure up to three times in fresh transactions, with short randomized delays and one retry-admission deadline. The player evaluation transaction rolls back and reports source unavailability when exact retention readback fails. An exact reservation replay in RELEASED or QUARANTINED state cannot authorize original NEW execution. -Game Session original-NEW execution and its authenticated recovery source, normal owner handoff, and the origin and historical FINAL receiving paths remain dependent work. Finalized usage retirement requires a genuine admitted-session teardown receipt from the selected owner and an exactly-once Account usage transition that preserves finalized replay. Bounded conservation and owner-governed evidence retention remain downstream. Preserve immutable predecessor evidence, deployed source and PKI qualification, and runtime registration and activation holds. +Game Session original-NEW execution and its authenticated recovery source, normal owner handoff, and the origin and historical FINAL receiving paths remain dependent work. Finalized usage retirement and settlement remain deferred: they require a genuine admitted-session teardown receipt from the selected owner and an exactly-once Account usage transition that preserves finalized replay. Bounded conservation and owner-governed evidence retention remain downstream. Preserve immutable predecessor evidence, deployed source and PKI qualification, and runtime registration, admission and activation holds. ### Controlled player-admission transport composition diff --git a/dev-tools/deploy/detect-hosted-v2-migration-activation.sh b/dev-tools/deploy/detect-hosted-v2-migration-activation.sh index 500c1fbeed..9572dec14f 100644 --- a/dev-tools/deploy/detect-hosted-v2-migration-activation.sh +++ b/dev-tools/deploy/detect-hosted-v2-migration-activation.sh @@ -80,6 +80,7 @@ fi game_session_v2="services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql" automation_v2="services/automation-scripting-service/src/main/resources/db/migration/V2__script_patch_readiness_single_active.sql" account_v25="services/account-service/src/main/resources/db/migration/V25__scope_profile_identity.sql" +account_migrations="services/account-service/src/main/resources/db/migration" migration_changed=false while IFS= read -r changed_path; do [[ -z "$changed_path" ]] && continue @@ -89,7 +90,13 @@ while IFS= read -r changed_path; do fi if [[ "$changed_path" =~ ^services/[^/]+/src/main/resources/db/migration/.+[.]sql$ ]]; then case "$changed_path" in - "$game_session_v2"|"$automation_v2"|"$account_v25") + "$game_session_v2"|"$automation_v2"|"$account_v25"|\ + "$account_migrations/V1040.1__account_capacity_origin_decisions.sql"|\ + "$account_migrations/V1040.2__bound_capacity_origin_refusals.sql"|\ + "$account_migrations/V1040.3__validate_only_inserted_refusal_budgets.sql"|\ + "$account_migrations/V1040.4__unique_capacity_origin_attempt.sql"|\ + "$account_migrations/V1040.5__arbitrate_origin_identity_before_refusal_budget.sql"|\ + "$account_migrations/V1040.6__index_retained_capacity_refusal_slots.sql") # A retained-database activation is safe only for the first addition of a supported # migration. Re-editing or deleting a retained migration cannot prove # Flyway checksum/data compatibility, so stop before namespace mutation. diff --git a/dev-tools/tests/hosted-v2-migration-activation-contract.sh b/dev-tools/tests/hosted-v2-migration-activation-contract.sh index 8ae237c90c..290083be1b 100644 --- a/dev-tools/tests/hosted-v2-migration-activation-contract.sh +++ b/dev-tools/tests/hosted-v2-migration-activation-contract.sh @@ -116,6 +116,37 @@ git -C "$repo" commit -qm "Account V25 migration" account_v25_sha="$(git -C "$repo" rev-parse HEAD)" assert_activation true push "$supported_v2_sha" "$account_v25_sha" +git -C "$repo" switch -qc account-capacity-origin "$account_v25_sha" +capacity_migration_dir="$repo/services/account-service/src/main/resources/db/migration" +for migration in \ + V1040.1__account_capacity_origin_decisions.sql \ + V1040.2__bound_capacity_origin_refusals.sql \ + V1040.3__validate_only_inserted_refusal_budgets.sql \ + V1040.4__unique_capacity_origin_attempt.sql \ + V1040.5__arbitrate_origin_identity_before_refusal_budget.sql \ + V1040.6__index_retained_capacity_refusal_slots.sql; do + printf '%s\n' '-- capacity origin migration fixture' >"$capacity_migration_dir/$migration" +done +git -C "$repo" add . +git -C "$repo" commit -qm "Account capacity origin migration series" +capacity_origin_sha="$(git -C "$repo" rev-parse HEAD)" +namespace_for_head "$account_v25_sha" +assert_activation true push "$account_v25_sha" "$capacity_origin_sha" +assert_activation true workflow_dispatch "" "$capacity_origin_sha" + +namespace_for_head "$capacity_origin_sha" +printf '%s\n' '-- unsupported later capacity migration' >"$capacity_migration_dir/V1040.7__unqualified.sql" +git -C "$repo" add . +git -C "$repo" commit -qm "Unsupported later capacity origin migration" +assert_rejected push "$capacity_origin_sha" "$(git -C "$repo" rev-parse HEAD)" + +git -C "$repo" switch -qc edited-capacity-origin "$capacity_origin_sha" +printf '%s\n' '-- retained migration changed' >>"$capacity_migration_dir/V1040.4__unique_capacity_origin_attempt.sql" +git -C "$repo" add . +git -C "$repo" commit -qm "Edit retained capacity uniqueness migration" +assert_rejected push "$capacity_origin_sha" "$(git -C "$repo" rev-parse HEAD)" + +git -C "$repo" switch -q account-v25 namespace_for_head "$account_v25_sha" echo '-- edited retained migration' >>"$repo/services/account-service/src/main/resources/db/migration/V25__scope_profile_identity.sql" git -C "$repo" add . diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 985bbc1d02..a82af66234 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -971,7 +971,14 @@ const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-$ async function scenario(kind, event = "pull_request") { let now = 1000, snapshots = 0, reads = 0; let qualifiedAttemptReads = 0, observedBaseMove = false, observedAttemptMove = false, waitedMillis = 0; - let typedListReads = 0; + let typedListReads = 0, listedAttempt = 1, postAttemptIdentityReads = 0; + const sparseAttempts = { + "ordinary-missing-attempt": undefined, "ordinary-null-attempt": null, + "ordinary-persistent-missing-attempt": undefined, "ordinary-persistent-null-attempt": null, + "ordinary-invalid-attempt": "1", "ordinary-zero-attempt": 0, + "ordinary-negative-attempt": -1, "ordinary-fractional-attempt": 1.5, + }; + const finalGetDrift = kind.startsWith("ordinary-final-get-"); const ordinary = kind.startsWith("ordinary-"); const movedBase = "e".repeat(40), movedMerge = "f".repeat(40); const failures = [], refs = []; @@ -1033,11 +1040,16 @@ async function scenario(kind, event = "pull_request") { const github = {rest: { pulls: {get: async () => { reads += 1; - const moved = kind === "ordinary-final-base-drift" && qualifiedAttemptReads > 0; + const afterFinalGet = finalGetDrift && qualifiedAttemptReads >= 2; + if (afterFinalGet) postAttemptIdentityReads++; + const moved = kind === "ordinary-final-base-drift" && qualifiedAttemptReads > 0 || + kind === "ordinary-final-get-base-drift" && afterFinalGet; observedBaseMove ||= moved; observedAttemptMove ||= kind === "ordinary-final-attempt-drift" && qualifiedAttemptReads > 0; - return {data: {state: "open", head: {sha: head}, - base: {ref: kind === "stale-final" && reads > 3 ? "other" : "develop", sha: moved ? movedBase : base}, + return {data: {state: afterFinalGet && kind === "ordinary-final-get-closed" ? "closed" : "open", + head: {sha: afterFinalGet && kind === "ordinary-final-get-head" ? "e".repeat(40) : head}, + base: {ref: kind === "stale-final" && reads > 3 || + afterFinalGet && kind === "ordinary-final-get-retarget" ? "other" : "develop", sha: moved ? movedBase : base}, merge_commit_sha: moved ? movedMerge : merge}}; }}, git: {getRef: async () => ({data: {ref: "refs/heads/develop", object: {sha: observedBaseMove ? movedBase : base}}})}, @@ -1063,6 +1075,7 @@ async function scenario(kind, event = "pull_request") { }, request: async (route, input) => { assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"); assert.equal(input.run_id, 42); assert.equal(input.attempt_number, 1); + if (ordinary) assert.equal(listedAttempt, 1, "attempt proof cannot precede complete typed list identity"); exactAttemptReads++; if (kind === "transient-exact-attempt" && exactAttemptReads <= 4) { throw Object.assign(new Error("temporary exact-attempt lookup"), {status: 502}); @@ -1079,6 +1092,7 @@ async function scenario(kind, event = "pull_request") { if (method === listJobs) { snapshots += 1; return kind === "duplicate-jobs" ? [job, {...job, id: 101}] : [job]; } assert.equal(method, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); assert.equal(input.run_id, 42); assert.equal(input.attempt_number, 1); + if (ordinary) assert.equal(listedAttempt, 1, "attempt jobs cannot precede complete typed list identity"); snapshots++; if (kind === "lagging-cleanup" && snapshots <= 2) { return [{...job, steps: job.steps.filter(step => step.name !== "Stop smoke stack")}]; @@ -1118,8 +1132,18 @@ async function scenario(kind, event = "pull_request") { }}; github.paginate.iterator = async function* (method, input) { assert.equal(method, listRuns); - if (ordinary && ++typedListReads === 1 && kind === "ordinary-sparse-head") { - yield {data: [{...source, head_sha: undefined}]}; return; + if (ordinary) { + typedListReads++; + if (Object.hasOwn(sparseAttempts, kind) && (typedListReads === 1 || + kind.startsWith("ordinary-persistent-") || kind.includes("invalid") || + kind.includes("zero") || kind.includes("negative") || kind.includes("fractional"))) { + listedAttempt = sparseAttempts[kind]; + yield {data: [{...source, run_attempt: listedAttempt}]}; return; + } + listedAttempt = 1; + if (typedListReads === 1 && kind === "ordinary-sparse-head") { + yield {data: [{...source, head_sha: undefined}]}; return; + } } if (event === "repository_dispatch" && input.event === "pull_request") { yield {data: [{...source, event: "pull_request", head_sha: head, conclusion: "cancelled"}]}; return; @@ -1129,7 +1153,8 @@ async function scenario(kind, event = "pull_request") { const clock = {now: () => now, parse: Date.parse}; await execute(github, context, {info: () => {}, warning: () => {}, setFailed: message => failures.push(message)}, clock, (callback, duration) => {now += duration; waitedMillis += duration; queueMicrotask(callback);}, require); - return {failures, refs, snapshots, exactAttemptReads, observedBaseMove, observedAttemptMove, waitedMillis}; + return {failures, refs, snapshots, exactAttemptReads, observedBaseMove, observedAttemptMove, waitedMillis, + typedListReads, postAttemptIdentityReads}; } (async () => { for (const event of ["pull_request", "repository_dispatch"]) { @@ -1173,12 +1198,44 @@ async function scenario(kind, event = "pull_request") { const sparseHead = await scenario("ordinary-sparse-head", "repository_dispatch"); assert.deepEqual(sparseHead.failures, [], "a temporarily missing typed list head waits for a complete run row"); assert(sparseHead.waitedMillis > 0); + for (const kind of ["ordinary-missing-attempt", "ordinary-null-attempt"]) { + const sparse = await scenario(kind, "repository_dispatch"); + assert.deepEqual(sparse.failures, [], `${kind} must re-list before reading exact attempt proof`); + assert.equal(sparse.typedListReads, 2); + assert.equal(sparse.waitedMillis, 15000); + assert(sparse.snapshots > 0 && sparse.exactAttemptReads > 0); + } + for (const kind of ["ordinary-persistent-missing-attempt", "ordinary-persistent-null-attempt"]) { + const sparse = await scenario(kind, "repository_dispatch"); + assert.equal(sparse.failures.length, 1); + assert.match(sparse.failures[0], /without the typed run-list attempt or head SHA/); + assert.equal(sparse.waitedMillis, 120000, "sparse list identity retains the existing snapshot allowance"); + assert.equal(sparse.snapshots, 0); + assert.equal(sparse.exactAttemptReads, 0); + } + for (const kind of ["ordinary-invalid-attempt", "ordinary-zero-attempt", "ordinary-negative-attempt", "ordinary-fractional-attempt"]) { + const invalid = await scenario(kind, "repository_dispatch"); + assert.deepEqual(invalid.failures, ["Typed runtime smoke producer lacks an exact attempt."]); + assert.equal(invalid.waitedMillis, 0); + assert.equal(invalid.snapshots, 0); + assert.equal(invalid.exactAttemptReads, 0); + } for (const kind of ["ordinary-final-base-drift", "ordinary-final-attempt-drift"]) { const moved = await scenario(kind, "repository_dispatch"); assert(kind.endsWith("base-drift") ? moved.observedBaseMove : moved.observedAttemptMove); assert.equal(moved.failures.length, 1); assert.match(moved.failures[0], /^Timed out waiting for the exact runtime-images/); } + const finalGetBase = await scenario("ordinary-final-get-base-drift", "repository_dispatch"); + assert(finalGetBase.observedBaseMove && finalGetBase.postAttemptIdentityReads > 0); + assert.equal(finalGetBase.failures.length, 1); + assert.match(finalGetBase.failures[0], /^Timed out waiting for the exact runtime-images/, + "base movement during the final GET cannot accept the old typed proof"); + for (const change of ["closed", "head", "retarget"]) { + const obsolete = await scenario(`ordinary-final-get-${change}`, "repository_dispatch"); + assert(obsolete.postAttemptIdentityReads > 0, `${change} during the final GET must reach the repeated PR fence`); + assert.deepEqual(obsolete.failures, [], "obsolete gates exit rather than failing the new PR identity"); + } console.log("Smoke producer contract passed: native outcomes, exact immutable definition/attempt, legacy proof and fail-closed cases"); })().catch(error => {console.error(error); process.exitCode = 1;}); NODE @@ -3963,6 +4020,10 @@ async function recoveredFailure(options = {}, selectedRun = null, selectedIdenti if (options.lookupError) throw options.lookupError; return replacement; }, (_label, call) => call(), {paginate: async (route, input) => { + assert.ok(Number.isSafeInteger(replacement.run_attempt) && replacement.run_attempt > 0, + "sparse or invalid list attempts cannot read attempt-bound jobs"); + assert.ok(["success", "failure"].includes(replacement.conclusion), + "sparse or invalid list conclusions cannot read terminal attempt jobs"); assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); assert.equal(input.run_id, replacement.id); assert.equal(input.attempt_number, replacement.run_attempt); return options.noProducer ? [] : [selectedCandidate]; @@ -3997,9 +4058,9 @@ async function failedProof(error, event = "pull_request") { assert.match(warnings[0], /^Canonical PLAY transition exception proof is unavailable:/); assert.deepEqual(outputs, []); } -async function selectedProducerFinalFence(event, moved = false, superseded = false, rerunDuringIdentity = false) { +async function selectedProducerFinalFence(event, moved = false, superseded = false, rerunDuringIdentity = false, duringFinal = null) { const outputs = [], failures = [], required = []; - let proofs = 0, sleeps = 0, attemptChanged = false; + let proofs = 0, sleeps = 0, attemptChanged = false, afterAttempt = false; const core = {warning: () => {}, setFailed: x => failures.push(x), setOutput: (...x) => outputs.push(x)}; core.summary = {addHeading() {return this;}, addRaw() {return this;}, async write() {}}; const execute = new Function("fullSmokeJob", "matching", "canonicalSmokeJobName", "currentIdentity", @@ -4012,22 +4073,67 @@ async function selectedProducerFinalFence(event, moved = false, superseded = fal TerminalGitHubRequestError, core, async (_label, current) => { required.push(current); attemptChanged = rerunDuringIdentity; + if (afterAttempt && ["closed", "head", "retarget"].includes(duringFinal)) return {obsolete: true}; return {...identity, canonicalPlayEligible: true, ...(current ? {sourceEvent: "repository_dispatch"} : {}), - ...(current && moved ? {baseSha: "e".repeat(40), mergeSha: "f".repeat(40)} : {})}; + ...(current && (moved || afterAttempt && duringFinal === "base") + ? {baseSha: "e".repeat(40), mergeSha: "f".repeat(40)} : {})}; }, selected => { const {canonicalPlayEligible, ...tuple} = selected; return JSON.stringify(tuple); }, - async () => !attemptChanged, resolve => {sleeps++; resolve();}, 0); + async () => {afterAttempt = true; return !attemptChanged;}, resolve => {sleeps++; resolve();}, 0); assert.equal(proofs, superseded ? 2 : 1); assert.equal(sleeps, superseded || rerunDuringIdentity ? 1 : 0); - assert.deepEqual(required, Array(proofs - (superseded ? 1 : 0)).fill(event === "repository_dispatch")); + const fenceCount = event === "repository_dispatch" && !moved && !rerunDuringIdentity ? 2 : 1; + assert.deepEqual(required, Array((proofs - (superseded ? 1 : 0)) * fenceCount).fill(event === "repository_dispatch")); assert.deepEqual(failures, []); - assert.equal(outputs.length, (event === "repository_dispatch" && moved) || rerunDuringIdentity ? 0 : 1, + assert.equal(outputs.length, (event === "repository_dispatch" && (moved || duringFinal)) || rerunDuringIdentity ? 0 : 1, "an exception must retain its exact attempt through the final live identity read"); } // Execute the failed-run branch so proof errors retain the deterministic failure diagnostic. const legacyFailedStart = script.indexOf('if (matching.conclusion !== "success")'); const legacyFailedEnd = script.indexOf("async function fenceCompletedRuntimeIdentity", legacyFailedStart); const legacyFailedBranch = script.slice(legacyFailedStart, legacyFailedEnd); +// Both ordinary recovery and the unchanged exception must fence the PR again +// after the final attempt GET, not merely before that awaited request. +async function recoveredFinalFence(disposition, change = null) { + let finalAttempts = 0, postAttemptFences = 0, resumedPolling = false; + const outputs = [], failures = []; + const selected = {...source, id: 98, event: "pull_request", conclusion: "failure"}; + const selectedIdentity = {...identity, sourceEvent: "pull_request", canonicalPlayEligible: true}; + const proofRun = {id: 99, run_attempt: 2, conclusion: "success"}; + const core = {info() {}, warning() {}, setFailed: value => failures.push(value), setOutput: (...value) => outputs.push(value)}; + core.summary = {addHeading() {return this;}, addRaw() {return this;}, async write() {}}; + const execute = new Function("matching", "repositoryName", "github", "owner", "repo", "canonicalSmokeJobName", + "currentIdentity", "withTransientGitHubRetry", "verifyKnownPlayFailure", "isCurrentPullRequestObsolete", + "TerminalGitHubRequestError", "core", "verifyFailedPullCanonicalRefresh", "context", "resolveCurrentIdentity", + "identityKey", "positiveInteger", "isCurrentCanonicalAttempt", "setTimeout", "sleepMs", "onResume", + `return (async () => { let requireCurrentIdentity = false, iterations = 0; + let absentRefreshKey = null, discoveredRefreshKey = null, absentRefreshObservedAt = null; + let incompleteRefreshKey = null, incompleteRefreshObservedAt = null, sameTupleCancellationDeadline = null; + smokeGatePolling: while (iterations++ < 1) { ${legacyFailedBranch} break; } + onResume(); })();`); + await execute(selected, repositoryName, {paginate: async () => [candidate]}, "benhook1013", "FireMUD", + canonicalSmokeJobName, selectedIdentity, (_label, call) => call(), async () => false, async () => false, + TerminalGitHubRequestError, core, async () => ({status: disposition, run: proofRun}), + {payload: {pull_request: {head: {repo: {full_name: repositoryName}}}}}, async (_label, live) => { + assert.equal(live, true); + if (finalAttempts > 0) { + postAttemptFences++; + if (["closed", "head", "retarget"].includes(change)) return {obsolete: true}; + if (change === "unavailable") return null; + } + return {...selectedIdentity, sourceEvent: "repository_dispatch", + ...(finalAttempts > 0 && change === "base" ? {baseSha: "e".repeat(40), mergeSha: "f".repeat(40)} : {})}; + }, selected => JSON.stringify([selected.baseRef, selected.baseSha, selected.headSha, selected.mergeSha, selected.sourceEvent]), + value => Number.isSafeInteger(value) && value > 0, async selected => { + assert.deepEqual(selected, proofRun); finalAttempts++; return true; + }, resolve => resolve(), 0, () => {resumedPolling = true;}); + assert.equal(finalAttempts, 1); + assert.equal(postAttemptFences, 1); + assert.deepEqual(failures, []); + assert.deepEqual(outputs, disposition === "verified" && change === null ? [["known_play_exception", "true"]] : []); + assert.equal(resumedPolling, ["base", "unavailable"].includes(change), + "changed or unavailable final identity resumes polling; obsolete identity exits"); +} async function failedLegacyProof(stage, error, event = "pull_request") { const warnings = [], failures = [], outputs = []; const github = {paginate: async () => { @@ -4147,6 +4253,10 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { : status === "nonterminal-step" ? {candidate: {steps: candidate.steps.map(step => step.name === "Stop smoke stack" ? {...step, status: "in_progress", conclusion: null} : step)}} : status === "missing-job" ? {noProducer: true} : status === "pending-job" ? {candidate: {status: "in_progress", conclusion: null}} + : status === "missing-attempt" ? {replacement: {run_attempt: undefined}} + : status === "null-attempt" ? {replacement: {run_attempt: null}} + : status === "missing-conclusion" ? {replacement: {conclusion: undefined}} + : status === "null-conclusion" ? {replacement: {conclusion: null}} : {replacement: {status, conclusion: status === "completed" ? "success" : null, run_attempt: statuses[0] === "superseded" && polls > 1 ? 3 : 2}}, selectedRun, selectedIdentity, true)).accepted; @@ -4279,11 +4389,12 @@ async function movedCancellation(ordinaryProof, listedOldReplacement = false) { assert.deepEqual(outputs, [], "ordinary proof never publishes an exception output"); assert.deepEqual(failures, ordinaryProof ? [] : ["Moved cancelled-run recovery did not supply authenticated smoke proof."]); } -async function sameTupleCancellation(replacementStatus, proofSequence = [], sparseAttempt = false) { - let now = 0, proofReads = 0, runtimeJobReads = 0, sleeps = 0; +async function sameTupleCancellation(replacementStatus, proofSequence = [], sparseAttempt = false, options = {}) { + let now = 0, proofReads = 0, runtimeJobReads = 0, sleeps = 0, listedReplacements = 0; const sameIdentity = {...identity, sourceEvent: "pull_request"}; const old = {...source, id: 98, event: "pull_request", status: "completed", conclusion: "cancelled", - head_sha: identity.headSha, head_branch: "feature", repository: {full_name: "other/repo"}, + head_sha: identity.headSha, head_branch: "feature", + repository: {full_name: options.recoverableOriginal ? repositoryName : "other/repo"}, display_title: `Build Runtime Images secure-pr-artifact pr-3390 base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`}; const replacement = {...source, id: 99, event: "repository_dispatch", status: replacementStatus, conclusion: replacementStatus === "completed" ? "success" : null, head_sha: workflowSha, @@ -4318,13 +4429,27 @@ async function sameTupleCancellation(replacementStatus, proofSequence = [], spar async () => true, isTransientGitHubFailure, hasPendingCanonicalSmokeTerminalEvidence, async () => false, async () => false, TerminalGitHubRequestError, core, async () => sameIdentity, selected => JSON.stringify(selected), resolve => {sleeps++; now += 10; resolve();}, 10, - {now: () => now}, 0, 1000, 1, async event => event === "pull_request" ? old : replacement, + {now: () => now}, 0, options.overallMs ?? 1000, 1, async event => { + if (event === "pull_request") return old; + if (now < (options.visibleAt ?? 0)) return null; + if (options.hiddenAfter !== undefined && now >= options.hiddenAfter) return null; + if (options.completeAt !== undefined) { + replacement.status = now < options.completeAt ? "in_progress" : "completed"; + replacement.conclusion = replacement.status === "completed" ? "success" : null; + } + if (options.listedAttempts) { + replacement.run_attempt = options.listedAttempts[Math.min(listedReplacements++, options.listedAttempts.length - 1)]; + } + return replacement; + }, "3390", "test identity", 50, {payload: {pull_request: {head: {ref: "feature", repo: {full_name: repositoryName}}}}}, 200, 100, 10, value => Number.isSafeInteger(value) && value > 0, async () => true, async (run, selected) => { proofReads++; assert.equal(run, replacement); + assert.ok(Number.isSafeInteger(run.run_attempt) && run.run_attempt > 0); + assert.ok(["success", "failure"].includes(run.conclusion)); assert.deepEqual(selected, sameIdentity); return proofSequence[Math.min(proofReads - 1, proofSequence.length - 1)] ?? false; }); @@ -4414,16 +4539,17 @@ function markerAccepted(overrides = {}) { assert.deepEqual(await sameTupleProof("skipped", false, true), {result: false, verifiers: ["ordinary"]}); const unprovenInProgressReplacement = await sameTupleCancellation("in_progress"); assert.equal(unprovenInProgressReplacement.failures.length, 1); - assert.match(unprovenInProgressReplacement.failures[0], /no freshly proven exact replacement/); - assert.equal(unprovenInProgressReplacement.now, 50, - "an in-progress speculative replacement cannot extend the original cancellation deadline"); + assert.match(unprovenInProgressReplacement.failures[0], /^Timed out waiting for the exact/); + assert.equal(unprovenInProgressReplacement.now, 1000, + "an identified in-progress replacement uses only the existing overall Smoke allowance"); assert.equal(unprovenInProgressReplacement.proofReads, 0); assert.equal(unprovenInProgressReplacement.runtimeJobReads, 0, "an unproven replacement does not take over the cancelled original"); const sparseReplacement = await sameTupleCancellation("completed", ["snapshot-pending"]); assert.equal(sparseReplacement.failures.length, 1); - assert.equal(sparseReplacement.now, 50, - "sparse exact replacement snapshots remain bounded by the original cancellation deadline"); + assert.match(sparseReplacement.failures[0], /within the snapshot convergence allowance/); + assert.equal(sparseReplacement.now, 100, + "sparse exact replacement proof retains its own terminal metadata bound, not the discovery-only deadline"); assert.equal(sparseReplacement.runtimeJobReads, 0); const sparseReplacementAttempt = await sameTupleCancellation("completed", [], true); assert.equal(sparseReplacementAttempt.failures.length, 1); @@ -4443,6 +4569,53 @@ function markerAccepted(overrides = {}) { assert.match(invalidReplacement.failures[0], /contradictory identity or invalid terminal smoke proof/); assert.equal(invalidReplacement.runtimeJobReads, 0, "invalid terminal replacement proof remains fail-closed rather than falling back to unverified jobs"); + const noReplacement = await sameTupleCancellation("completed", ["ordinary"], false, {visibleAt: Infinity}); + assert.equal(noReplacement.now, 50); + assert.match(noReplacement.failures[0], /has no exact repository_dispatch replacement/); + assert.equal(noReplacement.proofReads, 0, "a no-show still exhausts the discovery-only allowance"); + const recoverableNoShow = await sameTupleCancellation("completed", ["ordinary"], false, + {visibleAt: Infinity, recoverableOriginal: true}); + assert.equal(recoverableNoShow.now, 200, "eligible originals retain the longer existing discovery allowance"); + assert.match(recoverableNoShow.failures[0], /has no exact repository_dispatch replacement/); + const disappearedTerminal = await sameTupleCancellation("completed", ["snapshot-pending"], false, {hiddenAfter: 10}); + assert.equal(disappearedTerminal.now, 100); + assert.match(disappearedTerminal.failures[0], /within the snapshot convergence allowance/); + assert.equal(disappearedTerminal.proofReads, 1, + "a temporarily absent list row cannot reset an observed terminal metadata window"); + const lostAttemptIdentity = await sameTupleCancellation("completed", ["snapshot-pending"], false, + {listedAttempts: [2, null]}); + assert.equal(lostAttemptIdentity.now, 100); + assert.match(lostAttemptIdentity.failures[0], /within the snapshot convergence allowance/); + assert.equal(lostAttemptIdentity.proofReads, 1, + "a sparse row after positive identification neither reads proof early nor resets the terminal window"); + const tooLateReplacement = await sameTupleCancellation("completed", ["ordinary"], false, {visibleAt: 60}); + assert.equal(tooLateReplacement.now, 50); + assert.match(tooLateReplacement.failures[0], /has no exact repository_dispatch replacement/); + for (const options of [ + {visibleAt: 40, completeAt: 180}, {visibleAt: 50, completeAt: 180}, + {visibleAt: 190, completeAt: 400, recoverableOriginal: true}, + ]) { + const lateCompletion = await sameTupleCancellation("in_progress", ["snapshot-pending", "ordinary"], false, + options); + assert.deepEqual(lateCompletion.failures, [], "a visible exact replacement can finish after discovery expires"); + assert.deepEqual(lateCompletion.outputs, []); + assert.equal(lateCompletion.now, options.completeAt + 10, "terminal proof may converge within its separate bounded allowance"); + assert.equal(lateCompletion.proofReads, 2); + assert.equal(lateCompletion.runtimeJobReads, 0, "only freshly verified exact proof becomes authoritative"); + } + const overOverallLimit = await sameTupleCancellation("in_progress", ["ordinary"], false, + {visibleAt: 40, completeAt: 180, overallMs: 150}); + assert.equal(overOverallLimit.now, 150); + assert.match(overOverallLimit.failures[0], /^Timed out waiting for the exact/); + assert.equal(overOverallLimit.proofReads, 0, "discovery cannot extend the overall Smoke cap"); + const supersedingReplacement = await sameTupleCancellation("completed", ["attempt-superseded", "ordinary"], false, + {listedAttempts: [2, 3]}); + assert.deepEqual(supersedingReplacement.failures, []); + assert.equal(supersedingReplacement.proofReads, 2, "a freshly listed superseding exact attempt may recover"); + const regressedReplacement = await sameTupleCancellation("completed", ["attempt-superseded", "attempt-superseded", "ordinary"], false, + {listedAttempts: [2, 3, 2]}); + assert.match(regressedReplacement.failures[0], /regressed to an older run or attempt/); + assert.equal(regressedReplacement.proofReads, 2, "an older attempt cannot replace an already observed newer attempt"); assert.equal((await recoveredFailure({original: {conclusion: "timed_out"}})).accepted, true); await pendingRefreshCaller(["queued", "completed"], false, {originalConclusion: "timed_out"}); for (const siblingStatus of ["in_progress", "queued"]) { @@ -4477,6 +4650,12 @@ function markerAccepted(overrides = {}) { } await pendingRefreshCaller(["missing-step", "completed"]); await pendingRefreshCaller(["nonterminal-step", "completed"]); + await pendingRefreshCaller(["missing-attempt", "completed"]); + await pendingRefreshCaller(["null-attempt", "completed"]); + await pendingRefreshCaller(["missing-attempt", "null-attempt", "missing-attempt", "completed"], false, {snapshotExpires: true}); + await pendingRefreshCaller(["missing-conclusion", "completed"]); + await pendingRefreshCaller(["null-conclusion", "completed"]); + await pendingRefreshCaller(["missing-conclusion", "null-conclusion", "missing-conclusion", "completed"], false, {snapshotExpires: true}); await pendingRefreshCaller(["missing-step", "missing-step", "missing-step", "completed"], false, {snapshotExpires: true}); const missingCleanup = candidate.steps.filter(step => step.name !== "Stop smoke stack"); assert.equal((await recoveredFailure({candidate: {steps: missingCleanup}, mutateProof: data => { @@ -4524,7 +4703,31 @@ function markerAccepted(overrides = {}) { for (const status of ["queued", "in_progress", "waiting", "pending", "requested"]) { assert.deepEqual(await recoveredFailure({replacement: {status, conclusion: null}}), {accepted: "pending", verified: 0, queries: 1}); + assert.equal((await recoveredFailure({replacement: {status, conclusion: "success", run_attempt: undefined}})).accepted, false, + "a missing attempt must not hide a contradictory nonterminal conclusion"); + } + for (const run_attempt of [undefined, null]) { + assert.deepEqual(await recoveredFailure({replacement: {run_attempt}}), + {accepted: "snapshot-pending", verified: 0, queries: 1}, + "a missing typed replacement attempt waits without reading attempt proof"); } + for (const conclusion of [undefined, null]) { + assert.deepEqual(await recoveredFailure({replacement: {run_attempt: 2, status: "completed", conclusion}}), + {accepted: "snapshot-pending", verified: 0, queries: 1}, + "an exact completed typed attempt with missing conclusion must wait without reading job proof"); + assert.deepEqual(await recoveredFailure({replacement: {run_attempt: 0, conclusion}}), + {accepted: false, verified: 0, queries: 1}, "a missing conclusion cannot hide an invalid supplied attempt"); + } + for (const conclusion of ["", false, 0, {}, "cancelled", "timed_out"]) { + assert.deepEqual(await recoveredFailure({replacement: {conclusion}}), + {accepted: false, verified: 0, queries: 1}, "an invalid present conclusion cannot become pending"); + } + for (const run_attempt of [0, -1, 1.5, "2", true, {}]) { + assert.deepEqual(await recoveredFailure({replacement: {run_attempt}}), + {accepted: false, verified: 0, queries: 1}, "an invalid present attempt cannot become pending or read proof"); + } + assert.equal((await recoveredFailure({mutateProof: data => {data.source.run_attempt = 3;}})).accepted, false, + "an already-positive listed attempt still must match the exact attempt proof"); assert.deepEqual(await recoveredFailure({headRepository: "fork/FireMUD", absent: true}), {accepted: false, verified: 0, queries: 0}); await pendingRefreshCaller(["completed"], false, {labelRemoved: true}); @@ -4604,6 +4807,14 @@ function markerAccepted(overrides = {}) { } await selectedProducerFinalFence("repository_dispatch", false, true); await selectedProducerFinalFence("repository_dispatch", false, false, true); + for (const change of ["base", "closed", "head", "retarget"]) { + await selectedProducerFinalFence("repository_dispatch", false, false, false, change); + } + for (const disposition of ["ordinary", "verified"]) { + for (const change of [null, "base", "closed", "head", "retarget", "unavailable"]) { + await recoveredFinalFence(disposition, change); + } + } await pendingRefreshCaller(["completed"], true, {finalIdentity: {baseSha: "d".repeat(40)}}); await pendingRefreshCaller(["completed"], true, {finalIdentity: {mergeSha: "e".repeat(40)}}); await pendingRefreshCaller(["completed", "completed"], false, { @@ -4802,6 +5013,9 @@ Path(sys.argv[2] + ".admission").write_text(json.dumps( {name: publisher["jobs"][name]["if"] for name in ("source", "reconcile-failed-pr-runtime")} )) Path(sys.argv[2]).write_text(next(step["with"]["script"] for step in job["steps"] if "github-script" in step.get("uses", ""))) +Path(sys.argv[2] + ".dispatcher").write_text(next( + step["with"]["script"] for step in runtime["jobs"]["dispatch-pr-base-refreshes"]["steps"] if "github-script" in step.get("uses", "") +)) PY node - "$smoke_clock_fixture.reconcile" <<'NODE' const assert = require("node:assert/strict"), fs = require("node:fs"); @@ -4827,7 +5041,7 @@ const reconciler = "reconcile-failed-pr-runtime"; const validation = {name: validationName, path: validationPath}; for (const conclusion of ["success", "failure", "timed_out", "cancelled"]) { assert.equal(admits("source", {...validation, conclusion}), false, conclusion); - assert.equal(admits(reconciler, {...validation, conclusion}), conclusion === "cancelled", conclusion); + assert.equal(admits(reconciler, {...validation, conclusion}), ["success", "cancelled"].includes(conclusion), conclusion); assert.equal(admits("source", {conclusion}), conclusion === "success", conclusion); assert.equal(admits(reconciler, {conclusion}), conclusion !== "success", conclusion); } @@ -4835,6 +5049,7 @@ const qualified = path => `${path}@refs/heads/develop`; assert.equal(admits("source", {path: qualified(runtimePath)}), true); assert.equal(admits(reconciler, {path: qualified(runtimePath), conclusion: "failure"}), true); assert.equal(admits(reconciler, {...validation, path: qualified(validationPath), conclusion: "cancelled"}), true); +assert.equal(admits(reconciler, {...validation, path: qualified(validationPath), conclusion: "success"}), true); assert.equal(admits("source", {path: ".github/workflows/untrusted.yml"}), false); assert.equal(admits(reconciler, {...validation, path: ".github/workflows/untrusted.yml", conclusion: "cancelled"}), false); assert.equal(admits(reconciler, {...validation, conclusion: "cancelled", event: "push"}), false); @@ -4854,33 +5069,63 @@ async function run(kind, shared = {visible: false, posts: 0}) { display_title: `CI — Validation pr-42 base-${base} head-${head}`}; const wake = kind.startsWith("wake-"); if (wake) kind = kind.slice("wake-".length); - const cancelledCase = kind.startsWith("cancel-"); + const metadataWake = kind.startsWith("metadata-wake-"); + const cancelledCase = kind.startsWith("cancel-") || metadataWake; if (kind === "qualified-runtime") source.path = qualified(runtimePath); - const olderCi = cancelledCase && kind !== "cancel-older-failed" ? {...ci, conclusion: "success"} : ci; + const olderCi = cancelledCase && !["cancel-older-failed", "metadata-wake-older-failed"].includes(kind) ? {...ci, conclusion: "success"} : ci; const newerCancelled = {...ci, id: 91, conclusion: "cancelled", path: kind === "cancel-qualified" ? qualified(validationPath) : validationPath}; + const newerMetadata = {...ci, id: 92, conclusion: "success", + path: kind === "metadata-wake-qualified" ? qualified(validationPath) : validationPath}; const refresh = {...source, id: 110, event: "repository_dispatch", head_branch: "develop", head_sha: "d".repeat(40), created_at: shared.refreshCreatedAt ?? source.created_at}; - const event = structuredClone(wake ? newerCancelled : source); + const event = structuredClone(wake ? metadataWake ? newerMetadata : newerCancelled : source); event.name = event.display_title; if (kind === "malformed-callback-path") event.path += "@refs/heads/a..b"; if (kind === "cancel-wake-wrong-id") event.workflow_id = source.workflow_id; if (kind === "cancel-wake-stale-head") event.head_sha = base; if (kind === "cancel-wake-fork") event.head_repository.full_name = "fork/repo"; if (kind === "cancel-wake-nonterminal") event.status = "in_progress"; + if (kind === "metadata-wake-wrong-workflow") event.workflow_id = source.workflow_id; + if (kind === "metadata-wake-wrong-attempt") event.run_attempt = 2; + if (kind === "metadata-wake-stale-head") event.head_sha = base; + if (kind === "metadata-wake-foreign") event.repository.full_name = "foreign/repo"; + if (kind === "metadata-wake-fork") event.head_repository.full_name = "foreign/repo"; + if (kind === "metadata-wake-malformed-path") event.path += "@refs/heads/a..b"; if (kind === "typed-callback") event.event = "repository_dispatch"; if (kind === "nested-callback") event.event = "workflow_run"; if (kind === "fork") event.head_repository.full_name = "fork/repo"; if (kind === "success") event.conclusion = "success"; const startClock = Date.parse(source.created_at); const sameSecond = ["same-second", "ambiguous-same-second"].includes(kind); - let clock = startClock + (sameSecond ? 200 : 0), tupleReads = 0, sourceReads = 0, metadataReads = 0, ciInventoryReads = 0, refreshInventoryReads = 0; + let clock = startClock + (sameSecond ? 200 : 0), tupleReads = 0, sourceReads = 0, metadataReads = 0, wakeReads = 0, ciInventoryReads = 0, refreshInventoryReads = 0; + let observedCancelledJobs = []; const github = {rest: { actions: { + listJobsForWorkflowRunAttempt: async ({run_id, attempt_number, per_page, page}) => { + assert.equal(run_id, 91); + assert.equal(attempt_number, 1); + assert.equal(per_page, 100); + assert.equal(page, 1); + const jobs = structuredClone(observedCancelledJobs); + if (kind === "cancel-inventory-disagrees") jobs[1].conclusion = "failure"; + return {data: {jobs, total_count: jobs.length + (kind === "cancel-inventory-short" ? 1 : 0)}}; + }, getWorkflow: async ({workflow_id}) => ({data: workflow_id === "ci.yml" ? {id: 8, path: ".github/workflows/ci.yml", name: "CI — Validation"} : {id: 7, path: runtimePath, name: source.name}}), getWorkflowRun: async ({run_id}) => { + if (metadataWake && run_id === 92) { + wakeReads++; + if (kind === "metadata-wake-missing" || kind === "metadata-wake-late-missing" && wakeReads >= 8) return {data: null}; + if (kind === "metadata-wake-unavailable" || kind === "metadata-wake-late-unavailable" && wakeReads >= 8) { + throw new Error("wake unavailable"); + } + return {data: {...newerMetadata, + ...(kind === "metadata-wake-late-rerun" && wakeReads >= 8 ? {run_attempt: 2} : {}), + ...(kind === "metadata-wake-late-path" && wakeReads >= 8 ? {path: qualified(validationPath)} : {})}}; + } + if (metadataWake && run_id === 93) return {data: {...ci, id: 93, status: "in_progress", conclusion: null}}; if (run_id === 91) metadataReads++; if (cancelledCase && run_id === 90) return {data: olderCi}; if (cancelledCase && run_id === 91) return {data: {...newerCancelled, @@ -4894,6 +5139,7 @@ async function run(kind, shared = {visible: false, posts: 0}) { return {data: {...source, ...((kind === "stale-attempt" || kind === "late-rerun" && sourceReads > 1) ? {run_attempt: 2} : {})}}; }, listWorkflowRuns: async ({workflow_id, page, event: runEvent, created}) => { + (shared.inventoryPages ??= []).push({workflow_id, page, event: runEvent, post: shared.posts}); if (workflow_id === "ci.yml") ciInventoryReads++; let runs = workflow_id === "ci.yml" ? [{...ci, ...(kind === "ci-pending" ? {status: "in_progress"} : {})}] : shared.visible ? [refresh] : []; @@ -4903,6 +5149,12 @@ async function run(kind, shared = {visible: false, posts: 0}) { } if (workflow_id === "ci.yml" && cancelledCase) runs = kind === "cancel-wake-not-inventory" ? [olderCi] : kind === "cancel-wake-newer-ci" ? [{...ci, id: 92, status: "in_progress"}, newerCancelled, olderCi] : [newerCancelled, olderCi]; + if (workflow_id === "ci.yml" && metadataWake) { + runs = [newerMetadata, newerCancelled, olderCi]; + if (kind === "metadata-wake-only") runs = [newerMetadata]; + if (kind === "metadata-wake-absent" || kind === "metadata-wake-late-absent" && ciInventoryReads > 1) runs = [newerCancelled, olderCi]; + if (kind === "metadata-wake-newer-pending") runs.unshift({...ci, id: 93, status: "in_progress", conclusion: null}); + } if (workflow_id === "ci.yml" && ciInventoryReads > 1 && kind.startsWith("late-ci-")) { runs = kind === "late-ci-absent" ? [] : [{...ci, id: 91, ...(kind === "late-ci-pending" ? {status: "in_progress"} : {})}, ci]; } @@ -4924,6 +5176,19 @@ async function run(kind, shared = {visible: false, posts: 0}) { } if (kind === "post-read-forbidden") throw Object.assign(new Error("visibility forbidden"), {status: 403}); if (kind === "post-read-incomplete") return {data: {total_count: 1, workflow_runs: []}}; + if (kind.startsWith("visibility-")) { + (shared.visibilityPages ??= []).push(page); + const drift = kind === "visibility-drift-timeout" || shared.observations <= 2; + if (drift) { + const noise = Array.from({length: 101}, (_, i) => ({...refresh, id: 1000 + i, display_title: "unrelated"})); + const duplicate = kind.includes("duplicate"); + runs = page === 1 ? [refresh, ...noise.slice(0, 99)] : duplicate ? [refresh] : noise.slice(99); + if (kind === "visibility-contradictory-duplicate" && page === 2) runs[0] = {...refresh, head_sha: "e".repeat(40)}; + if (kind === "visibility-malformed-provenance" && page === 2) runs[0] = {...refresh, workflow_id: 999}; + return {data: {total_count: page === 1 || duplicate ? 101 : kind === "visibility-malformed-total" ? "102" : 102, + workflow_runs: runs}}; + } + } if (kind === "ambiguous-same-second") runs = [refresh, {...refresh, id: refresh.id + 1}]; if (kind === "ambiguous-visible" && clock - startClock >= 5000) { shared.visible = true; @@ -4940,7 +5205,11 @@ async function run(kind, shared = {visible: false, posts: 0}) { assert(Number.isFinite(floor)); runs = runs.filter(run => Date.parse(run.created_at) >= floor); } - return {data: {total_count: kind === "incomplete" ? 1001 : kind === "at-cap" ? 1000 : runs.length, workflow_runs: runs.slice((page - 1) * 100, page * 100)}}; + if (["at-cap", "below-cap"].includes(kind) && workflow_id === "ci.yml") { + const count = kind === "at-cap" ? 1000 : 999; + runs = [ci, ...Array.from({length: count - 1}, (_, i) => ({...ci, id: 1000 + i, display_title: "unrelated"}))]; + } + return {data: {total_count: kind === "incomplete" ? 1001 : runs.length, workflow_runs: runs.slice((page - 1) * 100, page * 100)}}; }, }, pulls: {get: async () => { tupleReads++; return {data: {state: "open", @@ -4967,6 +5236,31 @@ async function run(kind, shared = {visible: false, posts: 0}) { }, paginate: async (_route, request) => { assert.equal(_route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); assert.equal(request.attempt_number, 1); + if (metadataWake && request.run_id === 92) { + const expression = "github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Validation Gate)' || 'Validation Gate'"; + const gate = {id: 32, run_id: 92, run_attempt: 1, head_sha: head, + name: kind === "metadata-wake-expression" ? expression : kind === "metadata-wake-wrapped" ? "${{ " + expression + " }}" : "PR Metadata Edit (Validation Gate)", + workflow_name: "CI — Validation", status: "completed", conclusion: "skipped", + check_run_url: `https://api.github.com/repos/${repository}/check-runs/32`}; + if (kind === "metadata-wake-job-attempt") gate.run_attempt = 2; + if (kind === "metadata-wake-job-run") gate.run_id = 91; + if (kind === "metadata-wake-job-head") gate.head_sha = base; + if (kind === "metadata-wake-job-url") gate.check_run_url = "https://api.github.com/repos/foreign/repo/check-runs/32"; + if (kind === "metadata-wake-job-success") gate.conclusion = "success"; + if (kind === "metadata-wake-job-pending") gate.status = "in_progress"; + if (kind === "metadata-wake-plain-success") return []; + if (kind === "metadata-wake-mixed") return [gate, {...gate, id: 33, name: "Validation Gate"}]; + if (kind.startsWith("metadata-wake-preservation") || kind === "metadata-wake-substantive-success") { + Object.assign(gate, {name: "Validation Gate", conclusion: "success", steps: [ + {name: "Preserve successful required gate on metadata-only edit", status: "completed", + conclusion: kind === "metadata-wake-substantive-success" ? "skipped" : kind === "metadata-wake-preservation-failed" ? "failure" : "success"}, + {name: "Enforce validation success", status: "completed", + conclusion: kind === "metadata-wake-substantive-success" ? "success" : "skipped"}, + ]}); + if (kind === "metadata-wake-preservation-duplicate") gate.steps.push({...gate.steps[0]}); + } + return [gate]; + } if ((kind.startsWith("new-meta") || kind === "late-ci-new-metadata") && request.run_id === 91) { const expression = "github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Validation Gate)' || 'Validation Gate'"; const job = {id: 31, run_id: 91, run_attempt: 1, head_sha: head, @@ -5004,6 +5298,7 @@ async function run(kind, shared = {visible: false, posts: 0}) { run_attempt: kind === "cancel-upstream-wrong-attempt" ? 2 : 1, check_run_url: `https://api.github.com/repos/${repository}/check-runs/31`, conclusion: ({ + "metadata-wake-masked-failure": "failure", "cancel-upstream-failure": "failure", "cancel-upstream-timeout": "timed_out", "cancel-upstream-action": "action_required", "cancel-upstream-startup": "startup_failure", "cancel-upstream-in-flight": "cancelled", @@ -5017,7 +5312,8 @@ async function run(kind, shared = {visible: false, posts: 0}) { {...gate, name: "PR Metadata Edit (Validation Gate)", conclusion: "skipped", steps: []}, {...upstream, conclusion: "failure"}, ]; - return [gate, upstream]; + observedCancelledJobs = kind === "cancel-gate-only" ? [gate] : [gate, upstream]; + return observedCancelledJobs; } const metadata = kind === "metadata" || ["metadata-newer", "old-meta-rerun", "late-ci-old-metadata"].includes(kind) && request.run_id === 91; return [{id: 30, run_id: request.run_id, run_attempt: 1, head_sha: head, name: "Validation Gate", @@ -5047,6 +5343,9 @@ async function run(kind, shared = {visible: false, posts: 0}) { await assert.rejects(run("ambiguous-same-second", ambiguousSameSecond), /dispatch outcome is ambiguous/); assert.equal(ambiguousSameSecond.posts, 1, "ambiguous visibility must never repeat the POST"); assert.equal(await run("cancel-before-enforcement"), 1); + for (const kind of ["cancel-gate-only", "cancel-inventory-short", "cancel-inventory-disagrees"]) { + assert.equal(await run("wake-" + kind), 0, "incomplete cancellation proof cannot reveal older CI: " + kind); + } assert.equal(await run("qualified-runtime"), 1); assert.equal(await run("wake-cancel-qualified"), 1); assert.equal(await run("malformed-callback-path"), 0); @@ -5058,6 +5357,21 @@ async function run(kind, shared = {visible: false, posts: 0}) { assert.equal(await run("pending-newer", delayedWake), 0, "original completion cannot ignore pending CI"); assert.equal(await run("wake-cancel-before-enforcement", delayedWake), 1, "exact cancelled CI wake restores liveness"); assert.equal(await run("wake-cancel-before-enforcement", delayedWake), 1, "replayed wake does not redispatch"); + for (const kind of ["native", "qualified", "expression", "wrapped", "preservation"]) { + assert.equal(await run("wake-metadata-wake-" + kind), 1, "exact positive metadata wake reveals older substantive success: " + kind); + } + assert.equal(await run("wake-metadata-wake-native", delayedWake), 1, "metadata wake cannot redispatch an already visible refresh"); + for (const kind of ["wrong-workflow", "wrong-attempt", "stale-head", "foreign", "fork", "malformed-path", + "late-rerun", "late-path", "missing", "late-missing", "only", "absent", "late-absent", "newer-pending", "older-failed", "masked-failure", + "job-attempt", "job-run", "job-head", "job-url", "job-success", "job-pending", "plain-success", "mixed", + "preservation-failed", "preservation-duplicate", "substantive-success"]) { + assert.equal(await run("wake-metadata-wake-" + kind), 0, "metadata wake fails closed: " + kind); + } + for (const kind of ["unavailable", "late-unavailable"]) { + const state = {visible: false, posts: 0}; + await assert.rejects(run("wake-metadata-wake-" + kind, state), /wake unavailable/); + assert.equal(state.posts, 0); + } for (const scenario of ["cancel-wake-wrong-id", "cancel-wake-stale-head", "cancel-wake-fork", "cancel-wake-nonterminal", "cancel-rerun", "cancel-upstream-step-failed", "cancel-older-failed", "cancel-wake-not-inventory", "cancel-wake-newer-ci", "cancel-wake-newer-original", "cancel-wake-no-original"]) { @@ -5097,7 +5411,35 @@ async function run(kind, shared = {visible: false, posts: 0}) { const state = {visible: false, posts: 0}; await assert.rejects(run(scenario, state)); assert.equal(state.posts, ["incomplete", "at-cap"].includes(scenario) ? 0 : 1, "never retry unknown POST"); + if (scenario === "at-cap") assert.deepEqual(state.inventoryPages.filter(call => call.workflow_id === "ci.yml").map(call => call.page), [1], + "a coherent 1,000-row inventory is refused on page one, not because its page is short"); + } + const belowCap = {visible: false, posts: 0}; + assert.equal(await run("below-cap", belowCap), 1); + assert.deepEqual(belowCap.inventoryPages.filter(call => call.workflow_id === "ci.yml").map(call => call.page), + [...Array.from({length: 10}, (_, i) => i + 1), ...Array.from({length: 10}, (_, i) => i + 1)], + "the comparable 999-row inventory must paginate completely on both selections"); + for (const scenario of ["visibility-total-drift", "visibility-duplicate-drift"]) { + const state = {visible: false, posts: 0}; + assert.equal(await run(scenario, state), 1); + assert.deepEqual(state.visibilityPages, [1, 2, 1], "discard all pages and restart visibility at page one"); + assert.equal(state.posts, 1); } + for (const [scenario, reason] of [ + ["visibility-contradictory-duplicate", /contradictory duplicate/], + ["visibility-malformed-provenance", /conflicting native provenance/], + ["visibility-malformed-total", /inventory is incomplete/], + ]) { + const state = {visible: false, posts: 0}; + await assert.rejects(run(scenario, state), reason); + assert.deepEqual(state.visibilityPages, [1, 2], "malformed evidence must not restart visibility"); + assert.equal(state.posts, 1); + } + const drifting = {visible: false, posts: 0}; + await assert.rejects(run("visibility-drift-timeout", drifting), /accepted but visibility is unknown/); + assert.equal(drifting.posts, 1); + assert.deepEqual(drifting.visibilityPages, Array.from({length: 48}, (_, i) => i % 2 + 1), + "persistent drift retains the existing 120-second budget and lock, not a fresh deadline"); const readTransient = {visible: false, posts: 0}; assert.equal(await run("post-read-transient", readTransient), 1); assert.equal(readTransient.observations, 2); @@ -5135,3 +5477,102 @@ async function run(kind, shared = {visible: false, posts: 0}) { console.log("Failed original runtime reconciliation contracts passed (offline serialized model, not GitHub delivery proof)."); })().catch(error => {console.error(error); process.exitCode = 1;}); NODE + +# The dispatcher must use the same whole-inventory visibility restart, never a POST retry. +node - "$smoke_clock_fixture.reconcile.dispatcher" <<'NODE' +const assert = require("node:assert/strict"), fs = require("node:fs"); +const execute = new Function("github", "context", "core", "Date", "setTimeout", + `return (async () => {${fs.readFileSync(process.argv[2], "utf8")}\n})()`); +async function dispatch(kind) { + const repository = "example/firemud", base = "b".repeat(40), head = "a".repeat(40), merge = "c".repeat(40); + const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; + const pr = {number: 42, state: "open", mergeable: true, mergeable_state: "clean", merge_commit_sha: merge, + base: {ref: "develop", sha: base, repo: {full_name: repository}}, + head: {ref: "feature", sha: head, repo: {full_name: repository}}, + user: {login: "renovate[bot]"}, labels: [], changed_files: 1}; // No independent preview POST in this model. + const start = Date.parse("2026-11-18T00:00:00Z"); + let now = start, posts = 0, observations = 0; + const pages = [], failures = [], warnings = []; + const refresh = {id: 110, workflow_id: 7, run_attempt: 1, event: "repository_dispatch", + display_title: title, name: "Build Runtime Images", path: ".github/workflows/runtime-images.yml", + repository: {full_name: repository}, head_repository: {full_name: repository}, head_branch: "develop", + head_sha: "d".repeat(40), created_at: new Date(start).toISOString(), status: "queued", conclusion: null}; + const noise = Array.from({length: 101}, (_, i) => ({...refresh, id: 1000 + i, display_title: "unrelated"})); + const github = {rest: { + actions: { + getWorkflow: async () => ({data: {id: 7, path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images"}}), + listWorkflowRuns: async ({page, event}) => { + if (!posts && kind !== "preflight-drift") return {data: {total_count: 0, workflow_runs: []}}; + if (!posts && event !== "pull_request") return {data: {total_count: 0, workflow_runs: []}}; + if (posts) observations++; + pages.push(page); + const drift = kind === "preflight-drift" || kind === "persistent-drift" || observations <= 2; + if (!drift) return {data: {total_count: 1, workflow_runs: [refresh]}}; + const duplicate = kind.includes("duplicate"); + let rows = page === 1 ? [refresh, ...noise.slice(0, 99)] : duplicate ? [refresh] : noise.slice(99); + if (kind === "contradictory-duplicate" && page === 2) rows = [{...refresh, head_sha: "e".repeat(40)}]; + if (kind === "malformed-provenance" && page === 2) rows[0] = {...refresh, workflow_id: 999}; + if (kind === "same-page-duplicate" && page === 1) rows[1] = refresh; + return {data: {total_count: page === 1 || duplicate ? 101 : kind === "malformed-total" ? "102" : 102, + workflow_runs: rows}}; + }, + }, + pulls: {list: "pulls", listFiles: "files", get: async () => ({data: pr})}, + git: {getRef: async () => ({data: {ref: "refs/heads/develop", object: {sha: base}}})}, + repos: { + getCommit: async () => ({data: {sha: merge, parents: [{sha: base}, {sha: head}]}}), + createDispatchEvent: async ({event_type, request}) => { + assert.equal(event_type, "pr-runtime-base-refresh"); + assert.equal(request.retries, 0); + posts++; + }, + }, + }, paginate: async method => { + assert.ok(["pulls", "files"].includes(method), method); + return method === "pulls" ? [pr] : [{filename: "services/example/build.gradle.kts"}]; + }}; + await execute(github, {repo: {owner: "example", repo: "firemud"}, payload: { + repository: {full_name: repository, default_branch: "develop"}, + workflow_run: {event: "push", head_branch: "develop", head_sha: base, updated_at: new Date(start).toISOString()}, + }}, {info: () => {}, warning: text => warnings.push(text), setFailed: text => failures.push(text)}, + class extends Date { + constructor(...args) { super(...(args.length ? args : [now])); } + static now() { return now; } + }, (callback, delay) => { now += delay; callback(); }); + return {posts, pages, failures, warnings, elapsed: now - start}; +} +(async () => { + for (const kind of ["total-drift", "duplicate-drift"]) { + const result = await dispatch(kind); + assert.equal(result.posts, 1); + assert.deepEqual(result.pages, [1, 2, 1], "restart the actual dispatcher inventory from page one"); + assert.deepEqual(result.failures, []); + assert.equal(result.elapsed, 5000); + } + for (const [kind, reason, pages] of [ + ["contradictory-duplicate", /contradictory duplicate/, [1, 2]], + ["malformed-provenance", /untrusted native workflow identity/, [1, 2]], + ["malformed-total", /inventory is malformed/, [1, 2]], + ["same-page-duplicate", /duplicate or invalid run IDs/, [1]], + ]) { + const result = await dispatch(kind); + assert.equal(result.posts, 1); + assert.deepEqual(result.pages, pages, "malformed visibility evidence is terminal"); + assert.equal(result.failures.length, 1); + assert.match(result.failures[0], reason); + assert.equal(result.elapsed, 0, "no retry or early successful lock release on malformed evidence"); + } + const persistent = await dispatch("persistent-drift"); + assert.equal(persistent.posts, 1); + assert.equal(persistent.elapsed, 120000, "drift cannot renew the observation deadline or release the lock early"); + assert.equal(persistent.failures.length, 1); + assert.match(persistent.failures[0], /visibility is unknown/); + assert.deepEqual(persistent.pages, Array.from({length: 48}, (_, i) => i % 2 + 1)); + const preflight = await dispatch("preflight-drift"); + assert.equal(preflight.posts, 0, "pre-POST inventory drift remains fail closed, not retryable"); + assert.deepEqual(preflight.pages, [1, 2]); + assert.equal(preflight.failures.length, 1); + assert.match(preflight.failures[0], /inventory shifted/); + console.log("Runtime dispatcher visibility drift contracts passed (offline model only)."); +})().catch(error => {console.error(error); process.exitCode = 1;}); +NODE diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 138e2aa700..2b950f053e 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -1112,7 +1112,7 @@ async function runDispatcher({ ? inventory : refinement ? inventory.refined : inventory.initial ?? inventory.runs ?? []; const runs = [...suppliedRuns, - ...(request.event === "repository_dispatch" ? lateProducers : []), + ...lateProducers.filter(run => run.event === request.event), ...(request.event === "repository_dispatch" ? postedRuns : [])]; const createdMatch = /^(.+)\.\.\*$/.exec(request.created ?? ""); const createdFloor = createdMatch ? Date.parse(createdMatch[1]) : Number.NaN; @@ -1552,6 +1552,17 @@ async function runDispatcher({ assert.equal(previewDispatches(refreshedAfterReuse).length, 2, "the last-minute producer discovery must not suppress independent preview reconciliation"); assert.equal(refreshedAfterReuse.errors.length, 0, refreshedAfterReuse.errors.join("\n")); + const lateNative = await runDispatcher({ + tuples: [tuple], + lateProducer: producer(tuple, "pull_request", "in_progress", null, { + id: 90203, created_at: "2026-01-03T00:00:00Z", + }), + }); + assert.deepEqual(numbers(lateNative), [], + "a native producer that appears after the first inventory suppresses the exact runtime POST"); + assert.equal(previewDispatches(lateNative).length, 1, + "a newly visible runtime producer leaves independent preview reconciliation available"); + assert.equal(lateNative.errors.length, 0, lateNative.errors.join("\n")); const skippedFirst = await runDispatcher({ tuples: [tuple, sibling], filesByPr: { "101": [{ filename: "README.md" }] }, }); diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index f571822507..6f6e1d85b7 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -699,7 +699,7 @@ cat > "$artifact_dir/pr-runtime-provenance.json" < "$fixture_dir/source-run.json" < "$fixture_dir/pull-request.json" </dev/null 2>"$fixture_dir/attempt-error"; then + echo "publisher accepted an artifact after the resolved source attempt changed" >&2 + exit 1 +fi +grep -Fq 'source workflow attempt changed before artifact validation' "$fixture_dir/attempt-error" if run_validation pull_request feature/ci "$head_sha" repository_dispatch 2>"$fixture_dir/typed-source-error"; then echo "typed publication accepted a pull-request producer" >&2 exit 1 diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index 706f844959..3198d679f8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -596,9 +596,14 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); var budgets = new AccountCapacityRefusalBudgetRepository(dsl); var historicalTenant = source(); - transaction.executeWithoutResult(status -> - new FreshTenantIdentityAssociationRepository(dsl, "prod") - .importVerified(historicalTenant)); + var otherHistoricalTenant = source(); + assertThat(otherHistoricalTenant.canonicalTenantId()) + .isNotEqualTo(historicalTenant.canonicalTenantId()); + transaction.executeWithoutResult(status -> { + var tenants = new FreshTenantIdentityAssociationRepository(dsl, "prod"); + tenants.importVerified(historicalTenant); + tenants.importVerified(otherHistoricalTenant); + }); Flyway.configure() .dataSource(data) @@ -617,6 +622,7 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { UUID secondHistoricalAdmission = UUID.randomUUID(); UUID secondHistoricalAttempt = UUID.randomUUID(); UUID secondHistoricalDecision = UUID.fromString("00000000-0000-0000-0000-000000001042"); + UUID otherHistoricalDecision = UUID.fromString("00000000-0000-0000-0000-000000001043"); String historicalInsert = "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, ?, ?, ?, 'NO_ACCEPT', ?)"; dsl.execute( @@ -637,6 +643,15 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { "b".repeat(64), new byte[] {4, 5, 6}, secondHistoricalDecision); + dsl.execute( + historicalInsert, + otherHistoricalTenant.canonicalTenantId(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "6".repeat(64), + new byte[] {26, 27, 28}, + otherHistoricalDecision); var acceptedTenant = source(); var operations = new AccountTenantCreationBootstrapOperationRepository(dsl); @@ -714,18 +729,25 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { .target("1040.5") .load() .migrate(); - transaction.executeWithoutResult( - status -> budgets.provision(historicalTenant.canonicalTenantId(), 3)); + transaction.executeWithoutResult(status -> { + budgets.provision(historicalTenant.canonicalTenantId(), 3); + budgets.provision(otherHistoricalTenant.canonicalTenantId(), 3); + }); var provisionedBudgetAtV1040_5 = dsl.fetchSingle( "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", historicalTenant.canonicalTenantId()) .intoMap(); + var otherProvisionedBudgetAtV1040_5 = + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", + otherHistoricalTenant.canonicalTenantId()) + .intoMap(); var originalDecisions = dsl.fetch( "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM account_capacity_origin_decisions ORDER BY decision_id") .intoMaps(); - assertThat(originalDecisions).hasSize(3); + assertThat(originalDecisions).hasSize(4); Flyway.configure() .dataSource(data) @@ -743,19 +765,31 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { historicalTenant.canonicalTenantId()) .intoMap()) .isEqualTo(provisionedBudgetAtV1040_5); + assertThat( + dsl.fetchSingle( + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", + otherHistoricalTenant.canonicalTenantId()) + .intoMap()) + .isEqualTo(otherProvisionedBudgetAtV1040_5); Long remainingHeadroom = transaction.execute( status -> budgets.requireReady(historicalTenant.canonicalTenantId(), 3, 1)); assertThat(remainingHeadroom).isEqualTo(1L); + Long otherRemainingHeadroom = + transaction.execute( + status -> budgets.requireReady(otherHistoricalTenant.canonicalTenantId(), 3, 2)); + assertThat(otherRemainingHeadroom).isEqualTo(2L); assertThat( dsl.fetch( "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM account_capacity_origin_decisions ORDER BY decision_id") .intoMaps()) .isEqualTo(originalDecisions); assertThat(refusalSlots(dsl)) - .containsExactly( + .containsExactlyInAnyOrder( new RefusalSlot(historicalTenant.canonicalTenantId(), 1, firstHistoricalDecision), - new RefusalSlot(historicalTenant.canonicalTenantId(), 2, secondHistoricalDecision)); + new RefusalSlot(historicalTenant.canonicalTenantId(), 2, secondHistoricalDecision), + new RefusalSlot( + otherHistoricalTenant.canonicalTenantId(), 1, otherHistoricalDecision)); assertThat( dsl.fetchOne( "SELECT 1 FROM account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", @@ -770,7 +804,9 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { var expectedSlots = List.of( new RefusalSlot(historicalTenant.canonicalTenantId(), 1, firstHistoricalDecision), - new RefusalSlot(historicalTenant.canonicalTenantId(), 2, secondHistoricalDecision)); + new RefusalSlot(historicalTenant.canonicalTenantId(), 2, secondHistoricalDecision), + new RefusalSlot( + otherHistoricalTenant.canonicalTenantId(), 1, otherHistoricalDecision)); assertThatThrownBy(() -> dsl.execute( "INSERT INTO account_capacity_origin_refusal_slots (tenant_uuid, slot, decision_id) VALUES (?, 3, ?)", @@ -787,7 +823,7 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { .isInstanceOfSatisfying( org.jooq.exception.DataAccessException.class, failure -> assertThat(failure.sqlState()).isEqualTo("23514")); - assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); String insertedDecision = "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, refusal_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING"; @@ -805,7 +841,7 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { "SELECT 1 FROM account_capacity_origin_refusal_slots WHERE tenant_uuid = ?", acceptedTenant.canonicalTenantId())) .isNull(); - assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); assertTenantCapacityInventoryMatches(dsl, acceptedTenant.canonicalTenantId()); var acceptedOriginsBeforeReplay = originRows(dsl, acceptedTenant.canonicalTenantId()); @@ -916,7 +952,7 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { .isEqualTo(acceptedReservationsBeforeReplay); assertThat(usageRows(dsl, acceptedTenant.canonicalTenantId())) .isEqualTo(acceptedUsageBeforeReplay); - assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); UUID freshRequest = UUID.randomUUID(); UUID freshAdmission = UUID.randomUUID(); @@ -938,19 +974,21 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { assertThat(dsl.execute(insertedDecision, freshRefusal)).isEqualTo(1); status.setRollbackOnly(); }); - assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); assertThat(dsl.execute(insertedDecision, freshRefusal)).isEqualTo(1); expectedSlots = List.of( new RefusalSlot(historicalTenant.canonicalTenantId(), 1, firstHistoricalDecision), new RefusalSlot(historicalTenant.canonicalTenantId(), 2, secondHistoricalDecision), - new RefusalSlot(historicalTenant.canonicalTenantId(), 3, freshDecision)); - assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + new RefusalSlot(historicalTenant.canonicalTenantId(), 3, freshDecision), + new RefusalSlot( + otherHistoricalTenant.canonicalTenantId(), 1, otherHistoricalDecision)); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); Object[] refusalReplay = freshRefusal.clone(); refusalReplay[8] = UUID.randomUUID(); assertThat(dsl.execute(insertedDecision, refusalReplay)).isZero(); - assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); assertThat( dsl.execute( insertedDecision, @@ -965,7 +1003,7 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { UUID.randomUUID(), "CAPACITY_QUOTA_EXCEEDED")) .isZero(); - assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); assertThat( dsl.execute( insertedDecision, @@ -980,7 +1018,7 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { UUID.randomUUID(), null)) .isZero(); - assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); assertThatThrownBy(() -> dsl.execute( @@ -1001,8 +1039,8 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { assertThat(failure.sqlState()).isEqualTo("23514"); assertThat(failure).hasMessageContaining("Capacity refusal budget is exhausted"); }); - assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))).isEqualTo(5); - assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + assertThat(dsl.fetchCount(DSL.table("account_capacity_origin_decisions"))).isEqualTo(6); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); assertThatThrownBy(() -> dsl.execute( @@ -1028,7 +1066,7 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { failure -> assertThat(failure) .hasMessageContaining("Account capacity origin decisions are immutable")); - assertThat(refusalSlots(dsl)).containsExactlyElementsOf(expectedSlots); + assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); } finally { new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index 26fff3de37..cc5790ef77 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -430,7 +430,7 @@ void exactCapacityRefusalReplaysAfterHeadroomReturnsAndEvaluationExpires() { 7, "sha256:" + "e".repeat(64), "controlled-owner-no-execution".getBytes(StandardCharsets.US_ASCII)), - f.clock); + Clock.systemUTC()); assertThat( recovery .reconcile( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index 9472cf7084..ec19a58327 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -762,7 +762,7 @@ void globalAttemptConflictPrecedesFreshOrExpiredNonCreatingEvidence() throws Exc AccountTenantCapacityRepository.CapacityException.class, failure -> assertThat(failure.code()).isEqualTo(Failure.IDEMPOTENCY_CONFLICT)); verify(f.dsl, never()).execute(anyString(), any(Object[].class)); - verify(f.scopes, never()).findCanonicalEvidenceByTokenHash(anyString()); + verifyNoInteractions(f.accounts, f.memberships, f.issuances, f.scopes); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java index de52902641..4c8ab96af0 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java @@ -219,11 +219,11 @@ public void ping(PingRequest request, StreamObserver observer) { assertThat(previous.isShutdown()).isFalse(); assertThat(calls).hasValue(0); startFirst.countDown(); - assertThat(first.get(5, TimeUnit.SECONDS)).isEqualTo(expectedResponse); + assertThat(first.get(10, TimeUnit.SECONDS)).isEqualTo(expectedResponse); assertThat(calls).hasValue(1); assertThat(previous.isShutdown()).isFalse(); startSecond.countDown(); - assertThat(second.get(5, TimeUnit.SECONDS)).isEqualTo(expectedResponse); + assertThat(second.get(10, TimeUnit.SECONDS)).isEqualTo(expectedResponse); assertThat(calls).hasValue(2); assertThat(previous.isShutdown()).isTrue(); } finally { diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java index 0091c13db8..d96695180d 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java @@ -299,6 +299,8 @@ public static Optional readRefusalDetails( private static void requireRefusalAuthority(Request request, Refusal refusal) { if (request.capacityRearmFence() != 1) throw invalid(); + if (refusal.code() == Failure.TENANT_BILLING_BLOCKED && request.evidence().permitsCreation()) + throw invalid(); if (refusal.code() == Failure.CAPACITY_QUOTA_EXCEEDED && (!request.evidence().permitsCreation() || request.operation() != Operation.CAPACITY_CREATING)) throw invalid(); diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java index 3bc1d1be5f..d850c11d69 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java @@ -62,10 +62,13 @@ void onlyCanonicalFailureDetailsSurviveWithoutChangingTransportStatus() { @Test void domainRefusalsRequireTheExactOriginalAndExclusiveResponseAlternative() { - Request request = CapacityAdmissionTestFixture.playerRequest(); - var commitment = TenantCapacityAdmissionGrpcCodec.toResponse(request, result(request)); - assertThat(TenantCapacityAdmissionGrpcCodec.readRefusal(request, commitment)).isEmpty(); + Request creatingRequest = CapacityAdmissionTestFixture.playerRequest(); + var commitment = + TenantCapacityAdmissionGrpcCodec.toResponse(creatingRequest, result(creatingRequest)); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusal(creatingRequest, commitment)).isEmpty(); for (var code : List.of(Failure.TENANT_BILLING_BLOCKED, Failure.CAPACITY_QUOTA_EXCEEDED)) { + Request request = + CapacityAdmissionTestFixture.playerRequest(code == Failure.CAPACITY_QUOTA_EXCEEDED); var response = TenantCapacityAdmissionGrpcCodec.toRefusal(request, code); assertThat(TenantCapacityAdmissionGrpcCodec.readRefusal(request, response)).contains(code); assertThat(TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response)) @@ -105,6 +108,29 @@ void domainRefusalsRequireTheExactOriginalAndExclusiveResponseAlternative() { } } + @Test + void creatingEvidenceCannotCarryBillingRefusalOnEncodeOrDecode() { + var request = CapacityAdmissionTestFixture.playerRequest(); + assertThat(request.evidence().permitsCreation()).isTrue(); + assertThatThrownBy(() -> + TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.TENANT_BILLING_BLOCKED)) + .isInstanceOf(IllegalArgumentException.class); + var quota = + TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.CAPACITY_QUOTA_EXCEEDED); + var billing = + quota.toBuilder() + .setRefusal( + 0, + quota.getRefusal(0).toBuilder() + .setCode( + 0, + net.firedevops.firemud.account.v1.TenantCapacityAdmissionRefusal.Code + .TENANT_BILLING_BLOCKED)) + .build(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, billing)) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void nonCreatingEvidenceCannotCarryQuotaRefusal() { var request = CapacityAdmissionTestFixture.playerRequest(false); @@ -152,18 +178,12 @@ void nonExpandingRequestCannotCarryQuotaRefusal() { TenantCapacityAdmissionGrpcCodec.toRefusal( request, Failure.CAPACITY_QUOTA_EXCEEDED, id)) .isInstanceOf(IllegalArgumentException.class); - var billing = - TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.TENANT_BILLING_BLOCKED); + var quota = + TenantCapacityAdmissionGrpcCodec.toRefusal(original, Failure.CAPACITY_QUOTA_EXCEEDED, id); var forged = - billing.toBuilder() + quota.toBuilder() .setRefusal( - 0, - billing.getRefusal(0).toBuilder() - .setCode( - 0, - net.firedevops.firemud.account.v1.TenantCapacityAdmissionRefusal.Code - .CAPACITY_QUOTA_EXCEEDED) - .addDurableDenialId(id.toString())) + 0, quota.getRefusal(0).toBuilder().setMutationDigest(0, request.mutationDigest())) .build(); assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, forged)) .isInstanceOf(IllegalArgumentException.class); @@ -171,63 +191,50 @@ void nonExpandingRequestCannotCarryQuotaRefusal() { @Test void matchedRearmCannotCarryEitherOriginalRefusal() { - var original = CapacityAdmissionTestFixture.playerRequest(); - var request = - new Request( - original.identity(), - UUID.randomUUID(), - 2, - original.targetNamespace(), - original.context(), - original.operation(), - original.priorShape(), - original.requestedShape(), - original.evidence(), - original.capacityDelta(), - null) - .withDigest(); - var id = UUID.randomUUID(); - assertThatThrownBy(() -> - TenantCapacityAdmissionGrpcCodec.toRefusal( - request, Failure.CAPACITY_QUOTA_EXCEEDED, id)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> - TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.CAPACITY_QUOTA_EXCEEDED)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> - TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.TENANT_BILLING_BLOCKED)) - .isInstanceOf(IllegalArgumentException.class); - var originalBilling = - TenantCapacityAdmissionGrpcCodec.toRefusal(original, Failure.TENANT_BILLING_BLOCKED); - var billing = - originalBilling.toBuilder() - .setRefusal( - 0, - originalBilling.getRefusal(0).toBuilder() - .setAdmissionAttemptId(0, request.admissionAttemptId().toString()) - .setCapacityRearmFence(0, request.capacityRearmFence()) - .setMutationDigest(0, request.mutationDigest())) - .build(); - assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, billing)) - .isInstanceOf(IllegalArgumentException.class); - var wire = - billing.toBuilder() - .setRefusal( - 0, - billing.getRefusal(0).toBuilder() - .setCode( - 0, - net.firedevops.firemud.account.v1.TenantCapacityAdmissionRefusal.Code - .CAPACITY_QUOTA_EXCEEDED)) - .build(); - assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, wire)) - .isInstanceOf(IllegalArgumentException.class); - var forged = - wire.toBuilder() - .setRefusal(0, wire.getRefusal(0).toBuilder().addDurableDenialId(id.toString())) - .build(); - assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, forged)) - .isInstanceOf(IllegalArgumentException.class); + for (var code : List.of(Failure.TENANT_BILLING_BLOCKED, Failure.CAPACITY_QUOTA_EXCEEDED)) { + var original = + CapacityAdmissionTestFixture.playerRequest(code == Failure.CAPACITY_QUOTA_EXCEEDED); + var request = + new Request( + original.identity(), + UUID.randomUUID(), + 2, + original.targetNamespace(), + original.context(), + original.operation(), + original.priorShape(), + original.requestedShape(), + original.evidence(), + original.capacityDelta(), + null) + .withDigest(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.toRefusal(request, code)) + .isInstanceOf(IllegalArgumentException.class); + var originalRefusal = TenantCapacityAdmissionGrpcCodec.toRefusal(original, code); + var wire = + originalRefusal.toBuilder() + .setRefusal( + 0, + originalRefusal.getRefusal(0).toBuilder() + .setAdmissionAttemptId(0, request.admissionAttemptId().toString()) + .setCapacityRearmFence(0, request.capacityRearmFence()) + .setMutationDigest(0, request.mutationDigest())) + .build(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, wire)) + .isInstanceOf(IllegalArgumentException.class); + if (code == Failure.CAPACITY_QUOTA_EXCEEDED) { + var id = UUID.randomUUID(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.toRefusal(request, code, id)) + .isInstanceOf(IllegalArgumentException.class); + var forged = + wire.toBuilder() + .setRefusal(0, wire.getRefusal(0).toBuilder().addDurableDenialId(id.toString())) + .build(); + assertThatThrownBy( + () -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, forged)) + .isInstanceOf(IllegalArgumentException.class); + } + } } @Test @@ -251,20 +258,26 @@ void onlyExactQuotaRefusalMayCarryOneCanonicalNonnilAccountDecisionId() { receipt.toBuilder() .setDurableDenialId(0, decisionId.toString().toUpperCase(Locale.ROOT)) .build(), - receipt.toBuilder().setCapacityRearmFence(0, 2).build(), - TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.TENANT_BILLING_BLOCKED) - .getRefusal(0) - .toBuilder() - .addDurableDenialId(decisionId.toString()) - .build())) { + receipt.toBuilder().setCapacityRearmFence(0, 2).build())) { assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails( request, response.toBuilder().setRefusal(0, malformed).build())) .isInstanceOf(IllegalArgumentException.class); } + var billingRequest = CapacityAdmissionTestFixture.playerRequest(false); + var billing = + TenantCapacityAdmissionGrpcCodec.toRefusal(billingRequest, Failure.TENANT_BILLING_BLOCKED); + var forgedBilling = + billing.toBuilder() + .setRefusal( + 0, billing.getRefusal(0).toBuilder().addDurableDenialId(decisionId.toString())) + .build(); + assertThatThrownBy(() -> + TenantCapacityAdmissionGrpcCodec.readRefusalDetails(billingRequest, forgedBilling)) + .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.toRefusal( - request, Failure.TENANT_BILLING_BLOCKED, decisionId)) + billingRequest, Failure.TENANT_BILLING_BLOCKED, decisionId)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.toRefusal( From afd7054bc0dd90b50a6d02beb87b5a7d5c7e3e7a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:45:24 +1300 Subject: [PATCH 39/96] Qualify exact runtime retry and capacity review fixes --- .../workflows/publish-pr-runtime-images.yml | 91 ++++- .github/workflows/runtime-images.yml | 162 ++++++--- .github/workflows/smoke.yml | 121 +++++-- .../account-service/runtime-and-data.md | 2 +- ...system-architecture-database-migrations.md | 2 +- .../player-access-and-session.md | 2 +- .../detect-hosted-v2-migration-activation.sh | 4 + ...hosted-v2-migration-activation-contract.sh | 2 + .../pr-required-gate-context-contract.sh | 326 +++++++++++++++--- .../tests/pr-retarget-workflow-contract.sh | 279 +++++++++++++-- .../pr-runtime-image-publication-contract.sh | 187 +++++++++- ...acityMigrationPostgresIntegrationTest.java | 135 ++------ ...titlementOwnerPostgresIntegrationTest.java | 20 +- .../AbstractReloadingBlockingGrpcClient.java | 10 +- .../common/grpc/GrpcChannelFactory.java | 21 ++ .../TenantCapacityAdmissionGrpcCodec.java | 5 +- .../TenantCapacityAdmissionGrpcCodecTest.java | 33 ++ .../client/AccountTenantCapacityClient.java | 6 + .../AccountTenantCapacityClientMtlsTest.java | 186 +++++++++- 19 files changed, 1308 insertions(+), 286 deletions(-) diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 59530c91e0..15b333e6e0 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -248,10 +248,24 @@ jobs: return null; } ci = ciNative; - const jobs = await github.paginate( - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", - prePostOptions({...context.repo, run_id: ci.id, attempt_number: ci.run_attempt, per_page: 100}) - ); + const jobs = []; + let jobsTotal; + for (let page = 1; ; page++) { + // The paginator drops request.signal after page one. Each direct + // request must get a fresh signal for the same pre-POST deadline. + const {data} = await github.rest.actions.listJobsForWorkflowRunAttempt( + prePostOptions({...context.repo, run_id: ci.id, attempt_number: ci.run_attempt, per_page: 100, page}) + ); + if (!Number.isSafeInteger(data?.total_count) || data.total_count < 0 || + (jobsTotal !== undefined && data.total_count !== jobsTotal) || !Array.isArray(data.jobs) || + data.jobs.length !== Math.min(100, Math.max(0, data.total_count - (page - 1) * 100))) { + throw new Error("Qualified CI attempt job inventory is incomplete or inconsistent"); + } + jobsTotal ??= data.total_count; + // Keep duplicates so the existing native-evidence checks see them. + jobs.push(...data.jobs); + if (jobs.length === jobsTotal) break; + } const retryClassification = async () => { if (classificationAttempt >= 3) return false; await new Promise(resolve => setTimeout(resolve, 2000)); @@ -337,9 +351,8 @@ jobs: if (await retryClassification()) continue; return null; } - // The paginated adapter omits the provider's total. Recheck - // that the terminal attempt inventory is still complete and - // agrees with the first native page before revealing older CI. + // Recheck that the terminal attempt inventory is still complete + // and agrees with the first native page before revealing older CI. const {data: confirmedJobs} = await github.rest.actions.listJobsForWorkflowRunAttempt( prePostOptions({...context.repo, run_id: ci.id, attempt_number: ci.run_attempt, per_page: 100, page: 1}) ); @@ -449,13 +462,44 @@ jobs: } } const ids = new Set(runs.map(run => run.id)); - if (strictlyAfter === null) return {found: exact.length > 0, ids}; + if (strictlyAfter === null) { + for (const run of exact) { + // Only these two freshly verified unusable results may release + // the hold. Legacy failures (including PLAY) are not replayed. + if (run.status !== "completed" || !["cancelled", "timed_out"].includes(run.conclusion)) { + if (run.status === "completed" && run.conclusion === "failure") { + core.warning(`Exact typed refresh ${run.id} failed; recovery remains held for explicit investigation, not automatic replay.`); + } + return {found: true, ids}; + } + let current; + try { + ({data: current} = await github.rest.actions.getWorkflowRun( + prePostOptions({...context.repo, run_id: run.id}) + )); + } catch (error) { + core.warning(`Exact typed refresh ${run.id} terminal result could not be verified; recovery remains held without retry: ${error.message || error}`); + return {found: true, ids}; + } + if (!trusted(current) || current.id !== run.id || current.run_attempt !== run.run_attempt || + current.path !== run.path || current.name !== run.name || current.display_title !== event.display_title || + current.event !== "repository_dispatch" || current.head_branch !== context.payload.repository.default_branch || + current.head_sha !== run.head_sha || !sha(current.head_sha) || current.status !== "completed" || + current.conclusion !== run.conclusion) { + core.warning(`Exact typed refresh ${run.id} terminal result is unproven or superseded; recovery remains held without retry.`); + return {found: true, ids}; + } + } + // Retain every inventory ID, including verified unusable runs, + // so none can later be mistaken for receipt of this POST. + return {found: false, ids}; + } if (!(previousIds instanceof Set)) throw new Error("Final pre-dispatch refresh inventory IDs are missing"); const dispatchTime = Date.parse(strictlyAfter); if (!Number.isFinite(dispatchTime)) throw new Error("Invalid refresh dispatch timestamp"); // Run timestamps may have only second precision. Compare from the // POST's timestamp second and require one exact run absent from the - // final complete pre-POST inventory. + // final complete pre-POST inventory. This is receipt, not success. const secondFloor = Math.floor(dispatchTime / 1000) * 1000; const unseen = exact.filter(run => !previousIds.has(run.id)); const visible = unseen.filter(run => Date.parse(run.created_at) >= secondFloor); @@ -503,7 +547,9 @@ jobs: } // Keep the shared lock during observation even when the one POST response was lost. const deadline = Date.now() + 120000; + let rateLimitBackoffMs = 60000; while (Date.now() < deadline) { + let retryDelayMs = 5000; try { if ((await newerRefresh(dispatchStarted, deadline, dispatchStarted, previousRefreshIds)).found) { core.info(`Reconciled failed original runtime for PR #${number}; exact refresh is visible.`); @@ -513,17 +559,38 @@ jobs: if (error?.code === "REQUEST_DEADLINE_EXPIRED") break; const status = error?.status ?? error?.response?.status; const code = error?.code ?? error?.cause?.code; - const transient = code === "VISIBILITY_PAGINATION_DRIFT" || - [408, 425, 429, 500, 502, 503, 504].includes(status) || + const headers = error?.response?.headers ?? {}; + const retryAfter = String(headers["retry-after"] ?? "").trim(); + const retryAfterDate = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(retryAfter) + ? Date.parse(retryAfter) : NaN; + const retryAfterMs = /^\d+$/.test(retryAfter) ? Number(retryAfter) * 1000 + : Number.isFinite(retryAfterDate) && new Date(retryAfterDate).toUTCString() === retryAfter + ? Math.max(0, retryAfterDate - Date.now()) : NaN; + const hasRetryAfter = Number.isFinite(retryAfterMs) && retryAfterMs >= 0; + const primaryExhausted = String(headers["x-ratelimit-remaining"] ?? "").trim() === "0"; + const reset = String(headers["x-ratelimit-reset"] ?? "").trim(); + const resetMs = /^\d+$/.test(reset) ? Number(reset) * 1000 : NaN; + const rateLimited = [403, 429].includes(status) && (status === 429 || hasRetryAfter || primaryExhausted || + /\brate[ -]limit\b|\babuse detection\b/i.test(error?.response?.data?.message || error?.message || "")); + const transient = rateLimited || code === "VISIBILITY_PAGINATION_DRIFT" || + [408, 425, 500, 502, 503, 504].includes(status) || (status == null && (["ABORT_ERR", "ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"].includes(code) || ["AbortError", "TimeoutError"].includes(error?.name))); if (!transient) throw error; + if (rateLimited) { + // GitHub REST guidance: Retry-After first, then an exhausted + // primary reset; otherwise wait at least a minute and back off. + retryDelayMs = hasRetryAfter ? retryAfterMs + : primaryExhausted && Number.isFinite(resetMs) ? Math.max(0, resetMs - Date.now()) + : rateLimitBackoffMs; + rateLimitBackoffMs = Math.min(rateLimitBackoffMs * 2, 120000); + } core.warning("Exact refresh visibility read is temporarily unavailable; keep observing without retrying the POST."); } const remainingMs = deadline - Date.now(); if (remainingMs > 0) { - await new Promise(resolve => setTimeout(resolve, Math.min(5000, remainingMs))); + await new Promise(resolve => setTimeout(resolve, Math.min(retryDelayMs, remainingMs))); } } throw new Error(responseUnknown diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 82c606d4fa..fc59c75e60 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -523,15 +523,20 @@ jobs: }; const hasRuntimeChange = async (pullRequest) => { - const files = await github.paginate( - github.rest.pulls.listFiles, - fanoutOptions({ + const files = []; + for (let page = 1; ; page += 1) { + // Pagination must refresh the signal against the same fan-out deadline on every page. + const {data} = await github.rest.pulls.listFiles(fanoutOptions({ ...context.repo, pull_number: pullRequest.number, - per_page: 100, - }), - (response) => response.data - ); + per_page: 100, page, + })); + if (!Array.isArray(data) || data.length > 100) { + throw new Error(`PR #${pullRequest.number} changed-file page is malformed`); + } + files.push(...data); + if (data.length < 100) break; + } const expectedFileCount = pullRequest.changed_files; const validFileEntries = Number.isInteger(expectedFileCount) && files.length === expectedFileCount && @@ -795,7 +800,9 @@ jobs: const ref = path.slice(prefix.length); return validWorkflowRef(ref); }; - const findExactExistingProducer = (tuple, inventory) => { + // Bind both admission reads to the same terminal attempt; never cache native proof. + const disregardedTypedAttempts = new Map(); + const findExactExistingProducer = async (tuple, inventory) => { const expectedTitle = `Build Runtime Images secure-pr-artifact pr-${tuple.prNumber} ` + `base-${tuple.baseSha} head-${tuple.headSha} merge-${tuple.mergeSha} mode-required`; @@ -846,6 +853,43 @@ jobs: return [newest]; } if (newest.status === "completed") { + if (newest.event === "repository_dispatch" && ["cancelled", "timed_out"].includes(newest.conclusion)) { + const repository = `${context.repo.owner}/${context.repo.repo}`; + const defaultBranch = context.payload.repository?.default_branch; + const attemptBinding = JSON.stringify([ + newest.run_attempt, newest.conclusion, newest.head_sha, newest.path, newest.created_at, + ]); + if (!Number.isSafeInteger(newest.run_attempt) || newest.run_attempt <= 0 || + context.payload.repository?.full_name !== repository || + typeof defaultBranch !== "string" || !defaultBranch || newest.head_branch !== defaultBranch || + typeof newest.head_sha !== "string" || !shaPattern.test(newest.head_sha) || + (disregardedTypedAttempts.has(newest.id) && disregardedTypedAttempts.get(newest.id) !== attemptBinding)) { + throw new Error(`Terminal typed runtime producer ${newest.id} has incomplete or changed attempt identity`); + } + const {data: workflow} = await github.rest.actions.getWorkflow(fanoutOptions({ + ...context.repo, workflow_id: "runtime-images.yml", + })); + const {data: latest} = await github.rest.actions.getWorkflowRun(fanoutOptions({ + ...context.repo, run_id: newest.id, + })); + if (!Number.isSafeInteger(workflow?.id) || workflow.id <= 0 || + workflow.id !== newest.workflow_id || workflow.path !== expectedWorkflowPath || + workflow.name !== "Build Runtime Images" || + latest?.id !== newest.id || latest.run_attempt !== newest.run_attempt || + latest.workflow_id !== workflow.id || latest.event !== "repository_dispatch" || + latest.path !== newest.path || !workflowPathMatches(latest.path) || + ![workflow.name, expectedTitle].includes(latest.name) || latest.display_title !== expectedTitle || + latest.repository?.full_name !== repository || latest.head_repository?.full_name !== repository || + latest.head_branch !== defaultBranch || latest.head_sha !== newest.head_sha || + latest.created_at !== newest.created_at || latest.status !== "completed" || + latest.conclusion !== newest.conclusion) { + throw new Error(`Terminal typed runtime producer ${newest.id} no longer has the same trusted terminal attempt`); + } + // Neither conclusion can supply ordinary or diagnostic PLAY acceptance. + // Success/failure classification and POST visibility deliberately remain unchanged. + disregardedTypedAttempts.set(newest.id, attemptBinding); + return []; + } // Same-second or incomparable completion evidence is ambiguous and // suppresses a duplicate; only a valid, strictly older producer may recover. const ciCompleted = Date.parse(workflowRun.updated_at || ""); @@ -899,10 +943,21 @@ jobs: core.warning("Skipping PR runtime reconciliation: current CI workflow/run identity differs from callback."); return; } - const jobs = await github.paginate( - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", - fanoutOptions({...context.repo, run_id: source.id, attempt_number: source.run_attempt, per_page: 100}) - ); + const jobs = []; + let jobsTotal; + for (let page = 1; ; page += 1) { + const {data} = await github.rest.actions.listJobsForWorkflowRunAttempt(fanoutOptions({ + ...context.repo, run_id: source.id, attempt_number: source.run_attempt, per_page: 100, page, + })); + if (!Number.isSafeInteger(data?.total_count) || data.total_count < 0 || + (jobsTotal !== undefined && data.total_count !== jobsTotal) || !Array.isArray(data.jobs) || + data.jobs.length !== Math.min(100, Math.max(0, data.total_count - (page - 1) * 100))) { + throw new Error("Exact source CI attempt job inventory is incomplete or inconsistent"); + } + jobsTotal ??= data.total_count; + jobs.push(...data.jobs); + if (jobs.length === jobsTotal) break; + } const gates = jobs.filter((job) => job.name === "Validation Gate"); const gate = gates.length === 1 ? gates[0] : null; const preservation = gate?.steps?.filter((step) => @@ -945,20 +1000,25 @@ jobs: return; } + const listOpenPullRequests = async (scope) => { + const pulls = []; + for (let page = 1; ; page += 1) { + const {data} = await github.rest.pulls.list(fanoutOptions({ + ...context.repo, state: "open", ...scope, per_page: 100, page, + })); + if (!Array.isArray(data) || data.length > 100) { + throw new Error("Open pull request inventory page is malformed"); + } + pulls.push(...data); + if (data.length < 100) break; + } + return pulls; + }; // Protected push callbacks own dependent fan-out; PR callbacks for // those heads still reconcile their own exact source PR below. const protectedPrHead = workflowRun.event === "pull_request" && ["main", "develop"].includes(refreshBranch); - const pullRequests = protectedPrHead ? [] : await github.paginate( - github.rest.pulls.list, - fanoutOptions({ - ...context.repo, - state: "open", - base: refreshBranch, - per_page: 100, - }), - (response) => response.data - ); + const pullRequests = protectedPrHead ? [] : await listOpenPullRequests({base: refreshBranch}); const refreshTargets = []; for (let pullRequestIndex = 0; pullRequestIndex < pullRequests.length; pullRequestIndex += 1) { const listedPullRequest = pullRequests[pullRequestIndex]; @@ -994,16 +1054,7 @@ jobs: if (workflowRun.event === "pull_request") { // A retarget/edit can carry an unusable event merge SHA. CI completion // is only a reconcile signal: re-read its source's current exact tuple. - const sourcePullRequests = await github.paginate( - github.rest.pulls.list, - fanoutOptions({ - ...context.repo, - state: "open", - head: `${context.repo.owner}:${refreshBranch}`, - per_page: 100, - }), - (response) => response.data - ); + const sourcePullRequests = await listOpenPullRequests({head: `${context.repo.owner}:${refreshBranch}`}); for (const source of sourcePullRequests) { if (String(source.number) !== sourcePrNumber || source.state !== "open" || source.head?.sha !== refreshSha || @@ -1075,7 +1126,7 @@ jobs: } if (!fallbackReason) { try { - existingProducers = findExactExistingProducer(tuple, inventory); + existingProducers = await findExactExistingProducer(tuple, inventory); if (!inventory.complete) { // The REST contract does not specify a sort order, so a truncated page cannot prove omitted runs are older. existingProducers = []; @@ -1147,7 +1198,7 @@ jobs: try { runtimeInventoryPromise = loadExistingRuntimeRuns(); inventory = await runtimeInventoryPromise; - const latestProducers = findExactExistingProducer(tuple, inventory); + const latestProducers = await findExactExistingProducer(tuple, inventory); if (!inventory.complete || !latestProducers.length && inventory.absenceProven === false) { throw new Error(inventory.reason || "the final producer inventory cannot prove absence"); } @@ -1267,14 +1318,39 @@ jobs: const expectedRepository = `${context.repo.owner}/${context.repo.repo}`; const defaultBranch = context.payload.repository?.default_branch; let runtimeWorkflow = null; - const isTransientVisibilityError = error => { + let rateLimitBackoffMs = 60000; + // Only visibility GETs use this retry policy; dispatch POSTs remain one-shot. + const visibilityRetryDelay = error => { const status = error?.status ?? error?.response?.status; const code = error?.code ?? error?.cause?.code; - return code === "VISIBILITY_PAGINATION_DRIFT" || - [408, 425, 429, 500, 502, 503, 504].includes(status) || + const headers = error?.response?.headers ?? {}; + const retryAfter = String(headers["retry-after"] ?? "").trim(); + const retryAfterDate = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(retryAfter) + ? Date.parse(retryAfter) : NaN; + const retryAfterMs = /^\d+$/.test(retryAfter) ? Number(retryAfter) * 1000 + : Number.isFinite(retryAfterDate) && new Date(retryAfterDate).toUTCString() === retryAfter + ? Math.max(0, retryAfterDate - Date.now()) : NaN; + const hasRetryAfter = Number.isFinite(retryAfterMs) && retryAfterMs >= 0; + const primaryExhausted = String(headers["x-ratelimit-remaining"] ?? "").trim() === "0"; + const reset = String(headers["x-ratelimit-reset"] ?? "").trim(); + const resetMs = /^\d+$/.test(reset) ? Number(reset) * 1000 : NaN; + const rateLimited = [403, 429].includes(status) && (status === 429 || hasRetryAfter || primaryExhausted || + /\brate[ -]limit\b|\babuse detection\b/i.test(error?.response?.data?.message || error?.message || "")); + if (rateLimited) { + // GitHub REST guidance: Retry-After first, then an exhausted + // primary reset; otherwise wait at least a minute and back off. + const delay = hasRetryAfter ? retryAfterMs + : primaryExhausted && Number.isFinite(resetMs) ? Math.max(0, resetMs - Date.now()) + : rateLimitBackoffMs; + rateLimitBackoffMs = Math.min(rateLimitBackoffMs * 2, 120000); + return delay; + } + const transient = code === "VISIBILITY_PAGINATION_DRIFT" || + [408, 425, 500, 502, 503, 504].includes(status) || (status == null && (["ABORT_ERR", "ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"].includes(code) || ["AbortError", "TimeoutError"].includes(error?.name))); + return transient ? 5000 : null; }; if (pendingVisibility.length > 0) { try { @@ -1293,10 +1369,11 @@ jobs: } runtimeWorkflow = workflow; } catch (error) { - if (!isTransientVisibilityError(error)) throw error; + const retryDelayMs = visibilityRetryDelay(error); + if (retryDelayMs === null) throw error; core.warning("Producer workflow identity lookup is temporarily unavailable; retrying within the existing visibility deadline without retrying any POST."); const remaining = visibilityDeadline - Date.now(); - if (remaining > 0) await new Promise(resolve => setTimeout(resolve, Math.min(5000, remaining))); + if (remaining > 0) await new Promise(resolve => setTimeout(resolve, Math.min(retryDelayMs, remaining))); } } if (!runtimeWorkflow) { @@ -1312,6 +1389,7 @@ jobs: core.setFailed(`Refresh dispatch ${dispatchState} but visibility is unknown for PRs ${pendingVisibility.map(item => item.tuple.prNumber).join(", ")}; no retry issued`); break; } + let retryDelayMs = 5000; try { const observed = await readInventory( visibilitySince, @@ -1363,15 +1441,17 @@ jobs: } } } catch (error) { - if (!isTransientVisibilityError(error)) { + const delay = visibilityRetryDelay(error); + if (delay === null) { core.setFailed(`Runtime refresh visibility is uncertain; no retry issued: ${error.message || error}`); break; } + retryDelayMs = delay; core.warning("Runtime refresh visibility read is temporarily unavailable; keep observing without retrying any POST."); } if (pendingVisibility.length === 0) break; const remaining = visibilityDeadline - Date.now(); - if (remaining > 0) await new Promise(resolve => setTimeout(resolve, Math.min(5000, remaining))); + if (remaining > 0) await new Promise(resolve => setTimeout(resolve, Math.min(retryDelayMs, remaining))); } build-base-image: diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 5d424fdb76..003878ae03 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -632,7 +632,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "a10e3434165cc6b150e380a75bcf5b4298c8895121017e36238a04f503b3ec2b"; + const canonicalRuntimeWorkflowSha256 = "537fe7a43662a56c367c2a51d44b7cf17071e29aed0956e4bb19c5144a40e523"; // Only authenticated default-branch refreshes may use retained successful definitions. // Keep the pre-rollout default and predecessor definitions for mixed-version runs. const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set([ @@ -927,9 +927,10 @@ jobs: step.name === "Run credential-free full-stack smoke" ); if (smokeSteps.length > 1) return false; - if (smokeSteps.length === 1 && (smokeSteps[0].status !== "completed" || - smokeSteps[0].conclusion == null)) return pendingExactSnapshot(); - if (smokeSteps.length === 1 && smokeSteps[0].conclusion !== "success") return false; + if (smokeSteps.length === 0) return pendingExactSnapshot(); + if (smokeSteps[0].conclusion != null && smokeSteps[0].conclusion !== "success") return false; + if (smokeSteps[0].status !== "completed" || + smokeSteps[0].conclusion == null) return pendingExactSnapshot(); for (const name of [ "Stop smoke stack", "Require successful runtime smoke and authenticated cleanup", @@ -986,8 +987,9 @@ jobs: step.name === "Run credential-free full-stack smoke" ); if (smokeSteps.length > 1) return false; - if (smokeSteps.length === 1 && (smokeSteps[0].status !== "completed" || - smokeSteps[0].conclusion == null)) return true; + if (smokeSteps.length === 0) return true; + if (smokeSteps[0].conclusion != null && smokeSteps[0].conclusion !== "success") return false; + if (smokeSteps[0].status !== "completed" || smokeSteps[0].conclusion == null) return true; return job.steps.some((step) => step.name !== markerName && (step.status !== "completed" || step.conclusion == null)); } @@ -1138,8 +1140,18 @@ jobs: expectedSuccessfulSteps.includes(step.name)))) return false; } for (const other of jobs) { - if (other.id === job?.id) continue; + if (other === job) continue; + if ((other.id != null && (!positiveInteger(other.id) || other.id === job?.id)) || + (other.run_id != null && other.run_id !== source.id) || + (other.run_attempt != null && other.run_attempt !== source.run_attempt) || + (other.head_sha != null && other.head_sha !== source.head_sha) || + (other.check_run_url != null && other.id != null && + other.check_run_url !== `https://api.github.com/repos/${repositoryName}/check-runs/${other.id}`)) return false; if (["queued", "in_progress", "waiting", "pending", "requested"].includes(other.status)) incompleteSteps = true; + // A successful typed attempt can precede its sibling conclusions; + // keep it pending only under the caller's existing snapshot bound. + else if (allowIncompleteSteps && source.event === "repository_dispatch" && source.conclusion === "success" && + other.status === "completed" && other.conclusion == null) incompleteSteps = true; else if (other.status !== "completed" || !["success", "skipped"].includes(other.conclusion)) return false; } // Only the exception relies on the classifier from the verified PR merge. @@ -1843,6 +1855,14 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } + // Final identity/attempt reads consume the same absolute allowance. + if (Date.now() >= sameTupleCancellationDeadline) { + core.setFailed( + `Cancelled runtime-images run ${cancelledRunId} has no freshly proven exact replacement ` + + `after ${cancellationDiscoveryMs / 60000} minutes` + ); + return; + } if (replacementProof === "ordinary") { core.info(`Exact repository_dispatch replacement ${replacement.id}/${replacement.run_attempt} passed full-stack smoke and authenticated cleanup.`); return; @@ -2057,21 +2077,24 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } - if (needsLiveTuple) { - const finalIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception", true); - if (finalIdentity?.obsolete) return; - if (!finalIdentity || identityKey({...finalIdentity, sourceEvent: currentIdentity.sourceEvent}) !== - identityKey(currentIdentity)) { - if (finalIdentity) { - requireCurrentIdentity = true; - currentIdentity = finalIdentity; - } - continue smokeGatePolling; - } - if (!finalIdentity.canonicalPlayEligible) { - core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); - return; + // Re-read the live label after the awaited attempt lookup without + // replacing a native producer's immutable event comparison. + const finalIdentity = await resolveCurrentIdentity( + "Stopping stale canonical transition PLAY exception", requireCurrentIdentity || needsLiveTuple); + const comparableFinalIdentity = needsLiveTuple && finalIdentity + ? {...finalIdentity, sourceEvent: currentIdentity.sourceEvent} + : finalIdentity; + if (finalIdentity?.obsolete) return; + if (!finalIdentity || identityKey(comparableFinalIdentity) !== identityKey(currentIdentity)) { + if (finalIdentity) { + if (needsLiveTuple) requireCurrentIdentity = true; + currentIdentity = finalIdentity; } + continue smokeGatePolling; + } + if (!finalIdentity.canonicalPlayEligible) { + core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); + return; } core.setOutput("known_play_exception", "true"); core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); @@ -2115,6 +2138,24 @@ jobs: } if (cancelledRecoveryMoved && matching.event === "repository_dispatch") { + if (matching.run_attempt != null && !positiveInteger(matching.run_attempt)) { + core.setFailed("Typed runtime smoke producer lacks an exact attempt."); + return; + } + if (matching.run_attempt == null) { + // Re-list a sparse terminal inventory row before any exact proof lookup. + const snapshotKey = `cancelled-move-list:${matching.id}:${identityKey(currentIdentity)}`; + if (incompleteRefreshKey !== snapshotKey) { + incompleteRefreshKey = snapshotKey; + incompleteRefreshObservedAt = Date.now(); + } + if (Date.now() - incompleteRefreshObservedAt >= completedSnapshotTimeoutMs) { + core.setFailed("Moved cancelled-run recovery lacks an exact attempt within the snapshot convergence allowance."); + return; + } + await new Promise((resolve) => setTimeout(resolve, snapshotSleepMs)); + continue smokeGatePolling; + } let proof; try { const ordinaryProducerVerified = matching.conclusion === "success" && @@ -2361,9 +2402,15 @@ jobs: const markers = (fullSmokeJob.steps ?? []).filter((step) => step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" ); + if (markers.length > 1 || (markers.length === 1 && markers[0].conclusion != null && + !["success", "skipped"].includes(markers[0].conclusion))) { + core.setFailed("Runtime smoke proof is missing its unambiguous transition-exception disposition."); + return; + } let markerProof = false; if (matching.event === "repository_dispatch" && - (markers.length === 0 || (markers.length === 1 && markers[0].status !== "completed"))) { + (markers.length === 0 || (markers.length === 1 && + (markers[0].status !== "completed" || markers[0].conclusion == null)))) { try { markerProof = await verifyKnownPlayFailure( matching, fullSmokeJob, currentIdentity, true, true); @@ -2466,21 +2513,23 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } - if (needsLiveTuple) { - const finalIdentity = await resolveCurrentIdentity("Stopping stale canonical transition PLAY exception", true); - if (finalIdentity?.obsolete) return; - if (!finalIdentity || identityKey({...finalIdentity, sourceEvent: currentIdentity.sourceEvent}) !== - identityKey(currentIdentity)) { - if (finalIdentity) { - requireCurrentIdentity = true; - currentIdentity = finalIdentity; - } - continue smokeGatePolling; - } - if (!finalIdentity.canonicalPlayEligible) { - core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); - return; + // Native event proof also needs a fresh label after the attempt GET. + const finalIdentity = await resolveCurrentIdentity( + "Stopping stale canonical transition PLAY exception", requireCurrentIdentity || needsLiveTuple); + const comparableFinalIdentity = needsLiveTuple && finalIdentity + ? {...finalIdentity, sourceEvent: currentIdentity.sourceEvent} + : finalIdentity; + if (finalIdentity?.obsolete) return; + if (!finalIdentity || identityKey(comparableFinalIdentity) !== identityKey(currentIdentity)) { + if (finalIdentity) { + if (needsLiveTuple) requireCurrentIdentity = true; + currentIdentity = finalIdentity; } + continue smokeGatePolling; + } + if (!finalIdentity.canonicalPlayEligible) { + core.setFailed("Canonical PLAY transition exception label is absent or no longer eligible."); + return; } core.setOutput("known_play_exception", "true"); core.warning("Canonical PLAY transition exception accepted: LOGIN succeeded, direct backend PLAY failed ERROR ENTITLEMENT_UNAVAILABLE. No runtime qualification or image publication."); diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 847e13f2e8..6e35aa034c 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -94,7 +94,7 @@ Pre-v1 Account reset or deletion remains only the proposal in [ADR 0185](../../d V1040.6 backfills one immutable refusal slot per retained `NO_ACCEPT` decision as the contiguous sequence `1..N`. After origin identity arbitration, a fresh refusal takes the existing tenant budget lock, reads the highest slot through the tenant-slot index, and appends `N+1` in the same transaction. `requireReady` uses that indexed highest slot as the retained refusal count under this invariant to compute bounded headroom; the missing or mismatched budget and insufficient headroom remain fail-closed. Replay, conflict, and failed inserts leave the inventory unchanged. The migration preserves origin rows and provisioned limits. -The unregistered capacity owner requires exact retained evidence and current Account membership/issuance/scope source equality before creating a new positive player-binding reservation. Exact attempt retries replay before fresh-source or usage work; changed complete payloads conflict. The Account recovery component alone can finalize, release or rearm under its current durable claim and exact selected-owner readback; an ambiguous observation records only the bounded retry/deadline and retains the hold. No runtime readback producer or recovery client is registered. World lifecycle, authoritative prior-shape/zero-delta recovery, current selected-owner activation and complete end-to-end qualification remain held as detailed in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). +The unregistered capacity owner requires exact retained evidence and current Account membership/issuance/scope source equality before creating a new positive player-binding reservation. Exact attempt retries replay only durably retained outcomes before fresh-source or usage work; changed complete payloads conflict. A non-retained billing denial is not replayable and requires fresh current evidence on retry. The Account recovery component alone can finalize, release or rearm under its current durable claim and exact selected-owner readback; an ambiguous observation records only the bounded retry/deadline and retains the hold. No runtime readback producer or recovery client is registered. World lifecycle, authoritative prior-shape/zero-delta recovery, current selected-owner activation and complete end-to-end qualification remain held as detailed in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). The canonical gameplay LOGIN primary-credential adapter reuses Account’s password and email-OTP authority without creating a legacy token or session. Its owner transaction retains the verified challenge identity and consumes it only after new PENDING issuance; denial accounting and expiry cleanup commit under the existing owner denial path. Exact pending retry does not reverify or reconsume. Canonical-only verification pads to two KDF comparisons with non-authorizing process-local random decoy evidence using the existing Argon2 profile. The adapter participates only in the explicitly enabled protected LOGIN composition; default deployment behavior remains unchanged. Focused unit and real PostgreSQL proof and its controlled upstream/external-owner limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). Deployed authenticated issuance and timing parity remain unproved. diff --git a/design/architecture/system-architecture-database-migrations.md b/design/architecture/system-architecture-database-migrations.md index bf7ce003ff..6e0e896253 100644 --- a/design/architecture/system-architecture-database-migrations.md +++ b/design/architecture/system-architecture-database-migrations.md @@ -244,7 +244,7 @@ ORDER BY conrelid::regclass::text, conname; This catalog query identifies enforced references, not all domain-level reachability; the owner must also check release bundles, launch descriptors, remap sets, publish attempts, and asset workflows for the exact candidate IDs. If the draft cannot be proved disposable, the migration remains blocked for owner adjudication. After correction or approved draft removal, rerun both queries and require zero rows before retrying the same release. Never broaden the migration to rewrite or delete retained rows to make V27 pass. -The trusted dev-demo workflow preserves its existing clean namespace reset for ordinary pushes. A push that first adds the Game Session or Automation V2 Flyway migration, Account V25 profile-identity migration, or one of the explicitly listed Account V1040.1–V1040.6 capacity-origin migrations, in the trusted deployed-to-target range instead preserves the runtime database and uses the quiesced activation path. That path first proves the reserved nonmatching selector does not match a Pod, replaces each canonical Account, Game Session, and Automation Service selector, verifies each readback, and waits until all matching EndpointSlices contain no endpoints. It then scales all three writers to zero and proves their Deployments and writer Pods are quiescent before restoring the canonical Service selectors. If selector mutation, endpoint observation, scaling, or drain proof fails, the helper aborts before migration activation and attempts to leave the canonical Services closed. If closure cannot be verified or reapplied, an operator must verify and repair admission before retrying. Account writer quiescence also protects V25 profile uniqueness and the capacity-origin uniqueness, refusal guards and slot backfill. Edits or deletions of an existing supported migration fail before namespace mutation because retained-database and Flyway checksum state are uncertain. Other Flyway migrations in the exact deployed-to-target Git range fail detection before namespace mutation until explicit trusted support exists; non-migration pushes retain the clean reset. Both pushes and redispatches use only the exact deployed-head annotation from the owned `dev` namespace as the classification base and require valid Git ancestry to the target. A supplied push before-SHA can add an ancestry check but never replaces that deployed-head base. Missing or ambiguous namespace evidence stops the workflow before namespace mutation. This narrow exception avoids using namespace deletion as a substitute for proving the retained V1 data prerequisites. +The trusted dev-demo workflow preserves its existing clean namespace reset for ordinary pushes. A push that first adds the Game Session or Automation V2 Flyway migration, Account V25 profile-identity migration, or one of the explicitly listed Account V1040.1–V1040.6 capacity-origin migrations, in the trusted deployed-to-target range instead preserves the runtime database and uses the quiesced activation path. That path first proves the reserved nonmatching selector does not match a Pod, replaces each canonical Account, Game Session, and Automation Service selector, verifies each readback, and waits until all matching EndpointSlices contain no endpoints. It then scales all three writers to zero and proves their Deployments and writer Pods are quiescent before restoring the canonical Service selectors. If selector mutation, endpoint observation, scaling, or drain proof fails, the helper aborts before migration activation and attempts to leave the canonical Services closed. If closure cannot be verified or reapplied, an operator must verify and repair admission before retrying. Account writer quiescence also protects V25 profile uniqueness and the capacity-origin uniqueness, refusal guards and slot backfill. Edits or deletions of an existing supported migration fail before namespace mutation because retained-database and Flyway checksum state are uncertain. Other Flyway migrations in the exact deployed-to-target Git range fail detection before namespace mutation until explicit trusted support exists; non-migration pushes retain the clean reset. Both pushes and redispatches use only the exact deployed-head annotation from the owned `dev` namespace as the classification base and require valid Git ancestry to the target. A supplied push before-SHA can add an ancestry check but never replaces that deployed-head base. Missing or ambiguous namespace evidence stops the workflow before namespace mutation. If a retained database already contains Account V1040.1–V1040.3 origin decisions, the Account owner must verify that each retained admission-attempt UUID occurs once before activating V1040.4. Quiescence stops new writes, while the uniqueness migration rejects existing duplicates and preserves their evidence. Duplicate data requires an Account-owned forward disposition before retry. If the namespace already records the target SHA, classification stops before namespace mutation. A failed rollout or smoke check after the Helm release was recorded requires inspecting the existing release and migration state. Re-running that target must not convert the retained activation into an ordinary namespace reset. This narrow exception avoids using namespace deletion as a substitute for proving the retained V1 data prerequisites. Hosted candidate previews may activate a migration only when the trusted path independently proves both an isolated fresh database and absence of old writers. A newly recreated namespace or a manifest value is not database provenance when backing storage may be retained. If the preview credential cannot verify that proof, skip or fail the candidate activation before modifying its namespace; use the trusted post-merge quiesce path instead. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 778d226957..b51b387b71 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -34,7 +34,7 @@ The unregistered Account owner prepares exact initial reservation, replay and co The staged [Game Session capacity client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java) is manually composed and unregistered. It requires the exact same-namespace Account mTLS peer before releasing the request body, carries the complete typed request and verifies the exact response binding. Its call uses the minimum of the remaining absolute admission budget, incoming deadline and five-second cap, with bounded request/response sizes and no automatic mutation retry. A timeout, transport failure or inexact response leaves the original commitment indeterminate; the client neither admits gameplay nor performs an owner activation CAS. -After exact replay/conflict and retained/current source qualification, the Account owner returns `TENANT_BILLING_BLOCKED` only when the bound evidence does not permit creation. This refusal carries no durable decision receipt and is not a retained replayable outcome; a later retry must recheck current evidence. A creating request denied by quota instead commits an exact `NO_ACCEPT` decision under the finite tenant refusal budget before returning `CAPACITY_QUOTA_EXCEEDED` with its durable denial ID. That retained denial has no reservation or usage mutation, excludes acceptance for the same original and replays even after headroom returns or the evaluation expires. The client preserves the typed distinction and exposes a durable denial ID only when supplied by the authenticated Account response; a refusal without that receipt supplies no durable settlement proof. +After exact replay/conflict and retained/current source qualification, the Account owner returns `TENANT_BILLING_BLOCKED` only when the bound evidence does not permit creation. This refusal carries no durable decision receipt and is not a retained replayable outcome; a later retry must recheck current evidence. A creating request denied by quota instead commits an exact `NO_ACCEPT` decision under the finite tenant refusal budget before returning `CAPACITY_QUOTA_EXCEEDED` with its durable denial ID. That retained denial has no reservation or usage mutation, excludes acceptance for the same original and replays even after headroom returns or the evaluation expires. The client's transport `commit` path preserves the typed distinction and exposes a durable denial ID only when supplied by the authenticated Account response. Separately, `CapacityRefusedException.retainedQuotaDenial` exposes the retained ID without an RPC after the local owner verifies the exact retained binding. Billing denial has no durable denial ID; a refusal without that receipt supplies no durable settlement proof. Account [V1040.6](../../../services/account-service/src/main/resources/db/migration/V1040.6__index_retained_capacity_refusal_slots.sql) backfills immutable contiguous per-tenant refusal slots for retained `NO_ACCEPT` decisions without rewriting the original decisions or provisioned limits. After origin identity arbitration, each fresh refusal appends one slot under the existing tenant budget lock; replay, conflict and failed insertion do not spend a slot. Refusal admission and readiness headroom use the indexed highest slot rather than scanning lifetime origin history. Missing or mismatched budgets and exhausted headroom remain fail-closed; this adds no replenishment, reset or receipt-deletion authority. diff --git a/dev-tools/deploy/detect-hosted-v2-migration-activation.sh b/dev-tools/deploy/detect-hosted-v2-migration-activation.sh index 9572dec14f..8669939748 100644 --- a/dev-tools/deploy/detect-hosted-v2-migration-activation.sh +++ b/dev-tools/deploy/detect-hosted-v2-migration-activation.sh @@ -58,6 +58,10 @@ if ! git merge-base --is-ancestor "$base_sha" "$head_sha"; then echo "refusing hosted deployment: $reason_source is not an ancestor of the target SHA" >&2 exit 1 fi +if [[ "$base_sha" == "$head_sha" ]]; then + echo "refusing hosted deployment: the namespace already records the target SHA; inspect the existing rollout and database before retrying" >&2 + exit 1 +fi if [[ "$event_name" == push && -n "$event_before_sha" ]]; then if [[ ! "$event_before_sha" =~ ^[0-9a-f]{40}$ ]] || [[ "$event_before_sha" =~ ^0{40}$ ]]; then echo "refusing hosted deployment: supplied push before-SHA is malformed" >&2 diff --git a/dev-tools/tests/hosted-v2-migration-activation-contract.sh b/dev-tools/tests/hosted-v2-migration-activation-contract.sh index 290083be1b..0043cad401 100644 --- a/dev-tools/tests/hosted-v2-migration-activation-contract.sh +++ b/dev-tools/tests/hosted-v2-migration-activation-contract.sh @@ -135,6 +135,8 @@ assert_activation true push "$account_v25_sha" "$capacity_origin_sha" assert_activation true workflow_dispatch "" "$capacity_origin_sha" namespace_for_head "$capacity_origin_sha" +assert_rejected workflow_dispatch "" "$capacity_origin_sha" +assert_rejected push "$account_v25_sha" "$capacity_origin_sha" printf '%s\n' '-- unsupported later capacity migration' >"$capacity_migration_dir/V1040.7__unqualified.sql" git -C "$repo" add . git -C "$repo" commit -qm "Unsupported later capacity origin migration" diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index a82af66234..70a4ad8bd2 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -981,7 +981,7 @@ async function scenario(kind, event = "pull_request") { const finalGetDrift = kind.startsWith("ordinary-final-get-"); const ordinary = kind.startsWith("ordinary-"); const movedBase = "e".repeat(40), movedMerge = "f".repeat(40); - const failures = [], refs = []; + const failures = [], refs = [], infos = []; const context = {repo: {owner: "example", repo: "firemud"}, sha: ordinary ? null : merge, payload: { repository: {default_branch: "develop"}, pull_request: {number: 42, head: {sha: head, repo: {full_name: repository}}, @@ -1025,7 +1025,8 @@ async function scenario(kind, event = "pull_request") { if (kind === "not-required") job.name = "PR Full-Stack Smoke (runtime-required=false)"; if (kind === "step-skipped") job.steps = [{name: "Run credential-free full-stack smoke", status: "completed", conclusion: "skipped"}]; if (kind === "legacy-positive") job.steps = [{name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]; - if (kind === "failed-smoke-step") job.steps[1].conclusion = "failure"; + if (["failed-smoke-step", "ordinary-failed-smoke-step"].includes(kind)) job.steps[1].conclusion = "failure"; + if (kind === "ordinary-duplicate-smoke-step") job.steps.push({...job.steps[1]}); if (kind === "failed-run") source.conclusion = "failure"; const sourceMutations = { "wrong-repository": {repository: {full_name: "other/repo"}}, @@ -1094,6 +1095,9 @@ async function scenario(kind, event = "pull_request") { assert.equal(input.run_id, 42); assert.equal(input.attempt_number, 1); if (ordinary) assert.equal(listedAttempt, 1, "attempt jobs cannot precede complete typed list identity"); snapshots++; + if (kind === "ordinary-missing-smoke-step" || kind === "ordinary-delayed-smoke-step" && snapshots <= 2) { + return [{...job, steps: job.steps.filter(step => step.name !== "Run credential-free full-stack smoke")}]; + } if (kind === "lagging-cleanup" && snapshots <= 2) { return [{...job, steps: job.steps.filter(step => step.name !== "Stop smoke stack")}]; } @@ -1151,9 +1155,9 @@ async function scenario(kind, event = "pull_request") { yield {data: [source]}; }; const clock = {now: () => now, parse: Date.parse}; - await execute(github, context, {info: () => {}, warning: () => {}, setFailed: message => failures.push(message)}, + await execute(github, context, {info: message => infos.push(message), warning: () => {}, setFailed: message => failures.push(message)}, clock, (callback, duration) => {now += duration; waitedMillis += duration; queueMicrotask(callback);}, require); - return {failures, refs, snapshots, exactAttemptReads, observedBaseMove, observedAttemptMove, waitedMillis, + return {failures, refs, infos, snapshots, exactAttemptReads, observedBaseMove, observedAttemptMove, waitedMillis, typedListReads, postAttemptIdentityReads}; } (async () => { @@ -1195,6 +1199,21 @@ async function scenario(kind, event = "pull_request") { const ordinary = await scenario("ordinary-stable", "repository_dispatch"); assert.deepEqual(ordinary.failures, [], "unchanged ordinary typed proof passes"); assert.equal(ordinary.waitedMillis, 0); + assert.equal(ordinary.infos.some(message => message.startsWith("Stopping stale smoke gate before accepting full-stack proof ")), false, + "unchanged proof clears without the obsolete identity message"); + const delayedSmoke = await scenario("ordinary-delayed-smoke-step", "repository_dispatch"); + assert.deepEqual(delayedSmoke.failures, []); + assert.equal(delayedSmoke.waitedMillis, 15000, "ordinary typed proof waits for its affirmative successful smoke row"); + assert(delayedSmoke.snapshots >= 4); + const missingSmoke = await scenario("ordinary-missing-smoke-step", "repository_dispatch"); + assert.equal(missingSmoke.failures.length, 1); + assert.match(missingSmoke.failures[0], /after 8 retries/); + assert.equal(missingSmoke.waitedMillis, 120000, "absent ordinary smoke evidence cannot outlive the existing snapshot allowance"); + for (const kind of ["ordinary-duplicate-smoke-step", "ordinary-failed-smoke-step"]) { + const invalidSmoke = await scenario(kind, "repository_dispatch"); + assert.equal(invalidSmoke.failures.length, 1, `${kind} is not ordinary runtime proof`); + assert.equal(invalidSmoke.waitedMillis, 0, `${kind} is terminal, not delayed metadata`); + } const sparseHead = await scenario("ordinary-sparse-head", "repository_dispatch"); assert.deepEqual(sparseHead.failures, [], "a temporarily missing typed list head waits for a complete run row"); assert(sparseHead.waitedMillis > 0); @@ -1235,6 +1254,11 @@ async function scenario(kind, event = "pull_request") { const obsolete = await scenario(`ordinary-final-get-${change}`, "repository_dispatch"); assert(obsolete.postAttemptIdentityReads > 0, `${change} during the final GET must reach the repeated PR fence`); assert.deepEqual(obsolete.failures, [], "obsolete gates exit rather than failing the new PR identity"); + assert.ok(obsolete.infos.includes( + `Stopping stale smoke gate before accepting full-stack proof develop@${base}...${head}; ` + + `current PR state/base/head is ${change === "closed" ? "closed" : "open"}/` + + `${change === "retarget" ? "other" : "develop"}/${change === "head" ? "e".repeat(40) : head}` + ), `${change} must exit through the existing obsolete identity diagnostic, not silently accept proof`); } console.log("Smoke producer contract passed: native outcomes, exact immutable definition/attempt, legacy proof and fail-closed cases"); })().catch(error => {console.error(error); process.exitCode = 1;}); @@ -3953,17 +3977,21 @@ const transientTransportCodes = [...transientCodeList[1].matchAll(/"([^"]+)"/g)] const isTransientGitHubFailure = new Function("TerminalGitHubRequestError", "retryableStatuses", "transientTransportCodes", `${script.slice(retryHelpersStart, retryHelpersEnd)}; return isTransientGitHubFailure;`)( TerminalGitHubRequestError, new Set([408, 425, 429]), new Set(transientTransportCodes)); -async function finalAttemptCheck(latest, error = null) { +async function finalAttemptCheck(latest, error = null, onLookup = () => {}, + selected = {id: 99, run_attempt: 2, conclusion: "success"}) { const start = script.indexOf("async function isCurrentCanonicalAttempt("); const end = script.indexOf("async function verifyFailedPullCanonicalRefresh(", start); const check = new Function("github", "withTransientGitHubRetry", "owner", "repo", "TerminalGitHubRequestError", "retryableStatuses", "isTransientGitHubFailure", "core", `${script.slice(start, end)}; return isCurrentCanonicalAttempt;`)( {rest: {actions: {getWorkflowRun: async ({run_id}) => { - assert.equal(run_id, 99); if (error) throw error; return {data: latest}; + assert.equal(run_id, selected.id); + await onLookup(); + if (error) throw error; + return {data: latest}; }}}}, (_label, call) => call(), "benhook1013", "FireMUD", TerminalGitHubRequestError, new Set([408, 425, 429]), isTransientGitHubFailure, {warning: () => {}}); - return check({id: 99, run_attempt: 2, conclusion: "success"}); + return check(selected); } assert.ok(script.includes("const refreshDiscoveryTimeoutMs = prerequisiteAndQueueAllowanceMinutes * 60 * 1000;")); assert.ok(script.includes("const completedSnapshotTimeoutMs = 8 * snapshotSleepMs;")); @@ -4058,9 +4086,53 @@ async function failedProof(error, event = "pull_request") { assert.match(warnings[0], /^Canonical PLAY transition exception proof is unavailable:/); assert.deepEqual(outputs, []); } +// Exercise the actual marker-consumption branch with real exact-attempt proof, +// including a completed row whose conclusion arrives after its status. +async function pendingMarkerSnapshot(conclusions, duplicate = false) { + let now = 0, snapshots = 0, proofReads = 0, finalReads = 0, writes = 0, latestJob; + const outputs = [], failures = []; + const matching = {...source, event: "repository_dispatch", head_sha: workflowSha, head_branch: "develop"}; + const selectedIdentity = {...identity, sourceEvent: "repository_dispatch", canonicalPlayEligible: true}; + const core = {warning() {}, setFailed: value => failures.push(value), setOutput: (...value) => outputs.push(value)}; + core.summary = {addHeading() {return this;}, addRaw() {return this;}, async write() {writes++;}}; + const execute = new Function("matching", "canonicalSmokeJobName", "currentIdentity", "verifyKnownPlayFailure", + "verifyCanonicalSmokeProducer", "TerminalGitHubRequestError", "isTransientGitHubFailure", "core", + "resolveCurrentIdentity", "identityKey", "isCurrentCanonicalAttempt", "Date", "setTimeout", "sleepMs", + "completedSnapshotTimeoutMs", "readJob", + `return (async () => { let requireCurrentIdentity = false, incompleteRefreshKey = null, incompleteRefreshObservedAt = null; + smokeGatePolling: while (Date.now() < 100) { + const fullSmokeJob = readJob(); const typedRuntimeProof = true; + let canonicalProducerVerified = (await verifyCanonicalSmokeProducer(matching, fullSmokeJob, currentIdentity, true)) === true; + ${failedBranch} break; + } })();`); + await execute(matching, canonicalSmokeJobName, selectedIdentity, async (run, job, selected, incomplete, ordinary) => { + proofReads++; + assert.equal(run, matching); assert.equal(job, latestJob); assert.equal(selected, selectedIdentity); + assert.equal(incomplete, true); + const incompleteMarker = latestJob.steps.find(step => step.name.startsWith("Known canonical transition")).conclusion == null; + assert.equal(ordinary, incompleteMarker ? true : undefined); + return verify(data => {data.candidate.steps = structuredClone(latestJob.steps);}, "repository_dispatch", true, true, ordinary === true); + }, async () => verify(data => { + Object.assign(data.run, data.source); + data.candidate.steps = structuredClone(latestJob.steps); + }, "repository_dispatch", false, true), TerminalGitHubRequestError, isTransientGitHubFailure, core, + async () => selectedIdentity, selected => JSON.stringify(selected), async run => { + finalReads++; + return finalAttemptCheck(matching, null, () => {}, run); + }, {now: () => now}, resolve => {now += 10; resolve();}, 10, 30, () => { + latestJob = structuredClone({...candidate, head_sha: workflowSha}); + const marker = latestJob.steps.find(step => step.name.startsWith("Known canonical transition")); + const conclusion = conclusions[Math.min(snapshots++, conclusions.length - 1)]; + if (conclusion === undefined) delete marker.conclusion; + else marker.conclusion = conclusion; + if (duplicate) latestJob.steps.push({...marker}); + return latestJob; + }); + return {failures, outputs, now, snapshots, proofReads, finalReads, writes}; +} async function selectedProducerFinalFence(event, moved = false, superseded = false, rerunDuringIdentity = false, duringFinal = null) { const outputs = [], failures = [], required = []; - let proofs = 0, sleeps = 0, attemptChanged = false, afterAttempt = false; + let proofs = 0, sleeps = 0, attemptChanged = false, afterAttempt = false, labelRemoved = false; const core = {warning: () => {}, setFailed: x => failures.push(x), setOutput: (...x) => outputs.push(x)}; core.summary = {addHeading() {return this;}, addRaw() {return this;}, async write() {}}; const execute = new Function("fullSmokeJob", "matching", "canonicalSmokeJobName", "currentIdentity", @@ -4074,18 +4146,25 @@ async function selectedProducerFinalFence(event, moved = false, superseded = fal required.push(current); attemptChanged = rerunDuringIdentity; if (afterAttempt && ["closed", "head", "retarget"].includes(duringFinal)) return {obsolete: true}; - return {...identity, canonicalPlayEligible: true, + return {...identity, canonicalPlayEligible: !labelRemoved, ...(current ? {sourceEvent: "repository_dispatch"} : {}), ...(current && (moved || afterAttempt && duringFinal === "base") ? {baseSha: "e".repeat(40), mergeSha: "f".repeat(40)} : {})}; }, selected => { const {canonicalPlayEligible, ...tuple} = selected; return JSON.stringify(tuple); }, - async () => {afterAttempt = true; return !attemptChanged;}, resolve => {sleeps++; resolve();}, 0); + async selected => { + afterAttempt = true; + if (duringFinal === "label") return finalAttemptCheck({...selected, status: "completed"}, null, () => { + labelRemoved = true; + }, selected); + return !attemptChanged; + }, resolve => {sleeps++; resolve();}, 0); assert.equal(proofs, superseded ? 2 : 1); assert.equal(sleeps, superseded || rerunDuringIdentity ? 1 : 0); - const fenceCount = event === "repository_dispatch" && !moved && !rerunDuringIdentity ? 2 : 1; + const fenceCount = !(event === "repository_dispatch" && moved) && !rerunDuringIdentity ? 2 : 1; assert.deepEqual(required, Array((proofs - (superseded ? 1 : 0)) * fenceCount).fill(event === "repository_dispatch")); - assert.deepEqual(failures, []); - assert.equal(outputs.length, (event === "repository_dispatch" && (moved || duringFinal)) || rerunDuringIdentity ? 0 : 1, + assert.deepEqual(failures, duringFinal === "label" + ? ["Canonical PLAY transition exception label is absent or no longer eligible."] : []); + assert.equal(outputs.length, duringFinal === "label" || (event === "repository_dispatch" && (moved || duringFinal)) || rerunDuringIdentity ? 0 : 1, "an exception must retain its exact attempt through the final live identity read"); } // Execute the failed-run branch so proof errors retain the deterministic failure diagnostic. @@ -4184,6 +4263,7 @@ async function sameTupleProof(marker, ordinaryProof, exceptionProof) { async function pendingRefreshCaller(statuses, expires = false, options = {}) { const failures = [], outputs = []; let sleeps = 0, polls = 0, writes = 0, now = 0, currentChecks = 0, finalChecks = 0, nullReads = 0, directReads = 0; + let labelRemovedDuringFinal = false; const proofLive = {baseSha: identity.baseSha, mergeSha: identity.mergeSha}; const core = {info: () => {}, warning: () => {}, setFailed: value => failures.push(value), setOutput: (...value) => outputs.push(value)}; @@ -4262,7 +4342,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { selectedRun, selectedIdentity, true)).accepted; }, async () => false, TerminalGitHubRequestError, core, async (_label, requireCurrent) => { if (options.finalNull && _label === "Stopping stale canonical transition PLAY exception" && nullReads++ === 0) return null; - const eligible = !options.labelRemoved && !(options.withdrawDuringProof && polls > 0); + const eligible = !options.labelRemoved && !labelRemovedDuringFinal && !(options.withdrawDuringProof && polls > 0); if (requireCurrent) { currentChecks++; if (options.finalIdentity && polls > 0 && !options.recoverDrift) now += 30; @@ -4291,6 +4371,9 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { if (options.transientFinal && finalChecks === 1) { return finalAttemptCheck(null, Object.assign(new Error("temporary"), {status: 502})); } + if (options.withdrawDuringFinal) return finalAttemptCheck({...selected, status: "completed"}, null, () => { + labelRemovedDuringFinal = true; + }, selected); return !options.rerunFinal || finalChecks > 1; }, async () => "ordinary"); if (options.ordinaryAfterDrift) { @@ -4312,7 +4395,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { assert.deepEqual(failures, ["Runtime images run 98 did not complete successfully: run=failure"]); assert.deepEqual(outputs, []); assert.equal(writes, 0); - } else if (options.labelRemoved || options.withdrawDuringProof) { + } else if (options.labelRemoved || options.withdrawDuringProof || options.withdrawDuringFinal) { if (options.labelRemoved && statuses[0] === "absent") { assert.equal(failures.length, 1); assert.match(failures[0], /^Timed out waiting for the exact runtime-images/); @@ -4346,14 +4429,18 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { // Exercise the exact production loop through cancellation of an old tuple and // a successful refresh of the new tuple. Only independently verified ordinary // proof is accepted; a title match and green job are insufficient. -async function movedCancellation(ordinaryProof, listedOldReplacement = false) { +async function movedCancellation(ordinaryProof, listedOldReplacement = false, options = {}) { let now = 0, typedReads = 0, proofReads = 0, finalReads = 0; + let movedLists = 0, exceptionReads = 0; + const proofAttempts = []; const eventIdentity = {...identity, sourceEvent: "pull_request"}; const moved = {...identity, baseSha: "d".repeat(40), mergeSha: "e".repeat(40), sourceEvent: "repository_dispatch"}; const old = {...source, id: 98, event: "pull_request", status: "completed", conclusion: "cancelled", head_sha: identity.headSha, head_branch: "feature", display_title: `Build Runtime Images secure-pr-artifact pr-3390 base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`}; - const refresh = {...source, event: "repository_dispatch", status: "completed", conclusion: "success"}; + const refresh = {...source, event: "repository_dispatch", status: "completed", conclusion: "success", + head_sha: workflowSha, head_branch: "develop", + display_title: `Build Runtime Images secure-pr-artifact pr-3390 base-${moved.baseSha} head-${moved.headSha} merge-${moved.mergeSha} mode-required`}; const failures = [], outputs = []; const core = {info() {}, warning() {}, setFailed: x => failures.push(x), setOutput: (...x) => outputs.push(x)}; const execute = new Function("repositoryName", "workflowPath", "isRuntimeSourceWorkflowPath", "canonicalSmokeJobName", "withTransientGitHubRetry", @@ -4361,37 +4448,63 @@ async function movedCancellation(ordinaryProof, listedOldReplacement = false) { "isCurrentPullRequestObsolete", "core", "resolveCurrentIdentity", "identityKey", "setTimeout", "sleepMs", "Date", "started", "timeoutMs", "pullRequestCheckInterval", "findMatchingRuntimeImagesRun", "prNumber", "identityDiagnostic", "cancelledReplacementTimeoutMs", "context", - "refreshDiscoveryTimeoutMs", "completedSnapshotTimeoutMs", "positiveInteger", "isCurrentCanonicalAttempt", + "refreshDiscoveryTimeoutMs", "completedSnapshotTimeoutMs", "snapshotSleepMs", "positiveInteger", "isCurrentCanonicalAttempt", "verifySameTupleReplacementProof", `return (async () => { let pollIteration = 0; ${actualPollingLoop} })();`); await execute(repositoryName, workflowPath, isRuntimeSourceWorkflowPath, canonicalSmokeJobName, (_label, call) => call(), async (run, candidate, selected, incomplete, ordinary) => { + exceptionReads++; assert.equal(run, refresh); assert.equal(candidate, null); + assert.ok(Number.isSafeInteger(run.run_attempt) && run.run_attempt > 0, + "sparse moved inventory cannot enter the exact exception verifier"); assert.deepEqual(selected, moved); assert.equal(incomplete, true); assert.equal(ordinary, true); return false; }, async (run, candidate, selected, required) => { proofReads++; assert.equal(run, refresh); assert.equal(candidate, null); assert.deepEqual(selected, moved); assert.equal(required, true); + assert.ok(Number.isSafeInteger(run.run_attempt) && run.run_attempt > 0, + "sparse moved inventory must be re-listed before exact ordinary proof"); + proofAttempts.push(run.run_attempt); + if (options.listAttempts) return verify(data => { + data.identity = {...moved}; + Object.assign(data.run, refresh); + Object.assign(data.source, refresh); + Object.assign(data.latest, refresh); + data.candidate.run_attempt = run.run_attempt; + data.currentBase.object.sha = moved.baseSha; + data.currentPullRequest.merge_commit_sha = moved.mergeSha; + }, "repository_dispatch", false, true); return ordinaryProof; }, isTransientGitHubFailure, async () => false, core, async (_label, live) => live ? moved : eventIdentity, selected => JSON.stringify(selected), resolve => {now += 10; resolve();}, 10, {now: () => now}, 0, 100, 1, async (event, _title, selected) => { if (event === "pull_request") return old; typedReads++; - return selected.mergeSha === moved.mergeSha ? refresh - : listedOldReplacement ? {...refresh, id: refresh.id - 1} : null; + if (selected.mergeSha !== moved.mergeSha) return listedOldReplacement ? {...refresh, id: refresh.id - 1} : null; + if (options.listAttempts) { + const attempt = options.listAttempts[Math.min(movedLists++, options.listAttempts.length - 1)]; + if (attempt === undefined) delete refresh.run_attempt; + else refresh.run_attempt = attempt; + } + return refresh; }, "3390", "test identity", 20, {payload: {pull_request: {head: {ref: "feature", repo: {full_name: repositoryName}}}}}, - 60, 30, value => Number.isSafeInteger(value) && value > 0, async run => { - finalReads++; assert.equal(run, refresh); return true; + 60, 30, 10, value => Number.isSafeInteger(value) && value > 0, async run => { + finalReads++; assert.equal(run, refresh); + return options.listAttempts ? finalAttemptCheck(refresh, null, () => {}, run) : true; }, async () => "ordinary"); - assert.equal(typedReads, 2); assert.equal(proofReads, 1); assert.equal(finalReads, ordinaryProof ? 1 : 0); + if (!options.listAttempts) { + assert.equal(typedReads, 2); assert.equal(proofReads, 1); assert.equal(finalReads, ordinaryProof ? 1 : 0); + assert.deepEqual(failures, ordinaryProof ? [] : ["Moved cancelled-run recovery did not supply authenticated smoke proof."]); + } assert.deepEqual(outputs, [], "ordinary proof never publishes an exception output"); - assert.deepEqual(failures, ordinaryProof ? [] : ["Moved cancelled-run recovery did not supply authenticated smoke proof."]); + return {failures, outputs, now, typedReads, movedLists, proofReads, exceptionReads, finalReads, proofAttempts}; } async function sameTupleCancellation(replacementStatus, proofSequence = [], sparseAttempt = false, options = {}) { let now = 0, proofReads = 0, runtimeJobReads = 0, sleeps = 0, listedReplacements = 0; - const sameIdentity = {...identity, sourceEvent: "pull_request"}; + let finalIdentityReads = 0, finalAttemptReads = 0; + const sameIdentity = {...identity, sourceEvent: "pull_request", + ...(options.siblingConclusions ? {canonicalPlayEligible: true} : {})}; const old = {...source, id: 98, event: "pull_request", status: "completed", conclusion: "cancelled", head_sha: identity.headSha, head_branch: "feature", repository: {full_name: options.recoverableOriginal ? repositoryName : "other/repo"}, @@ -4427,7 +4540,13 @@ async function sameTupleCancellation(replacementStatus, proofSequence = [], spar return [smokeJob]; }}, "benhook1013", "FireMUD", canonicalSmokeJobName, (_label, call) => call(), async () => false, async () => true, isTransientGitHubFailure, hasPendingCanonicalSmokeTerminalEvidence, async () => false, - async () => false, TerminalGitHubRequestError, core, async () => sameIdentity, + async () => false, TerminalGitHubRequestError, core, async label => { + if (label === "Fencing proven cancelled-run replacement") { + finalIdentityReads++; + now += options.finalIdentityReadMs ?? 0; + } + return sameIdentity; + }, selected => JSON.stringify(selected), resolve => {sleeps++; now += 10; resolve();}, 10, {now: () => now}, 0, options.overallMs ?? 1000, 1, async event => { if (event === "pull_request") return old; @@ -4444,16 +4563,30 @@ async function sameTupleCancellation(replacementStatus, proofSequence = [], spar }, "3390", "test identity", 50, {payload: {pull_request: {head: {ref: "feature", repo: {full_name: repositoryName}}}}}, - 200, 100, 10, value => Number.isSafeInteger(value) && value > 0, async () => true, + 200, 100, 10, value => Number.isSafeInteger(value) && value > 0, async () => { + finalAttemptReads++; + now += options.finalAttemptReadMs ?? 0; + return true; + }, async (run, selected) => { proofReads++; assert.equal(run, replacement); assert.ok(Number.isSafeInteger(run.run_attempt) && run.run_attempt > 0); assert.ok(["success", "failure"].includes(run.conclusion)); assert.deepEqual(selected, sameIdentity); + if (options.finalIdentityReadMs || options.finalAttemptReadMs) { + assert.equal(now, 0, "proof is complete before only the final reads advance the fake clock"); + } + if (options.siblingConclusions) { + const conclusion = options.siblingConclusions[Math.min(proofReads - 1, options.siblingConclusions.length - 1)]; + return verify(data => { + data.jobs.push({id: 999, run_id: run.id, run_attempt: run.run_attempt, head_sha: workflowSha, + name: "Dispatch Trusted PR Runtime Publication", status: "completed", conclusion}); + }, "repository_dispatch", true, true); + } return proofSequence[Math.min(proofReads - 1, proofSequence.length - 1)] ?? false; }); - return {failures, outputs, now, proofReads, runtimeJobReads, sleeps}; + return {failures, outputs, now, proofReads, runtimeJobReads, sleeps, finalIdentityReads, finalAttemptReads}; } // Exercise the real resolver, not merely a stub that honors requireCurrent. async function refreshFinalIdentity(eventUnavailable = false) { @@ -4514,6 +4647,40 @@ function markerAccepted(overrides = {}) { await failedProof(Object.assign(new Error("unavailable"), {status: 404}), event); await failedProof(null, event); } + for (const missing of [null, undefined]) { + for (const conclusion of ["success", "skipped"]) { + const marker = await pendingMarkerSnapshot([missing, conclusion]); + assert.deepEqual(marker.failures, []); + assert.equal(marker.now, 10, "a completed marker needs a valid conclusion before supplying proof"); + assert.equal(marker.snapshots, 2); + assert.equal(marker.proofReads, conclusion === "success" ? 2 : 1); + assert.deepEqual(marker.outputs, conclusion === "success" ? [["known_play_exception", "true"]] : []); + assert.equal(marker.writes, conclusion === "success" ? 1 : 0); + assert.equal(marker.finalReads, conclusion === "success" ? 1 : 0); + } + } + const missingMarker = await pendingMarkerSnapshot([null, undefined, null, undefined, "success"]); + assert.deepEqual(missingMarker.failures, ["Runtime smoke proof is missing its unambiguous transition-exception disposition."]); + assert.deepEqual(missingMarker.outputs, []); + assert.equal(missingMarker.now, 30, "alternating missing marker conclusions retain one current-attempt snapshot allowance"); + assert.equal(missingMarker.snapshots, 4); + assert.equal(missingMarker.finalReads, 0); + assert.equal(missingMarker.writes, 0); + for (const conclusion of ["failure", "cancelled", "timed_out", "unknown", ""]) { + const invalidMarker = await pendingMarkerSnapshot([conclusion, "success"]); + assert.deepEqual(invalidMarker.failures, ["Runtime smoke proof is missing its unambiguous transition-exception disposition."]); + assert.deepEqual(invalidMarker.outputs, []); + assert.equal(invalidMarker.now, 0); + assert.equal(invalidMarker.proofReads, 0); + assert.equal(invalidMarker.writes, 0); + } + for (const conclusion of [null, "success", "skipped"]) { + const duplicateMarker = await pendingMarkerSnapshot([conclusion], true); + assert.equal(duplicateMarker.failures.length, 1); + assert.deepEqual(duplicateMarker.outputs, []); + assert.equal(duplicateMarker.now, 0, "duplicate markers are terminal even with a missing conclusion"); + assert.equal(duplicateMarker.proofReads, 0); + } for (const stage of ["jobs", "proof"]) { const terminal = new TerminalGitHubRequestError("permission denied"); await assert.rejects(failedLegacyProof(stage, terminal), error => error === terminal); @@ -4533,6 +4700,31 @@ function markerAccepted(overrides = {}) { await movedCancellation(false); await movedCancellation(true, true); await movedCancellation(false, true); + for (const attempt of [null, undefined]) { + const converged = await movedCancellation(true, false, {listAttempts: [attempt, 2]}); + assert.deepEqual(converged.failures, []); + assert.equal(converged.now, 10, "a sparse moved terminal row waits before exact proof"); + assert.equal(converged.movedLists, 2); + assert.deepEqual(converged.proofAttempts, [2], "only the newly complete exact native attempt is verified"); + assert.equal(converged.exceptionReads, 0); + assert.equal(converged.finalReads, 1); + } + const sparseMoved = await movedCancellation(true, false, {listAttempts: [null, undefined, null, undefined, 2]}); + assert.deepEqual(sparseMoved.failures, + ["Moved cancelled-run recovery lacks an exact attempt within the snapshot convergence allowance."]); + assert.equal(sparseMoved.now, 30, "alternating absent/null attempts cannot reset the sparse snapshot budget"); + assert.equal(sparseMoved.movedLists, 4); + assert.equal(sparseMoved.proofReads, 0); + assert.equal(sparseMoved.exceptionReads, 0); + assert.equal(sparseMoved.finalReads, 0); + for (const attempt of [0, -1, 1.5, "2", false, "", {}]) { + const invalidMoved = await movedCancellation(true, false, {listAttempts: [attempt, 2]}); + assert.deepEqual(invalidMoved.failures, ["Typed runtime smoke producer lacks an exact attempt."]); + assert.equal(invalidMoved.now, 0, "invalid supplied attempts are terminal, not sparse metadata"); + assert.equal(invalidMoved.proofReads, 0); + assert.equal(invalidMoved.exceptionReads, 0); + assert.equal(invalidMoved.finalReads, 0); + } assert.deepEqual(await sameTupleProof("success", false, true), {result: true, verifiers: ["exception"]}); assert.deepEqual(await sameTupleProof("success", true, false), {result: false, verifiers: ["exception"]}); assert.deepEqual(await sameTupleProof("skipped", true, false), {result: "ordinary", verifiers: ["ordinary"]}); @@ -4564,6 +4756,37 @@ function markerAccepted(overrides = {}) { assert.equal(sequencedReplacement.runtimeJobReads, 0, "a freshly proved replacement needs only the final currentness fences, without rereading its job inventory"); assert.equal(sequencedReplacement.now, 10); + for (const exception of [false, true]) { + const finalReadOverrun = await sameTupleCancellation("completed", exception ? [] : ["ordinary"], false, + {overallMs: 25, finalIdentityReadMs: 10, finalAttemptReadMs: 10, + ...(exception ? {siblingConclusions: ["skipped"]} : {})}); + assert.equal(finalReadOverrun.failures.length, 1); + assert.match(finalReadOverrun.failures[0], /has no freshly proven exact replacement/); + assert.deepEqual(finalReadOverrun.outputs, [], "neither ordinary nor exception proof can clear after the absolute cancellation deadline"); + assert.equal(finalReadOverrun.now, 30); + assert.equal(finalReadOverrun.proofReads, 1); + assert.equal(finalReadOverrun.sleeps, 0); + assert.equal(finalReadOverrun.finalIdentityReads, 2); + assert.equal(finalReadOverrun.finalAttemptReads, 1); + } + const finalReadsWithinBudget = await sameTupleCancellation("completed", ["ordinary"], false, + {overallMs: 31, finalIdentityReadMs: 10, finalAttemptReadMs: 10}); + assert.deepEqual(finalReadsWithinBudget.failures, [], "the final deadline fence still accepts within the same allowance"); + assert.equal(finalReadsWithinBudget.now, 30); + const delayedSibling = await sameTupleCancellation("completed", [], false, {siblingConclusions: [null, "skipped"]}); + assert.deepEqual(delayedSibling.failures, []); + assert.deepEqual(delayedSibling.outputs, [["known_play_exception", "true"]]); + assert.equal(delayedSibling.proofReads, 2, "a completed sibling with no conclusion cannot supply proof before fresh valid evidence"); + assert.equal(delayedSibling.now, 10, "delayed sibling conclusion converges only after a bounded pause"); + const missingSiblingConclusion = await sameTupleCancellation("completed", [], false, {siblingConclusions: [null]}); + assert.match(missingSiblingConclusion.failures[0], /within the snapshot convergence allowance/); + assert.deepEqual(missingSiblingConclusion.outputs, []); + assert.equal(missingSiblingConclusion.now, 100, "a persistently missing sibling conclusion cannot extend the existing snapshot budget"); + const failedSibling = await sameTupleCancellation("completed", [], false, {siblingConclusions: ["failure", "skipped"]}); + assert.match(failedSibling.failures[0], /contradictory identity or invalid terminal smoke proof/); + assert.deepEqual(failedSibling.outputs, []); + assert.equal(failedSibling.proofReads, 1, "an explicit terminal sibling failure is rejected without waiting for generic green history"); + assert.equal(failedSibling.now, 0); const invalidReplacement = await sameTupleCancellation("completed", [false]); assert.equal(invalidReplacement.failures.length, 1); assert.match(invalidReplacement.failures[0], /contradictory identity or invalid terminal smoke proof/); @@ -4626,6 +4849,29 @@ function markerAccepted(overrides = {}) { "repository_dispatch", true, true), true); assert.equal(await verify(data => {data.jobs.push({id: 999, status: "completed", conclusion: "failure"});}, "repository_dispatch", true, true), false); + const nullableSibling = data => { + data.jobs.push({id: 999, run_id: data.source.id, run_attempt: data.source.run_attempt, + head_sha: data.source.head_sha, status: "completed", conclusion: null}); + }; + assert.equal(await verify(nullableSibling, "repository_dispatch", true, true), "snapshot-pending"); + assert.equal(await verify(nullableSibling, "repository_dispatch", true, false), false, + "a missing sibling conclusion cannot be accepted without bounded convergence"); + assert.equal(await verify(nullableSibling, "pull_request", true, true), false, + "typed snapshot convergence does not broaden native PR proof"); + for (const change of [ + {run_id: 98}, {run_attempt: 3}, {head_sha: "e".repeat(40)}, + {check_run_url: "https://example.com/check"}, {id: candidate.id}, + {conclusion: "failure"}, {conclusion: "timed_out"}, {conclusion: "cancelled"}, {conclusion: "unknown"}, {conclusion: ""}, + ]) { + assert.equal(await verify(data => { + nullableSibling(data); + Object.assign(data.jobs.at(-1), change); + }, "repository_dispatch", true, true), false, `missing sibling metadata cannot hide contradictory proof: ${JSON.stringify(change)}`); + } + assert.equal(await verify(data => { + nullableSibling(data); + data.jobs.push({id: 998, status: "completed", conclusion: "failure"}); + }, "repository_dispatch", true, true), false, "a pending sibling snapshot cannot hide a different terminal sibling failure"); assert.equal(await verify(data => { data.jobs.push({id: 999, status: "in_progress", conclusion: null}); data.currentPullRequest.head.sha = "e".repeat(40); @@ -4734,6 +4980,7 @@ function markerAccepted(overrides = {}) { await pendingRefreshCaller(["completed"], false, {headRepository: "fork/FireMUD"}); await pendingRefreshCaller(["completed"], false, {directProof: true}); await pendingRefreshCaller(["completed"], false, {directProof: true, labelRemoved: true}); + await pendingRefreshCaller(["completed"], false, {directProof: true, withdrawDuringFinal: true}); await pendingRefreshCaller(["completed", "completed"], false, { recoverDrift: true, labelRemoved: true, finalIdentity: {baseSha: "d".repeat(40), mergeSha: "e".repeat(40)}, @@ -4804,6 +5051,7 @@ function markerAccepted(overrides = {}) { for (const event of ["pull_request", "repository_dispatch"]) { await selectedProducerFinalFence(event); await selectedProducerFinalFence(event, true); + await selectedProducerFinalFence(event, false, false, false, "label"); } await selectedProducerFinalFence("repository_dispatch", false, true); await selectedProducerFinalFence("repository_dispatch", false, false, true); @@ -5099,17 +5347,18 @@ async function run(kind, shared = {visible: false, posts: 0}) { const startClock = Date.parse(source.created_at); const sameSecond = ["same-second", "ambiguous-same-second"].includes(kind); let clock = startClock + (sameSecond ? 200 : 0), tupleReads = 0, sourceReads = 0, metadataReads = 0, wakeReads = 0, ciInventoryReads = 0, refreshInventoryReads = 0; - let observedCancelledJobs = []; + let cancelledAttemptReads = 0; const github = {rest: { actions: { - listJobsForWorkflowRunAttempt: async ({run_id, attempt_number, per_page, page}) => { - assert.equal(run_id, 91); + listJobsForWorkflowRunAttempt: async request => { + const {run_id, attempt_number, per_page, page} = request; assert.equal(attempt_number, 1); assert.equal(per_page, 100); assert.equal(page, 1); - const jobs = structuredClone(observedCancelledJobs); - if (kind === "cancel-inventory-disagrees") jobs[1].conclusion = "failure"; - return {data: {jobs, total_count: jobs.length + (kind === "cancel-inventory-short" ? 1 : 0)}}; + const recheck = run_id === 91 && cancelledCase && ++cancelledAttemptReads % 2 === 0; + const jobs = structuredClone(await fixtureCIJobs(request)); + if (recheck && kind === "cancel-inventory-disagrees") jobs[1].conclusion = "failure"; + return {data: {jobs, total_count: jobs.length + (recheck && kind === "cancel-inventory-short" ? 1 : 0)}}; }, getWorkflow: async ({workflow_id}) => ({data: workflow_id === "ci.yml" ? {id: 8, path: ".github/workflows/ci.yml", name: "CI — Validation"} @@ -5233,8 +5482,8 @@ async function run(kind, shared = {visible: false, posts: 0}) { if (kind !== "invisible") shared.visible = true; }, }, - }, paginate: async (_route, request) => { - assert.equal(_route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); + }}; + async function fixtureCIJobs(request) { assert.equal(request.attempt_number, 1); if (metadataWake && request.run_id === 92) { const expression = "github.event_name == 'pull_request' && github.event.action == 'edited' && github.event.changes.base.ref == null && 'PR Metadata Edit (Validation Gate)' || 'Validation Gate'"; @@ -5312,8 +5561,7 @@ async function run(kind, shared = {visible: false, posts: 0}) { {...gate, name: "PR Metadata Edit (Validation Gate)", conclusion: "skipped", steps: []}, {...upstream, conclusion: "failure"}, ]; - observedCancelledJobs = kind === "cancel-gate-only" ? [gate] : [gate, upstream]; - return observedCancelledJobs; + return kind === "cancel-gate-only" ? [gate] : [gate, upstream]; } const metadata = kind === "metadata" || ["metadata-newer", "old-meta-rerun", "late-ci-old-metadata"].includes(kind) && request.run_id === 91; return [{id: 30, run_id: request.run_id, run_attempt: 1, head_sha: head, name: "Validation Gate", @@ -5321,7 +5569,7 @@ async function run(kind, shared = {visible: false, posts: 0}) { steps: ["unclassified-newer", "late-ci-unknown"].includes(kind) && request.run_id === 91 ? [] : [ {name: "Preserve successful required gate on metadata-only edit", status: "completed", conclusion: metadata ? "success" : "skipped"}, {name: "Enforce validation success", status: "completed", conclusion: metadata ? "skipped" : "failure"}]}]; - }}; + } await execute(github, {repo: {owner: "example", repo: "firemud"}, eventName: "workflow_run", payload: {workflow_run: event, repository: {full_name: repository, default_branch: "develop"}}}, {info: () => {}, warning: message => { (shared.warnings ??= []).push(message); }, diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 2b950f053e..16616c7231 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -866,6 +866,7 @@ const titleFor = (tuple) => const producer = (tuple, event, status, conclusion = null, overrides = {}) => ({ id: Number(tuple.prNumber) * 100 + (event === "pull_request" ? 1 : 2), workflow_id: 701, + run_attempt: 1, name: "Build Runtime Images", path: ".github/workflows/runtime-images.yml", event, @@ -899,6 +900,7 @@ async function runDispatcher({ visibilityResponse = null, filesFailurePr = null, postFailureVisible = false, postFailureStatus = null, fanoutCutoffAfterInventory = false, fanoutCutoffAfterPreviewPr = null, expireAfterFirstApiRequest = false, pullGetFailures = {}, lateProducer = null, runtimeWorkflowLookupFailures = [], + pullListResponse = null, apiRequestMillis = 0, runtimeRunOverrides = {}, initialTime = "2026-01-08T00:00:00Z", }) { const dispatches = []; @@ -911,9 +913,11 @@ async function runDispatcher({ const inventoryCalls = []; const observationPostCounts = []; const timerPostCounts = []; + const timerDelays = []; const deadlineSignals = []; const apiRequestRecords = []; const lateProducers = []; + const runtimeRunReads = []; let lateProducerAdded = false; let runtimeWorkflowLookupCount = 0; let waitedMillis = 0; @@ -972,7 +976,7 @@ async function runDispatcher({ assert(deadlineSignals.includes(options.request.signal), `${name} must use the actual extracted deadline helper`); assert(Number.isSafeInteger(options.request.signal.timeoutMs) && options.request.signal.timeoutMs > 0, `${name} must receive a positive remaining wall-clock deadline`); - apiRequestRecords.push({name, options, abortedAtIssue: options.request.signal.aborted}); + apiRequestRecords.push({name, options, issuedAt: fakeNow, abortedAtIssue: options.request.signal.aborted}); if (expireOnFirstRequest) { expireOnFirstRequest = false; fakeNow += options.request.signal.timeoutMs; @@ -981,6 +985,7 @@ async function runDispatcher({ error.name = "TimeoutError"; throw error; } + fakeNow += apiRequestMillis; return options.request.signal; }; const github = { @@ -1002,9 +1007,11 @@ async function runDispatcher({ list: async (request) => { recordApiRequest("pulls.list", request); pullListRequests.push(request); - return { data: (request.head ? sourceTuples : tuples) + const pulls = (request.head ? sourceTuples : tuples) .filter((tuple) => request.head || tuple.baseRef === request.base) - .map(pullRequestFor) }; + .map(pullRequestFor); + return { data: pullListResponse ? pullListResponse(request, pulls) + : pulls.slice((request.page - 1) * 100, request.page * 100) }; }, get: async (request) => { recordApiRequest("pulls.get", request); @@ -1028,7 +1035,8 @@ async function runDispatcher({ recordApiRequest("pulls.listFiles", request); const {pull_number} = request; if (String(pull_number) === filesFailurePr) throw new Error("fixture changed-files lookup failed"); - return { data: filesByPr[String(pull_number)] ?? [{ filename: "services/example/src/Main.java" }] }; + const files = filesByPr[String(pull_number)] ?? [{ filename: "services/example/src/Main.java" }]; + return { data: files.slice((request.page - 1) * 100, request.page * 100) }; }, }, repos: { @@ -1080,16 +1088,37 @@ async function runDispatcher({ if (workflow_id === "runtime-images.yml") { runtimeWorkflowLookupCount += 1; const failure = runtimeWorkflowLookupFailures[runtimeWorkflowLookupCount - 1]; - if (failure) throw Object.assign(new Error("fixture producer workflow lookup failed"), {status: failure}); + if (failure) throw Object.assign(new Error("fixture producer workflow lookup failed"), + typeof failure === "number" ? {status: failure} : failure); return {data: {id: 701, path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images"}}; } return {data: {id: ciRun.workflow_id, path: ".github/workflows/ci.yml", name: "CI — Validation", ...(ciEvidence.workflow ?? {})}}; }, getWorkflowRun: async (request) => { recordApiRequest("actions.getWorkflowRun", request); + if (request.run_id !== ciRun.id) { + runtimeRunReads.push(request.run_id); + const reads = runtimeRunReads.filter(id => id === request.run_id).length; + const runs = [...Object.values(inventories).flatMap(inventory => Array.isArray(inventory) + ? inventory : [...(inventory.initial ?? inventory.runs ?? []), ...(inventory.refined ?? [])]), + ...lateProducers, ...postedRuns]; + const run = runs.find(run => run?.id === request.run_id); + assert(run, "native runtime lookup must target an inventoried producer"); + const override = runtimeRunOverrides[request.run_id]; + return {data: {...run, ...(typeof override === "function" ? override(reads, run) : override ?? {})}}; + } ciRunReads += 1; return { data: { ...ciRun, ...(ciEvidence.run ?? {}), ...(ciRunReads > 1 ? ciEvidence.latest ?? {} : {}) } }; }, + listJobsForWorkflowRunAttempt: async (request) => { + recordApiRequest("actions.listJobsForWorkflowRunAttempt", request); + ciJobRequests.push(request); + const jobs = ciEvidence.jobs ?? [ciGate]; + return {data: ciEvidence.jobPage ? ciEvidence.jobPage(request, jobs) : { + total_count: jobs.length, + jobs: jobs.slice((request.page - 1) * 100, request.page * 100), + }}; + }, listWorkflowRuns: async (request) => { recordApiRequest("actions.listWorkflowRuns", request); inventoryCalls.push(request); @@ -1145,15 +1174,6 @@ async function runDispatcher({ }, }, }, - paginate: async (endpoint, request, map) => { - if (typeof endpoint === "string") { - assert.equal(endpoint, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); - recordApiRequest("paginate.jobs", request); - ciJobRequests.push(request); - return ciEvidence.jobs ?? [ciGate]; - } - return map(await endpoint(request)); - }, }; const context = { repo: { owner: "owner", repo: "repo" }, @@ -1182,6 +1202,7 @@ async function runDispatcher({ }; global.setTimeout = (resolve, millis) => { timerPostCounts.push(dispatches.filter(item => item.event_type === "pr-runtime-base-refresh").length); + timerDelays.push(millis); waitedMillis += millis; fakeNow += millis; resolve(); @@ -1201,7 +1222,7 @@ async function runDispatcher({ } return { dispatches, errors, infos, warnings, inventoryCalls, observationPostCounts, timerPostCounts, waitedMillis, ciJobRequests, pullListRequests, pullReads, refRequests, deadlineSignals, apiRequestRecords, - runtimeWorkflowLookupCount, fatalError }; + runtimeWorkflowLookupCount, runtimeRunReads, timerDelays, fatalError }; } (async () => { @@ -1210,7 +1231,9 @@ async function runDispatcher({ const previewDispatches = (result) => result.dispatches.filter((item) => item.event_type === "preview-deploy"); const assertRequestContracts = (result) => { assert.equal(result.fatalError, null, "the mocked dispatcher must complete unless a deadline-abort fixture is selected"); - for (const {name, options} of result.apiRequestRecords) { + assert.equal(new Set(result.apiRequestRecords.map(({options}) => options.request.signal)).size, + result.apiRequestRecords.length, "every direct API request must receive a fresh deadline signal"); + for (const {name, options, issuedAt} of result.apiRequestRecords) { const request = options.request; const oneShot = name === "repos.createDispatchEvent"; assert.deepEqual(Object.keys(request).sort(), oneShot ? ["retries", "signal"] : ["signal"], @@ -1220,6 +1243,8 @@ async function runDispatcher({ assert(result.deadlineSignals.includes(request.signal), `${name} must use a source-derived AbortSignal timeout`); assert(Number.isSafeInteger(request.signal.timeoutMs) && request.signal.timeoutMs > 0, `${name} must receive a positive remaining wall-clock deadline`); + assert.equal(request.signal.timeoutMs, request.signal.deadline - issuedAt, + `${name} must refresh its timeout at the actual page request boundary`); assert.equal(result.apiRequestRecords.find((call) => call.name === name && call.options === options).abortedAtIssue, false, `${name} must not issue a request with an already-expired signal`); } @@ -1240,11 +1265,64 @@ async function runDispatcher({ } assert.equal(reconcile.ciJobRequests.length, 1, "PR callbacks require one exact current native CI attempt jobs request"); const {request: ciJobRequestOptions, ...ciJobRequest} = reconcile.ciJobRequests[0]; - assert.deepEqual(ciJobRequest, { owner: "owner", repo: "repo", run_id: 7001, attempt_number: 1, per_page: 100 }, + assert.deepEqual(ciJobRequest, { owner: "owner", repo: "repo", run_id: 7001, attempt_number: 1, per_page: 100, page: 1 }, "PR callbacks require the exact current native CI attempt jobs request shape"); assert.deepEqual(Object.keys(ciJobRequestOptions).sort(), ["signal"], "CI job listing carries only its AbortSignal request option"); assert.equal(reconcile.deadlineSignals[0].timeoutMs, 12 * 60 * 1000, "the first fan-out API call receives the full wall-clock budget"); assertRequestContracts(reconcile); + const pagedFiles = [...Array.from({length: 100}, (_, index) => ({filename: `docs/page-${index}.md`})), + {filename: "services/example/src/Main.java"}]; + const pagedCiJobs = (request, jobs) => { + const completeJobs = [...Array.from({length: 100}, (_, index) => ({id: 8100 + index, name: "Other job"})), ...jobs]; + return {total_count: completeJobs.length, jobs: completeJobs.slice((request.page - 1) * 100, request.page * 100)}; + }; + const pagedFanout = await runDispatcher({ + tuples: [child], sourceTuples: [source], callback: prCallback, apiRequestMillis: 25, + pullListResponse: (request, pulls) => [ + ...Array.from({length: 100}, (_, index) => ({number: 2000 + index, state: "closed"})), ...pulls, + ].slice((request.page - 1) * 100, request.page * 100), + filesByPr: {[source.prNumber]: pagedFiles}, + pullOverrides: {[source.prNumber]: {changed_files: pagedFiles.length}}, + ciEvidence: {jobPage: pagedCiJobs}, + }); + assert.deepEqual(runtimeDispatches(pagedFanout).map(item => item.client_payload.pr_number).sort(), + [source.prNumber, child.prNumber].sort(), "page-two source, dependent, CI gate and runtime file evidence must all be retained"); + assert.deepEqual(pagedFanout.errors, []); + const assertFanoutPages = (requests, expectedScope) => { + assert.deepEqual(requests.map(({request, ...scope}) => scope), [1, 2].map(page => ({ + owner: "owner", repo: "repo", ...expectedScope, per_page: 100, page, + })), "direct page requests must preserve their exact API scope"); + assert(requests[1].request.signal.timeoutMs < requests[0].request.signal.timeoutMs, + "later pages must receive only the remaining fan-out budget, not a reused timeout"); + assert.equal(requests[0].request.signal.deadline, requests[1].request.signal.deadline, + "pagination cannot extend the shared fan-out deadline"); + }; + assertFanoutPages(pagedFanout.ciJobRequests, {run_id: 7001, attempt_number: 1}); + assertFanoutPages(pagedFanout.pullListRequests.filter(request => request.base), {state: "open", base: source.headRef}); + assertFanoutPages(pagedFanout.pullListRequests.filter(request => request.head), {state: "open", head: `owner:${source.headRef}`}); + assertFanoutPages(pagedFanout.apiRequestRecords.filter(({name, options}) => + name === "pulls.listFiles" && String(options.pull_number) === source.prNumber).map(({options}) => options), + {pull_number: Number(source.prNumber)}); + assertRequestContracts(pagedFanout); + for (const jobPage of [ + () => ({total_count: 1, jobs: []}), + () => ({total_count: 1, jobs: {}}), + (request, jobs) => request.page === 1 ? pagedCiJobs(request, jobs) + : {total_count: 102, jobs: [jobs[0], {id: 9999, name: "Other job"}]}, + ]) { + await assert.rejects(runDispatcher({tuples: [child], sourceTuples: [source], callback: prCallback, + ciEvidence: {jobPage}}), /Exact source CI attempt job inventory is incomplete or inconsistent/, + "short, malformed or shifted exact-attempt job pages cannot authorize dispatch"); + } + const cutoffJobPages = []; + await assert.rejects(runDispatcher({ + tuples: [child], sourceTuples: [source], callback: prCallback, apiRequestMillis: 4 * 60 * 1000, + ciEvidence: {jobPage: (request, jobs) => { + cutoffJobPages.push(request.page); + return pagedCiJobs(request, jobs); + }}, + }), /Runtime fan-out deadline reached; request not issued/); + assert.deepEqual(cutoffJobPages, [1], "a completed first page at the cutoff must not issue page two or reach a handoff"); for (const branch of ["main", "develop", "feature/parent"]) { const branchSource = { ...source, headRef: branch, baseRef: branch === "develop" ? "main" : "develop" }; const dependent = { ...child, baseRef: branch }; @@ -1737,6 +1815,92 @@ async function runDispatcher({ }); assert.equal(numbers(result).length, expected, "completed refresh suppresses an earlier or same-second signal"); } + const terminalTyped = conclusion => producer(tuple, "repository_dispatch", "completed", conclusion, { + created_at: "2026-01-03T00:00:00Z", + }); + for (const conclusion of ["cancelled", "timed_out"]) { + const existing = terminalTyped(conclusion); + for (const signalAt of ["2026-01-02T00:00:00Z", "2026-01-03T00:00:00.200Z", "2026-01-04T00:00:00Z"]) { + const replaced = await runDispatcher({tuples: [tuple], callback: {updated_at: signalAt}, + inventories: {repository_dispatch: [existing]}, + }); + assert.deepEqual(numbers(replaced), ["101"], `${conclusion} exact typed producer permits only one replacement`); + assert.deepEqual(replaced.runtimeRunReads, [existing.id, existing.id], + "both initial selection and the final pre-POST fence require fresh native terminal-attempt proof"); + assert.equal(previewDispatches(replaced).length, 1, "terminal runtime recovery retains independent preview handoff"); + assert.deepEqual(replaced.errors, []); + assertRequestContracts(replaced); + } + const unresolved = await runDispatcher({tuples: [tuple], callback: {updated_at: "2026-01-02T00:00:00Z"}, + inventories: {repository_dispatch: [existing]}, postFailurePr: "101", + }); + assert.deepEqual(numbers(unresolved), ["101"], "an unresolved replacement POST is never issued a second time"); + assert.equal(unresolved.waitedMillis, 120000); + assert(unresolved.errors.some(message => message.includes("attempted but visibility is unknown")), + "the old terminal run cannot confirm receipt of its replacement"); + } + for (const conclusion of ["failure", "success", null]) { + const held = await runDispatcher({tuples: [tuple], callback: {updated_at: "2026-01-02T00:00:00Z"}, + inventories: {repository_dispatch: [terminalTyped(conclusion)]}, + }); + assert.deepEqual(numbers(held), [], + "legacy failure/PLAY, success and unknown dispositions keep the existing typed refresh hold"); + assert.deepEqual(held.runtimeRunReads, [], "this narrow rule must not classify other terminal PLAY outcomes"); + assert.deepEqual(held.errors, []); + } + const cancelledTyped = terminalTyped("cancelled"); + for (const changed of [ + {run_attempt: 2}, {run_attempt: 0}, {run_attempt: null}, {id: cancelledTyped.id + 1}, + {repository: {full_name: "other/repo"}}, {head_repository: {full_name: "fork/repo"}}, + {workflow_id: 999}, {path: ".github/workflows/other.yml"}, {event: "pull_request"}, + {name: "Other workflow"}, {display_title: "different tuple"}, {head_branch: "feature/ci"}, + {head_sha: sha("f")}, {created_at: "2026-01-03T00:00:01Z"}, + {status: "in_progress", conclusion: null}, {conclusion: "timed_out"}, {conclusion: "failure"}, + ]) { + for (const failedRead of [1, 2]) { + const changedNative = await runDispatcher({tuples: [tuple], callback: {updated_at: "2026-01-02T00:00:00Z"}, + inventories: {repository_dispatch: [cancelledTyped]}, + runtimeRunOverrides: {[cancelledTyped.id]: reads => reads === failedRead ? changed : {}}, + }); + assert.deepEqual(numbers(changedNative), [], "changed native evidence at either admission read prevents replacement"); + assert.equal(changedNative.runtimeRunReads.length, failedRead); + assert(changedNative.errors.some(message => message.includes("same trusted terminal attempt"))); + assertRequestContracts(changedNative); + } + } + for (const failedRead of [1, 2]) { + const unavailableNative = await runDispatcher({tuples: [tuple], + inventories: {repository_dispatch: [cancelledTyped]}, + runtimeRunOverrides: {[cancelledTyped.id]: reads => { + if (reads === failedRead) throw Object.assign(new Error("terminal native lookup unavailable"), {status: 503}); + return {}; + }}, + }); + assert.deepEqual(numbers(unavailableNative), [], "unavailable native evidence is not replacement authority"); + assert(unavailableNative.errors.some(message => message.includes("terminal native lookup unavailable"))); + const unavailableWorkflow = await runDispatcher({tuples: [tuple], + inventories: {repository_dispatch: [cancelledTyped]}, + runtimeWorkflowLookupFailures: failedRead === 1 ? [503] : [null, 503], + }); + assert.deepEqual(numbers(unavailableWorkflow), [], "canonical workflow lookup must succeed at both admission fences"); + assert(unavailableWorkflow.errors.some(message => message.includes("fixture producer workflow lookup failed"))); + } + const shiftingTerminalInventory = [cancelledTyped]; + const shiftedTerminalAttempt = await runDispatcher({tuples: [tuple], + inventories: {repository_dispatch: shiftingTerminalInventory}, + runtimeRunOverrides: {[cancelledTyped.id]: reads => { + if (reads === 1) shiftingTerminalInventory[0] = {...cancelledTyped, run_attempt: 2}; + return {}; + }}, + }); + assert.deepEqual(numbers(shiftedTerminalAttempt), [], + "a newly listed terminal attempt cannot replace the attempt bound by the first admission read in this callback"); + assert(shiftedTerminalAttempt.errors.some(message => message.includes("incomplete or changed attempt identity"))); + const missingTerminalAttempt = await runDispatcher({tuples: [tuple], + inventories: {repository_dispatch: [{...cancelledTyped, run_attempt: null}]}, + }); + assert.deepEqual(numbers(missingTerminalAttempt), [], "the inventory must identify a positive attempt before native proof lookup"); + assert.deepEqual(missingTerminalAttempt.runtimeRunReads, []); const invisible = await runDispatcher({ tuples: [tuple], hideDispatchVisibility: true }); assert.deepEqual(numbers(invisible), ["101"], "accepted invisible POST must never be repeated"); assert(invisible.errors.some(message => message.includes("visibility is unknown"))); @@ -1809,8 +1973,69 @@ async function runDispatcher({ assert.equal(expiredProducerIdentity.waitedMillis, 120000); assert(expiredProducerIdentity.errors.some(message => message.includes("visibility deadline"))); assertRequestContracts(expiredProducerIdentity); + const visibilityEpoch = Date.parse("2026-01-08T00:00:00Z"); + const rateLimitError = (status, headers = {}, message = "fixture read refusal") => ({ + status, message, response: {status, headers, data: {message}}, + }); + for (const [label, failure, expectedDelay] of [ + ["Retry-After seconds overrides primary reset", rateLimitError(403, {"retry-after": "7", + "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(visibilityEpoch / 1000 + 90)}), 7000], + ["Retry-After HTTP date", rateLimitError(429, {"retry-after": new Date(visibilityEpoch + 12000).toUTCString()}), 12000], + ["exhausted primary reset", rateLimitError(403, {"x-ratelimit-remaining": "0", + "x-ratelimit-reset": String(visibilityEpoch / 1000 + 90)}), 90000], + ["malformed Retry-After falls back to primary reset", rateLimitError(403, {"retry-after": "tomorrow", + "x-ratelimit-remaining": "0", "x-ratelimit-reset": String(visibilityEpoch / 1000 + 10)}), 10000], + ["429 without guidance", rateLimitError(429), 60000], + ["secondary limit without guidance", rateLimitError(403, {}, "You have exceeded a secondary rate limit."), 60000], + ["abuse limit without guidance", rateLimitError(403, {}, "abuse detection mechanism"), 60000], + ["primary limit with unusable reset", rateLimitError(403, {"x-ratelimit-remaining": "0", + "x-ratelimit-reset": "invalid"}), 60000], + ]) { + for (const phase of ["identity", "inventory"]) { + let reads = 0; + const recovered = await runDispatcher({tuples: [tuple], + ...(phase === "identity" ? {runtimeWorkflowLookupFailures: [failure]} : { + visibilityResponse: (_request, posted) => { + if (++reads === 1) throw failure; + return {total_count: posted.length, workflow_runs: posted}; + }, + }), + }); + assert.deepEqual(numbers(recovered), ["101"], `${phase}: ${label} must retry only GET observation`); + assert.deepEqual(recovered.timerDelays, [expectedDelay], `${phase}: ${label} must honor GitHub REST delay guidance`); + assert.equal(phase === "identity" ? recovered.runtimeWorkflowLookupCount : reads, 2); + assert.deepEqual(recovered.errors, [], `${phase}: ${label} can confirm the one handoff after waiting`); + assertRequestContracts(recovered); + } + } + for (const phase of ["identity", "inventory"]) { + let reads = 0; + const beyondDeadline = rateLimitError(429, {"retry-after": "300"}); + const exhausted = await runDispatcher({tuples: [tuple], + ...(phase === "identity" ? {runtimeWorkflowLookupFailures: [beyondDeadline]} : { + visibilityResponse: () => { reads += 1; throw beyondDeadline; }, + }), + }); + assert.deepEqual(numbers(exhausted), ["101"], "a rate limit cannot repeat the accepted POST"); + assert.deepEqual(exhausted.timerDelays, [120000], "rate-limit waiting cannot extend the shared visibility deadline"); + assert.equal(phase === "identity" ? exhausted.runtimeWorkflowLookupCount : reads, 1, + "a Retry-After beyond the remaining budget must not issue another GET"); + assert(exhausted.errors.some(message => message.includes(phase === "identity" ? "visibility deadline" : "visibility is unknown"))); + } + let sharedQuotaReads = 0; + const sharedQuotaDeadline = await runDispatcher({tuples: [tuple], + runtimeWorkflowLookupFailures: [rateLimitError(403, {}, "secondary rate limit")], + visibilityResponse: () => { sharedQuotaReads += 1; throw rateLimitError(429); }, + }); + assert.deepEqual(numbers(sharedQuotaDeadline), ["101"]); + assert.deepEqual(sharedQuotaDeadline.timerDelays, [60000, 60000], + "rate-limit waits are capped by the same deadline across identity and inventory GETs"); + assert.equal(sharedQuotaReads, 1); + assert(sharedQuotaDeadline.errors.some(message => message.includes("visibility is unknown"))); for (const [failure, reason] of [ [() => { throw Object.assign(new Error("visibility forbidden"), {status: 403}); }, "visibility forbidden"], + [() => { throw rateLimitError(403, {"retry-after": "invalid", "x-ratelimit-remaining": "1", + "x-ratelimit-reset": String(visibilityEpoch / 1000 + 10)}, "permission denied"); }, "permission denied"], [() => ({total_count: 1, workflow_runs: []}), "recent run inventory is incomplete"], ]) { const terminal = await runDispatcher({tuples: transientTuples, visibilityResponse: failure}); @@ -1836,14 +2061,28 @@ async function runDispatcher({ assert.deepEqual(numbers(conflicting), ["101"], "a conflicting native identity never retries the POST"); assert(conflicting.errors.some(error => error.includes("untrusted native workflow identity"))); } + let shiftedObservationReads = 0; const shiftedObservation = await runDispatcher({tuples: [tuple], visibilityResponse: ({page}, [posted]) => ({ - total_count: page === 1 ? 101 : 102, + total_count: ++shiftedObservationReads === 1 ? 101 : 102, workflow_runs: page === 1 ? Array.from({length: 100}, (_, index) => ({ ...posted, id: 700000 + index, display_title: "unrelated" - })) : [posted], + })) : [posted, {...posted, id: 800000, display_title: "new unrelated run"}], })}); assert.deepEqual(numbers(shiftedObservation), ["101"], "a shifting observation inventory never retries the accepted POST"); - assert(shiftedObservation.errors.some(error => error.includes("visibility is uncertain"))); + assert.deepEqual(shiftedObservation.inventoryCalls.filter(request => request.created === visibilityFloor).map(request => request.page), + [1, 2, 1, 2], "discard shifted pages, reread from page one, then confirm the complete stable two-page inventory"); + assert.equal(shiftedObservation.waitedMillis, 5000); + assert.deepEqual(shiftedObservation.errors, [], "a consistent complete reread confirms visibility without another POST"); + const shortPageObservation = await runDispatcher({tuples: [tuple], visibilityResponse: ({page}, [posted]) => ({ + total_count: 102, + workflow_runs: page === 1 ? Array.from({length: 100}, (_, index) => ({ + ...posted, id: 700000 + index, display_title: "unrelated" + })) : [posted], + })}); + assert.deepEqual(numbers(shortPageObservation), ["101"], "a short second page never retries the accepted POST"); + assert.deepEqual(shortPageObservation.inventoryCalls.filter(request => request.created === visibilityFloor).map(request => request.page), [1, 2]); + assert.equal(shortPageObservation.waitedMillis, 0, "a short page for its own total is terminal, not pagination drift"); + assert(shortPageObservation.errors.some(error => error.includes("recent run inventory is incomplete"))); const staleObservation = await runDispatcher({tuples: [tuple], visibilityResponse: (_request, [posted]) => ({ total_count: 1, workflow_runs: [{...posted, created_at: "2026-01-07T23:59:58Z"}], })}); diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 6f6e1d85b7..3b7b0c1102 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -230,11 +230,13 @@ const refreshDeadline = refreshNow + 12 * 60 * 1000; const refreshSignals = []; const refreshRequests = []; const runtimeSelector = refreshSelector( - {rest: {pulls: {listFiles: "listFiles"}}, paginate: async (_endpoint, request) => { + {rest: {pulls: {listFiles: async request => { refreshRequests.push(request); refreshNow += 250; - return refreshEntries; - }}, + assert.equal(request.per_page, 100); + assert.equal(request.page, 1); + return {data: refreshEntries}; + }}}}, {repo: {}, payload: {}}, {warning: () => {}}, {now: () => refreshNow}, @@ -250,9 +252,9 @@ async function refreshDecision(paths) { const nowBeforeRequest = refreshNow; const hasRuntimeChange = await runtimeSelector; const result = await hasRuntimeChange({number: 42, changed_files: refreshEntries.length}); - assert.equal(refreshRequests.length, requestIndex + 1, "changed-file selection performs exactly one paginated API request"); + assert.equal(refreshRequests.length, requestIndex + 1, "changed-file selection performs exactly one direct page request for a short inventory"); const {request, ...normalOptions} = refreshRequests[requestIndex]; - assert.deepEqual(normalOptions, {pull_number: 42, per_page: 100}, "changed-file request preserves its exact normal option shape"); + assert.deepEqual(normalOptions, {pull_number: 42, per_page: 100, page: 1}, "changed-file request preserves its exact normal option shape"); assert.deepEqual(Object.keys(request).sort(), ["signal"], "changed-file request has only the source-derived AbortSignal option"); assert.equal(request.signal, refreshSignals.at(-1)); assert.equal(request.signal.timeoutMs, refreshDeadline - nowBeforeRequest, @@ -408,10 +410,15 @@ const gate = { {name: "Enforce validation success", status: "completed", conclusion: "success"}, ], }; +const typedRefresh = { + ...source, id: 8500, event: "repository_dispatch", head_branch: "develop", head_sha: base, + status: "completed", conclusion: "cancelled", created_at: "2026-01-08T00:00:00Z", +}; async function runReconcile({ ambiguousPost = true, expireFirstRequest = false, initialDiscoveryUnavailable = false, ciRuns = [ciRun], ciNativeRuns = {}, ciJobsByRun = {}, postVisibilityRuns = null, + postVisibilityFailures = [], preflightRefreshRuns = [], refreshNativeRuns = {}, } = {}) { let now = Date.parse("2026-01-08T00:00:00Z"); let expire = expireFirstRequest; @@ -421,6 +428,8 @@ async function runReconcile({ const requests = []; const inventoryRequests = []; const nativeJobRunIds = []; + const nativeRefreshRunIds = []; + const nativeRefreshReadCounts = new Map(); const signals = []; const dispatchRequests = []; const warnings = []; @@ -482,7 +491,30 @@ async function runReconcile({ }, getWorkflowRun: async options => { record("actions.getWorkflowRun", options, {owner, repo, run_id: options.run_id}); - return {data: options.run_id === source.id ? source : ciNativeRuns[options.run_id] ?? ciRun}; + if (options.run_id === source.id) return {data: source}; + const refresh = preflightRefreshRuns.find(run => run.id === options.run_id); + if (refresh || Object.hasOwn(refreshNativeRuns, options.run_id)) { + nativeRefreshRunIds.push(options.run_id); + const readIndex = nativeRefreshReadCounts.get(options.run_id) ?? 0; + nativeRefreshReadCounts.set(options.run_id, readIndex + 1); + const responses = Object.hasOwn(refreshNativeRuns, options.run_id) + ? refreshNativeRuns[options.run_id] : refresh; + const response = Array.isArray(responses) ? responses[Math.min(readIndex, responses.length - 1)] : responses; + if (response instanceof Error) throw response; + return {data: response}; + } + return {data: ciNativeRuns[options.run_id] ?? ciRun}; + }, + listJobsForWorkflowRunAttempt: async options => { + const {run_id, attempt_number, page} = options; + record("actions.listJobsForWorkflowRunAttempt", options, { + owner, repo, run_id, attempt_number, per_page: 100, page, + }); + assert.equal(attempt_number, (ciNativeRuns[run_id] ?? ciRun).run_attempt); + assert(Number.isInteger(page) && page > 0); + nativeJobRunIds.push(run_id); + const jobs = ciJobsByRun[run_id] ?? [gate]; + return {data: {total_count: jobs.length, jobs: jobs.slice((page - 1) * 100, page * 100)}}; }, listWorkflowRuns: async options => { const {workflow_id: workflowId, event, head_sha: requestedHead, created, per_page, page} = options; @@ -498,8 +530,18 @@ async function runReconcile({ } let runs = []; if (workflowId === "ci.yml") runs = ciRuns; - if (workflowId === "runtime-images.yml" && event === "repository_dispatch" && visibleRun) { - runs = postVisibilityRuns ?? [visibleRun]; + if (workflowId === "runtime-images.yml" && event === "repository_dispatch") { + if (visibleRun) { + const failure = postVisibilityFailures.shift(); + if (failure) { + throw Object.assign(new Error("fixture visibility failure"), { + status: failure.status, response: {headers: failure.headers}, + }); + } + runs = postVisibilityRuns ?? [visibleRun]; + } else { + runs = preflightRefreshRuns; + } } return {data: {total_count: runs.length, workflow_runs: runs}}; }, @@ -540,14 +582,7 @@ async function runReconcile({ }, }, }, - paginate: async (route, options) => { - assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs"); - record("paginate.jobs", options, { - owner, repo, run_id: options.run_id, attempt_number: options.attempt_number, per_page: 100, - }); - nativeJobRunIds.push(options.run_id); - return ciJobsByRun[options.run_id] ?? [gate]; - }, + }; let failure = null; try { @@ -556,7 +591,7 @@ async function runReconcile({ } catch (error) { failure = error; } - return {failure, now, requests, signals, inventoryRequests, nativeJobRunIds, + return {failure, now, requests, signals, inventoryRequests, nativeJobRunIds, nativeRefreshRunIds, dispatchRequests, postAttempts, warnings, infos}; } @@ -589,6 +624,30 @@ async function runReconcile({ assertExactPostVisibilityFilter(uncertainPost); assert(uncertainPost.requests.every(({signal}) => signal.timeoutMs > 0), "every mocked GitHub request receives a positive wall-clock AbortSignal budget"); + const rateLimitedVisibility = await runReconcile({ + postVisibilityFailures: [{status: 403, headers: {"retry-after": "20"}}], + }); + assert.equal(rateLimitedVisibility.failure, null); + assert.equal(rateLimitedVisibility.now - uncertainPost.now, 20000); + assertExactPostVisibilityFilter(rateLimitedVisibility); + const deniedVisibility = await runReconcile({postVisibilityFailures: [{status: 403}]}); + assert.match(deniedVisibility.failure?.message, /fixture visibility failure/); + assert.equal(deniedVisibility.now, uncertainPost.now); + assertExactPostVisibilityFilter(deniedVisibility); + const retriedVisibilityDeadline = await runReconcile({ + postVisibilityFailures: [{status: 429, headers: {"retry-after": "300"}}], + }); + assert.match(retriedVisibilityDeadline.failure?.message, /visibility is unknown/); + assert.equal(retriedVisibilityDeadline.now, uncertainPost.now + 120000); + assertExactPostVisibilityFilter(retriedVisibilityDeadline); + const pagedJobs = await runReconcile({ + ciJobsByRun: {[ciRun.id]: [...Array.from({length: 100}, (_, i) => ({id: 500 + i, name: "Sibling"})), gate]}, + }); + assert.equal(pagedJobs.failure, null); + const jobPages = pagedJobs.requests.filter(row => row.name === "actions.listJobsForWorkflowRunAttempt"); + assert.deepEqual(jobPages.map(row => row.options.page), [1, 2, 1, 2]); + assert.equal(new Set(jobPages.map(row => row.signal)).size, jobPages.length); + assert.equal(pagedJobs.postAttempts, 1); const sameSecondVisible = await runReconcile({ postVisibilityRuns: [{ id: 9001, workflow_id: 777, run_attempt: 1, @@ -618,6 +677,97 @@ async function runReconcile({ request.created === postVisibilityFloor ).length, 24, "out-of-filter stale evidence remains unaccepted throughout the bounded observation window"); assertExactPostVisibilityFilter(stalePostVisibility); + for (const conclusion of ["cancelled", "timed_out"]) { + for (const ambiguousPost of [false, true]) { + const unusable = {...typedRefresh, conclusion, run_attempt: 2}; + const recovered = await runReconcile({preflightRefreshRuns: [unusable], ambiguousPost}); + assert.equal(recovered.failure, null, `verified ${conclusion} typed refresh must not suppress recovery`); + assert.deepEqual(recovered.nativeRefreshRunIds, [unusable.id, unusable.id], + "both initial and final preflight must freshly verify the same positive native attempt"); + const nativeReads = recovered.requests.filter(row => + row.name === "actions.getWorkflowRun" && row.options.run_id === unusable.id); + assert.equal(new Set(nativeReads.map(row => row.signal)).size, 2, + "each terminal-result verification uses a fresh pre-dispatch deadline signal"); + assert.equal(recovered.dispatchRequests.length, 1); + assertExactPostVisibilityFilter(recovered); + } + } + const combinedUnusable = await runReconcile({preflightRefreshRuns: [ + typedRefresh, {...typedRefresh, id: typedRefresh.id + 1, conclusion: "timed_out"}, + ]}); + assert.equal(combinedUnusable.failure, null); + assert.deepEqual(combinedUnusable.nativeRefreshRunIds, + [typedRefresh.id, typedRefresh.id + 1, typedRefresh.id, typedRefresh.id + 1], + "every exact terminal candidate must be freshly verified at both preflight fences"); + assertExactPostVisibilityFilter(combinedUnusable); + for (const change of [ + {id: typedRefresh.id + 1}, {run_attempt: 0}, {run_attempt: 2}, {workflow_id: 778}, + {path: ".github/workflows/other.yml"}, {path: `${typedRefresh.path}@refs/heads/develop`}, + {name: "other"}, {name: sourceTitle}, {display_title: sourceTitle.replace(base, sha("d"))}, + {event: "pull_request"}, {repository: {full_name: "fork/FireMUD"}}, + {head_repository: {full_name: "fork/FireMUD"}}, {head_branch: "feature/ci"}, + {head_sha: sha("d")}, {head_sha: "invalid"}, {status: "in_progress", conclusion: null}, + {status: undefined}, {conclusion: "timed_out"}, {conclusion: "failure"}, + {conclusion: "success"}, {conclusion: undefined}, + ]) { + const drifted = await runReconcile({ + preflightRefreshRuns: [typedRefresh], refreshNativeRuns: {[typedRefresh.id]: {...typedRefresh, ...change}}, + }); + assert.equal(drifted.failure, null); + assert.equal(drifted.postAttempts, 0, `native terminal-result drift must retain the hold: ${JSON.stringify(change)}`); + assert.deepEqual(drifted.nativeRefreshRunIds, [typedRefresh.id], "unproven native evidence is never retried"); + assert(drifted.warnings.some(message => message.includes("unproven or superseded"))); + } + const finalPreflightDrift = await runReconcile({ + preflightRefreshRuns: [typedRefresh], + refreshNativeRuns: {[typedRefresh.id]: [typedRefresh, {...typedRefresh, run_attempt: 2}]}, + }); + assert.equal(finalPreflightDrift.failure, null); + assert.equal(finalPreflightDrift.postAttempts, 0, "a superseding attempt at the final native fence retains the hold"); + assert.deepEqual(finalPreflightDrift.nativeRefreshRunIds, [typedRefresh.id, typedRefresh.id]); + for (const unavailable of [undefined, null, ...[403, 404, 503].map(status => + Object.assign(new Error("fixture native terminal evidence unavailable"), {status}))]) { + const held = await runReconcile({ + preflightRefreshRuns: [typedRefresh], refreshNativeRuns: {[typedRefresh.id]: unavailable}, + }); + assert.equal(held.failure, null); + assert.equal(held.postAttempts, 0, "unavailable native terminal evidence cannot authorize recovery"); + assert.deepEqual(held.nativeRefreshRunIds, [typedRefresh.id], "unavailable verification is not retried"); + assert(held.warnings.some(message => message.includes("recovery remains held without retry"))); + } + for (const change of [ + {status: "queued", conclusion: null}, {status: "in_progress", conclusion: null}, + {status: "completed", conclusion: "success"}, {status: "completed", conclusion: "skipped"}, + {status: "completed", conclusion: null}, + ]) { + const held = await runReconcile({preflightRefreshRuns: [{...typedRefresh, ...change}]}); + assert.equal(held.failure, null); + assert.equal(held.postAttempts, 0, "all other exact typed results continue suppressing recovery"); + assert.deepEqual(held.nativeRefreshRunIds, [], "only cancelled/timed_out results enter native verification"); + } + const legacyFailedPlay = {...typedRefresh, id: typedRefresh.id + 1, conclusion: "failure"}; + const legacyFailureHold = await runReconcile({preflightRefreshRuns: [typedRefresh, legacyFailedPlay]}); + assert.equal(legacyFailureHold.failure, null); + assert.equal(legacyFailureHold.postAttempts, 0, + "a legacy failed PLAY typed refresh retains its hold even alongside a verified cancelled result"); + assert.deepEqual(legacyFailureHold.nativeRefreshRunIds, [typedRefresh.id]); + assert(legacyFailureHold.warnings.some(message => message.includes(String(legacyFailedPlay.id)) && + message.includes("failed") && message.includes("explicit investigation, not automatic replay")), + "legacy failure holds must be reported separately from supported terminal recovery"); + const preexistingUnusableReceipt = await runReconcile({ + preflightRefreshRuns: [typedRefresh], postVisibilityRuns: [typedRefresh], + }); + assert.match(preexistingUnusableReceipt.failure?.message ?? "", /visibility is unknown/, + "a verified unusable ID in the dispatch second remains in the complete pre-POST snapshot, not a new receipt"); + assert.deepEqual(preexistingUnusableReceipt.nativeRefreshRunIds, [typedRefresh.id, typedRefresh.id], + "post-POST visibility never reclassifies terminal producer outcomes"); + assertExactPostVisibilityFilter(preexistingUnusableReceipt); + for (const conclusion of ["cancelled", "timed_out", "failure"]) { + const terminalReceipt = await runReconcile({postVisibilityRuns: [{...typedRefresh, id: 9001, conclusion}]}); + assert.equal(terminalReceipt.failure, null, `a new exact ${conclusion} run still establishes POST receipt, not success`); + assert.deepEqual(terminalReceipt.nativeRefreshRunIds, [], "receipt must not require a usable terminal producer result"); + assertExactPostVisibilityFilter(terminalReceipt); + } const unavailableInitialDiscovery = await runReconcile({initialDiscoveryUnavailable: true}); assert.match(unavailableInitialDiscovery.failure?.message ?? "", /initial runtime discovery unavailable/); assert.equal(unavailableInitialDiscovery.postAttempts, 0, @@ -647,7 +797,8 @@ async function runReconcile({ "the reconciler starts with its exact two-minute pre-dispatch wall-clock budget"); assert.equal(expiredRequest.requests[0].signal.aborted, true, "the API mock observed the signal expire"); assert.equal(expiredRequest.postAttempts, 0, "deadline abortion fails closed before repository dispatch"); - process.stdout.write("Failed-source reconciliation deadline and one-shot fixtures passed\n"); + process.stdout.write("Failed-source reconciliation terminal-preflight, deadline and one-shot fixtures passed\n"); + process.stdout.write("Legacy failed PLAY hold fixture passed; explicit recovery remains separate\n"); })().catch(error => { console.error(error); process.exitCode = 1; }); JS diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index 3198d679f8..0452f82147 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -10,6 +10,7 @@ import java.util.List; import java.util.Objects; import java.util.UUID; +import javax.sql.DataSource; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.repository.AccountCapacityRefusalBudgetRepository; import net.firedevops.firemud.accountservice.repository.AccountRepository; @@ -19,6 +20,7 @@ import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.configuration.FluentConfiguration; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterAll; @@ -44,21 +46,22 @@ static void stop() { POSTGRES.stop(); } + private static FluentConfiguration capacityMigrations(DataSource data, String schema) { + return Flyway.configure() + .dataSource(data) + .schemas(schema) + .defaultSchema(schema) + .placeholders(java.util.Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + } + @Test void duplicateHistoricalOriginAttemptsStopUpgradeWithoutRewritingEvidence() { String schema = "capacity_duplicate_" + UUID.randomUUID().toString().replace("-", ""); new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); var data = POSTGRES.dataSource(schema); try { - Flyway.configure() - .dataSource(data) - .schemas(schema) - .defaultSchema(schema) - .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .target("1040.1") - .load() - .migrate(); + capacityMigrations(data, schema).target("1040.1").load().migrate(); var dsl = DSL.using(data, SQLDialect.POSTGRES); UUID attempt = UUID.randomUUID(); for (int index = 0; index < 2; index++) { @@ -72,29 +75,12 @@ void duplicateHistoricalOriginAttemptsStopUpgradeWithoutRewritingEvidence() { new byte[] {1}, UUID.randomUUID()); } - Flyway.configure() - .dataSource(data) - .schemas(schema) - .defaultSchema(schema) - .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .target("1040.3") - .load() - .migrate(); + capacityMigrations(data, schema).target("1040.3").load().migrate(); var original = dsl.fetch( "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM account_capacity_origin_decisions ORDER BY decision_id") .intoMaps(); - assertThatThrownBy(() -> - Flyway.configure() - .dataSource(data) - .schemas(schema) - .defaultSchema(schema) - .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .target("1040.4") - .load() - .migrate()) + assertThatThrownBy(() -> capacityMigrations(data, schema).target("1040.4").load().migrate()) .isInstanceOf(org.flywaydb.core.api.FlywayException.class) .hasStackTraceContaining("account_capacity_origin_attempt_unique") .satisfies(failure -> { @@ -121,15 +107,7 @@ void budgetConflictDoesNotMaskRetainedHistoryAndFirstInstallStillChecksIt() { new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); var data = POSTGRES.dataSource(schema); try { - Flyway.configure() - .dataSource(data) - .schemas(schema) - .defaultSchema(schema) - .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .target("1040.1") - .load() - .migrate(); + capacityMigrations(data, schema).target("1040.1").load().migrate(); var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); var tenant = source(); @@ -147,14 +125,7 @@ void budgetConflictDoesNotMaskRetainedHistoryAndFirstInstallStillChecksIt() { new byte[] {1}, UUID.randomUUID()); } - Flyway.configure() - .dataSource(data) - .schemas(schema) - .defaultSchema(schema) - .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .load() - .migrate(); + capacityMigrations(data, schema).load().migrate(); var budgets = new AccountCapacityRefusalBudgetRepository(dsl); assertThatThrownBy(() -> transaction.executeWithoutResult( @@ -236,15 +207,7 @@ void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); var data = POSTGRES.dataSource(schema); try { - Flyway.configure() - .dataSource(data) - .schemas(schema) - .defaultSchema(schema) - .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .target("1038") - .load() - .migrate(); + capacityMigrations(data, schema).target("1038").load().migrate(); var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); var repository = new FreshTenantIdentityAssociationRepository(dsl, "prod"); @@ -258,14 +221,7 @@ void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { operations, new AccountRepository(dsl).save(creator()), existing); })); assertThat(historical.status()).isEqualTo("IN_PROGRESS"); - Flyway.configure() - .dataSource(data) - .schemas(schema) - .defaultSchema(schema) - .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .load() - .migrate(); + capacityMigrations(data, schema).load().migrate(); var retained = transaction.execute(status -> repository.read(existing.canonicalTenantId())); assertThat(retained).contains(existing); assertThat( @@ -351,14 +307,7 @@ void refusalBudgetRunsAfterIdentityArbitrationAndCountsTheInsertedLastSlot() thr new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); var data = POSTGRES.dataSource(schema); try { - Flyway.configure() - .dataSource(data) - .schemas(schema) - .defaultSchema(schema) - .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .load() - .migrate(); + capacityMigrations(data, schema).load().migrate(); var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); var tenant = source(); @@ -583,15 +532,7 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); var data = POSTGRES.dataSource(schema); try { - Flyway.configure() - .dataSource(data) - .schemas(schema) - .defaultSchema(schema) - .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .target("1038") - .load() - .migrate(); + capacityMigrations(data, schema).target("1038").load().migrate(); var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); var budgets = new AccountCapacityRefusalBudgetRepository(dsl); @@ -605,15 +546,7 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { tenants.importVerified(otherHistoricalTenant); }); - Flyway.configure() - .dataSource(data) - .schemas(schema) - .defaultSchema(schema) - .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .target("1040.1") - .load() - .migrate(); + capacityMigrations(data, schema).target("1040.1").load().migrate(); UUID firstHistoricalRequest = UUID.randomUUID(); UUID firstHistoricalAdmission = UUID.randomUUID(); UUID firstHistoricalAttempt = UUID.randomUUID(); @@ -720,15 +653,7 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { AccountTenantCapacityRepository.at(reconcileDeadline)); }); - Flyway.configure() - .dataSource(data) - .schemas(schema) - .defaultSchema(schema) - .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .target("1040.5") - .load() - .migrate(); + capacityMigrations(data, schema).target("1040.5").load().migrate(); transaction.executeWithoutResult(status -> { budgets.provision(historicalTenant.canonicalTenantId(), 3); budgets.provision(otherHistoricalTenant.canonicalTenantId(), 3); @@ -748,17 +673,15 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM account_capacity_origin_decisions ORDER BY decision_id") .intoMaps(); assertThat(originalDecisions).hasSize(4); + var acceptedReservationsAtV1040_5 = reservationRows(dsl, acceptedTenant.canonicalTenantId()); + var acceptedUsageAtV1040_5 = usageRows(dsl, acceptedTenant.canonicalTenantId()); - Flyway.configure() - .dataSource(data) - .schemas(schema) - .defaultSchema(schema) - .placeholders(java.util.Map.of("serviceSchema", schema)) - .locations("classpath:db/migration") - .target("1040.6") - .load() - .migrate(); + capacityMigrations(data, schema).target("1040.6").load().migrate(); + assertThat(reservationRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedReservationsAtV1040_5); + assertThat(usageRows(dsl, acceptedTenant.canonicalTenantId())) + .isEqualTo(acceptedUsageAtV1040_5); assertThat( dsl.fetchSingle( "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index cc5790ef77..212d448414 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -383,11 +383,13 @@ void exactCapacityRefusalReplaysAfterHeadroomReturnsAndEvaluationExpires() { firstHold = occupying; } } - String readHeld = - "SELECT held_units FROM account_tenant_capacity_usage" + String readUsage = + "SELECT held_units, used_units, usage_revision FROM account_tenant_capacity_usage" + " WHERE tenant_uuid=? AND owner_service='game-session-service'"; - assertThat(f.dsl.fetchSingle(readHeld, f.tenantId).get("held_units", Long.class)) - .isEqualTo(quota); + var usageBeforeDenial = f.dsl.fetchSingle(readUsage, f.tenantId).intoMap(); + assertThat(usageBeforeDenial) + .containsEntry("held_units", quota) + .containsEntry("used_units", 0L); UUID requestId = request.identity().requestId(); var decision = new java.util.concurrent.atomic.AtomicReference(); assertThatThrownBy(() -> f.capacityOwner.commit(request, PEER)) @@ -399,6 +401,7 @@ void exactCapacityRefusalReplaysAfterHeadroomReturnsAndEvaluationExpires() { assertThat(error.durableDenialId()).isNotNull(); decision.set(error.durableDenialId()); }); + assertThat(f.dsl.fetchSingle(readUsage, f.tenantId).intoMap()).isEqualTo(usageBeforeDenial); String readDenial = "SELECT *, xmin::text AS row_version FROM account_capacity_origin_decisions" + " WHERE tenant_uuid=? AND request_id=? AND admission_id=?"; @@ -430,7 +433,7 @@ void exactCapacityRefusalReplaysAfterHeadroomReturnsAndEvaluationExpires() { 7, "sha256:" + "e".repeat(64), "controlled-owner-no-execution".getBytes(StandardCharsets.US_ASCII)), - Clock.systemUTC()); + f.clock); assertThat( recovery .reconcile( @@ -438,8 +441,10 @@ void exactCapacityRefusalReplaysAfterHeadroomReturnsAndEvaluationExpires() { AccountTenantCapacityRecoveryWorker.NoCommitAction.RELEASE) .state()) .isEqualTo(TenantCapacityAdmission.State.RELEASED); - assertThat(f.dsl.fetchSingle(readHeld, f.tenantId).get("held_units", Long.class)) - .isEqualTo(quota - 1); + var usageBeforeReplay = f.dsl.fetchSingle(readUsage, f.tenantId).intoMap(); + assertThat(usageBeforeReplay) + .containsEntry("held_units", quota - 1) + .containsEntry("used_units", 0L); // The exact durable refusal must win over both returned quota headroom and expired evidence. Instant evaluationExpiresAt = request.evidence().expiresAt(); assertThat(f.clock.instant()).isBefore(evaluationExpiresAt); @@ -467,6 +472,7 @@ void exactCapacityRefusalReplaysAfterHeadroomReturnsAndEvaluationExpires() { assertThat(error.code()).isEqualTo(Failure.CAPACITY_QUOTA_EXCEEDED); assertThat(error.durableDenialId()).isEqualTo(decision.get()); }); + assertThat(f.dsl.fetchSingle(readUsage, f.tenantId).intoMap()).isEqualTo(usageBeforeReplay); assertThat(f.dsl.fetchSingle(readDenial, identity).intoMap()) .usingRecursiveComparison() .isEqualTo(retained); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java index e14ecd367c..6fdd0138a0 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java @@ -181,7 +181,10 @@ protected final synchronized void reloadChannel() throws SSLException { target = defaultTarget(); } ManagedChannel newChannel = - channelFactory.buildChannel(target, defaultPort(), tlsProps, keepAliveEnabled()); + channelRetriesEnabled() + ? channelFactory.buildChannel(target, defaultPort(), tlsProps, keepAliveEnabled()) + : channelFactory.buildChannelWithoutRetries( + target, defaultPort(), tlsProps, keepAliveEnabled()); TStub newStub; try { newStub = buildStub(newChannel); @@ -214,6 +217,11 @@ protected boolean keepAliveEnabled() { return true; } + /** Retains standard channel behavior unless a dedicated client owns explicit mutation replay. */ + protected boolean channelRetriesEnabled() { + return true; + } + protected Logger logger() { return logger; } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java index cbdd32ecc6..8c2df0706d 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcChannelFactory.java @@ -24,6 +24,24 @@ public ManagedChannel buildChannel( boolean keepAlive, ResolvedGrpcTlsMaterial tlsMaterial) throws SSLException { + return buildChannel(target, defaultPort, properties, keepAlive, tlsMaterial, true); + } + + /** Builds a dedicated channel whose mutations require explicit reconciliation before replay. */ + public ManagedChannel buildChannelWithoutRetries( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + return buildChannel(target, defaultPort, properties, keepAlive, null, false); + } + + private ManagedChannel buildChannel( + String target, + int defaultPort, + CommonGrpcClientProperties properties, + boolean keepAlive, + ResolvedGrpcTlsMaterial tlsMaterial, + boolean retriesEnabled) + throws SSLException { String resolved = target; if (resolved == null || resolved.isBlank()) { resolved = "localhost:" + defaultPort; @@ -32,6 +50,7 @@ public ManagedChannel buildChannel( if (properties.isPlaintext()) { ManagedChannelBuilder builder = createPlaintextBuilder(resolved, defaultPort); configureKeepAlive(builder, keepAlive); + if (!retriesEnabled) builder.disableRetry(); return builder.build(); } @@ -61,6 +80,8 @@ public ManagedChannel buildChannel( builder = builder.sslContext(sslBuilder.build()); } configureKeepAlive(builder, keepAlive); + // Resolver-supplied service config must not enable retries or hedging on this channel. + if (!retriesEnabled) builder.disableRetry(); return builder.build(); } diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java index d96695180d..d7998ecfc0 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodec.java @@ -299,8 +299,9 @@ public static Optional readRefusalDetails( private static void requireRefusalAuthority(Request request, Refusal refusal) { if (request.capacityRearmFence() != 1) throw invalid(); - if (refusal.code() == Failure.TENANT_BILLING_BLOCKED && request.evidence().permitsCreation()) - throw invalid(); + if (refusal.code() == Failure.TENANT_BILLING_BLOCKED + && (request.evidence().permitsCreation() + || request.operation() != Operation.CAPACITY_CREATING)) throw invalid(); if (refusal.code() == Failure.CAPACITY_QUOTA_EXCEEDED && (!request.evidence().permitsCreation() || request.operation() != Operation.CAPACITY_CREATING)) throw invalid(); diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java index d850c11d69..7887429652 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java @@ -189,6 +189,39 @@ void nonExpandingRequestCannotCarryQuotaRefusal() { .isInstanceOf(IllegalArgumentException.class); } + @Test + void nonExpandingRequestCannotCarryBillingRefusal() { + var original = CapacityAdmissionTestFixture.playerRequest(false); + var request = + new Request( + original.identity(), + original.admissionAttemptId(), + 1, + original.targetNamespace(), + original.context(), + TenantCapacityAdmission.Operation.NON_EXPANDING_RECOVERY, + original.requestedShape(), + original.requestedShape(), + original.evidence(), + 0L, + null) + .withDigest(); + request.requireStructurallyValid(); + assertThatThrownBy(() -> + TenantCapacityAdmissionGrpcCodec.toRefusal(request, Failure.TENANT_BILLING_BLOCKED)) + .isInstanceOf(IllegalArgumentException.class); + var billing = + TenantCapacityAdmissionGrpcCodec.toRefusal(original, Failure.TENANT_BILLING_BLOCKED); + var mismatchedOperation = + billing.toBuilder() + .setRefusal( + 0, billing.getRefusal(0).toBuilder().setMutationDigest(0, request.mutationDigest())) + .build(); + assertThatThrownBy( + () -> TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, mismatchedOperation)) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void matchedRearmCannotCarryEitherOriginalRefusal() { for (var code : List.of(Failure.TENANT_BILLING_BLOCKED, Failure.CAPACITY_QUOTA_EXCEEDED)) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java index debd777ddc..4996d9d043 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java @@ -175,6 +175,12 @@ protected String defaultTarget() { return "account-service:6565"; } + @Override + protected boolean channelRetriesEnabled() { + // Even a trailers-only failure is indeterminate until the exact original is reconciled. + return false; + } + @Override protected AccountServiceGrpc.AccountServiceBlockingStub buildStub(ManagedChannel channel) { return AccountServiceGrpc.newBlockingStub(channel) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index 2e25905c17..4a112ad6dd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -8,9 +8,13 @@ import io.grpc.ConnectivityState; import io.grpc.Context; import io.grpc.Deadline; +import io.grpc.EquivalentAddressGroup; import io.grpc.ManagedChannel; import io.grpc.Metadata; import io.grpc.MethodDescriptor; +import io.grpc.NameResolver; +import io.grpc.NameResolverProvider; +import io.grpc.NameResolverRegistry; import io.grpc.Server; import io.grpc.ServerInterceptors; import io.grpc.ServerStreamTracer; @@ -22,11 +26,16 @@ import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.grpc.stub.StreamObserver; import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.time.Clock; import java.time.ZoneOffset; +import java.util.Collection; +import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; @@ -162,6 +171,70 @@ public void commitTenantCapacityAdmission( } } + @Test + void resolverRetryPolicyRetriesStandardChannelButNotCapacityCommit() throws Exception { + AtomicInteger calls = new AtomicInteger(); + Server server = + startServer( + "account", + new AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest request, + StreamObserver observer) { + calls.incrementAndGet(); + // No response headers/message: the service-config policy can retry this failure. + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + }); + var resolver = new RetryPolicyNameResolverProvider(server.getPort()); + var registry = NameResolverRegistry.getDefaultRegistry(); + registry.register(resolver); + try { + String target = resolver.getDefaultScheme() + ":///account"; + var tls = pki.clientProperties(directory, pki.identity("client")); + var factory = new GrpcChannelFactory(); + var request = CapacityAdmissionTestFixture.playerRequest(); + var standard = factory.buildChannel(target, 6565, tls, true); + try { + assertThatThrownBy(() -> + AccountServiceGrpc.newBlockingStub(standard) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .commitTenantCapacityAdmission( + TenantCapacityAdmissionGrpcCodec.toRequest(request))) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(calls) + .hasValue(2); // Positive control: the resolver policy really enables replay. + } finally { + standard.shutdownNow(); + assertThat(standard.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService(target); + try (var client = + new AccountTenantCapacityClient( + endpoints, + tls, + factory, + "prod", + Clock.fixed(CapacityAdmissionTestFixture.NOW, ZoneOffset.UTC))) { + client.init(); + assertThatThrownBy(() -> client.commit(request, deadline())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE)); + assertThat(calls).hasValue(3); // Exactly one additional transport attempt, not two. + } + } finally { + registry.deregister(resolver); + stop(server); + } + } + @Test void nonCreatingEvidenceReachesControlledAccountAndReturnsStructuredPolicyDenial() throws Exception { @@ -485,12 +558,16 @@ void commitReachesItsTransportDeadlineWhileTlsReloadIsBlocked() throws Exception try (var client = client(server, tls, factory); var executor = Executors.newSingleThreadExecutor()) { client.init(); + assertThat(factory.singleAttemptBuilds).hasValue(1); + assertThat(factory.standardBuilds).hasValue(0); var request = CapacityAdmissionTestFixture.playerRequest(); client.commit(request, deadline()); respond.set(false); try { Files.writeString(Path.of(tls.getCertChain()), "\n", StandardOpenOption.APPEND); assertThat(factory.reloadStarted.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(factory.singleAttemptBuilds).hasValue(2); + assertThat(factory.standardBuilds).hasValue(0); long explicitDeadline = CapacityAdmissionTestFixture.NOW.toEpochMilli() + 3_000L; var timedOut = executor.submit(() -> @@ -507,6 +584,7 @@ void commitReachesItsTransportDeadlineWhileTlsReloadIsBlocked() throws Exception } finally { factory.releaseReload.countDown(); } + assertThat(factory.reloadBuilt.await(5, TimeUnit.SECONDS)).isTrue(); } } finally { try { @@ -794,13 +872,34 @@ private static void stop(Server server) throws InterruptedException { private static final class BlockingReloadChannelFactory extends GrpcChannelFactory { private final AtomicBoolean initialBuild = new AtomicBoolean(true); + private final AtomicInteger standardBuilds = new AtomicInteger(); + private final AtomicInteger singleAttemptBuilds = new AtomicInteger(); private final CountDownLatch reloadStarted = new CountDownLatch(1); private final CountDownLatch releaseReload = new CountDownLatch(1); + private final CountDownLatch reloadBuilt = new CountDownLatch(1); @Override public ManagedChannel buildChannel( String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) throws SSLException { + standardBuilds.incrementAndGet(); + awaitReload(); + return super.buildChannel(target, defaultPort, properties, keepAlive); + } + + @Override + public ManagedChannel buildChannelWithoutRetries( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + int builds = singleAttemptBuilds.incrementAndGet(); + awaitReload(); + ManagedChannel channel = + super.buildChannelWithoutRetries(target, defaultPort, properties, keepAlive); + if (builds > 1) reloadBuilt.countDown(); + return channel; + } + + private void awaitReload() throws SSLException { if (!initialBuild.getAndSet(false)) { reloadStarted.countDown(); try { @@ -810,7 +909,6 @@ public ManagedChannel buildChannel( throw new SSLException("Test reload wait interrupted", interrupted); } } - return super.buildChannel(target, defaultPort, properties, keepAlive); } } @@ -826,11 +924,97 @@ public ManagedChannel buildChannel( super.buildChannel(target, defaultPort, properties, keepAlive), this); } + @Override + public ManagedChannel buildChannelWithoutRetries( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + return new CallOptionsCapturingManagedChannel( + super.buildChannelWithoutRetries(target, defaultPort, properties, keepAlive), this); + } + private void resetCapturedDeadline() { capturedDeadline.set(null); } } + private static final class RetryPolicyNameResolverProvider extends NameResolverProvider { + private final int port; + + private RetryPolicyNameResolverProvider(int port) { + this.port = port; + } + + @Override + protected boolean isAvailable() { + return true; + } + + @Override + protected int priority() { + return 0; // The test-only scheme must not replace the registry's default resolver. + } + + @Override + public String getDefaultScheme() { + return "capacity-retry-test"; + } + + @Override + public Collection> getProducedSocketAddressTypes() { + return List.of(InetSocketAddress.class); + } + + @Override + public NameResolver newNameResolver(URI targetUri, NameResolver.Args args) { + if (!getDefaultScheme().equals(targetUri.getScheme())) return null; + var serviceConfig = + args.getServiceConfigParser() + .parseServiceConfig( + Map.of( + "methodConfig", + List.of( + Map.of( + "name", + List.of( + Map.of( + "service", + AccountServiceGrpc.SERVICE_NAME, + "method", + "CommitTenantCapacityAdmission")), + "retryPolicy", + Map.of( + "maxAttempts", + 2.0, + "initialBackoff", + "0.01s", + "maxBackoff", + "0.01s", + "backoffMultiplier", + 1.0, + "retryableStatusCodes", + List.of("UNAVAILABLE")))))); + return new NameResolver() { + @Override + public String getServiceAuthority() { + return "localhost"; + } + + @Override + public void start(Listener2 listener) { + listener.onResult( + ResolutionResult.newBuilder() + .setAddresses( + List.of(new EquivalentAddressGroup(new InetSocketAddress("127.0.0.1", port)))) + .setServiceConfig(serviceConfig) + .build()); + } + + @Override + public void shutdown() {} + }; + } + } + private static final class CallOptionsCapturingManagedChannel extends ManagedChannel { private final ManagedChannel delegate; private final CallOptionsCapturingChannelFactory capture; From ec45bf71ffcc08d85d3478736832c7df7adb500b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:17:31 +1300 Subject: [PATCH 40/96] Recognize the exact PR merge ref in runtime evidence --- .../workflows/publish-pr-runtime-images.yml | 10 +++- .github/workflows/smoke.yml | 15 +++--- .../pr-required-gate-context-contract.sh | 40 +++++++++++++-- .../pr-runtime-image-publication-contract.sh | 51 +++++++++++++++++++ 4 files changed, 104 insertions(+), 12 deletions(-) diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 15b333e6e0..4bce5e8083 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -679,12 +679,20 @@ jobs: if (!Number.isSafeInteger(event.id) || event.id !== sourceId || !Number.isSafeInteger(event.run_attempt) || event.run_attempt <= 0 || !isTrustedWorkflowPath(event.path)) throw new Error("publication callback path or run identity is not trusted"); - for (const field of ["id", "workflow_id", "run_attempt", "path", "display_title", "event", "conclusion", "head_branch", "head_sha"]) { + for (const field of ["id", "workflow_id", "run_attempt", "display_title", "event", "conclusion", "head_branch", "head_sha"]) { if (run[field] !== event[field]) throw new Error(`source API ${field} differs from callback`); } for (const field of ["repository", "head_repository"]) { if (run[field]?.full_name !== event[field]?.full_name) throw new Error(`source API ${field} differs from callback`); } + // Native PR callbacks and run lookups may differ only in whether + // this exact PR's canonical merge ref is included in the path. + const mergePath = `${workflow.path}@refs/pull/${title[1]}/merge`; + if (run.path !== event.path && !(run.event === "pull_request" && + ((run.path === workflow.path && event.path === mergePath) || + (event.path === workflow.path && run.path === mergePath)))) { + throw new Error("source API path differs from callback"); + } } if (run.status === "completed") { if (run.conclusion !== "success") throw new Error("publication source run did not succeed"); diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 003878ae03..8cf0422315 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -756,8 +756,11 @@ jobs: } } - function isRuntimeSourceWorkflowPath(value) { + function isRuntimeSourceWorkflowPath(value, sourceEvent, currentPrNumber) { if (value === workflowPath) return true; + // Only the current native PR attempt may name its synthetic merge ref. + if (sourceEvent === "pull_request" && + value === `${workflowPath}@refs/pull/${currentPrNumber}/merge`) return true; const prefix = workflowPath + "@"; if (typeof value !== "string" || !value.startsWith(prefix)) return false; const rawRef = value.slice(prefix.length); @@ -810,7 +813,7 @@ jobs: `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; if ((source.id != null && source.id !== run.id) || (source.run_attempt != null && source.run_attempt !== run.run_attempt)) return false; - if ((source.path != null && !isRuntimeSourceWorkflowPath(source.path)) || + if ((source.path != null && !isRuntimeSourceWorkflowPath(source.path, run.event, prNumber)) || (source.repository?.full_name != null && source.repository.full_name !== repositoryName) || (source.workflow_id != null && !positiveInteger(source.workflow_id)) || (source.display_title != null && source.display_title !== expectedTitle) || @@ -821,7 +824,7 @@ jobs: return pendingExactSnapshot(); } if ( - !isRuntimeSourceWorkflowPath(source.path) || source.repository?.full_name !== repositoryName || + !isRuntimeSourceWorkflowPath(source.path, source.event, prNumber) || source.repository?.full_name !== repositoryName || !positiveInteger(source.workflow_id) || source.display_title !== expectedTitle || source.event !== run.event || !["pull_request", "repository_dispatch"].includes(source.event) ) return false; @@ -1009,7 +1012,7 @@ jobs: `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; if ((source.id != null && source.id !== run.id) || (source.run_attempt != null && source.run_attempt !== run.run_attempt)) return false; - if ((source.path != null && !isRuntimeSourceWorkflowPath(source.path)) || + if ((source.path != null && !isRuntimeSourceWorkflowPath(source.path, run.event, prNumber)) || (source.repository?.full_name != null && source.repository.full_name !== repositoryName) || (source.workflow_id != null && !positiveInteger(source.workflow_id)) || (source.display_title != null && source.display_title !== expectedTitle) || @@ -1020,7 +1023,7 @@ jobs: return allowIncompleteSteps ? "snapshot-pending" : false; } if ( - !isRuntimeSourceWorkflowPath(source.path) || source.repository?.full_name !== repositoryName || + !isRuntimeSourceWorkflowPath(source.path, source.event, prNumber) || source.repository?.full_name !== repositoryName || !positiveInteger(source.workflow_id) || source.display_title !== expectedTitle || source.event !== run.event ) return false; @@ -1639,7 +1642,7 @@ jobs: const recoverableCancellation = matching.event === "pull_request" && matching.repository?.full_name === repositoryName && matching.head_repository?.full_name === repositoryName && - isRuntimeSourceWorkflowPath(matching.path) && positiveInteger(matching.workflow_id) && + isRuntimeSourceWorkflowPath(matching.path, matching.event, prNumber) && positiveInteger(matching.workflow_id) && positiveInteger(matching.id) && positiveInteger(matching.run_attempt) && matching.head_sha === currentIdentity.headSha && matching.display_title === expectedDisplayTitle && typeof matching.head_branch === "string" && matching.head_branch.length > 0 && diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 70a4ad8bd2..f711d174f8 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -4998,11 +4998,41 @@ function markerAccepted(overrides = {}) { data.definitions[workflowPath].content = Buffer.from("wrong immutable producer").toString("base64"); data.definitions[workflowPath].size = Buffer.byteLength("wrong immutable producer"); }})).accepted, false, "an untrusted typed run must fail before waiting for omitted jobs"); - for (const suffix of ["@develop", "@refs/heads/develop", "@feature+metadata", "@feature@metadata", "@refs/heads/feature./test", "@feature/ā"]) { - assert.equal(await verify(data => { data.source.path = workflowPath + suffix; }, "repository_dispatch", false), true); - } - for (const path of [workflowPath + "@refs/heads/a..b", workflowPath + "@refs/heads/trailing.", workflowPath + "@@", workflowPath + "@refs/tags/develop", ".github/workflows/other.yml@develop"]) { - assert.equal(await verify(data => { data.source.path = path; }, "repository_dispatch", false), false); + for (const knownPlay of [false, true]) { + for (const event of ["pull_request", "repository_dispatch"]) { + for (const suffix of ["", "@develop", "@refs/heads/develop", "@feature+metadata", "@feature@metadata", "@refs/heads/feature./test", "@feature/ā"]) { + assert.equal(await verify(data => { data.source.path = workflowPath + suffix; }, event, knownPlay), true); + } + assert.equal(await verify(data => { + data.source.path = `${workflowPath}@refs/pull/${data.pr}/merge`; + }, event, knownPlay), event === "pull_request", "merge-ref spelling requires a native current-PR attempt"); + for (const suffix of ["@refs/heads/a..b", "@refs/heads/trailing.", "@@", "@refs/tags/develop", + "@refs/pull/3391/merge", "@refs/pull/03390/merge", "@refs/pull/3390/head", + "@refs/pull/3390/merge/extra", "@refs/pull/3390/merge@develop", "@refs/pull/3390/merge.lock"]) { + assert.equal(await verify(data => { data.source.path = workflowPath + suffix; }, event, knownPlay), false, + `${event}: invalid runtime source path suffix ${suffix}`); + } + assert.equal(await verify(data => { data.source.path = ".github/workflows/other.yml@develop"; }, event, knownPlay), false); + } + assert.equal(await verify(data => { + data.pr = "3451"; + data.source.display_title = data.source.display_title.replace("pr-3390", `pr-${data.pr}`); + data.source.path = `${workflowPath}@refs/pull/${data.pr}/merge`; + }, "pull_request", knownPlay), true, "merge-ref matching follows the current PR number, not a fixed allowlist"); + for (const invalidate of [ + data => {data.source.id++;}, data => {data.source.run_attempt++;}, + data => {data.source.repository.full_name = "attacker/FireMUD";}, + data => {data.source.display_title += " unrelated";}, + data => {data.source.head_sha = "e".repeat(40);}, + data => {data.latest.run_attempt++;}, + data => {data.jobs[0].conclusion = "failure";}, + data => {data.definitions[workflowPath].size++;}, + ]) { + assert.equal(await verify(data => { + data.source.path = `${workflowPath}@refs/pull/${data.pr}/merge`; + invalidate(data); + }, "pull_request", knownPlay), false, "merge-ref spelling cannot bypass existing exact producer proof"); + } } const marker = "Known canonical transition PLAY failure with successful authenticated cleanup"; const ordinary = candidate.steps.map(step => step.name === marker diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 3b7b0c1102..24075ce4fa 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -322,6 +322,57 @@ for (const publishable of ["false", "", undefined]) { const prCallback = {...callbackContext, payload: {repository, workflow_run: prSource}}; await assert.rejects(resolve({runs: [prSource]}), /publication source run provenance is not trusted/); assert.equal((await resolve({runs: [prSource], context: prCallback})).output.artifact_name, direct.output.artifact_name); + const mergePath = `${source.path}@refs/pull/42/merge`; + for (const [apiPath, callbackPath] of [[source.path, mergePath], [mergePath, source.path]]) { + const apiRun = {...prSource, path: apiPath}; + const callbackRun = {...prSource, path: callbackPath}; + const context = {...prCallback, payload: {repository, workflow_run: callbackRun}}; + const resolved = await resolve({runs: [apiRun], context}); + assert.deepEqual(JSON.parse(resolved.output.source), apiRun, "path equivalence preserves the exact native API source"); + assert.equal(resolved.output.artifact_name, direct.output.artifact_name); + for (const change of [ + {id: 4243}, {id: "4242"}, {workflow_id: 778}, {workflow_id: "777"}, + {run_attempt: 2}, {run_attempt: "1"}, {run_attempt: 0}, + {repository: {full_name: "fork/FireMUD"}}, {head_repository: {full_name: "fork/FireMUD"}}, + {head_sha: sha("d")}, {head_branch: "other"}, {event: "repository_dispatch"}, + {display_title: title.replace("pr-42", "pr-43")}, + {display_title: title.replace(`base-${sha("b")}`, `base-${sha("d")}`)}, + {display_title: title.replace(`merge-${sha("c")}`, `merge-${sha("d")}`)}, + {display_title: title.replace("mode-required", "mode-optional")}, + {conclusion: "failure"}, + ]) { + await assert.rejects(resolve({runs: [{...apiRun, ...change}], context}), + `path equivalence must not mask API identity drift: ${JSON.stringify(change)}`); + await assert.rejects(resolve({runs: [apiRun], context: { + ...context, payload: {repository, workflow_run: {...callbackRun, ...change}}, + }}), `path equivalence must not mask callback identity drift: ${JSON.stringify(change)}`); + } + await assert.rejects(resolve({runs: [{...apiRun, status: "in_progress"}], context}), /bounded wait/); + // A typed refresh must retain exact path equality, even for a PR-shaped suffix. + await assert.rejects(resolve({runs: [{...source, path: apiPath}], context: { + ...callbackContext, payload: {repository, workflow_run: {...source, path: callbackPath}}, + }}), /source API path differs from callback/); + } + for (const suffix of ["refs/pull/43/merge", "refs/pull/042/merge", "refs/pull/42/head", + "refs/pull/42/merge/extra", "refs/pull/42/merge-other", "refs/heads/feature/ci"]) { + const wrongPath = `${source.path}@${suffix}`; + for (const [apiPath, callbackPath] of [[source.path, wrongPath], [wrongPath, source.path], + [mergePath, wrongPath], [wrongPath, mergePath]]) { + await assert.rejects(resolve({runs: [{...prSource, path: apiPath}], context: { + ...prCallback, payload: {repository, workflow_run: {...prSource, path: callbackPath}}, + }}), /source API path differs from callback/); + } + } + for (const eventSource of [source, prSource]) { + for (const path of [source.path, `${source.path}@refs/heads/feature/ci`, mergePath]) { + assert.equal((await resolve({runs: [{...eventSource, path}], context: { + ...callbackContext, payload: {repository, workflow_run: {...eventSource, path}}, + }})).output.title, direct.output.title, "already equal trusted paths remain valid"); + } + await assert.rejects(resolve({runs: [{...eventSource, path: `${source.path}@refs/heads/feature/ci`}], context: { + ...callbackContext, payload: {repository, workflow_run: {...eventSource, path: `${source.path}@refs/heads/other`}}, + }}), /source API path differs from callback/); + } const publisherWorkflow = fs.readFileSync(process.argv[5], "utf8"); assert.ok(publisherWorkflow.includes("if: ${{ needs.source.outputs.source != '' }}"), "no source must skip privileged publication"); const download = publisherWorkflow.split(" - name: Download successful PR image artifacts\n")[1] From e5bd2ceb58b28a76534de3996c7066f52883e175 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:28:30 +1300 Subject: [PATCH 41/96] Exercise direct REST pagination in the runtime contract --- .../tests/pr-required-gate-context-contract.sh | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index f711d174f8..90ded06f9f 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -5795,7 +5795,19 @@ async function dispatch(kind) { workflow_runs: rows}}; }, }, - pulls: {list: "pulls", listFiles: "files", get: async () => ({data: pr})}, + pulls: { + list: async ({state, base: baseBranch, per_page, page, request}) => { + assert.deepEqual([state, baseBranch, per_page, page], ["open", "develop", 100, 1]); + assert.ok(request.signal instanceof AbortSignal); + return {data: [pr]}; + }, + listFiles: async ({pull_number, per_page, page, request}) => { + assert.deepEqual([pull_number, per_page, page], [42, 100, 1]); + assert.ok(request.signal instanceof AbortSignal); + return {data: [{filename: "services/example/build.gradle.kts"}]}; + }, + get: async () => ({data: pr}), + }, git: {getRef: async () => ({data: {ref: "refs/heads/develop", object: {sha: base}}})}, repos: { getCommit: async () => ({data: {sha: merge, parents: [{sha: base}, {sha: head}]}}), @@ -5805,9 +5817,6 @@ async function dispatch(kind) { posts++; }, }, - }, paginate: async method => { - assert.ok(["pulls", "files"].includes(method), method); - return method === "pulls" ? [pr] : [{filename: "services/example/build.gradle.kts"}]; }}; await execute(github, {repo: {owner: "example", repo: "firemud"}, payload: { repository: {full_name: repository, default_branch: "develop"}, From a6f568565a0a7f54dd0f597103f602868c6bc6fd Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:39:33 +1300 Subject: [PATCH 42/96] Prove runtime artifact attempts and failed PLAY retry eligibility --- .../workflows/publish-pr-runtime-images.yml | 147 +++++++++-- .github/workflows/runtime-images.yml | 28 +- .github/workflows/smoke.yml | 2 +- .../architecture/system-architecture-cicd.md | 4 +- .../tests/pr-retarget-workflow-contract.sh | 24 +- .../pr-runtime-image-publication-contract.sh | 243 ++++++++++++++++-- 6 files changed, 404 insertions(+), 44 deletions(-) diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 4bce5e8083..d19f91a9b0 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -87,6 +87,27 @@ jobs: const trusted = run => run?.workflow_id === workflow.id && matchesPath(run.path, workflow.path) && run.repository?.full_name === repository && run.head_repository?.full_name === repository && [workflow.name, run.display_title].includes(run.name) && positive(run.id) && positive(run.run_attempt); + // A legacy diagnostic can use a failed runtime run. A complete + // native producer job with a skipped marker is affirmative proof + // that this exact failed attempt cannot supply that exception. + const provesOrdinaryTypedFailure = async run => { + const {data} = await github.rest.actions.listJobsForWorkflowRunAttempt(prePostOptions({ + ...context.repo, run_id: run.id, attempt_number: run.run_attempt, per_page: 100, page: 1, + })); + if (!Array.isArray(data?.jobs) || data.jobs.length > 100 || data.total_count !== data.jobs.length) return false; + const producers = data.jobs.filter(job => job?.name === "PR Full-Stack Smoke (runtime-required=true)"); + const job = producers[0]; + if (producers.length !== 1 || !positive(job.id) || job.run_id !== run.id || + job.run_attempt !== run.run_attempt || job.head_sha !== run.head_sha || + ![workflow.name, run.display_title].includes(job.workflow_name) || + job.status !== "completed" || job.conclusion !== "failure" || !Array.isArray(job.steps)) return false; + const markers = job.steps.filter(step => step?.name === "Known canonical transition PLAY failure with successful authenticated cleanup"); + if (markers.length !== 1 || markers[0].status !== "completed" || markers[0].conclusion !== "skipped") return false; + const times = [run.run_started_at, job.started_at, markers[0].started_at, markers[0].completed_at, + job.completed_at, run.updated_at].map(value => + typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value) ? Date.parse(value) : NaN); + return times.every((time, index) => Number.isFinite(time) && (index === 0 || time >= times[index - 1])); + }; // Inventory incompleteness is unknown, never permission to dispatch duplicates. const inventory = async (workflowId, filter, deadline = prePostDeadline, phase = "Pre-dispatch", validateVisibilityRun = null) => { const runs = [], ids = new Map(); @@ -464,12 +485,7 @@ jobs: const ids = new Set(runs.map(run => run.id)); if (strictlyAfter === null) { for (const run of exact) { - // Only these two freshly verified unusable results may release - // the hold. Legacy failures (including PLAY) are not replayed. - if (run.status !== "completed" || !["cancelled", "timed_out"].includes(run.conclusion)) { - if (run.status === "completed" && run.conclusion === "failure") { - core.warning(`Exact typed refresh ${run.id} failed; recovery remains held for explicit investigation, not automatic replay.`); - } + if (run.status !== "completed" || !["cancelled", "timed_out", "failure"].includes(run.conclusion)) { return {found: true, ids}; } let current; @@ -489,6 +505,15 @@ jobs: core.warning(`Exact typed refresh ${run.id} terminal result is unproven or superseded; recovery remains held without retry.`); return {found: true, ids}; } + if (current.conclusion === "failure") { + let unusable = false; + try { unusable = await provesOrdinaryTypedFailure(current); } + catch { /* An incomplete provider response cannot authorize a retry. */ } + if (!unusable) { + core.warning(`Exact typed refresh ${run.id} failed; recovery remains held for explicit investigation, not automatic replay.`); + return {found: true, ids}; + } + } } // Retain every inventory ID, including verified unusable runs, // so none can later be mistaken for receipt of this POST. @@ -654,8 +679,28 @@ jobs: return ref.split("/").every(part => part && part !== "." && part !== ".." && !part.startsWith(".") && !part.endsWith(".lock")); } + function sameSourcePath(left, right, event, pull) { + if (left === right) return true; + const mergePath = `${workflow.path}@refs/pull/${pull}/merge`; + return event === "pull_request" && + (left === workflow.path && right === mergePath || right === workflow.path && left === mergePath); + } const titlePattern = /^Build Runtime Images secure-pr-artifact pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40}) merge-([0-9a-f]{40}) mode-required$/; const deadline = Date.now() + 120000; + const proofOptions = options => { + const remaining = deadline - Date.now(); + if (remaining <= 0) throw new Error("publication producer proof exceeded its bounded deadline"); + return {...options, request: {signal: AbortSignal.timeout(remaining)}}; + }; + const timestamp = value => { + const match = typeof value === "string" && /^(?:\d{4}-\d{2}-\d{2})T\d{2}:\d{2}:\d{2}(?:\.(\d{1,3}))?Z$/.exec(value); + const time = match ? Date.parse(value) : NaN; + if (!Number.isFinite(time) || new Date(time).toISOString() !== + `${value.slice(0, 19)}.${(match[1] || "").padEnd(3, "0")}Z`) { + throw new Error("publication producer proof has a missing or invalid UTC timestamp"); + } + return time; + }; for (;;) { const { data: run } = await github.rest.actions.getWorkflowRun({ ...context.repo, run_id: sourceId, @@ -687,25 +732,93 @@ jobs: } // Native PR callbacks and run lookups may differ only in whether // this exact PR's canonical merge ref is included in the path. - const mergePath = `${workflow.path}@refs/pull/${title[1]}/merge`; - if (run.path !== event.path && !(run.event === "pull_request" && - ((run.path === workflow.path && event.path === mergePath) || - (event.path === workflow.path && run.path === mergePath)))) { + if (!sameSourcePath(run.path, event.path, run.event, title[1])) { throw new Error("source API path differs from callback"); } } if (run.status === "completed") { if (run.conclusion !== "success") throw new Error("publication source run did not succeed"); - const jobs = await github.paginate(github.rest.actions.listJobsForWorkflowRun, { - ...context.repo, run_id: sourceId, per_page: 100, - }); - if (jobs.some(job => job.name === "PR Full-Stack Smoke (runtime-required=true)" && - (job.steps ?? []).some(step => - step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" && - step.status === "completed" && step.conclusion === "success"))) { + const {data: attempt} = await github.rest.actions.getWorkflowRunAttempt(proofOptions({ + ...context.repo, run_id: sourceId, attempt_number: run.run_attempt, + })); + // Run-wide creation/start timestamps are not rerun execution authority. + // Only the exact native attempt may bound the producer's execution. + for (const field of ["id", "workflow_id", "run_attempt", "display_title", "event", + "head_branch", "head_sha", "status", "conclusion"]) { + if (attempt?.[field] !== run[field]) throw new Error(`source attempt ${field} differs from selected run`); + } + if (!sameSourcePath(run.path, attempt.path, run.event, title[1])) { + throw new Error("source attempt path differs from selected run"); + } + if (![workflow.name, run.display_title].includes(attempt.name) || + attempt.repository?.full_name !== repository || attempt.head_repository?.full_name !== repository) { + throw new Error("publication source attempt provenance is not trusted"); + } + const created = timestamp(attempt.created_at); + const started = timestamp(attempt.run_started_at); + const updated = timestamp(attempt.updated_at); + // Native attempt and job timestamps can differ in subsecond precision; + // permit only their boundary second, never an earlier execution second. + const attemptStart = Math.floor(started / 1000) * 1000; + const attemptEnd = Math.floor(updated / 1000) * 1000 + 999; + if (created >= started + 1000 || created > updated || started > attemptEnd) { + throw new Error("publication source attempt chronology is inconsistent"); + } + const jobs = [], ids = new Set(); + let total; + for (let page = 1; page <= 10; page++) { + const {data} = await github.rest.actions.listJobsForWorkflowRunAttempt(proofOptions({ + ...context.repo, run_id: sourceId, attempt_number: run.run_attempt, per_page: 100, page, + })); + if (!Number.isSafeInteger(data?.total_count) || data.total_count < 0 || data.total_count > 1000 || + (total !== undefined && data.total_count !== total) || !Array.isArray(data.jobs) || + data.jobs.length !== Math.min(100, Math.max(0, data.total_count - (page - 1) * 100))) { + throw new Error("publication source attempt job inventory is incomplete or inconsistent"); + } + total ??= data.total_count; + for (const job of data.jobs) { + if (!Number.isSafeInteger(job?.id) || job.id <= 0 || ids.has(job.id) || + typeof job.name !== "string" || !job.name.trim() || job.run_id !== sourceId || + job.run_attempt !== run.run_attempt || job.head_sha !== run.head_sha || + ![workflow.name, run.display_title].includes(job.workflow_name)) { + throw new Error("publication source attempt job inventory has duplicate or unattributable jobs"); + } + ids.add(job.id); + jobs.push(job); + } + if (jobs.length === total) break; + } + if (jobs.length !== total) throw new Error("publication source attempt job inventory exceeds bounded pagination"); + const producers = jobs.filter(job => ["PR Full-Stack Smoke (runtime-required=true)", + "PR Full-Stack Smoke (runtime-required=false)"].includes(job.name)); + if (producers.length !== 1 || producers[0].status !== "completed" || + producers[0].conclusion !== "success" || !Array.isArray(producers[0].steps)) { + throw new Error("publication requires one successful attributable artifact producer job"); + } + const producer = producers[0]; + const jobStart = timestamp(producer.started_at), jobEnd = timestamp(producer.completed_at); + if (jobStart < attemptStart || jobEnd < jobStart || jobEnd > attemptEnd) { + throw new Error("publication artifact producer did not execute within the selected native attempt"); + } + if (producer.name === "PR Full-Stack Smoke (runtime-required=true)" && + producer.steps.some(step => + step?.name === "Known canonical transition PLAY failure with successful authenticated cleanup" && + step.status === "completed" && step.conclusion === "success")) { core.notice("CI passed under the canonical PLAY transition exception; no runtime images are eligible for publication."); return; } + const uploads = producer.steps.filter(step => step?.name === "Upload preview image artifact"); + const upload = uploads[0]; + if (uploads.length !== 1 || upload.status !== "completed" || upload.conclusion !== "success" || + !Number.isSafeInteger(upload.number) || upload.number <= 0 || + producer.steps.filter(step => step?.number === upload.number).length !== 1) { + throw new Error("publication requires the producer's actual successful Upload preview image artifact step"); + } + const uploadStart = timestamp(upload.started_at), uploadEnd = timestamp(upload.completed_at); + if (uploadStart < jobStart || uploadEnd < uploadStart || uploadEnd > jobEnd) { + throw new Error("publication artifact upload did not execute within the selected producer job"); + } + if (Date.now() >= deadline) throw new Error("publication producer proof exceeded its bounded deadline"); core.setOutput("source", JSON.stringify(run)); core.setOutput("title", run.display_title); core.setOutput("artifact_name", `pr-runtime-images-pr-merge-${title[4]}`); diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index fc59c75e60..861860964a 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -800,6 +800,27 @@ jobs: const ref = path.slice(prefix.length); return validWorkflowRef(ref); }; + // The older PLAY diagnostic can leave the source run red. Only a + // complete native attempt with its marker explicitly skipped can + // prove that a failed producer did not supply that exception. + const provesOrdinaryTypedFailure = async (run, workflowName) => { + const {data} = await github.rest.actions.listJobsForWorkflowRunAttempt(fanoutOptions({ + ...context.repo, run_id: run.id, attempt_number: run.run_attempt, per_page: 100, page: 1, + })); + if (!Array.isArray(data?.jobs) || data.jobs.length > 100 || data.total_count !== data.jobs.length) return false; + const producers = data.jobs.filter(job => job?.name === "PR Full-Stack Smoke (runtime-required=true)"); + const job = producers[0]; + if (producers.length !== 1 || !Number.isSafeInteger(job.id) || job.id <= 0 || + job.run_id !== run.id || job.run_attempt !== run.run_attempt || job.head_sha !== run.head_sha || + ![workflowName, run.display_title].includes(job.workflow_name) || + job.status !== "completed" || job.conclusion !== "failure" || !Array.isArray(job.steps)) return false; + const markers = job.steps.filter(step => step?.name === "Known canonical transition PLAY failure with successful authenticated cleanup"); + if (markers.length !== 1 || markers[0].status !== "completed" || markers[0].conclusion !== "skipped") return false; + const times = [run.run_started_at, job.started_at, markers[0].started_at, markers[0].completed_at, + job.completed_at, run.updated_at].map(value => + typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value) ? Date.parse(value) : NaN); + return times.every((time, index) => Number.isFinite(time) && (index === 0 || time >= times[index - 1])); + }; // Bind both admission reads to the same terminal attempt; never cache native proof. const disregardedTypedAttempts = new Map(); const findExactExistingProducer = async (tuple, inventory) => { @@ -853,7 +874,7 @@ jobs: return [newest]; } if (newest.status === "completed") { - if (newest.event === "repository_dispatch" && ["cancelled", "timed_out"].includes(newest.conclusion)) { + if (newest.event === "repository_dispatch" && ["cancelled", "timed_out", "failure"].includes(newest.conclusion)) { const repository = `${context.repo.owner}/${context.repo.repo}`; const defaultBranch = context.payload.repository?.default_branch; const attemptBinding = JSON.stringify([ @@ -885,8 +906,9 @@ jobs: latest.conclusion !== newest.conclusion) { throw new Error(`Terminal typed runtime producer ${newest.id} no longer has the same trusted terminal attempt`); } - // Neither conclusion can supply ordinary or diagnostic PLAY acceptance. - // Success/failure classification and POST visibility deliberately remain unchanged. + if (newest.conclusion === "failure" && !await provesOrdinaryTypedFailure(latest, workflow.name)) { + return [newest]; + } disregardedTypedAttempts.set(newest.id, attemptBinding); return []; } diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 8cf0422315..8c981e520a 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -632,7 +632,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "537fe7a43662a56c367c2a51d44b7cf17071e29aed0956e4bb19c5144a40e523"; + const canonicalRuntimeWorkflowSha256 = "6482868075dd050438a52b0f2cf2537f7a469d21cabf2759b79b30aa4466e0a9"; // Only authenticated default-branch refreshes may use retained successful definitions. // Keep the pre-rollout default and predecessor definitions for mixed-version runs. const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set([ diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 97900635be..445b215b40 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -90,9 +90,9 @@ A typed runtime refresh hands off publication explicitly after its required cred For typed publication, `source_run_id` selects a native Actions run for lookup; neither the payload nor its title is source authority. The no-checkout resolver binds the returned native `run.id` to that supplied ID and its `workflow_id` to the separately resolved runtime workflow identity (`Build Runtime Images` at `.github/workflows/runtime-images.yml`). The native run path must be that workflow path or its validated ref-suffixed form, and its name must be the owner workflow name or exact canonical display title. It requires native `event=repository_dispatch`, the current repository in both `repository` and `head_repository`, `head_branch` equal to the repository default branch, a lowercase 40-character native `head_sha` for that default-branch source revision, and the canonical runtime title carrying the exact PR number/base/head/merge tuple and `mode-required`. The type and default-branch ref are also checked at the handoff boundary. This trusted typed source identity comes from GitHub's Actions run and workflow records, not from caller-supplied tuple fields. -The publisher's no-checkout, Actions-read-only resolver reads only the supplied exact source run and owning runtime workflow identity. A dispatch can arrive before its source workflow finishes, so the resolver waits for actual terminal success within a two-minute budget; malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. The resolver never substitutes a successful status. Both trigger paths retain the same exact source, current PR/base/head/merge, artifact provenance, and immutable-tag validation. The publisher checks the resolved native source attempt again after download and refuses a superseded attempt before registry access. Publishing jobs serialize on the verified merge-bound source title across both paths; duplicate publication preserves identical existing images and rejects conflicting image bytes. Explicit dispatch avoids relying on a workflow-run callback from a token-origin refresh without weakening the source or registry boundary. +The publisher's no-checkout, Actions-read-only resolver reads only the supplied exact source run and owning runtime workflow identity. A dispatch can arrive before its source workflow finishes, so the resolver waits for actual terminal success within a two-minute budget; malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. The resolver never substitutes a successful status. Both trigger paths retain the same exact source, current PR/base/head/merge, artifact provenance, and immutable-tag validation. Before selecting the artifact, the resolver requires one successful native producer job and its successful upload step within the exact attempt’s execution window. A partial rerun that retains an earlier upload cannot qualify that upload as part of the current attempt. The publisher checks the resolved native source attempt again after download and refuses a superseded attempt before registry access. Publishing jobs serialize on the verified merge-bound source title across both paths; duplicate publication preserves identical existing images and rejects conflicting image bytes. Explicit dispatch avoids relying on a workflow-run callback from a token-origin refresh without weakening the source or registry boundary. -The trusted publisher also reconciles a failed, cancelled, or timed-out original same-repository PR runtime run when substantive Validation already completed. This API-only job has `contents: write` solely to request an exact typed refresh; it never checks out PR code. It verifies current native source and CI attempts, the live base/head/merge tuple, and absence of a newer original or typed refresh before dispatch. A cancelled Validation callback can also wake recovery. The exact cancelled attempt must prove that enforcement never started and that none of its prerequisite jobs failed. An exact terminal metadata-only Validation attempt can also wake the reconciler once its native jobs positively identify it as metadata-only. The reconciler skips that attempt as proof. Recovery past a cancelled Validation attempt requires an earlier successful substantive attempt for the same comparison. Typed-refresh and nested workflow callbacks cannot recursively invoke this recovery. The CI dispatcher and completion reconciler share an API-job concurrency group with `queue: max`; runtime builds remain parallel. Unknown or incomplete producer inventory fails closed. Before each candidate runtime POST, the dispatcher rechecks the current PR tuple and base ref, then refreshes the complete producer inventory to suppress any newly reusable exact producer. Each handoff sends one POST. An uncertain dispatch is not blindly repeated. Accepted handoffs share one 120-second visibility window after fan-out rather than delaying each later target in turn. The dispatcher resolves the current native runtime workflow identity before classifying observed producers and retries only transient identity lookup failures within that existing visibility deadline; it never retries a POST. Visibility requires a complete native producer inventory, the exact tuple title and current workflow/repository identity, a new run ID absent from the complete pre-POST snapshot, and a creation timestamp no earlier than the dispatch timestamp second. Preview reconciliation checks its own current tuple independently of runtime handoff uncertainty; a failed target does not automatically suppress independent later targets. This is bounded coordination, not exactly-once delivery or an unbounded no-starvation guarantee: GitHub admits at most 100 pending jobs in the group, inventories and job durations are bounded, and existing superseding base callbacks can cancel obsolete work. Remaining unknown outcomes require fresh evidence rather than presumed success. +The trusted publisher also reconciles a failed, cancelled, or timed-out original same-repository PR runtime run when substantive Validation already completed. This API-only job has `contents: write` solely to request an exact typed refresh; it never checks out PR code. It verifies current native source and CI attempts, the live base/head/merge tuple, and absence of a newer original or typed refresh before dispatch. A cancelled Validation callback can also wake recovery. The exact cancelled attempt must prove that enforcement never started and that none of its prerequisite jobs failed. An exact terminal metadata-only Validation attempt can also wake the reconciler once its native jobs positively identify it as metadata-only. The reconciler skips that attempt as proof. Recovery past a cancelled Validation attempt requires an earlier successful substantive attempt for the same comparison. Typed-refresh and nested workflow callbacks cannot recursively invoke this recovery. The CI dispatcher and completion reconciler share an API-job concurrency group with `queue: max`; runtime builds remain parallel. Unknown or incomplete producer inventory fails closed. Before each candidate runtime POST, the dispatcher rechecks the current PR tuple and base ref, then refreshes the complete producer inventory to suppress any newly reusable exact producer. Each handoff sends one POST. An uncertain dispatch is not blindly repeated. A failed typed refresh can release its duplicate-dispatch hold when a current exact-attempt job read proves ordinary smoke failure and an explicitly skipped PLAY exception marker. A successful exception or ambiguous marker keeps the hold. Accepted handoffs share one 120-second visibility window after fan-out rather than delaying each later target in turn. The dispatcher resolves the current native runtime workflow identity before classifying observed producers and retries only transient identity lookup failures within that existing visibility deadline; it never retries a POST. Visibility requires a complete native producer inventory, the exact tuple title and current workflow/repository identity, a new run ID absent from the complete pre-POST snapshot, and a creation timestamp no earlier than the dispatch timestamp second. Preview reconciliation checks its own current tuple independently of runtime handoff uncertainty; a failed target does not automatically suppress independent later targets. This is bounded coordination, not exactly-once delivery or an unbounded no-starvation guarantee: GitHub admits at most 100 pending jobs in the group, inventories and job durations are bounded, and existing superseding base callbacks can cancel obsolete work. Remaining unknown outcomes require fresh evidence rather than presumed success. Smoke Gate retains affirmative successful smoke-step evidence for earlier producers. When GitHub omits or delays step metadata, the canonical producer additionally qualifies through its native `PR Full-Stack Smoke (runtime-required=true)` job identity and successful terminal job outcome. This producer has stable smoke and cleanup step IDs and an unconditional terminal guard. Ordinary runtime qualification requires both Actions-native outcomes to be `success` and the transition-exception marker to be explicitly skipped. Missing marker metadata cannot use the native-job fallback: a successful job alone may instead represent the bounded exception described below. Skipped, missing, cancelled, or failed execution or authenticated cleanup cannot qualify as real runtime proof. Non-required image builds use a different evaluated job name. The gate verifies the exact successful run attempt, owning repository/workflow/event, native job ID/attempt/head/check URL, canonical PR/base/head/merge title, ordered merge parents, and current PR head/base branch before accepting this path. It also rechecks that no newer attempt superseded that source. Job success, logs, command-written outputs, and image artifacts alone are not smoke proof. The existing native job name does not widen the held-admission proof scope defined above. A separate, temporary diagnostic exception lets the required Smoke Gate succeed for a same-repository `benhook1013/FireMUD` pull request whose current live PR carries the `canonical-play-transition` label. A `pull_request` producer also requires the source event label and exact verified PR-event base/head/merge tuple. A typed `pr-runtime-base-refresh` producer instead derives label authority from its verified live same-repository PR, never dispatch payload labels, and requires the exact current base/head/merge tuple again at consumption. Both paths require the latest successful CI attempt with its explicit exception marker while the PR head and base branch remain current. During the default-branch workflow rollout, the exact previous fail-red producer fingerprint remains accepted only with its original failed smoke and terminal guard plus successful marker and cleanup; it supplies the same diagnostic exception and no runtime qualification. The smoke invocation retains its failed Actions-native outcome through step-level continuation; only the exact label, classifier and successful authenticated cleanup can make the mandatory final guard accept that failed probe. Every other probe failure still fails CI. GitHub reports the continued step conclusion as success, so the consumer verifies the immutable marker rather than treating that conclusion as runtime proof. The fingerprinted producer must attest the classified direct-backend `PLAY` `ERROR ENTITLEMENT_UNAVAILABLE` after successful held-admission qualification and backend `LOGIN`, with successful authenticated cleanup. The executing workflow is fingerprinted at the PR merge revision or typed refresh's native default-branch revision, respectively; classifiers, held-admission qualification, authenticated cleanup, certificate setup, and their checked-in environment and Compose inputs are always fingerprinted at the tested PR merge. Its original smoke failure remains visible in the probe logs, summary and Actions-native outcome; unrelated failures still block, and image export and upload must be skipped. The typed publication handoff also requires a real successful image upload. A trusted workflow-run publisher detects the exception marker before exposing a publication source and skips its privileged job; a successful CI conclusion under exception does not authorize registry access or preview images. This is gate acceptance for the nonproduction canonical cutover, not successful smoke, runtime qualification, branch-image promotion, hosted preview eligibility, or production activation. Trusted `main`/`develop` branch publication still requires real passing `LOGIN` → `PLAY` → `LOOK` smoke and cannot use this exception; after the cutover merges, branch images remain on hold until the Account entitlement path is repaired. Remove the label-based marker and consumer exception when fresh-image backend `LOGIN` → `PLAY` → `LOOK` passes, then remove this transitional contract. The [player access tracker](../project-management/implementation-tracking/player-access-and-session.md#temporary-canonical-play-transition-exception) records the current cutover proof gap. diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 16616c7231..d724baf299 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -900,7 +900,7 @@ async function runDispatcher({ visibilityResponse = null, filesFailurePr = null, postFailureVisible = false, postFailureStatus = null, fanoutCutoffAfterInventory = false, fanoutCutoffAfterPreviewPr = null, expireAfterFirstApiRequest = false, pullGetFailures = {}, lateProducer = null, runtimeWorkflowLookupFailures = [], - pullListResponse = null, apiRequestMillis = 0, runtimeRunOverrides = {}, + pullListResponse = null, apiRequestMillis = 0, runtimeRunOverrides = {}, runtimeAttemptJobs = {}, initialTime = "2026-01-08T00:00:00Z", }) { const dispatches = []; @@ -1112,6 +1112,7 @@ async function runDispatcher({ }, listJobsForWorkflowRunAttempt: async (request) => { recordApiRequest("actions.listJobsForWorkflowRunAttempt", request); + if (request.run_id !== ciRun.id) return {data: runtimeAttemptJobs[request.run_id] ?? {total_count: 0, jobs: []}}; ciJobRequests.push(request); const jobs = ciEvidence.jobs ?? [ciGate]; return {data: ciEvidence.jobPage ? ciEvidence.jobPage(request, jobs) : { @@ -1845,9 +1846,28 @@ async function runDispatcher({ }); assert.deepEqual(numbers(held), [], "legacy failure/PLAY, success and unknown dispositions keep the existing typed refresh hold"); - assert.deepEqual(held.runtimeRunReads, [], "this narrow rule must not classify other terminal PLAY outcomes"); + if (conclusion !== "failure") assert.deepEqual(held.runtimeRunReads, [], "unrelated conclusions need no native classification"); assert.deepEqual(held.errors, []); } + const failedTyped = {...terminalTyped("failure"), run_started_at: "2026-01-03T00:01:00Z", updated_at: "2026-01-03T00:04:00Z"}; + const diagnosticMarker = {name: "Known canonical transition PLAY failure with successful authenticated cleanup", status: "completed", + conclusion: "skipped", started_at: "2026-01-03T00:02:00Z", completed_at: "2026-01-03T00:02:00Z"}; + const failedJob = {id: 72, name: "PR Full-Stack Smoke (runtime-required=true)", workflow_name: failedTyped.display_title, + run_id: failedTyped.id, run_attempt: failedTyped.run_attempt, head_sha: failedTyped.head_sha, status: "completed", conclusion: "failure", + started_at: "2026-01-03T00:01:01Z", completed_at: "2026-01-03T00:03:00Z", steps: [diagnosticMarker]}; + for (const [jobs, total, expected] of [ + [[failedJob], 1, ["101"]], + [[{...failedJob, steps: [{...diagnosticMarker, conclusion: "success"}]}], 1, []], + [[{...failedJob, steps: [{...diagnosticMarker, conclusion: null}]}], 1, []], + [[{...failedJob, steps: [diagnosticMarker, diagnosticMarker]}], 1, []], + [[{...failedJob, started_at: "2026-01-03T00:00:59Z"}], 1, []], + [[failedJob], 2, []], + ]) { + const result = await runDispatcher({tuples:[tuple], callback:{updated_at: "2026-01-02T00:00:00Z"}, + inventories: {repository_dispatch:[failedTyped]}, runtimeAttemptJobs: {[failedTyped.id]: {total_count: total, jobs}}}); + assert.deepEqual(numbers(result), expected); + assert.deepEqual(result.errors, []); + } const cancelledTyped = terminalTyped("cancelled"); for (const changed of [ {run_attempt: 2}, {run_attempt: 0}, {run_attempt: null}, {id: cancelledTyped.id + 1}, diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 24075ce4fa..3013fdc216 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -182,7 +182,7 @@ node - "$resolver_script" "$dispatch_script" "$RUNTIME_WORKFLOW" "$WORKFLOW" "$f const fs = require("fs"); const assert = require("assert/strict"); const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; -const resolver = new AsyncFunction("github", "context", "core", "Date", "setTimeout", fs.readFileSync(process.argv[2], "utf8")); +const resolver = new AsyncFunction("github", "context", "core", "Date", "setTimeout", "AbortSignal", fs.readFileSync(process.argv[2], "utf8")); const dispatch = new AsyncFunction("github", "context", fs.readFileSync(process.argv[3], "utf8")); const smokeScope = new AsyncFunction("github", "context", "core", fs.readFileSync(process.argv[7], "utf8")); const refreshSelector = new AsyncFunction("github", "context", "core", "Date", "AbortSignal", @@ -190,24 +190,83 @@ const refreshSelector = new AsyncFunction("github", "context", "core", "Date", " const sha = character => character.repeat(40); const title = `Build Runtime Images secure-pr-artifact pr-42 base-${sha("b")} head-${sha("a")} merge-${sha("c")} mode-required`; const repository = { full_name: "benhook1013/FireMUD", default_branch: "develop" }; -const source = { id: 4242, workflow_id: 777, run_attempt: 1, path: ".github/workflows/runtime-images.yml", name: title, display_title: title, event: "repository_dispatch", repository, head_repository: repository, head_branch: "develop", head_sha: sha("b"), status: "completed", conclusion: "success" }; +const source = { id: 4242, workflow_id: 777, run_attempt: 1, path: ".github/workflows/runtime-images.yml", name: title, display_title: title, event: "repository_dispatch", repository, head_repository: repository, head_branch: "develop", head_sha: sha("b"), status: "completed", conclusion: "success", created_at: "2026-01-08T00:00:00Z", run_started_at: "2026-01-08T00:00:00.500Z", updated_at: "2026-01-08T00:04:00Z" }; const baseContext = { eventName: "repository_dispatch", ref: "refs/heads/develop", repo: {owner: "benhook1013", repo: "FireMUD"}, runId: 4242, payload: { repository, action: "pr-runtime-image-publication", client_payload: { source_run_id: "4242" } } }; -async function resolve({ context = baseContext, runs = [source], workflow = { id: 777, name: "Build Runtime Images", path: source.path }, error = false, jobs = [] } = {}) { +function producerFor(run, required = true) { + const start = Math.floor(Date.parse(run.run_started_at) / 1000) * 1000; + const at = seconds => new Date(start + seconds * 1000).toISOString(); + return {id: 8001, run_id: run.id, run_attempt: run.run_attempt, head_sha: run.head_sha, + workflow_name: "Build Runtime Images", name: `PR Full-Stack Smoke (runtime-required=${required})`, + status: "completed", conclusion: "success", started_at: at(1), completed_at: at(180), + steps: [{name: "Upload preview image artifact", number: 20, status: "completed", conclusion: "success", + started_at: at(120), completed_at: at(122)}]}; +} +async function resolve({ context = baseContext, runs = [source], workflow = { id: 777, name: "Build Runtime Images", path: source.path }, + error = false, jobs = null, nativeAttempt, jobPages = null, attemptError = false, jobError = false, + expectException = false, expireAfterAttempt = false, expireAfterJobs = false } = {}) { let reads = 0, clock = 0; - const output = {}; - const github = { paginate: async () => jobs, rest: { actions: { - getWorkflow: async () => ({data: workflow}), - getWorkflowRun: async request => { assert.equal(request.run_id, 4242); reads++; if (error) throw Error("API unavailable"); return {data: runs[Math.min(reads - 1, runs.length - 1)]}; }, + let selected; + const output = {}, proofRequests = [], signals = []; + class FixtureDate extends Date { static now() { return clock; } } + const recordProof = (method, options, paged = false) => { + const {request, ...normal} = options; + assert.deepEqual(normal, {...baseContext.repo, run_id: selected.id, attempt_number: selected.run_attempt, + ...(paged ? {per_page: 100, page: proofRequests.filter(row => row.method === method).length + 1} : {})}, + `${method} must address the exact selected native attempt with explicit direct pagination`); + assert.deepEqual(Object.keys(request), ["signal"]); + assert.equal(request.signal, signals.at(-1)); + assert.equal(request.signal.timeoutMs, 120000 - clock, "each proof read uses its remaining wall-clock budget"); + assert(request.signal.timeoutMs > 0); + proofRequests.push({method, ...normal, signal: request.signal}); + }; + const github = { paginate: async () => { throw Error("producer proof must not use the run-wide paginator"); }, rest: { actions: { + getWorkflow: async options => { + assert.deepEqual(options, {...baseContext.repo, workflow_id: "runtime-images.yml"}); + return {data: workflow}; + }, + getWorkflowRun: async options => { + assert.deepEqual(options, {...baseContext.repo, run_id: 4242}); + reads++; + if (error) throw Error("API unavailable"); + selected = runs[Math.min(reads - 1, runs.length - 1)]; + return {data: selected}; + }, + getWorkflowRunAttempt: async options => { + recordProof("getWorkflowRunAttempt", options); + if (attemptError) throw Error("native attempt unavailable"); + if (expireAfterAttempt) clock += 120000; + return {data: nativeAttempt === undefined ? selected : nativeAttempt}; + }, + listJobsForWorkflowRunAttempt: async options => { + recordProof("listJobsForWorkflowRunAttempt", options, true); + if (jobError) throw Error("native jobs unavailable"); + if (expireAfterJobs) clock += 120000; + if (jobPages) return {data: jobPages[options.page - 1]}; + const inventory = jobs ?? [producerFor(selected)]; + return {data: {total_count: inventory.length, jobs: inventory.slice((options.page - 1) * 100, options.page * 100)}}; + }, + listJobsForWorkflowRun: async () => { throw Error("run-wide jobs cannot prove an artifact producer attempt"); }, } } }; - await resolver(github, context, {notice: () => {}, setOutput: (key, value) => {output[key] = value;}}, {now: () => {clock += 60000; return clock;}}, fn => fn()); - if (jobs.some(job => (job.steps ?? []).some(step => step.conclusion === "success"))) { + try { + await resolver(github, context, {notice: () => {}, setOutput: (key, value) => {output[key] = value;}}, + FixtureDate, fn => {clock += 60000; fn();}, + {timeout: milliseconds => {const signal = {timeoutMs: milliseconds}; signals.push(signal); return signal;}}); + } catch (failure) { + assert.deepEqual(output, {}, "invalid, incomplete or unavailable proof must expose no source before failing closed"); + throw failure; + } + assert.equal(proofRequests[0]?.method, "getWorkflowRunAttempt"); + assert(proofRequests.slice(1).every(row => row.method === "listJobsForWorkflowRunAttempt")); + assert.equal(new Set(proofRequests.map(row => row.signal)).size, proofRequests.length, + "each direct proof request must receive a fresh timeout signal"); + if (expectException) { assert.deepEqual(output, {}, "exception attempts must expose no publication source"); - return {reads, output}; + return {reads, output, proofRequests}; } assert.equal(output.title, title); assert.equal(output.artifact_name, `pr-runtime-images-pr-merge-${sha("c")}`); assert.equal(JSON.parse(output.source).status, "completed"); - return {reads, output}; + return {reads, output, proofRequests}; } const runtimeWorkflow = fs.readFileSync(process.argv[4], "utf8"); const diagnosticPaths = [ @@ -307,11 +366,133 @@ for (const publishable of ["false", "", undefined]) { await dispatch({rest: {repos: {createDispatchEvent: async payload => {dispatched = payload;}}}}, baseContext); assert.deepEqual(dispatched, {...baseContext.repo, event_type: "pr-runtime-image-publication", client_payload: {source_run_id: "4242"}}); const direct = await resolve(); - const exceptionJob = {name: "PR Full-Stack Smoke (runtime-required=true)", steps: [{ + const exceptionJob = {...producerFor(source), steps: [{ name: "Known canonical transition PLAY failure with successful authenticated cleanup", - status: "completed", conclusion: "success"}]}; - assert.deepEqual((await resolve({jobs: [exceptionJob]})).output, {}); - assert.equal((await resolve({jobs: [{...exceptionJob, steps: [{...exceptionJob.steps[0], conclusion: "skipped"}]}]})).output.title, title); + number: 24, status: "completed", conclusion: "success"}]}; + assert.deepEqual((await resolve({jobs: [exceptionJob], expectException: true})).output, {}); + assert.equal((await resolve({jobs: [{...exceptionJob, steps: [ + ...producerFor(source).steps, {...exceptionJob.steps[0], conclusion: "skipped"}, + ]}]})).output.title, title); + const producer = producerFor(source); + const uploadStep = producer.steps[0]; + assert.equal((await resolve({jobs: [producerFor(source, false)]})).output.title, title, + "a positively proved runtime-required=false build remains publishable"); + assert.equal((await resolve({jobs: [{...producer, workflow_name: title}]})).output.title, title); + assert.equal((await resolve({nativeAttempt: {...source, name: "Build Runtime Images"}})).output.title, title, + "both native workflow-name projections retain exact title identity"); + assert.equal((await resolve({nativeAttempt: {...source, created_at: "2026-01-08T00:00:01Z"}})).output.title, title, + "native attempt creation can be rounded to the following second within one second of start"); + assert.equal((await resolve({jobs: [{...producer, started_at: "2026-01-08T00:00:00Z"}]})).output.title, title, + "second-precision first-attempt execution may share the native fractional start's boundary second"); + + // A run-wide projection can retain the original timestamps on a rerun. Only + // the exact-attempt endpoint's own execution window can qualify its producer. + const rerun = {...source, run_attempt: 2}; + const attempt2 = {...rerun, created_at: "2026-01-08T01:00:00Z", + run_started_at: "2026-01-08T01:00:00.500Z", updated_at: "2026-01-08T01:04:00Z"}; + const rerunProducer = producerFor(attempt2); + const rerunResult = await resolve({runs: [rerun], nativeAttempt: attempt2, jobs: [rerunProducer]}); + assert.deepEqual(JSON.parse(rerunResult.output.source), rerun, + "exact valid rerun proof preserves the selected source projection and existing artifact identity"); + assert.deepEqual(rerunResult.proofRequests.map(({method, attempt_number}) => [method, attempt_number]), + [["getWorkflowRunAttempt", 2], ["listJobsForWorkflowRunAttempt", 2]]); + assert.equal((await resolve({runs: [rerun], nativeAttempt: attempt2, jobs: [producerFor(attempt2, false)]})).output.title, + title, "a positively proved runtime-required=false rerun remains publishable"); + await assert.rejects(resolve({runs: [rerun], nativeAttempt: attempt2, jobs: [{...producer, id: 18001, run_attempt: 2}]}), + /did not execute within the selected native attempt/, + "copied attempt-1 producer timestamps cannot qualify a job relabelled as attempt 2"); + await assert.rejects(resolve({runs: [rerun], nativeAttempt: attempt2, + jobs: [{...rerunProducer, steps: [uploadStep]}]}), /upload did not execute within/, + "a fresh rerun job cannot lend its window to a carried-forward upload step"); + const rerunException = {...rerunProducer, steps: exceptionJob.steps}; + assert.deepEqual((await resolve({runs: [rerun], nativeAttempt: attempt2, + jobs: [rerunException], expectException: true})).output, {}, + "the exact-attempt canonical PLAY exception short-circuits without requiring an upload"); + + for (const change of [ + {id: 4243}, {id: "4242"}, {run_attempt: 1}, {run_attempt: "2"}, {run_attempt: undefined}, + {workflow_id: 778}, {path: ".github/workflows/other.yml"}, {path: `${source.path}@refs/heads/develop`}, + {name: "other"}, {display_title: "other"}, {event: "pull_request"}, {head_branch: "other"}, + {head_sha: sha("a")}, {head_sha: undefined}, {repository: {full_name: "fork/FireMUD"}}, + {head_repository: {full_name: "fork/FireMUD"}}, {status: "in_progress"}, {conclusion: "failure"}, + ]) { + await assert.rejects(resolve({runs: [rerun], nativeAttempt: {...attempt2, ...change}, jobs: [rerunProducer]}), + `exact native attempt identity must not drift: ${JSON.stringify(change)}`); + } + await assert.rejects(resolve({nativeAttempt: null}), /source attempt/); + await assert.rejects(resolve({attemptError: true}), /native attempt unavailable/); + await assert.rejects(resolve({jobError: true}), /native jobs unavailable/); + await assert.rejects(resolve({expireAfterAttempt: true}), /bounded deadline/, + "expiry after native metadata prevents any job request or source output"); + await assert.rejects(resolve({expireAfterJobs: true}), /bounded deadline/, + "a last job response arriving after the proof deadline cannot expose a source"); + for (const field of ["created_at", "run_started_at", "updated_at"]) { + for (const value of [undefined, null, "", "not-a-date", "2026-02-30T00:00:00Z", "2026-01-08T00:00:00+00:00"]) { + await assert.rejects(resolve({nativeAttempt: {...source, [field]: value}}), /UTC timestamp/); + } + } + for (const change of [ + {created_at: "2026-01-08T00:00:02Z"}, {updated_at: "2026-01-07T23:59:59Z"}, + ]) await assert.rejects(resolve({nativeAttempt: {...source, ...change}}), /chronology/); + for (const change of [ + {id: 0}, {id: "8001"}, {run_id: 4243}, {run_attempt: 2}, {run_attempt: undefined}, + {head_sha: sha("a")}, {head_sha: undefined}, {workflow_name: "other"}, + {name: "PR Full-Stack Smoke (runtime-required=unknown)"}, {status: "in_progress"}, + {conclusion: "skipped"}, {conclusion: "failure"}, {conclusion: "cancelled"}, + {steps: undefined}, {steps: {}}, {steps: []}, + {started_at: undefined}, {completed_at: null}, {started_at: "2026-01-07T23:59:59Z"}, + {completed_at: "2026-01-08T00:00:00Z"}, {completed_at: "2026-01-08T00:04:01Z"}, + ]) { + await assert.rejects(resolve({jobs: [{...producer, ...change}]}), + `producer proof must be complete, successful, attributable and chronological: ${JSON.stringify(change)}`); + } + for (const change of [ + {name: "Upload other artifact"}, {number: undefined}, {number: 0}, {number: "20"}, + {status: "in_progress"}, {conclusion: "skipped"}, {conclusion: "failure"}, {conclusion: "cancelled"}, + {started_at: undefined}, {completed_at: undefined}, {started_at: "2026-01-08T00:00:00Z"}, + {completed_at: "2026-01-08T00:01:59Z"}, {completed_at: "2026-01-08T00:03:01Z"}, + ]) { + await assert.rejects(resolve({jobs: [{...producer, steps: [{...uploadStep, ...change}]}]}), + `the actual upload step must prove successful execution inside its producer: ${JSON.stringify(change)}`); + } + for (const steps of [[uploadStep, uploadStep], [uploadStep, {...uploadStep, number: 21}], + [uploadStep, {...uploadStep, name: "Other step"}]]) { + await assert.rejects(resolve({jobs: [{...producer, steps}]}), /actual successful Upload/, + "duplicate upload names or step numbers are ambiguous proof"); + } + const sibling = {...producer, id: 8002, name: "Sibling"}; + await assert.rejects(resolve({jobs: [{...producer, steps: []}, sibling]}), /actual successful Upload/, + "a successful upload in another job cannot substitute for the producer's upload"); + await assert.rejects(resolve({jobs: [sibling]}), /one successful attributable artifact producer/); + await assert.rejects(resolve({jobs: []}), /one successful attributable artifact producer/); + await assert.rejects(resolve({jobs: [producer, {...producer, id: 8002}]}), /one successful attributable artifact producer/); + await assert.rejects(resolve({jobs: [producer, {...producerFor(source, false), id: 8002}]}), + /one successful attributable artifact producer/, "both evaluated producer names together remain ambiguous"); + await assert.rejects(resolve({jobs: [producer, producer]}), /duplicate or unattributable/); + + const siblings = Array.from({length: 999}, (_, index) => ({...sibling, id: 9000 + index})); + const paged = await resolve({jobs: [...siblings.slice(0, 100), producer]}); + assert.deepEqual(paged.proofRequests.slice(1).map(row => row.page), [1, 2], + "the producer may be proved only after reading every page of its exact attempt inventory"); + const bounded = await resolve({jobs: [...siblings, producer]}); + assert.deepEqual(bounded.proofRequests.slice(1).map(row => row.page), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + await assert.rejects(resolve({jobs: [...siblings, {...sibling, id: 10000}, producer]}), /inventory/, + "over-budget inventories fail closed rather than truncating to a plausible producer"); + for (const data of [undefined, {}, {total_count: -1, jobs: []}, {total_count: 1.5, jobs: [producer]}, + {total_count: "1", jobs: [producer]}, {total_count: 1, jobs: null}, {total_count: 2, jobs: [producer]}, + {total_count: 0, jobs: [producer]}]) { + await assert.rejects(resolve({jobPages: [data]}), /inventory/); + } + const firstPage = siblings.slice(0, 99).concat(producer); + for (const lastPage of [undefined, {total_count: 102, jobs: [sibling, {...sibling, id: 8003}]}, + {total_count: 101, jobs: []}, {total_count: 101, jobs: [firstPage[0]]}]) { + await assert.rejects(resolve({jobPages: [{total_count: 101, jobs: firstPage}, lastPage]}), /inventory/, + "a valid producer on page one cannot authorize incomplete, shifting or duplicate later evidence"); + } + await assert.rejects(resolve({expectException: true, jobPages: [ + {total_count: 101, jobs: [...siblings.slice(0, 99), exceptionJob]}, + {total_count: 101, jobs: []}, + ]}), /inventory/, "the PLAY exception is classified from the same complete exact-attempt inventory"); const pending = {...source, status: "in_progress", conclusion: null}; assert.equal((await resolve({runs: [pending, source]})).reads, 2); const callbackContext = {...baseContext, eventName: "workflow_run", payload: {repository, workflow_run: source}}; @@ -320,6 +501,8 @@ for (const publishable of ["false", "", undefined]) { assert.equal(callback.output.artifact_name, direct.output.artifact_name); const prSource = {...source, event: "pull_request", head_sha: sha("a"), head_branch: "feature/ci"}; const prCallback = {...callbackContext, payload: {repository, workflow_run: prSource}}; + assert.equal((await resolve({runs: [prSource], context: prCallback, + nativeAttempt: {...prSource, path: `${source.path}@refs/pull/42/merge`}})).output.title, title); await assert.rejects(resolve({runs: [prSource]}), /publication source run provenance is not trusted/); assert.equal((await resolve({runs: [prSource], context: prCallback})).output.artifact_name, direct.output.artifact_name); const mergePath = `${source.path}@refs/pull/42/merge`; @@ -412,7 +595,7 @@ for (const publishable of ["false", "", undefined]) { await assert.rejects(resolve({context: {...baseContext, payload: {...baseContext.payload, client_payload: {source_run_id: "4242", extra: true}}}})); await assert.rejects(resolve({context: {...baseContext, payload: {...baseContext.payload, client_payload: {source_run_id: "../4242"}}}})); await assert.rejects(resolve({context: {...callbackContext, payload: {repository, workflow_run: {...source, head_sha: sha("d")}}}}), /differs from callback/); - console.log("Exact source handoff and terminal-resolution fixtures passed."); + console.log("Exact source handoff, terminal-resolution and bounded artifact-producer proof fixtures passed."); })().catch(error => { console.error(error); process.exitCode = 1; }); JS @@ -469,7 +652,7 @@ const typedRefresh = { async function runReconcile({ ambiguousPost = true, expireFirstRequest = false, initialDiscoveryUnavailable = false, ciRuns = [ciRun], ciNativeRuns = {}, ciJobsByRun = {}, postVisibilityRuns = null, - postVisibilityFailures = [], preflightRefreshRuns = [], refreshNativeRuns = {}, + postVisibilityFailures = [], preflightRefreshRuns = [], refreshNativeRuns = {}, refreshAttemptJobs = {}, } = {}) { let now = Date.parse("2026-01-08T00:00:00Z"); let expire = expireFirstRequest; @@ -561,6 +744,12 @@ async function runReconcile({ record("actions.listJobsForWorkflowRunAttempt", options, { owner, repo, run_id, attempt_number, per_page: 100, page, }); + const refresh = preflightRefreshRuns.find(run => run.id === run_id); + if (refresh) { + assert.equal(attempt_number, refresh.run_attempt); + assert.equal(page, 1); + return {data: refreshAttemptJobs[run_id] ?? {total_count: 0, jobs: []}}; + } assert.equal(attempt_number, (ciNativeRuns[run_id] ?? ciRun).run_attempt); assert(Number.isInteger(page) && page > 0); nativeJobRunIds.push(run_id); @@ -796,12 +985,28 @@ async function runReconcile({ assert.equal(held.postAttempts, 0, "all other exact typed results continue suppressing recovery"); assert.deepEqual(held.nativeRefreshRunIds, [], "only cancelled/timed_out results enter native verification"); } - const legacyFailedPlay = {...typedRefresh, id: typedRefresh.id + 1, conclusion: "failure"}; + const legacyFailedPlay = {...typedRefresh, id: typedRefresh.id + 1, conclusion: "failure", + run_started_at: "2026-01-06T00:00:00Z", updated_at: "2026-01-06T00:03:00Z"}; + const marker = {name: "Known canonical transition PLAY failure with successful authenticated cleanup", status: "completed", + conclusion: "skipped", started_at: "2026-01-06T00:01:00Z", completed_at: "2026-01-06T00:01:00Z"}; + const failedJob = {id: 122, name: "PR Full-Stack Smoke (runtime-required=true)", run_id: legacyFailedPlay.id, + run_attempt: legacyFailedPlay.run_attempt, head_sha: legacyFailedPlay.head_sha, workflow_name: "Build Runtime Images", + status: "completed", conclusion: "failure", started_at: "2026-01-06T00:00:01Z", completed_at: "2026-01-06T00:02:00Z", steps: [marker]}; + for (const [job, expectedPosts] of [ + [failedJob, 1], + [{...failedJob, steps: [{...marker, conclusion: "success"}]}, 0], + [{...failedJob, started_at: "2026-01-05T23:59:59Z"}, 0], + ]) { + const result = await runReconcile({preflightRefreshRuns: [legacyFailedPlay], + refreshAttemptJobs: {[legacyFailedPlay.id]: {total_count: 1, jobs: [job]}}}); + assert.equal(result.failure, null); + assert.equal(result.postAttempts, expectedPosts); + } const legacyFailureHold = await runReconcile({preflightRefreshRuns: [typedRefresh, legacyFailedPlay]}); assert.equal(legacyFailureHold.failure, null); assert.equal(legacyFailureHold.postAttempts, 0, "a legacy failed PLAY typed refresh retains its hold even alongside a verified cancelled result"); - assert.deepEqual(legacyFailureHold.nativeRefreshRunIds, [typedRefresh.id]); + assert.deepEqual(legacyFailureHold.nativeRefreshRunIds, [typedRefresh.id, legacyFailedPlay.id]); assert(legacyFailureHold.warnings.some(message => message.includes(String(legacyFailedPlay.id)) && message.includes("failed") && message.includes("explicit investigation, not automatic replay")), "legacy failure holds must be reported separately from supported terminal recovery"); From a9fbd8579572f8486f8ff47e1d8e821b4d8fb726 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 01:30:49 +1300 Subject: [PATCH 43/96] Correct smoke recovery and Account proof from both review lanes --- .../workflows/publish-pr-runtime-images.yml | 74 ++++-- .github/workflows/runtime-images.yml | 181 +++++++------ .github/workflows/smoke.yml | 131 ++++++++-- .../account-service/api-contracts.md | 6 +- .../account-service/runtime-and-data.md | 2 +- .../game-session-service/runtime-and-data.md | 4 +- ...system-architecture-database-migrations.md | 9 + .../pr-required-gate-context-contract.sh | 244 ++++++++++++++++-- .../tests/pr-retarget-workflow-contract.sh | 162 +++++++++++- .../pr-runtime-image-publication-contract.sh | 172 ++++++++++-- dev-tools/tests/smoke-transport-contract.sh | 24 +- ...acityMigrationPostgresIntegrationTest.java | 207 +++++++++++---- ...titlementOwnerPostgresIntegrationTest.java | 11 +- ...tSessionOwnerEvidenceReadGrpcMtlsTest.java | 66 ++++- 14 files changed, 1038 insertions(+), 255 deletions(-) diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index d19f91a9b0..5911fe2c6f 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -84,6 +84,9 @@ jobs: return typeof path === "string" && path.startsWith(prefix) && validWorkflowRef(path.slice(prefix.length)); }; + const samePrPath = (left, right, path, number) => left === right || + left === path && right === `${path}@refs/pull/${number}/merge` || + right === path && left === `${path}@refs/pull/${number}/merge`; const trusted = run => run?.workflow_id === workflow.id && matchesPath(run.path, workflow.path) && run.repository?.full_name === repository && run.head_repository?.full_name === repository && [workflow.name, run.display_title].includes(run.name) && positive(run.id) && positive(run.run_attempt); @@ -91,6 +94,15 @@ jobs: // native producer job with a skipped marker is affirmative proof // that this exact failed attempt cannot supply that exception. const provesOrdinaryTypedFailure = async run => { + const matchesSelected = candidate => candidate && + ["id", "workflow_id", "run_attempt", "path", "display_title", "event", "head_branch", "head_sha", "status", "conclusion"] + .every(field => candidate[field] === run[field]) && + [workflow.name, run.display_title].includes(candidate.name) && + candidate.repository?.full_name === repository && candidate.head_repository?.full_name === repository; + const {data: attempt} = await github.rest.actions.getWorkflowRunAttempt(prePostOptions({ + ...context.repo, run_id: run.id, attempt_number: run.run_attempt, + })); + if (!matchesSelected(attempt)) return false; const {data} = await github.rest.actions.listJobsForWorkflowRunAttempt(prePostOptions({ ...context.repo, run_id: run.id, attempt_number: run.run_attempt, per_page: 100, page: 1, })); @@ -103,10 +115,26 @@ jobs: job.status !== "completed" || job.conclusion !== "failure" || !Array.isArray(job.steps)) return false; const markers = job.steps.filter(step => step?.name === "Known canonical transition PLAY failure with successful authenticated cleanup"); if (markers.length !== 1 || markers[0].status !== "completed" || markers[0].conclusion !== "skipped") return false; - const times = [run.run_started_at, job.started_at, markers[0].started_at, markers[0].completed_at, - job.completed_at, run.updated_at].map(value => - typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value) ? Date.parse(value) : NaN); - return times.every((time, index) => Number.isFinite(time) && (index === 0 || time >= times[index - 1])); + const timestamp = value => { + const match = typeof value === "string" && /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?(Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.exec(value); + const time = match ? Date.parse(value) : NaN; + const wall = match ? `${match[1]}.${(match[2] || "").padEnd(3, "0")}Z` : ""; + const wallMillis = Date.parse(wall); + return Number.isFinite(time) && Number.isFinite(wallMillis) && new Date(wallMillis).toISOString() === wall ? time : NaN; + }; + const [start, jobStart, jobEnd, end] = [attempt.run_started_at, job.started_at, job.completed_at, attempt.updated_at].map(timestamp); + if (![start, jobStart, jobEnd, end].every(Number.isFinite) || end < start || + jobStart < Math.floor(start / 1000) * 1000 || jobEnd < jobStart || jobEnd > Math.floor(end / 1000) * 1000 + 999) return false; + // A skipped step normally has no execution timestamps. If supplied, + // both timestamps must still agree with the actually attempted job. + const marker = markers[0]; + if (marker.started_at != null || marker.completed_at != null) { + const markerStart = timestamp(marker.started_at), markerEnd = timestamp(marker.completed_at); + if (!Number.isFinite(markerStart) || !Number.isFinite(markerEnd) || + markerStart < jobStart || markerEnd < markerStart || markerEnd > jobEnd) return false; + } + const {data: latest} = await github.rest.actions.getWorkflowRun(prePostOptions({...context.repo, run_id: run.id})); + return matchesSelected(latest); }; // Inventory incompleteness is unknown, never permission to dispatch duplicates. const inventory = async (workflowId, filter, deadline = prePostDeadline, phase = "Pre-dispatch", validateVisibilityRun = null) => { @@ -160,7 +188,7 @@ jobs: run.event === "pull_request" && run.status === "completed" && run.conclusion === callback.conclusion && run.repository?.full_name === repository && run.head_repository?.full_name === repository && run.head_sha === wakeHead && run.head_branch === callback.head_branch && - run.display_title === callback.display_title && run.path === callback.path && + run.display_title === callback.display_title && samePrPath(run.path, callback.path, ciWorkflow.path, wakeNumber) && [ciWorkflow.name, callback.display_title].includes(run.name); if (!matchesWake(callback)) return; wakeCurrent = async () => { @@ -193,7 +221,7 @@ jobs: return trusted(run) && run.id === event.id && run.run_attempt === event.run_attempt && run.event === "pull_request" && run.status === "completed" && run.conclusion === event.conclusion && run.head_sha === head && run.display_title === event.display_title && run.head_branch === event.head_branch && - run.path === event.path; + samePrPath(run.path, event.path, workflow.path, number); }; if (!await sourceCurrent()) return; const currentTuple = async () => { @@ -229,6 +257,7 @@ jobs: const matchesCiIdentity = (run, expected) => run && run.id === expected?.id && run.run_attempt === expected?.run_attempt && positive(run.run_attempt) && run.workflow_id === ciWorkflow.id && matchesPath(run.path, ciWorkflow.path) && + samePrPath(run.path, expected.path, ciWorkflow.path, number) && run.event === "pull_request" && run.repository?.full_name === repository && run.head_repository?.full_name === repository && run.head_sha === head && run.head_branch === event.head_branch && run.display_title === ciTitle && @@ -245,7 +274,7 @@ jobs: // is positively classified as metadata, never from its conclusion alone. const recordMetadataWake = () => { if (validationWake && callback.conclusion === "success" && ci.id === callback.id) { - if (ci.run_attempt !== callback.run_attempt || ci.path !== callback.path || + if (ci.run_attempt !== callback.run_attempt || !samePrPath(ci.path, callback.path, ciWorkflow.path, number) || ci.conclusion !== callback.conclusion) return false; skippedExactWake = true; } @@ -659,9 +688,15 @@ jobs: } const sourceId = Number(sourceIdText); const repository = `${context.repo.owner}/${context.repo.repo}`; - const { data: workflow } = await github.rest.actions.getWorkflow({ + const deadline = Date.now() + 120000; + const proofOptions = options => { + const remaining = deadline - Date.now(); + if (remaining <= 0) throw new Error("publication producer proof exceeded its bounded deadline"); + return {...options, request: {signal: AbortSignal.timeout(remaining)}}; + }; + const { data: workflow } = await github.rest.actions.getWorkflow(proofOptions({ ...context.repo, workflow_id: "runtime-images.yml", - }); + })); if (!Number.isSafeInteger(workflow.id) || workflow.id <= 0 || workflow.name !== "Build Runtime Images" || workflow.path !== ".github/workflows/runtime-images.yml") { throw new Error("runtime source workflow identity is not trusted"); @@ -686,25 +721,20 @@ jobs: (left === workflow.path && right === mergePath || right === workflow.path && left === mergePath); } const titlePattern = /^Build Runtime Images secure-pr-artifact pr-([1-9][0-9]*) base-([0-9a-f]{40}) head-([0-9a-f]{40}) merge-([0-9a-f]{40}) mode-required$/; - const deadline = Date.now() + 120000; - const proofOptions = options => { - const remaining = deadline - Date.now(); - if (remaining <= 0) throw new Error("publication producer proof exceeded its bounded deadline"); - return {...options, request: {signal: AbortSignal.timeout(remaining)}}; - }; const timestamp = value => { - const match = typeof value === "string" && /^(?:\d{4}-\d{2}-\d{2})T\d{2}:\d{2}:\d{2}(?:\.(\d{1,3}))?Z$/.exec(value); + const match = typeof value === "string" && /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?(Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.exec(value); const time = match ? Date.parse(value) : NaN; - if (!Number.isFinite(time) || new Date(time).toISOString() !== - `${value.slice(0, 19)}.${(match[1] || "").padEnd(3, "0")}Z`) { - throw new Error("publication producer proof has a missing or invalid UTC timestamp"); + const wallTime = match ? `${match[1]}.${(match[2] || "").padEnd(3, "0")}Z` : ""; + const wallMillis = Date.parse(wallTime); + if (!Number.isFinite(time) || !Number.isFinite(wallMillis) || new Date(wallMillis).toISOString() !== wallTime) { + throw new Error("publication producer proof has a missing or invalid ISO timestamp"); } return time; }; for (;;) { - const { data: run } = await github.rest.actions.getWorkflowRun({ + const { data: run } = await github.rest.actions.getWorkflowRun(proofOptions({ ...context.repo, run_id: sourceId, - }); + })); const title = typeof run.display_title === "string" && run.display_title.match(titlePattern); if (run.id !== sourceId || run.workflow_id !== workflow.id || !Number.isSafeInteger(run.run_attempt) || run.run_attempt <= 0 || @@ -828,7 +858,7 @@ jobs: run.conclusion != null || Date.now() >= deadline) { throw new Error("publication source did not reach a real terminal success within the bounded wait"); } - await new Promise(resolve => setTimeout(resolve, 2000)); + await new Promise(resolve => setTimeout(resolve, Math.min(2000, deadline - Date.now()))); } publish: diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 861860964a..47305b10ac 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -800,10 +800,23 @@ jobs: const ref = path.slice(prefix.length); return validWorkflowRef(ref); }; + const samePrPath = (left, right, path, number) => left === right || + left === path && right === `${path}@refs/pull/${number}/merge` || + right === path && left === `${path}@refs/pull/${number}/merge`; // The older PLAY diagnostic can leave the source run red. Only a // complete native attempt with its marker explicitly skipped can // prove that a failed producer did not supply that exception. const provesOrdinaryTypedFailure = async (run, workflowName) => { + const repository = `${context.repo.owner}/${context.repo.repo}`; + const matchesSelected = candidate => candidate && + ["id", "workflow_id", "run_attempt", "path", "display_title", "event", "head_branch", "head_sha", "status", "conclusion"] + .every(field => candidate[field] === run[field]) && + [workflowName, run.display_title].includes(candidate.name) && + candidate.repository?.full_name === repository && candidate.head_repository?.full_name === repository; + const {data: attempt} = await github.rest.actions.getWorkflowRunAttempt(fanoutOptions({ + ...context.repo, run_id: run.id, attempt_number: run.run_attempt, + })); + if (!matchesSelected(attempt)) return false; const {data} = await github.rest.actions.listJobsForWorkflowRunAttempt(fanoutOptions({ ...context.repo, run_id: run.id, attempt_number: run.run_attempt, per_page: 100, page: 1, })); @@ -816,10 +829,26 @@ jobs: job.status !== "completed" || job.conclusion !== "failure" || !Array.isArray(job.steps)) return false; const markers = job.steps.filter(step => step?.name === "Known canonical transition PLAY failure with successful authenticated cleanup"); if (markers.length !== 1 || markers[0].status !== "completed" || markers[0].conclusion !== "skipped") return false; - const times = [run.run_started_at, job.started_at, markers[0].started_at, markers[0].completed_at, - job.completed_at, run.updated_at].map(value => - typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value) ? Date.parse(value) : NaN); - return times.every((time, index) => Number.isFinite(time) && (index === 0 || time >= times[index - 1])); + const timestamp = value => { + const match = typeof value === "string" && /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?(Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.exec(value); + const time = match ? Date.parse(value) : NaN; + const wall = match ? `${match[1]}.${(match[2] || "").padEnd(3, "0")}Z` : ""; + const wallMillis = Date.parse(wall); + return Number.isFinite(time) && Number.isFinite(wallMillis) && new Date(wallMillis).toISOString() === wall ? time : NaN; + }; + const [start, jobStart, jobEnd, end] = [attempt.run_started_at, job.started_at, job.completed_at, attempt.updated_at].map(timestamp); + if (![start, jobStart, jobEnd, end].every(Number.isFinite) || end < start || + jobStart < Math.floor(start / 1000) * 1000 || jobEnd < jobStart || jobEnd > Math.floor(end / 1000) * 1000 + 999) return false; + // A skipped step normally has no execution timestamps. If supplied, + // both timestamps must still agree with the actually attempted job. + const marker = markers[0]; + if (marker.started_at != null || marker.completed_at != null) { + const markerStart = timestamp(marker.started_at), markerEnd = timestamp(marker.completed_at); + if (!Number.isFinite(markerStart) || !Number.isFinite(markerEnd) || + markerStart < jobStart || markerEnd < markerStart || markerEnd > jobEnd) return false; + } + const {data: latest} = await github.rest.actions.getWorkflowRun(fanoutOptions({...context.repo, run_id: run.id})); + return matchesSelected(latest); }; // Bind both admission reads to the same terminal attempt; never cache native proof. const disregardedTypedAttempts = new Map(); @@ -860,69 +889,70 @@ jobs: } } ordered.sort((left, right) => Date.parse(right.created_at) - Date.parse(left.created_at)); - if (ordered.length > 1 && Date.parse(ordered[0].created_at) === Date.parse(ordered[1].created_at)) { - throw new Error("newest exact runtime producer has an ambiguous created_at timestamp"); - } - const newest = ordered[0]; - if (!newest) { - return []; - } - if (["queued", "waiting", "requested", "pending", "in_progress"].includes(newest.status)) { - if (newest.conclusion !== null && newest.conclusion !== undefined) { - throw new Error(`run ${newest.id} has a conclusion while still ${newest.status}`); + for (const [index, newest] of ordered.entries()) { + if (index + 1 < ordered.length && Date.parse(newest.created_at) === Date.parse(ordered[index + 1].created_at)) { + throw new Error("newest exact runtime producer has an ambiguous created_at timestamp"); } - return [newest]; - } - if (newest.status === "completed") { - if (newest.event === "repository_dispatch" && ["cancelled", "timed_out", "failure"].includes(newest.conclusion)) { - const repository = `${context.repo.owner}/${context.repo.repo}`; - const defaultBranch = context.payload.repository?.default_branch; - const attemptBinding = JSON.stringify([ - newest.run_attempt, newest.conclusion, newest.head_sha, newest.path, newest.created_at, - ]); - if (!Number.isSafeInteger(newest.run_attempt) || newest.run_attempt <= 0 || - context.payload.repository?.full_name !== repository || - typeof defaultBranch !== "string" || !defaultBranch || newest.head_branch !== defaultBranch || - typeof newest.head_sha !== "string" || !shaPattern.test(newest.head_sha) || - (disregardedTypedAttempts.has(newest.id) && disregardedTypedAttempts.get(newest.id) !== attemptBinding)) { - throw new Error(`Terminal typed runtime producer ${newest.id} has incomplete or changed attempt identity`); + if (["queued", "waiting", "requested", "pending", "in_progress"].includes(newest.status)) { + if (newest.conclusion !== null && newest.conclusion !== undefined) { + throw new Error(`run ${newest.id} has a conclusion while still ${newest.status}`); } - const {data: workflow} = await github.rest.actions.getWorkflow(fanoutOptions({ - ...context.repo, workflow_id: "runtime-images.yml", - })); - const {data: latest} = await github.rest.actions.getWorkflowRun(fanoutOptions({ - ...context.repo, run_id: newest.id, - })); - if (!Number.isSafeInteger(workflow?.id) || workflow.id <= 0 || - workflow.id !== newest.workflow_id || workflow.path !== expectedWorkflowPath || - workflow.name !== "Build Runtime Images" || - latest?.id !== newest.id || latest.run_attempt !== newest.run_attempt || - latest.workflow_id !== workflow.id || latest.event !== "repository_dispatch" || - latest.path !== newest.path || !workflowPathMatches(latest.path) || - ![workflow.name, expectedTitle].includes(latest.name) || latest.display_title !== expectedTitle || - latest.repository?.full_name !== repository || latest.head_repository?.full_name !== repository || - latest.head_branch !== defaultBranch || latest.head_sha !== newest.head_sha || - latest.created_at !== newest.created_at || latest.status !== "completed" || - latest.conclusion !== newest.conclusion) { - throw new Error(`Terminal typed runtime producer ${newest.id} no longer has the same trusted terminal attempt`); + return [newest]; + } + if (newest.status === "completed") { + if (newest.event === "repository_dispatch" && ["cancelled", "timed_out", "failure"].includes(newest.conclusion)) { + const repository = `${context.repo.owner}/${context.repo.repo}`; + const defaultBranch = context.payload.repository?.default_branch; + const attemptBinding = JSON.stringify([ + newest.run_attempt, newest.conclusion, newest.head_sha, newest.path, newest.created_at, + ]); + if (!Number.isSafeInteger(newest.run_attempt) || newest.run_attempt <= 0 || + context.payload.repository?.full_name !== repository || + typeof defaultBranch !== "string" || !defaultBranch || newest.head_branch !== defaultBranch || + typeof newest.head_sha !== "string" || !shaPattern.test(newest.head_sha) || + (disregardedTypedAttempts.has(newest.id) && disregardedTypedAttempts.get(newest.id) !== attemptBinding)) { + throw new Error(`Terminal typed runtime producer ${newest.id} has incomplete or changed attempt identity`); + } + const {data: workflow} = await github.rest.actions.getWorkflow(fanoutOptions({ + ...context.repo, workflow_id: "runtime-images.yml", + })); + const {data: latest} = await github.rest.actions.getWorkflowRun(fanoutOptions({ + ...context.repo, run_id: newest.id, + })); + if (!Number.isSafeInteger(workflow?.id) || workflow.id <= 0 || + workflow.id !== newest.workflow_id || workflow.path !== expectedWorkflowPath || + workflow.name !== "Build Runtime Images" || + latest?.id !== newest.id || latest.run_attempt !== newest.run_attempt || + latest.workflow_id !== workflow.id || latest.event !== "repository_dispatch" || + latest.path !== newest.path || !workflowPathMatches(latest.path) || + ![workflow.name, expectedTitle].includes(latest.name) || latest.display_title !== expectedTitle || + latest.repository?.full_name !== repository || latest.head_repository?.full_name !== repository || + latest.head_branch !== defaultBranch || latest.head_sha !== newest.head_sha || + latest.created_at !== newest.created_at || latest.status !== "completed" || + latest.conclusion !== newest.conclusion) { + throw new Error(`Terminal typed runtime producer ${newest.id} no longer has the same trusted terminal attempt`); + } + if (newest.conclusion === "failure" && !await provesOrdinaryTypedFailure(latest, workflow.name)) { + return [newest]; + } + disregardedTypedAttempts.set(newest.id, attemptBinding); + // Discarding an unusable replacement does not establish + // absence: an earlier exact producer may still be running. + continue; } - if (newest.conclusion === "failure" && !await provesOrdinaryTypedFailure(latest, workflow.name)) { + // Same-second or incomparable completion evidence is ambiguous and + // suppresses a duplicate; only a valid, strictly older producer may recover. + const ciCompleted = Date.parse(workflowRun.updated_at || ""); + if (newest.event === "repository_dispatch" && + (!Number.isFinite(ciCompleted) || + Math.floor(Date.parse(newest.created_at) / 1000) >= Math.floor(ciCompleted / 1000))) { return [newest]; } - disregardedTypedAttempts.set(newest.id, attemptBinding); - return []; - } - // Same-second or incomparable completion evidence is ambiguous and - // suppresses a duplicate; only a valid, strictly older producer may recover. - const ciCompleted = Date.parse(workflowRun.updated_at || ""); - if (newest.event === "repository_dispatch" && - (!Number.isFinite(ciCompleted) || - Math.floor(Date.parse(newest.created_at) / 1000) >= Math.floor(ciCompleted / 1000))) { - return [newest]; + continue; } - return []; + throw new Error(`run ${newest.id} has an unknown status and cannot be classified`); } - throw new Error(`run ${newest.id} has an unknown status and cannot be classified`); + return []; }; if (!shaPattern.test(refreshSha) || typeof refreshBranch !== "string" || @@ -949,7 +979,8 @@ jobs: run.head_branch === refreshBranch && run.head_sha === refreshSha && run.display_title === workflowRun.display_title && [ciName, workflowRun.display_title].includes(run.name) && - workflowPathMatches(run.path, ciPath) && run.path === workflowRun.path; + workflowPathMatches(run.path, ciPath) && + samePrPath(run.path, workflowRun.path, ciPath, titleMatch?.[1]); if (!titleMatch || titleMatch[3] !== refreshSha) { core.warning("Skipping PR runtime reconciliation: callback lacks exact CI PR/base/head title metadata."); return; @@ -1104,8 +1135,6 @@ jobs: } const pendingVisibility = []; let visibilitySince; - let runtimeInventoryPromise; - let runtimeInventoryError = null; const reportFanoutCutoff = (targetIndex, stage) => { const incompleteTargets = refreshTargets.slice(targetIndex) .map(({tuple: targetTuple}) => `#${targetTuple.prNumber}`).join(", "); @@ -1135,16 +1164,13 @@ jobs: let existingProducers = []; let fallbackReason = null; let inventory; - if (runtimeInventoryError) { - fallbackReason = runtimeInventoryError; - } else { - try { - runtimeInventoryPromise ??= loadExistingRuntimeRuns(); - inventory = await runtimeInventoryPromise; - } catch (error) { - fallbackReason = error.message || String(error); - runtimeInventoryError = fallbackReason; - } + try { + // Earlier targets and preview work can outlive a producer. + // Classify this target from a fresh complete snapshot, not a + // prior target's queued/in-progress duplicate hold. + inventory = await loadExistingRuntimeRuns(); + } catch (error) { + fallbackReason = error.message || String(error); } if (!fallbackReason) { try { @@ -1166,8 +1192,6 @@ jobs: break; } core.setFailed(`Cannot verify exact runtime producer inventory for PR #${tuple.prNumber}; no dispatch issued: ${fallbackReason}`); - runtimeInventoryPromise = undefined; - runtimeInventoryError = null; break runtimeRefresh; } if (existingProducers.length > 0) { @@ -1218,8 +1242,7 @@ jobs: // both duplicate suppression and the visibility baseline after // the potentially slow live comparison checks. try { - runtimeInventoryPromise = loadExistingRuntimeRuns(); - inventory = await runtimeInventoryPromise; + inventory = await loadExistingRuntimeRuns(); const latestProducers = await findExactExistingProducer(tuple, inventory); if (!inventory.complete || !latestProducers.length && inventory.absenceProven === false) { throw new Error(inventory.reason || "the final producer inventory cannot prove absence"); @@ -1234,8 +1257,6 @@ jobs: break; } core.setFailed(`Cannot verify final runtime producer inventory for PR #${tuple.prNumber}; no dispatch issued: ${error.message || error}`); - runtimeInventoryPromise = undefined; - runtimeInventoryError = null; break runtimeRefresh; } if (Date.now() >= fanoutDeadline) { @@ -1281,10 +1302,8 @@ jobs: } pending.responseUnknown = true; core.warning(`Runtime refresh handoff for PR #${tuple.prNumber} is uncertain; no retry issued: ${error.message || error}`); - runtimeInventoryPromise = undefined; break runtimeRefresh; } - runtimeInventoryPromise = undefined; } } else if (runtimeChanges === false) { core.info(`Skipping PR runtime image refresh for #${tuple.prNumber}: no runtime-changing files.`); diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 8c981e520a..d6ffca8b1f 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -632,7 +632,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "6482868075dd050438a52b0f2cf2537f7a469d21cabf2759b79b30aa4466e0a9"; + const canonicalRuntimeWorkflowSha256 = "094ece17d1b7418151b808959028fea2584f434629e1c5f1e5bfaed3cebeeb3c"; // Only authenticated default-branch refreshes may use retained successful definitions. // Keep the pre-rollout default and predecessor definitions for mixed-version runs. const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set([ @@ -930,10 +930,14 @@ jobs: step.name === "Run credential-free full-stack smoke" ); if (smokeSteps.length > 1) return false; - if (smokeSteps.length === 0) return pendingExactSnapshot(); - if (smokeSteps[0].conclusion != null && smokeSteps[0].conclusion !== "success") return false; - if (smokeSteps[0].status !== "completed" || - smokeSteps[0].conclusion == null) return pendingExactSnapshot(); + // Only the fingerprinted terminal guard can attest an omitted probe + // row. Older definitions still need affirmative step evidence. + if (smokeSteps.length === 0 && !currentDefinition) return pendingExactSnapshot(); + if (smokeSteps.length === 1) { + if (smokeSteps[0].conclusion != null && smokeSteps[0].conclusion !== "success") return false; + if (smokeSteps[0].status !== "completed" || + smokeSteps[0].conclusion == null) return pendingExactSnapshot(); + } for (const name of [ "Stop smoke stack", "Require successful runtime smoke and authenticated cleanup", @@ -1232,6 +1236,22 @@ jobs: } } + // Cancellation/timeout grants waiting time, never smoke proof. Even that bounded + // recovery requires an attributable native typed producer for this tuple. + function isReplaceableTypedProducer(run, identity) { + const title = `Build Runtime Images secure-pr-artifact pr-${prNumber} ` + + `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; + return run.event === "repository_dispatch" && run.status === "completed" && + ["cancelled", "timed_out"].includes(run.conclusion) && positiveInteger(run.id) && positiveInteger(run.run_attempt) && + positiveInteger(run.workflow_id) && run.repository?.full_name === repositoryName && + run.head_repository?.full_name === repositoryName && + isRuntimeSourceWorkflowPath(run.path, run.event, prNumber) && run.display_title === title && + typeof context.payload.repository?.default_branch === "string" && + context.payload.repository.default_branch.length > 0 && + run.head_branch === context.payload.repository.default_branch && + typeof run.head_sha === "string" && /^[0-9a-f]{40}$/.test(run.head_sha); + } + async function verifyFailedPullCanonicalRefresh(run, identity) { if (repositoryName !== "benhook1013/FireMUD" || context.payload.pull_request.head.repo?.full_name !== repositoryName || @@ -1251,6 +1271,9 @@ jobs: if (["queued", "in_progress", "waiting", "pending", "requested"].includes(replacement.status)) { return replacement.conclusion == null ? "pending" : false; } + if (replacement.status === "completed" && ["cancelled", "timed_out"].includes(replacement.conclusion)) { + return isReplaceableTypedProducer(replacement, identity) ? replacement.conclusion : false; + } if (replacement.status !== "completed" || (replacement.conclusion != null && !["success", "failure"].includes(replacement.conclusion))) return false; const proofRun = {id: replacement.id, run_attempt: replacement.run_attempt, @@ -1524,9 +1547,12 @@ jobs: let absentRefreshObservedAt = null; let requireCurrentIdentity = false; let cancelledRunId = null; + let cancelledRunAttempt = null; let cancelledRunObservedAt = null; let cancelledReplacement = null; let cancelledRecoveryMoved = false; + let cancelledTypedRecoveryKey = null; + let cancelledTypedRecoveryObservedAt = null; async function verifySameTupleReplacementProof(replacement, identity) { if (replacement.event !== "repository_dispatch" || !positiveInteger(replacement.id) || !positiveInteger(replacement.run_attempt) || @@ -1615,20 +1641,25 @@ jobs: currentIdentity.sourceEvent === "pull_request" && cancelledRunId !== null && (matching?.id !== cancelledRunId || + matching.run_attempt !== cancelledRunAttempt || matching.status !== "completed" || matching.conclusion !== "cancelled") ) { cancelledRunId = null; + cancelledRunAttempt = null; cancelledRunObservedAt = null; cancelledReplacement = null; + incompleteRefreshKey = null; + incompleteRefreshObservedAt = null; } if ( currentIdentity.sourceEvent === "pull_request" && matching?.status === "completed" && matching.conclusion === "cancelled" ) { - if (cancelledRunId !== matching.id) { + if (cancelledRunId !== matching.id || cancelledRunAttempt !== matching.run_attempt) { cancelledRunId = matching.id; + cancelledRunAttempt = matching.run_attempt; cancelledRunObservedAt = Date.now(); cancelledReplacement = null; } @@ -1654,7 +1685,8 @@ jobs: (replacement.id > cancelledReplacement.id || (replacement.id === cancelledReplacement.id && replacement.run_attempt > cancelledReplacement.run_attempt)); - if (cancelledReplacement?.terminalObservedAt != null && !supersedingReplacement && + if (!["cancelled", "timed_out"].includes(replacement?.conclusion) && + cancelledReplacement?.terminalObservedAt != null && !supersedingReplacement && Date.now() - cancelledReplacement.terminalObservedAt >= completedSnapshotTimeoutMs) { core.setFailed("Cancelled runtime replacement did not expose complete exact smoke proof within the snapshot convergence allowance."); return; @@ -1671,7 +1703,8 @@ jobs: continue smokeGatePolling; } } - if (!cancelledReplacement && Date.now() - cancelledRunObservedAt >= cancellationDiscoveryMs) { + if ((!cancelledReplacement || cancelledReplacement.awaitingReplacement) && + Date.now() - cancelledRunObservedAt >= cancellationDiscoveryMs) { if (await isCurrentPullRequestObsolete("Stopping obsolete cancelled-run smoke gate for")) { return; } @@ -1693,7 +1726,8 @@ jobs: const liveIdentity = await resolveCurrentIdentity("Fencing listed cancelled-run replacement", true); if (liveIdentity?.obsolete) return; if (!liveIdentity) { - if (!cancelledReplacement && Date.now() - cancelledRunObservedAt >= cancellationDiscoveryMs) { + if ((!cancelledReplacement || cancelledReplacement.awaitingReplacement) && + Date.now() - cancelledRunObservedAt >= cancellationDiscoveryMs) { core.setFailed("Cancelled runtime replacement lacks a verified live PR tuple."); return; } @@ -1727,6 +1761,23 @@ jobs: replacement.run_attempt !== cancelledReplacement.run_attempt)) { cancelledReplacement = {id: replacement.id, run_attempt: replacement.run_attempt, terminalObservedAt: null}; } + if (replacement.status === "completed" && ["cancelled", "timed_out"].includes(replacement.conclusion)) { + if (!isReplaceableTypedProducer(replacement, currentIdentity)) { + core.setFailed("Cancelled or timed-out typed runtime producer has an invalid source identity."); + return; + } + cancelledReplacement.awaitingReplacement = true; + cancelledReplacement.terminalObservedAt = null; + incompleteRefreshKey = null; + incompleteRefreshObservedAt = null; + if (Date.now() - cancelledRunObservedAt >= cancellationDiscoveryMs) { + core.setFailed("Cancelled runtime replacement has no newer exact producer within the recovery allowance."); + return; + } + core.info(`Exact typed replacement ${replacement.id}/${replacement.run_attempt} ended ${replacement.conclusion}; waiting for a newer exact producer.`); + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } if (cancelledReplacement?.id === replacement.id && (replacement.status === "completed" || replacement.status == null)) { cancelledReplacement.terminalObservedAt ??= Date.now(); @@ -1880,6 +1931,45 @@ jobs: } if (matching) { core.info(`Found runtime-images run ${matching.id} with status=${matching.status} conclusion=${matching.conclusion}`); + if (matching.event === "repository_dispatch" && matching.status === "completed" && + matching.conclusion == null) { + if (matching.run_attempt != null && !positiveInteger(matching.run_attempt)) { + core.setFailed("Typed runtime smoke producer lacks an exact attempt."); + return; + } + // A sparse run-list row must be re-listed; a jobs read cannot + // supply its conclusion. Null and absent share one bounded age. + const snapshotKey = `typed-list-conclusion:${matching.id}:${matching.run_attempt ?? "missing"}:${identityKey(currentIdentity)}`; + if (incompleteRefreshKey !== snapshotKey) { + incompleteRefreshKey = snapshotKey; + incompleteRefreshObservedAt = Date.now(); + } + if (Date.now() - incompleteRefreshObservedAt >= completedSnapshotTimeoutMs) { + core.setFailed("Completed typed runtime producer lacks a conclusion within the snapshot convergence allowance."); + return; + } + await new Promise((resolve) => setTimeout(resolve, snapshotSleepMs)); + continue smokeGatePolling; + } + if (matching.event === "repository_dispatch" && matching.status === "completed" && + ["cancelled", "timed_out"].includes(matching.conclusion)) { + if (!isReplaceableTypedProducer(matching, currentIdentity)) { + core.setFailed("Cancelled or timed-out typed runtime producer has an invalid source identity."); + return; + } + const recoveryKey = identityKey(currentIdentity); + if (cancelledTypedRecoveryKey !== recoveryKey) { + cancelledTypedRecoveryKey = recoveryKey; + cancelledTypedRecoveryObservedAt = Date.now(); + } + if (Date.now() - cancelledTypedRecoveryObservedAt >= refreshDiscoveryTimeoutMs) { + core.setFailed("Cancelled or timed-out typed runtime producer has no newer exact producer within the recovery allowance."); + return; + } + core.info(`Exact typed runtime producer ${matching.id}/${matching.run_attempt} ended ${matching.conclusion}; waiting for a newer exact producer.`); + await new Promise((resolve) => setTimeout(resolve, sleepMs)); + continue smokeGatePolling; + } if (matching.status !== "completed") { await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue; @@ -1927,10 +2017,13 @@ jobs: } } catch (error) { if (error instanceof TerminalGitHubRequestError) throw error; - if (isTransientGitHubFailure(error)) { + if (isTransientGitHubFailure(error) && (matching.event !== "pull_request" || + context.payload.pull_request.head.repo?.full_name !== repositoryName)) { await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } + // Unavailable original proof cannot attest that original, but + // must not starve the independent exact-refresh proof below. core.warning(`Canonical PLAY transition exception proof is unavailable: ${error?.message ?? String(error)}`); } try { @@ -1955,7 +2048,9 @@ jobs: } const refreshProof = await verifyFailedPullCanonicalRefresh(matching, currentIdentity); const refreshKey = `${matching.id}:${identityKey(currentIdentity)}`; - if (refreshProof === "absent" && discoveredRefreshKey !== refreshKey) { + const replaceableRefresh = ["cancelled", "timed_out"].includes(refreshProof); + if (replaceableRefresh) discoveredRefreshKey = null; + if ((refreshProof === "absent" && discoveredRefreshKey !== refreshKey) || replaceableRefresh) { const missingKey = refreshKey; if (absentRefreshKey !== missingKey) { absentRefreshKey = missingKey; @@ -1986,7 +2081,7 @@ jobs: incompleteRefreshKey = null; incompleteRefreshObservedAt = null; } - if (refreshProof === "pending" || refreshProof === "absent" || snapshotPending) { + if (refreshProof === "pending" || refreshProof === "absent" || replaceableRefresh || snapshotPending) { core.info("Exact canonical refresh is pending; continuing within the existing smoke-gate deadline."); await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; @@ -2161,10 +2256,14 @@ jobs: } let proof; try { - const ordinaryProducerVerified = matching.conclusion === "success" && - (await verifyCanonicalSmokeProducer(matching, null, currentIdentity, true)) === true; + const ordinaryProducerProof = matching.conclusion === "success" && + await verifyCanonicalSmokeProducer(matching, null, currentIdentity, true); + const ordinaryProducerVerified = ordinaryProducerProof === true; proof = ordinaryProducerVerified ? "ordinary" : await verifyKnownPlayFailure(matching, null, currentIdentity, true, true); + if (proof === false && ["snapshot-pending", "attempt-superseded"].includes(ordinaryProducerProof)) { + proof = ordinaryProducerProof; + } if (proof === "ordinary" && !ordinaryProducerVerified) { const ordinaryProof = await verifyCanonicalSmokeProducer(matching, null, currentIdentity, true); if (ordinaryProof !== true) { @@ -2354,9 +2453,9 @@ jobs: const markerNeedsVerification = !(fullSmokeJob.steps ?? []).some((step) => step.name === "Known canonical transition PLAY failure with successful authenticated cleanup" && step.status === "completed" && step.conclusion != null); - if (fullSmokeStep?.status === "completed" && (markerNeedsVerification || + if ((fullSmokeStep?.status === "completed" && markerNeedsVerification) || (canonicalProof !== "snapshot-pending" && - !hasPendingCanonicalSmokeTerminalEvidence(fullSmokeJob)))) break; + !hasPendingCanonicalSmokeTerminalEvidence(fullSmokeJob))) break; } else if (fullSmokeStep?.status === "completed") { // The native pull_request path keeps its existing step-proof behavior. break; diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index ea7bec95ef..15f451fd15 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -233,11 +233,13 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 canonical Account UUIDs. Account resolves known subjects through one local UUID batch query with the same persisted provenance and source-row checks as scalar identity reads, then returns policies keyed by UUID. Unknown or unproven entries are intentionally omitted so Social applies complete `PRIVATE` redaction. - `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current gRPC adapter returns `FAILED_PRECONDITION` before selector parsing or owner reads; this does not implement the target export operation. -- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays. A request outside the proof-backed rearm contract that changes a bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest returns an idempotency conflict before usage mutation. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns the typed `TENANT_BILLING_BLOCKED` response. This billing refusal does not consume the quota-refusal budget or create a durable decision receipt; it remains available when no refusal-budget row exists. Fresh creation-eligible evidence with checked insufficient capacity returns the typed `CAPACITY_QUOTA_EXCEEDED` response only after the exact durable `NO_ACCEPT` decision commits. If its refusal budget is missing or exhausted, Account returns non-OK `ENTITLEMENT_UNAVAILABLE` instead; no quota receipt or settlement authority is issued. Each refusal is bound to the exact original attempt, mutation digest, snapshot and evaluation. A quota refusal includes the immutable Account decision UUID only after an exact durable `NO_ACCEPT` commits. A matching exact retry returns the retained receipt. A quota refusal without that receipt grants no evidence settlement authority. The response contains exactly one commitment or one typed refusal. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a changed exact retry. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). -- `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact attempt-and-fence retries replay; a changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. +- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry of the currently bound reservation attempt, fence, complete payload and digest replays its durably retained result. A request outside the proof-backed rearm contract that changes a bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest returns an idempotency conflict before usage mutation. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns the typed `TENANT_BILLING_BLOCKED` response. This billing refusal does not consume the quota-refusal budget or create a durable decision receipt; it remains available when no refusal-budget row exists. Fresh creation-eligible evidence with checked insufficient capacity returns the typed `CAPACITY_QUOTA_EXCEEDED` response only after the exact durable `NO_ACCEPT` decision commits. If its refusal budget is missing or exhausted, Account returns non-OK `ENTITLEMENT_UNAVAILABLE` instead; no quota receipt or settlement authority is issued. Each refusal is bound to the exact original attempt, mutation digest, snapshot and evaluation. A quota refusal includes the immutable Account decision UUID only after an exact durable `NO_ACCEPT` commits. A matching exact retry returns the retained receipt. A quota refusal without that receipt grants no evidence settlement authority. The response contains exactly one commitment or one typed refusal. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a changed exact retry. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +- `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact retries of the currently bound attempt, fence, complete payload and digest replay its durably retained reservation result; superseded pre-rearm attempts do not replay after a committed rearm. This reservation rule is separate from replay of an exact retained quota-denial decision, which has no reservation. A changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. Exact replay is guaranteed only for outcomes Account durably retained. A billing or non-creating entitlement refusal that did not retain a decision receipt is not a replayable outcome; a later retry rechecks current evidence freshness before deciding and cannot treat the earlier refusal as a retained result. +Lost-response recovery remains an activation prerequisite for the unregistered capacity caller. Before enabling it, Account and Game Session must supply and qualify the read-only reconciliation step for the original outer identity, attempt, fence, complete payload and digest, including recovery of the exact durable quota-denial ID while the original Game Session reserve remains active. The existing commit adapter and Account's retained-denial replay do not supply that caller recovery step. Its qualification must lose the original denial response, restore quota headroom and restart the caller, then recover the same denial without a new attempt, reservation or refusal slot. Missing or ambiguous evidence keeps the original reserve and admission closed; a fresh request or automatic mutation retry is not a recovery substitute. The remaining caller and owner-readback scope is recorded in the [strict tenant-capacity owner tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). + The shared [capacity-admission/v1 schema](../../../../services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json) declares the exact ADR 0047 seven-field mapping and bounds. Its `accountEvidence` member is canonical padded base64 of the complete existing Account bundle bytes, validated by the closed variant codec with canonical re-encoding equality before hashing. This binds every evidence field and cutoff/checkpoint byte, not a digest or reconstructed subset. `capacity_delta` is `optional int64`; missing presence is invalid and a present zero remains distinct. The Game Session and World alternatives retain distinct typed contexts. The ordinary registered Account receiver does not expose this private composition, and no route is enabled by adding the proto. - `ExportTenantData` – tenant-wide billing-safe export for one tenant, available to the caller's live `tenantAdmin` membership while gameplay is billing-blocked and limited to tenant-owned exportable records plus minimum stable subject references. The target request is tenant-only. The legacy account-targeted gRPC handler returns `FAILED_PRECONDITION` before parsing selectors or reading Account data because no authorized internal caller is configured; the target tenant-only transport and authorization remain unimplemented. This containment does not change the separately authorized REST/service export path. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 6e35aa034c..f9ead5fcca 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -88,7 +88,7 @@ Current public bootstrap, direct-scope, JOIN, connect-token and numeric entitlem Strict capacity follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). The prepared V1040 storage records immutable exact Account evaluation bytes, one stable outer request/reservation identity, the current attempt/digest and monotonic rearm/reservation fences, prior-attempt evidence, recovery claims, and durable held/used units. Deferred PostgreSQL constraints compare the complete reservation inventory with usage; eligibility reads and issuer-local counters cannot initialize or replace it. Zero usage is established only when the existing creator bootstrap commits against a genuinely new fresh-tenant association born in that same Account transaction, with the exact creation tuple and nonadmitting sequence-zero baseline. Earlier tenants are not backfilled. The actual player evaluator retains its complete bundle inside its final source transaction, so failed source commit exposes neither a capacity evaluation nor an entitlement result. Reservations use conservative microsecond expiry bounds without extending the evidence lifetime. The same prepared recovery schema retains its immutable read history and `capacity-recovery/1` retry budget. Deadline or budget exhaustion quarantines the original complete hold; it does not expire, release or replace it. No live recovery source/scheduler or quarantine-resolution authority is registered. -V1040.1 serializes the exact Account `ACCEPTED` and `NO_ACCEPT` origin decisions against reservation creation and rearm. A pre-V1040.1 writer cannot create a reservation after the guard applies. The [database migration compatibility and writer-quiescence policy](../../system-architecture-database-migrations.md#version-aware-migration-checklist) governs deployment. A reset must preserve results for still-eligible retries and may proceed only once external-action outcomes are known and any receipts to be discarded have passed their retry and reconciliation window. V1040.2 retains an exact quota denial under an explicitly installed finite tenant refusal limit. The same serializable owner transaction checks quota and chooses between a reservation and a denial. The denial carries no reservation and permanently excludes acceptance for the exact original. Exact replay returns the same decision even after capacity becomes available. An unavailable refusal budget or uncertain outcome leaves Game Session's reserve active. Account neither frees nor rearms an accepted reservation through this path. Before enabling any admission producer, the Account operator must provision every supported canonical tenant through `AccountCapacityRefusalBudgetRepository.provision` and call `requireReady` with the same explicit lifetime limit and the bounded admission cohort headroom in one writable owner transaction while producers remain quiescent. Commit only after both succeed; otherwise roll back the undersized installation so it does not permanently bind an unusable limit. Sizing is explicit: the finite lifetime limit must cover retained denials plus the planned denial cohort; it is not the gameplay capacity quota or an automatically replenished rate limit. Exact provisioning retries preserve the row and its historical evidence; a different limit conflicts. Missing, mismatched or insufficient budgets fail readiness. Readiness is a local observation, not a reservation or authority to admit, and the SQL trigger remains the runtime concurrency authority. Exhaustion requires stopping new admission and an independently designed retention-safe lifecycle, never deleting denials or resetting/increasing this immutable budget. No exhaustion detector or admission-producer stop control is implemented by these private repositories: the positive reservation path does not consult refusal headroom. Qualifying that stop, including last-slot consumption followed by available capacity, is an unmet activation prerequisite; provisioning readiness alone cannot satisfy it. These private methods do not register an endpoint, seed tenants automatically or activate the default-off capacity component. +V1040.1 serializes the exact Account `ACCEPTED` and `NO_ACCEPT` origin decisions against reservation creation and rearm. A pre-V1040.1 writer cannot create a reservation after the guard applies. The [database migration compatibility and writer-quiescence policy](../../system-architecture-database-migrations.md#version-aware-migration-checklist) governs deployment. A reset must preserve results for still-eligible retries. It may proceed only after all external-action intents have settled, their authoritative outcomes are known, and any receipts to be discarded have passed their retry and reconciliation window. V1040.2 retains an exact quota denial under an explicitly installed finite tenant refusal limit. The same serializable owner transaction checks quota and chooses between a reservation and a denial. The denial carries no reservation and permanently excludes acceptance for the exact original. Exact replay returns the same decision even after capacity becomes available. An unavailable refusal budget or uncertain outcome leaves Game Session's reserve active. Account neither frees nor rearms an accepted reservation through this path. Before enabling any admission producer, the Account operator must provision every supported canonical tenant through `AccountCapacityRefusalBudgetRepository.provision` and call `requireReady` with the same explicit lifetime limit and the bounded admission cohort headroom in one writable owner transaction while producers remain quiescent. Commit only after both succeed; otherwise roll back the undersized installation so it does not permanently bind an unusable limit. Sizing is explicit: the finite lifetime limit must cover retained denials plus the planned denial cohort; it is not the gameplay capacity quota or an automatically replenished rate limit. Exact provisioning retries preserve the row and its historical evidence; a different limit conflicts. Missing, mismatched or insufficient budgets fail readiness. Readiness is a local observation, not a reservation or authority to admit, and the SQL trigger remains the runtime concurrency authority. Exhaustion requires stopping new admission and an independently designed retention-safe lifecycle, never deleting denials or resetting/increasing this immutable budget. No exhaustion detector or admission-producer stop control is implemented by these private repositories: the positive reservation path does not consult refusal headroom. Qualifying that stop, including last-slot consumption followed by available capacity, is an unmet activation prerequisite; provisioning readiness alone cannot satisfy it. These private methods do not register an endpoint, seed tenants automatically or activate the default-off capacity component. Pre-v1 Account reset or deletion remains only the proposal in [ADR 0185](../../decisions/adr-0185-no-data-carry-over-before-v1.md), whose status is **Proposed - Pending Human Review**; this capacity implementation adds no reset, budget-reset, or refusal-receipt deletion operation. If ADR 0185 is later accepted, the reset must follow the [database migration compatibility and writer-quiescence policy](../../system-architecture-database-migrations.md#version-aware-migration-checklist) and keep every still-eligible exact retry or reconciliation read able to recover its original durable owner result, including a committed external action whose response was lost. Otherwise, discard a receipt only after the action family's documented retry and reconciliation window is proved ended and delayed requests are fenced from executing again. Uncertain action outcomes or retry eligibility block reset, and a provider reset or replay rejection does not replace recovery of the original result. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index c9024fc349..a1d439efa5 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -14,7 +14,9 @@ The exact current Game Session owner establishes irreversible closure of serving The target Game Session owner persists the teardown identity and progress in its own PostgreSQL storage, then retains the immutable terminal evidence under that same identity. A replacement worker reads the persisted progress and exact receipt rather than reconstructing either from Redis, an in-memory job or the current binding alone. The receipt binds the original admission, FINAL evidence, binding lineage and exact Account reservation; conflicting identities or stale owner fences must be refused. After a lost or ambiguous Account response, that retained receipt and its original fence remain historical immutable evidence, not present sender authority: redelivery is performed only by the currently authenticated replacement owner under its current owner authority, without replacing or advancing the original teardown identity or receipt fence. -Qualification must prove a restart after irreversible closure or settlement but before the terminal receipt exists, then verify the replacement completes that same teardown from durable progress with serving and resume still closed. Separately prove restart before send, Account commit followed by response loss and worker restart, and exact receipt replay without a second decrement. Account—not Game Session—atomically retains the retirement receipt and decrements used capacity. Wrong identity or fence must fail closed, and no failure or retry may reopen serving or resume. These are acceptance requirements, not claims that the target path or its restart proof exists today. +Each applicable settlement must either commit atomically with its Game Session progress record in the same owner-local transaction, or expose exact durable owner readback under an immutable sub-operation identity and request digest retained before dispatch. For an already-admitted effect, retain its original mutation identity and participant binding under the [effect reconciliation contract](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects); teardown must not allocate a replacement effect. If settlement commits but its response or progress update is lost, the replacement owner reads that exact outcome and persists the recovered progress before completing the terminal receipt. The teardown identity, a missing progress row, a timeout or Redis absence alone proves neither settlement nor no-commit. Unavailable, ambiguous or mismatched owner evidence keeps teardown unresolved, serving and resume closed, and the corresponding Account used units unretired. A settlement without either recovery boundary blocks retirement qualification. + +Qualification must prove a restart after irreversible closure or settlement but before the terminal receipt exists, then verify the replacement completes that same teardown from durable progress with serving and resume still closed. For every independently committing settlement, also prove settlement commit followed by response loss and a crash before progress persistence: the replacement must recover the exact original owner outcome without a second logical settlement or a new sub-operation identity. Separately prove restart before send, Account commit followed by response loss and worker restart, and exact receipt replay without a second decrement. Account—not Game Session—atomically retains the retirement receipt and decrements used capacity. Wrong identity or fence must fail closed, and no failure or retry may reopen serving or resume. These are acceptance requirements, not claims that the target path or its restart proof exists today. ## Implementation Status diff --git a/design/architecture/system-architecture-database-migrations.md b/design/architecture/system-architecture-database-migrations.md index 6e0e896253..482d03ad47 100644 --- a/design/architecture/system-architecture-database-migrations.md +++ b/design/architecture/system-architecture-database-migrations.md @@ -250,6 +250,15 @@ Hosted candidate previews may activate a migration only when the trusted path in Migration changes use the canonical [Validation and Runtime Proof](../developer-workflows/validation-and-runtime-proof.md) workflow to select formatting, checks, and runtime proof, with execution results recorded in PR/CI evidence and, when applicable, synchronized into the owning implementation tracker. This document does not duplicate that workflow or act as a validation ledger. +#### Verification after the dev-demo target is recorded + +The trusted workflow records `firemud.dev/last-dev-demo-head-sha` after staged deployment succeeds, before the remaining readiness, bootstrap and TCP smoke steps. That annotation records deployment, not successful runtime qualification. The [deployment classifier](../../dev-tools/deploy/detect-hosted-v2-migration-activation.sh) deliberately refuses the same target SHA; do not clear, rewind or replace the annotation, reset the namespace, or rerun Helm merely to repeat validation. The verification-only procedure below applies to an existing release whose original smoke-account bootstrap completed; it is not a workflow-resume or bootstrap-recovery mechanism. An authorized operator may verify that release and repeat only its remaining checks: + +1. Recover the exact target SHA, namespace, release name, image identities, selected certificate profile, rendered manifest and values from the original deployment record. Verify that the namespace is the owned `dev` environment and its annotation still equals that SHA. Read the existing Helm release status, revision and manifest, and compare the running workloads and image identities with that exact release. A changed release, mixed target, incomplete deployment or ambiguous namespace stops verification and requires deployment-owner recovery; this procedure neither deploys nor authorizes repair. +2. Have each affected database owner verify the actual configured service schema and Flyway history against the target's immutable migration set, including exact versions, script names, checksums and successful installation. Retain that read-only result with the original deployment record. Missing, failed or contradictory history blocks continuation. Do not use `flywayRepair`, edit history, rerun migrations or infer migration success from the namespace annotation or Pod readiness. +3. Repeat the remaining readiness checks from the [trusted dev-demo workflow](../../.github/workflows/dev-demo.yml), using its original runtime/requester credential separation and selected certificate profile. The existing [`wait-for-hosted-runtime-rollouts.sh`](../../dev-tools/hosted/shared/wait-for-hosted-runtime-rollouts.sh) accepts `dev 120`. For the hosted-controller profile, also run [`wait-for-hosted-identity.sh`](../../dev-tools/hosted/preview/wait-for-hosted-identity.sh) with `dev-demo`, the exact target SHA, `dev` and `900`, then the workflow's operator `hosted-bridge` preflight against the retained rendered artifact, release and Telnet NodePort. Verify the workflow's application readiness endpoints too; rollout completion alone is not application readiness. Missing original inputs or any failed readiness check leaves qualification incomplete. +4. Confirm that the original smoke-account bootstrap completed and use that existing account, world, hostname, port and TLS trust configuration with [`hosted-login-look-smoke.sh`](../../dev-tools/hosted/shared/hosted-login-look-smoke.sh). Supply the original `SMOKE_TELNET_HOST`, `TCP_PORT`, `SMOKE_LOGIN_EMAIL`, `SMOKE_PASSWORD`, `SMOKE_WORLD` and any explicit CA input through their protected channels; never print credentials or weaken TLS or expected `LOGIN`/`PLAY`/`LOOK` outcomes. If bootstrap did not complete, stop for separately authorized Account/bootstrap recovery rather than creating replacement data as part of verification. Retain the new readiness results and smoke transcript against the same target and release, explicitly separate from the original failed run. A failed repeat remains failed qualification; it is not permission to reset or redeploy. + ### Cross-Service Identifier Migration Classify each identifier migration before changing storage or wire shape: diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index 90ded06f9f..b7fd4f5e3d 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -968,7 +968,7 @@ const execute = new Function("github", "context", "core", "Date", "setTimeout", const head = "a".repeat(40), base = "b".repeat(40), merge = "c".repeat(40), defaultSha = "d".repeat(40); const repository = "example/firemud"; const title = `Build Runtime Images secure-pr-artifact pr-42 base-${base} head-${head} merge-${merge} mode-required`; -async function scenario(kind, event = "pull_request") { +async function scenario(kind, event = "pull_request", listedConclusion = null) { let now = 1000, snapshots = 0, reads = 0; let qualifiedAttemptReads = 0, observedBaseMove = false, observedAttemptMove = false, waitedMillis = 0; let typedListReads = 0, listedAttempt = 1, postAttemptIdentityReads = 0; @@ -1026,6 +1026,11 @@ async function scenario(kind, event = "pull_request") { if (kind === "step-skipped") job.steps = [{name: "Run credential-free full-stack smoke", status: "completed", conclusion: "skipped"}]; if (kind === "legacy-positive") job.steps = [{name: "Run credential-free full-stack smoke", status: "completed", conclusion: "success"}]; if (["failed-smoke-step", "ordinary-failed-smoke-step"].includes(kind)) job.steps[1].conclusion = "failure"; + if (kind === "ordinary-skipped-smoke-step") job.steps[1].conclusion = "skipped"; + if (kind === "ordinary-omitted-smoke-failed-cleanup") { + job.steps = job.steps.filter(step => step.name !== "Run credential-free full-stack smoke"); + job.steps.find(step => step.name === "Stop smoke stack").conclusion = "failure"; + } if (kind === "ordinary-duplicate-smoke-step") job.steps.push({...job.steps[1]}); if (kind === "failed-run") source.conclusion = "failure"; const sourceMutations = { @@ -1138,6 +1143,21 @@ async function scenario(kind, event = "pull_request") { assert.equal(method, listRuns); if (ordinary) { typedListReads++; + if ((kind.startsWith("ordinary-cancelled-") || kind.startsWith("ordinary-timed-out-")) && + (!["ordinary-cancelled-replacement", "ordinary-timed-out-replacement"].includes(kind) || now < 61000)) { + yield {data: [{...source, id: kind.endsWith("-chain") ? 41 + Math.floor((now - 1000) / 60000) : 41, + conclusion: kind.startsWith("ordinary-timed-out-") ? "timed_out" : "cancelled", ...(kind.endsWith("-invalid-source") + ? {head_repository: {full_name: "other/repo"}} : {})}]}; + return; + } + if (kind.startsWith("ordinary-list-conclusion-") && (typedListReads === 1 || kind.endsWith("-persistent") || + kind.endsWith("-invalid"))) { + yield {data: [{...source, conclusion: kind.endsWith("-undefined") ? undefined + : kind.endsWith("-persistent") ? typedListReads % 2 === 0 ? undefined : null + : kind.endsWith("-invalid") ? listedConclusion : null, + ...(kind.endsWith("-invalid-attempt") ? {run_attempt: 0} : {})}]}; + return; + } if (Object.hasOwn(sparseAttempts, kind) && (typedListReads === 1 || kind.startsWith("ordinary-persistent-") || kind.includes("invalid") || kind.includes("zero") || kind.includes("negative") || kind.includes("fractional"))) { @@ -1203,17 +1223,54 @@ async function scenario(kind, event = "pull_request") { "unchanged proof clears without the obsolete identity message"); const delayedSmoke = await scenario("ordinary-delayed-smoke-step", "repository_dispatch"); assert.deepEqual(delayedSmoke.failures, []); - assert.equal(delayedSmoke.waitedMillis, 15000, "ordinary typed proof waits for its affirmative successful smoke row"); - assert(delayedSmoke.snapshots >= 4); + assert.equal(delayedSmoke.waitedMillis, 0, "the fingerprinted native terminal guard attests an omitted smoke row"); const missingSmoke = await scenario("ordinary-missing-smoke-step", "repository_dispatch"); - assert.equal(missingSmoke.failures.length, 1); - assert.match(missingSmoke.failures[0], /after 8 retries/); - assert.equal(missingSmoke.waitedMillis, 120000, "absent ordinary smoke evidence cannot outlive the existing snapshot allowance"); - for (const kind of ["ordinary-duplicate-smoke-step", "ordinary-failed-smoke-step"]) { + assert.deepEqual(missingSmoke.failures, []); + assert.equal(missingSmoke.waitedMillis, 0, "an omitted smoke row is allowed only with complete canonical native proof"); + for (const kind of ["ordinary-duplicate-smoke-step", "ordinary-failed-smoke-step", "ordinary-skipped-smoke-step", + "ordinary-omitted-smoke-failed-cleanup"]) { const invalidSmoke = await scenario(kind, "repository_dispatch"); assert.equal(invalidSmoke.failures.length, 1, `${kind} is not ordinary runtime proof`); assert.equal(invalidSmoke.waitedMillis, 0, `${kind} is terminal, not delayed metadata`); } + for (const ending of ["cancelled", "timed-out"]) { + const replacement = await scenario(`ordinary-${ending}-replacement`, "repository_dispatch"); + assert.deepEqual(replacement.failures, [], "a newer exact typed producer can replace a known cancellation or timeout"); + assert.equal(replacement.waitedMillis, 60000); + for (const suffix of ["no-replacement", "chain"]) { + const unusable = await scenario(`ordinary-${ending}-${suffix}`, "repository_dispatch"); + assert.deepEqual(unusable.failures, + ["Cancelled or timed-out typed runtime producer has no newer exact producer within the recovery allowance."]); + assert.equal(unusable.waitedMillis, 45 * 60000, "more unusable producers cannot renew the same tuple's recovery budget"); + assert.equal(unusable.exactAttemptReads, 0, "cancelled/timed-out attempts supply no successful proof"); + } + const ambiguous = await scenario(`ordinary-${ending}-invalid-source`, "repository_dispatch"); + assert.deepEqual(ambiguous.failures, ["Cancelled or timed-out typed runtime producer has an invalid source identity."]); + assert.equal(ambiguous.waitedMillis, 0); + } + for (const suffix of ["null", "undefined"]) { + const sparse = await scenario(`ordinary-list-conclusion-${suffix}`, "repository_dispatch"); + assert.deepEqual(sparse.failures, []); + assert.equal(sparse.typedListReads, 2, "completed typed rows must be re-listed before routing by conclusion"); + assert.equal(sparse.waitedMillis, 15000); + assert(sparse.exactAttemptReads > 0 && sparse.snapshots > 0); + } + const persistentConclusion = await scenario("ordinary-list-conclusion-persistent", "repository_dispatch"); + assert.deepEqual(persistentConclusion.failures, + ["Completed typed runtime producer lacks a conclusion within the snapshot convergence allowance."]); + assert.equal(persistentConclusion.waitedMillis, 120000, "null/absent alternation cannot reset the snapshot bound"); + assert.equal(persistentConclusion.exactAttemptReads, 0); + assert.equal(persistentConclusion.snapshots, 0, "job proof cannot fill a missing run-list conclusion"); + const invalidSparseAttempt = await scenario("ordinary-list-conclusion-invalid-attempt", "repository_dispatch"); + assert.deepEqual(invalidSparseAttempt.failures, ["Typed runtime smoke producer lacks an exact attempt."]); + assert.equal(invalidSparseAttempt.waitedMillis, 0); + for (const conclusion of ["", false, 0, {}, "neutral", "unknown"]) { + const invalid = await scenario("ordinary-list-conclusion-invalid", "repository_dispatch", conclusion); + assert.equal(invalid.failures.length, 1, "an explicit invalid conclusion is not sparse metadata"); + assert.equal(invalid.waitedMillis, 0); + assert.equal(invalid.exactAttemptReads, 0); + assert.equal(invalid.snapshots, 0); + } const sparseHead = await scenario("ordinary-sparse-head", "repository_dispatch"); assert.deepEqual(sparseHead.failures, [], "a temporarily missing typed list head waits for a complete run row"); assert(sparseHead.waitedMillis > 0); @@ -3999,9 +4056,14 @@ assert.ok(script.includes("const completedSnapshotTimeoutMs = 8 * snapshotSleepM const refreshStart = script.indexOf("async function verifyFailedPullCanonicalRefresh("); const refreshEnd = script.indexOf("// Commit objects", refreshStart); const refreshFunction = script.slice(refreshStart, refreshEnd); +const cancelledTypedFunction = script.slice(script.indexOf("function isReplaceableTypedProducer("), refreshStart); +const isReplaceableTypedProducer = new Function("prNumber", "positiveInteger", "repositoryName", "isRuntimeSourceWorkflowPath", "context", + `${cancelledTypedFunction}; return isReplaceableTypedProducer;`)("3390", value => Number.isSafeInteger(value) && value > 0, + repositoryName, isRuntimeSourceWorkflowPath, {payload: {repository: {default_branch: "develop"}}}); async function recoveredFailure(options = {}, selectedRun = null, selectedIdentity = identity, raw = false) { const original = selectedRun ?? {id: 98, event: "pull_request", status: "completed", conclusion: "failure", ...options.original}; - const replacement = options.absent ? null : {...source, head_sha: workflowSha, id: original.id + 1, run_attempt: 2, event: "repository_dispatch", + const replacement = options.absent ? null : {...source, head_sha: workflowSha, head_branch: "develop", + id: original.id + 1, run_attempt: 2, event: "repository_dispatch", status: "completed", conclusion: "success", ...options.replacement}; const selectedTitle = `Build Runtime Images secure-pr-artifact pr-3390 base-${selectedIdentity.baseSha} ` + `head-${selectedIdentity.headSha} merge-${selectedIdentity.mergeSha} mode-required`; @@ -4037,7 +4099,7 @@ async function recoveredFailure(options = {}, selectedRun = null, selectedIdenti } const execute = new Function("repositoryName", "prNumber", "positiveInteger", "findMatchingRuntimeImagesRun", "withTransientGitHubRetry", "github", "owner", "repo", "canonicalSmokeJobName", "verifyKnownPlayFailure", - "verifyCanonicalSmokeProducer", "context", + "verifyCanonicalSmokeProducer", "context", "isReplaceableTypedProducer", `${refreshFunction}; return verifyFailedPullCanonicalRefresh;`); const recover = execute(options.repository || repositoryName, "3390", value => Number.isSafeInteger(value) && value > 0, async (event, title, selected) => { @@ -4063,7 +4125,7 @@ async function recoveredFailure(options = {}, selectedRun = null, selectedIdenti verifyReplacement(selected, job, proofIdentity, true, allowIncompleteSteps, allowOrdinary), (selected, job, proofIdentity, requireTerminalSmokeProof) => verifyReplacement(selected, job, proofIdentity, false, requireTerminalSmokeProof), - {payload: {pull_request: {head: {repo: {full_name: options.headRepository || repositoryName}}}}}); + {payload: {pull_request: {head: {repo: {full_name: options.headRepository || repositoryName}}}}}, isReplaceableTypedProducer); const proof = await recover(original, selectedIdentity); return {accepted: raw ? proof : proof?.status === "verified" ? true : proof?.status === "snapshot-pending" ? "snapshot-pending" : proof, verified, queries}; @@ -4242,7 +4304,7 @@ const loopStart = script.indexOf("let currentIdentity = null;"); const replacementVerifier = script.indexOf("async function verifySameTupleReplacementProof(", loopStart); const pollStart = script.indexOf("smokeGatePolling: while", replacementVerifier); assert.ok(loopStart >= 0 && replacementVerifier > loopStart && pollStart > replacementVerifier); -const actualPollingLoop = script.slice(loopStart, replacementVerifier) + script.slice(pollStart); +const actualPollingLoop = cancelledTypedFunction + script.slice(loopStart, replacementVerifier) + script.slice(pollStart); async function sameTupleProof(marker, ordinaryProof, exceptionProof) { const replacement = {...source, event: "repository_dispatch", head_sha: workflowSha}; const job = {...candidate, head_sha: workflowSha, steps: candidate.steps.map(value => @@ -4263,6 +4325,7 @@ async function sameTupleProof(marker, ordinaryProof, exceptionProof) { async function pendingRefreshCaller(statuses, expires = false, options = {}) { const failures = [], outputs = []; let sleeps = 0, polls = 0, writes = 0, now = 0, currentChecks = 0, finalChecks = 0, nullReads = 0, directReads = 0; + let originalJobReads = 0; let labelRemovedDuringFinal = false; const proofLive = {baseSha: identity.baseSha, mergeSha: identity.mergeSha}; const core = {info: () => {}, warning: () => {}, @@ -4281,6 +4344,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { "verifySameTupleReplacementProof", `return (async () => { let pollIteration = 0; ${actualPollingLoop} })();`); await execute(repositoryName, workflowPath, isRuntimeSourceWorkflowPath, {rest: {actions: {listJobsForWorkflowRun: "jobs"}}, paginate: async () => { + originalJobReads++; if (options.originalError) throw options.originalError; const job = structuredClone(candidate); if (options.ordinaryAfterDrift) job.steps.find(s => s.name.startsWith("Known canonical")).conclusion = "skipped"; @@ -4325,7 +4389,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { assert.equal(result.accepted, false, "the old refresh must fail its live tuple proof"); return false; } - return (await recoveredFailure(options.headRepository ? {headRepository: options.headRepository} + const recoveryOptions = options.headRepository ? {headRepository: options.headRepository} : status === "absent" ? {absent: true} : status === "older" ? {replacement: {id: 97}} : status === "superseded" ? {latest: {run_attempt: 3}, mutateProof: data => {data.latest.run_attempt = 3;}} @@ -4333,13 +4397,16 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { : status === "nonterminal-step" ? {candidate: {steps: candidate.steps.map(step => step.name === "Stop smoke stack" ? {...step, status: "in_progress", conclusion: null} : step)}} : status === "missing-job" ? {noProducer: true} : status === "pending-job" ? {candidate: {status: "in_progress", conclusion: null}} + : ["cancelled", "timed_out"].includes(status) ? {replacement: {status: "completed", conclusion: status}} : status === "missing-attempt" ? {replacement: {run_attempt: undefined}} : status === "null-attempt" ? {replacement: {run_attempt: null}} : status === "missing-conclusion" ? {replacement: {conclusion: undefined}} : status === "null-conclusion" ? {replacement: {conclusion: null}} : {replacement: {status, conclusion: status === "completed" ? "success" : null, - run_attempt: statuses[0] === "superseded" && polls > 1 ? 3 : 2}}, - selectedRun, selectedIdentity, true)).accepted; + run_attempt: statuses[0] === "superseded" && polls > 1 ? 3 : 2}}; + if (options.ordinaryRecovery) recoveryOptions.candidate = {steps: candidate.steps.map(step => + step.name.startsWith("Known canonical") ? {...step, conclusion: "skipped"} : step)}; + return (await recoveredFailure(recoveryOptions, selectedRun, selectedIdentity, true)).accepted; }, async () => false, TerminalGitHubRequestError, core, async (_label, requireCurrent) => { if (options.finalNull && _label === "Stopping stale canonical transition PLAY exception" && nullReads++ === 0) return null; const eligible = !options.labelRemoved && !labelRemovedDuringFinal && !(options.withdrawDuringProof && polls > 0); @@ -4376,7 +4443,7 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { }, selected); return !options.rerunFinal || finalChecks > 1; }, async () => "ordinary"); - if (options.ordinaryAfterDrift) { + if (options.ordinaryAfterDrift || options.ordinaryRecovery) { assert.deepEqual(failures, []); assert.deepEqual(outputs, []); assert.equal(writes, 0); } else if (options.directInvalid) { assert.deepEqual(failures, [options.omitGeneralMarker @@ -4425,6 +4492,9 @@ async function pendingRefreshCaller(statuses, expires = false, options = {}) { assert.equal(sleeps, options.directSnapshots ? (options.snapshotExpires ? 2 : options.directSnapshots.length - 1) : options.ordinaryAfterDrift || options.labelRemoved && statuses[0] !== "absent" || options.withdrawDuringProof || options.rejectedObject ? 0 : options.labelRemoved && statuses[0] === "absent" ? 1 : options.absentExpires ? 4 : options.snapshotExpires ? 2 : options.finalIdentity ? (statuses[0] === "absent" ? 1 : 0) : expires ? statuses.length : statuses.length - 1); + if (options.originalError) assert.equal(originalJobReads, polls, + "each unavailable original job read must still reach the independent refresh lookup"); + return {failures, outputs, polls, originalJobReads, sleeps, now}; } // Exercise the exact production loop through cancellation of an old tuple and // a successful refresh of the new tuple. Only independently verified ordinary @@ -4441,6 +4511,25 @@ async function movedCancellation(ordinaryProof, listedOldReplacement = false, op const refresh = {...source, event: "repository_dispatch", status: "completed", conclusion: "success", head_sha: workflowSha, head_branch: "develop", display_title: `Build Runtime Images secure-pr-artifact pr-3390 base-${moved.baseSha} head-${moved.headSha} merge-${moved.mergeSha} mode-required`}; + const verifyMovedOrdinary = knownPlay => verify(data => { + data.identity = {...moved}; + for (const native of [data.run, data.source, data.latest]) Object.assign(native, refresh); + data.candidate.run_attempt = refresh.run_attempt; + data.currentBase.object.sha = moved.baseSha; + data.currentPullRequest.merge_commit_sha = moved.mergeSha; + const marker = data.candidate.steps.find(step => step.name.startsWith("Known canonical")); + marker.conclusion = "skipped"; + const incomplete = options.incompleteOrdinary === "persistent" || proofReads === 1; + if (options.incompleteOrdinary === "contradictory") { + data.candidate.steps.find(step => step.name === "Run credential-free full-stack smoke").conclusion = "failure"; + } else if (incomplete) { + data.candidate.steps = data.candidate.steps.filter(step => step.name !== "Stop smoke stack"); + } + if (incomplete) { + data.jobs.push({id: 999, run_id: refresh.id, run_attempt: refresh.run_attempt, head_sha: workflowSha, + name: "Dispatch Trusted PR Runtime Publication", conclusion: null}); + } + }, "repository_dispatch", knownPlay, true, knownPlay); const failures = [], outputs = []; const core = {info() {}, warning() {}, setFailed: x => failures.push(x), setOutput: (...x) => outputs.push(x)}; const execute = new Function("repositoryName", "workflowPath", "isRuntimeSourceWorkflowPath", "canonicalSmokeJobName", "withTransientGitHubRetry", @@ -4458,6 +4547,7 @@ async function movedCancellation(ordinaryProof, listedOldReplacement = false, op assert.ok(Number.isSafeInteger(run.run_attempt) && run.run_attempt > 0, "sparse moved inventory cannot enter the exact exception verifier"); assert.deepEqual(selected, moved); assert.equal(incomplete, true); assert.equal(ordinary, true); + if (options.incompleteOrdinary) return verifyMovedOrdinary(true); return false; }, async (run, candidate, selected, required) => { proofReads++; assert.equal(run, refresh); assert.equal(candidate, null); @@ -4465,6 +4555,7 @@ async function movedCancellation(ordinaryProof, listedOldReplacement = false, op assert.ok(Number.isSafeInteger(run.run_attempt) && run.run_attempt > 0, "sparse moved inventory must be re-listed before exact ordinary proof"); proofAttempts.push(run.run_attempt); + if (options.incompleteOrdinary) return verifyMovedOrdinary(false); if (options.listAttempts) return verify(data => { data.identity = {...moved}; Object.assign(data.run, refresh); @@ -4493,7 +4584,7 @@ async function movedCancellation(ordinaryProof, listedOldReplacement = false, op finalReads++; assert.equal(run, refresh); return options.listAttempts ? finalAttemptCheck(refresh, null, () => {}, run) : true; }, async () => "ordinary"); - if (!options.listAttempts) { + if (!options.listAttempts && !options.incompleteOrdinary) { assert.equal(typedReads, 2); assert.equal(proofReads, 1); assert.equal(finalReads, ordinaryProof ? 1 : 0); assert.deepEqual(failures, ordinaryProof ? [] : ["Moved cancelled-run recovery did not supply authenticated smoke proof."]); } @@ -4510,7 +4601,7 @@ async function sameTupleCancellation(replacementStatus, proofSequence = [], spar repository: {full_name: options.recoverableOriginal ? repositoryName : "other/repo"}, display_title: `Build Runtime Images secure-pr-artifact pr-3390 base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`}; const replacement = {...source, id: 99, event: "repository_dispatch", status: replacementStatus, - conclusion: replacementStatus === "completed" ? "success" : null, head_sha: workflowSha, + conclusion: replacementStatus === "completed" ? "success" : null, head_sha: workflowSha, head_branch: "develop", ...(sparseAttempt ? {run_attempt: undefined} : {})}; const smokeJob = {...candidate, id: 123, run_id: replacement.id, run_attempt: replacement.run_attempt, head_sha: replacement.head_sha, name: canonicalSmokeJobName, conclusion: "success", @@ -4549,7 +4640,10 @@ async function sameTupleCancellation(replacementStatus, proofSequence = [], spar }, selected => JSON.stringify(selected), resolve => {sleeps++; now += 10; resolve();}, 10, {now: () => now}, 0, options.overallMs ?? 1000, 1, async event => { - if (event === "pull_request") return old; + if (event === "pull_request") { + if (options.originalAttemptAt !== undefined) old.run_attempt = now < options.originalAttemptAt ? 1 : 2; + return old; + } if (now < (options.visibleAt ?? 0)) return null; if (options.hiddenAfter !== undefined && now >= options.hiddenAfter) return null; if (options.completeAt !== undefined) { @@ -4559,10 +4653,18 @@ async function sameTupleCancellation(replacementStatus, proofSequence = [], spar if (options.listedAttempts) { replacement.run_attempt = options.listedAttempts[Math.min(listedReplacements++, options.listedAttempts.length - 1)]; } + if (options.listedConclusions) { + replacement.conclusion = options.listedConclusions[Math.min(listedReplacements++, options.listedConclusions.length - 1)]; + } + if (options.cancelledUntil !== undefined) { + replacement.conclusion = now < options.cancelledUntil ? options.unusableConclusion ?? "cancelled" : "success"; + replacement.id = now < options.cancelledUntil ? 99 : 100; + if (options.invalidCancelledSource) replacement.head_repository = {full_name: "other/repo"}; + } return replacement; }, "3390", "test identity", 50, - {payload: {pull_request: {head: {ref: "feature", repo: {full_name: repositoryName}}}}}, + {payload: {repository: {default_branch: "develop"}, pull_request: {head: {ref: "feature", repo: {full_name: repositoryName}}}}}, 200, 100, 10, value => Number.isSafeInteger(value) && value > 0, async () => { finalAttemptReads++; now += options.finalAttemptReadMs ?? 0; @@ -4700,6 +4802,17 @@ function markerAccepted(overrides = {}) { await movedCancellation(false); await movedCancellation(true, true); await movedCancellation(false, true); + const movedOrdinaryLag = await movedCancellation(true, false, {incompleteOrdinary: "converge"}); + assert.deepEqual(movedOrdinaryLag.failures, []); + assert.equal(movedOrdinaryLag.now, 10, "missing cleanup and sibling status keep moved ordinary proof pending"); + assert.equal(movedOrdinaryLag.proofReads, 2); + assert.equal(movedOrdinaryLag.exceptionReads, 1, "a negative diagnostic verifier cannot discard ordinary snapshot-pending"); + const movedOrdinaryMissing = await movedCancellation(true, false, {incompleteOrdinary: "persistent"}); + assert.deepEqual(movedOrdinaryMissing.failures, ["Moved cancelled-run recovery timed out waiting for authenticated smoke proof."]); + assert.equal(movedOrdinaryMissing.now, 30, "persistent incomplete moved proof retains its snapshot bound"); + const movedOrdinaryInvalid = await movedCancellation(true, false, {incompleteOrdinary: "contradictory"}); + assert.deepEqual(movedOrdinaryInvalid.failures, ["Moved cancelled-run recovery did not supply authenticated smoke proof."]); + assert.equal(movedOrdinaryInvalid.now, 0, "an explicit failed ordinary smoke step is not snapshot lag"); for (const attempt of [null, undefined]) { const converged = await movedCancellation(true, false, {listAttempts: [attempt, 2]}); assert.deepEqual(converged.failures, []); @@ -4749,6 +4862,16 @@ function markerAccepted(overrides = {}) { "missing replacement attempt identity remains pending only until the original cancellation deadline"); assert.equal(sparseReplacementAttempt.proofReads, 0); assert.equal(sparseReplacementAttempt.runtimeJobReads, 0); + const nullReplacementConclusion = await sameTupleCancellation("completed", ["ordinary"], false, + {listedConclusions: [null, "success"]}); + assert.deepEqual(nullReplacementConclusion.failures, []); + assert.equal(nullReplacementConclusion.now, 10); + assert.equal(nullReplacementConclusion.proofReads, 1, "a null typed conclusion cannot enter exact terminal proof"); + const persistentReplacementConclusion = await sameTupleCancellation("completed", ["ordinary"], false, + {listedConclusions: [null]}); + assert.equal(persistentReplacementConclusion.now, 100); + assert.match(persistentReplacementConclusion.failures[0], /within the snapshot convergence allowance/); + assert.equal(persistentReplacementConclusion.proofReads, 0); const sequencedReplacement = await sameTupleCancellation("completed", ["snapshot-pending", "ordinary"]); assert.deepEqual(sequencedReplacement.failures, []); assert.equal(sequencedReplacement.proofReads, 2, @@ -4796,6 +4919,43 @@ function markerAccepted(overrides = {}) { assert.equal(noReplacement.now, 50); assert.match(noReplacement.failures[0], /has no exact repository_dispatch replacement/); assert.equal(noReplacement.proofReads, 0, "a no-show still exhausts the discovery-only allowance"); + const newlyCancelledAttempt = await sameTupleCancellation("completed", ["ordinary"], false, + {originalAttemptAt: 40, visibleAt: 80}); + assert.deepEqual(newlyCancelledAttempt.failures, []); + assert.equal(newlyCancelledAttempt.now, 80, "a new cancelled attempt of the same run gets its own discovery window"); + assert.equal(newlyCancelledAttempt.proofReads, 1); + const repeatedNewAttempt = await sameTupleCancellation("completed", ["ordinary"], false, + {originalAttemptAt: 40, visibleAt: Infinity}); + assert.equal(repeatedNewAttempt.now, 90, "repeated observations of attempt 2 cannot renew its deadline"); + assert.match(repeatedNewAttempt.failures[0], /has no exact repository_dispatch replacement/); + const discardedSpeculation = await sameTupleCancellation("completed", ["snapshot-pending"], false, + {originalAttemptAt: 40, hiddenAfter: 40}); + assert.equal(discardedSpeculation.now, 90, "a new original attempt discards the prior attempt's speculative terminal window"); + assert.match(discardedSpeculation.failures[0], /has no exact repository_dispatch replacement/); + const cancelledReplacement = await sameTupleCancellation("completed", ["ordinary"], false, + {cancelledUntil: 150, recoverableOriginal: true}); + assert.deepEqual(cancelledReplacement.failures, []); + assert.equal(cancelledReplacement.now, 150, "a cancelled typed replacement waits for a newer producer beyond snapshot convergence"); + assert.equal(cancelledReplacement.proofReads, 1, "the cancelled typed attempt is never proof"); + const cancelledNoShow = await sameTupleCancellation("completed", ["ordinary"], false, + {cancelledUntil: Infinity, recoverableOriginal: true}); + assert.equal(cancelledNoShow.now, 200, "typed cancellation cannot extend the original recovery deadline"); + assert.match(cancelledNoShow.failures[0], /no newer exact producer within the recovery allowance/); + assert.equal(cancelledNoShow.proofReads, 0); + const invalidCancelledReplacement = await sameTupleCancellation("completed", ["ordinary"], false, + {cancelledUntil: 150, recoverableOriginal: true, invalidCancelledSource: true}); + assert.deepEqual(invalidCancelledReplacement.failures, ["Cancelled or timed-out typed runtime producer has an invalid source identity."]); + assert.equal(invalidCancelledReplacement.now, 0); + const timedOutReplacement = await sameTupleCancellation("completed", ["ordinary"], false, + {cancelledUntil: 150, recoverableOriginal: true, unusableConclusion: "timed_out"}); + assert.deepEqual(timedOutReplacement.failures, []); + assert.equal(timedOutReplacement.now, 150, "a timed-out refresh can be replaced beyond the terminal snapshot window"); + assert.equal(timedOutReplacement.proofReads, 1, "a timed-out attempt is not proof"); + const timedOutNoShow = await sameTupleCancellation("completed", ["ordinary"], false, + {cancelledUntil: Infinity, recoverableOriginal: true, unusableConclusion: "timed_out"}); + assert.equal(timedOutNoShow.now, 200); + assert.match(timedOutNoShow.failures[0], /no newer exact producer within the recovery allowance/); + assert.equal(timedOutNoShow.proofReads, 0); const recoverableNoShow = await sameTupleCancellation("completed", ["ordinary"], false, {visibleAt: Infinity, recoverableOriginal: true}); assert.equal(recoverableNoShow.now, 200, "eligible originals retain the longer existing discovery allowance"); @@ -4933,6 +5093,12 @@ function markerAccepted(overrides = {}) { data.jobs[0].steps.push(step("Start database", "failure")); }, latest: {run_attempt: 2}})).accepted, false); await pendingRefreshCaller(["absent", "absent", "absent", "absent", "absent", "completed"], false, {absentExpires: true}); + await pendingRefreshCaller(["cancelled", "queued", "completed"]); + await pendingRefreshCaller(["timed_out", "queued", "completed"]); + await pendingRefreshCaller(["cancelled", "timed_out", "cancelled", "timed_out", "timed_out", "completed"], false, + {absentExpires: true}); + await pendingRefreshCaller(["cancelled", "cancelled", "cancelled", "cancelled", "cancelled", "completed"], false, + {absentExpires: true}); await pendingRefreshCaller(["absent", "absent", "absent", "completed"]); // Validation may outlast the former5min-equivalent window. await pendingRefreshCaller(["missing-job", "missing-job", "missing-job", "completed"], false, {snapshotExpires: true}); await pendingRefreshCaller(["completed"], false, {rejectedObject: true}); @@ -4964,7 +5130,20 @@ function markerAccepted(overrides = {}) { assert.deepEqual(await recoveredFailure({replacement: {run_attempt: 0, conclusion}}), {accepted: false, verified: 0, queries: 1}, "a missing conclusion cannot hide an invalid supplied attempt"); } - for (const conclusion of ["", false, 0, {}, "cancelled", "timed_out"]) { + for (const conclusion of ["cancelled", "timed_out"]) { + assert.deepEqual(await recoveredFailure({replacement: {conclusion}}), + {accepted: conclusion, verified: 0, queries: 1}, "a known cancelled/timed-out refresh is bounded pending, never proof"); + for (const change of [ + {run_attempt: null}, {workflow_id: null}, {path: ".github/workflows/other.yml"}, + {repository: {full_name: "other/repo"}}, {head_repository: {full_name: "other/repo"}}, + {head_sha: "not-an-oid"}, {head_sha: [workflowSha]}, {head_branch: undefined}, + {head_branch: "feature"}, {display_title: "ambiguous"}, + ]) { + assert.deepEqual(await recoveredFailure({replacement: {conclusion, ...change}}), + {accepted: false, verified: 0, queries: 1}, "ambiguous unusable source identity cannot enter recovery"); + } + } + for (const conclusion of ["", false, 0, {}]) { assert.deepEqual(await recoveredFailure({replacement: {conclusion}}), {accepted: false, verified: 0, queries: 1}, "an invalid present conclusion cannot become pending"); } @@ -5040,6 +5219,14 @@ function markerAccepted(overrides = {}) { const ordinaryOptions = {candidate: {steps: ordinary}, mutateProof(data) {data.currentPullRequest.labels = [];}}; assert.equal((await recoveredFailure(ordinaryOptions, null, identity, true)).accepted.status, "ordinary", "an authenticated passing typed run with explicitly skipped exception needs no label"); + const ordinaryWithoutSmoke = ordinary.filter(step => step.name !== "Run credential-free full-stack smoke"); + assert.equal((await recoveredFailure({...ordinaryOptions, candidate: {steps: ordinaryWithoutSmoke}})).accepted.status, "ordinary", + "a fingerprinted successful native job and guard attest an omitted smoke row during recovery too"); + assert.equal(await verify(data => { + Object.assign(data.run, data.source); + data.legacyDefinition = true; + data.candidate.steps = structuredClone(ordinaryWithoutSmoke); + }, "repository_dispatch", false, true), "snapshot-pending", "an older producer still needs affirmative smoke-step evidence"); const ordinaryMissingCleanup = ordinary.map(step => step.name === "Stop smoke stack" ? {...step, conclusion: "failure"} : step); assert.equal((await recoveredFailure({...ordinaryOptions, candidate: {steps: ordinaryMissingCleanup}})).accepted, false, @@ -5051,6 +5238,21 @@ function markerAccepted(overrides = {}) { await pendingRefreshCaller(["missing-job", "pending-job", "completed"]); await pendingRefreshCaller(["absent", "absent"], true); await pendingRefreshCaller(["completed"], false, {originalError: Object.assign(new Error("missing"), {status: 404})}); + const unavailableOriginal = () => Object.assign(new Error("original attempt jobs remain unavailable"), {status: 502}); + const recoveredUnavailable = await pendingRefreshCaller(["missing-conclusion", "completed"], false, + {originalError: unavailableOriginal()}); + assert.equal(recoveredUnavailable.originalJobReads, 2); + assert.equal(recoveredUnavailable.sleeps, 1, "a null replacement conclusion waits before fresh exact proof, despite original read errors"); + await pendingRefreshCaller(["missing-conclusion", "completed"], false, + {originalError: unavailableOriginal(), ordinaryRecovery: true}); + await pendingRefreshCaller(["completed"], false, {originalError: unavailableOriginal(), rejectedObject: true}); + await pendingRefreshCaller(["missing-conclusion", "null-conclusion", "missing-conclusion", "completed"], false, + {originalError: unavailableOriginal(), snapshotExpires: true}); + await pendingRefreshCaller(["absent", "absent", "absent", "absent", "absent", "completed"], false, + {originalError: unavailableOriginal(), absentExpires: true}); + const originalPermissionDenied = new TerminalGitHubRequestError("original attempt jobs permission denied"); + await assert.rejects(pendingRefreshCaller(["completed"], false, {originalError: originalPermissionDenied}), + error => error === originalPermissionDenied, "terminal permission errors must not enter refresh recovery"); for (const change of [ data => {data.jobs = [];}, data => {data.jobs[0].status = "in_progress"; data.jobs[0].conclusion = null;}, @@ -5110,7 +5312,7 @@ function markerAccepted(overrides = {}) { {original: {id: 0}}, {replacement: {run_attempt: 0}}, {replacement: {event: "pull_request"}}, {replacement: {status: "unknown"}}, - {replacement: {conclusion: "cancelled"}}, + {replacement: {conclusion: "cancelled", head_branch: "other"}}, ]) { const result = await recoveredFailure(options); assert.equal(result.accepted, false, JSON.stringify(options)); diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index d724baf299..bfb834b790 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -900,8 +900,8 @@ async function runDispatcher({ visibilityResponse = null, filesFailurePr = null, postFailureVisible = false, postFailureStatus = null, fanoutCutoffAfterInventory = false, fanoutCutoffAfterPreviewPr = null, expireAfterFirstApiRequest = false, pullGetFailures = {}, lateProducer = null, runtimeWorkflowLookupFailures = [], - pullListResponse = null, apiRequestMillis = 0, runtimeRunOverrides = {}, runtimeAttemptJobs = {}, - initialTime = "2026-01-08T00:00:00Z", + pullListResponse = null, apiRequestMillis = 0, runtimeRunOverrides = {}, runtimeAttemptJobs = {}, runtimeNativeAttempts = {}, + initialTime = "2026-01-08T00:00:00Z", afterPreviewDispatch = null, }) { const dispatches = []; const postedRuns = []; @@ -918,6 +918,7 @@ async function runDispatcher({ const apiRequestRecords = []; const lateProducers = []; const runtimeRunReads = []; + const mockFailures = []; let lateProducerAdded = false; let runtimeWorkflowLookupCount = 0; let waitedMillis = 0; @@ -1079,6 +1080,7 @@ async function runDispatcher({ if (request.event_type === "preview-deploy" && request.client_payload.pr_number === fanoutCutoffAfterPreviewPr) { fakeNow += 12 * 60 * 1000; } + if (request.event_type === "preview-deploy" && afterPreviewDispatch) afterPreviewDispatch(request); }, }, actions: { @@ -1110,6 +1112,18 @@ async function runDispatcher({ ciRunReads += 1; return { data: { ...ciRun, ...(ciEvidence.run ?? {}), ...(ciRunReads > 1 ? ciEvidence.latest ?? {} : {}) } }; }, + getWorkflowRunAttempt: async (request) => { + recordApiRequest("actions.getWorkflowRunAttempt", request); + const {request: requestOptions, ...normal} = request; + assert.deepEqual(normal, {owner: "owner", repo: "repo", run_id: request.run_id, attempt_number: request.attempt_number}); + const runs = Object.values(inventories).flatMap(inventory => Array.isArray(inventory) ? inventory : inventory.runs ?? []); + const run = runs.find(run => run?.id === request.run_id); + assert(run, "native exact attempt must address an inventoried runtime producer"); + assert.equal(request.attempt_number, run.run_attempt); + const attempt = Object.hasOwn(runtimeNativeAttempts, run.id) ? runtimeNativeAttempts[run.id] : run; + if (attempt instanceof Error) throw attempt; + return {data: attempt}; + }, listJobsForWorkflowRunAttempt: async (request) => { recordApiRequest("actions.listJobsForWorkflowRunAttempt", request); if (request.run_id !== ciRun.id) return {data: runtimeAttemptJobs[request.run_id] ?? {total_count: 0, jobs: []}}; @@ -1176,6 +1190,17 @@ async function runDispatcher({ }, }, }; + // Expected fail-closed results must come from production classification, not + // from request assertions swallowed by its conservative evidence catches. + for (const namespace of Object.values(github.rest)) { + for (const [name, method] of Object.entries(namespace)) namespace[name] = async (...args) => { + try { return await method(...args); } + catch (error) { + if (error.code === "ERR_ASSERTION") mockFailures.push(error.message); + throw error; + } + }; + } const context = { repo: { owner: "owner", repo: "repo" }, payload: { @@ -1221,6 +1246,7 @@ async function runDispatcher({ Date.now = originalDateNow; global.setTimeout = originalSetTimeout; } + assert.deepEqual(mockFailures, [], "mock contract assertion failures never count as production refusals"); return { dispatches, errors, infos, warnings, inventoryCalls, observationPostCounts, timerPostCounts, waitedMillis, ciJobRequests, pullListRequests, pullReads, refRequests, deadlineSignals, apiRequestRecords, runtimeWorkflowLookupCount, runtimeRunReads, timerDelays, fatalError }; @@ -1271,6 +1297,21 @@ async function runDispatcher({ assert.deepEqual(Object.keys(ciJobRequestOptions).sort(), ["signal"], "CI job listing carries only its AbortSignal request option"); assert.equal(reconcile.deadlineSignals[0].timeoutMs, 12 * 60 * 1000, "the first fan-out API call receives the full wall-clock budget"); assertRequestContracts(reconcile); + const ciPath = ".github/workflows/ci.yml"; + for (const [callbackPath, apiPath] of [[ciPath, `${ciPath}@refs/pull/101/merge`], + [`${ciPath}@refs/pull/101/merge`, ciPath]]) { + const equivalent = await runDispatcher({tuples: [child], sourceTuples: [source], + callback: {...prCallback, path: callbackPath}, ciEvidence: {run: {path: apiPath}}}); + assert.deepEqual(runtimeDispatches(equivalent).map(item => item.client_payload.pr_number).sort(), + [source.prNumber, child.prNumber].sort(), "native CI callback/API paths may differ only by this exact PR's merge ref"); + assert.deepEqual(equivalent.errors, []); + } + for (const suffix of ["refs/pull/102/merge", "refs/pull/0101/merge", "refs/pull/101/head", "refs/heads/develop"]) { + const drift = await runDispatcher({tuples: [child], sourceTuples: [source], callback: prCallback, + ciEvidence: {run: {path: `${ciPath}@${suffix}`}}}); + assert.deepEqual(drift.dispatches, [], "another PR/ref cannot use native path equivalence"); + assert(drift.warnings.some(message => message.includes("identity differs from callback"))); + } const pagedFiles = [...Array.from({length: 100}, (_, index) => ({filename: `docs/page-${index}.md`})), {filename: "services/example/src/Main.java"}]; const pagedCiJobs = (request, jobs) => { @@ -1472,7 +1513,7 @@ async function runDispatcher({ request.page === 1 && typeof request.created === "string" && !Number.isNaN(Date.parse(request.created.replace(/\.\.\*$/, "")) ) - ), "the shared inventory must query only one bounded recent page per event"); + ), "each target inventory must query only one bounded recent page per event when complete"); } for (const event of ["pull_request", "repository_dispatch"]) { @@ -1603,6 +1644,62 @@ async function runDispatcher({ }); assert.deepEqual(numbers(existingFirst), ["102"], "existing first PR must not starve second"); assert.equal(existingFirst.errors.length, 0, existingFirst.errors.join("\n")); + for (const event of ["pull_request", "repository_dispatch"]) { + for (const [status, conclusion, earlierActive] of [ + ["completed", "cancelled", false], + ["completed", "timed_out", false], + ["in_progress", null, false], + ["completed", "cancelled", true], + ]) { + const laterProducer = producer(sibling, event, "queued", null, {created_at: "2026-01-03T00:00:00Z"}); + const inventories = { + pull_request: [producer(tuple, "pull_request", "in_progress")], + repository_dispatch: [], + }; + inventories[event].push(laterProducer); + if (earlierActive) inventories.pull_request.push(producer(sibling, "pull_request", "in_progress", null, { + id: 90204, created_at: "2026-01-02T00:00:00Z", + })); + let transitions = 0; + const changedBetweenTargets = await runDispatcher({ + tuples: [tuple, sibling], inventories, + afterPreviewDispatch: request => { + if (request.client_payload.pr_number !== tuple.prNumber) return; + transitions += 1; + // Replace the REST row; do not mutate the earlier snapshot in place. + inventories[event] = inventories[event].map(run => run.id === laterProducer.id + ? {...run, status, conclusion} : run); + }, + }); + const needsRefresh = status === "completed" && !earlierActive; + assert.equal(transitions, 1, "the later producer changes only after the first target's preview handoff"); + assert.deepEqual(numbers(changedBetweenTargets), needsRefresh ? [sibling.prNumber] : [], + `${event} ${status}/${conclusion} must use target-fresh evidence without duplicating an earlier active exact producer`); + assert.equal(changedBetweenTargets.inventoryCalls.filter(request => + request.created !== "2026-01-08T00:00:00.000Z..*" + ).length, needsRefresh ? 6 : 4, + "each target gets both event inventories, with another full snapshot only before a required runtime POST"); + assert.equal(previewDispatches(changedBetweenTargets).length, 2, + "fresh producer classification must retain independent preview reconciliation for both targets"); + assert.deepEqual(changedBetweenTargets.errors, [], "fresh terminal or active producer evidence is classifiable"); + assertRequestContracts(changedBetweenTargets); + } + } + const unavailableLaterInventories = {pull_request: [ + producer(tuple, "pull_request", "in_progress"), producer(sibling, "pull_request", "queued"), + ]}; + const unavailableLaterInventory = await runDispatcher({ + tuples: [tuple, sibling], inventories: unavailableLaterInventories, + afterPreviewDispatch: request => { + if (request.client_payload.pr_number === tuple.prNumber) unavailableLaterInventories.pull_request = {malformed: true}; + }, + }); + assert.deepEqual(numbers(unavailableLaterInventory), [], "unavailable target-fresh evidence cannot authorize a runtime POST"); + assert(unavailableLaterInventory.errors.some(message => + message.includes("Cannot verify exact runtime producer inventory for PR #102") && message.includes("inventory is malformed")), + "an earlier queued snapshot cannot hide a later target's unknown producer evidence"); + assert.equal(previewDispatches(unavailableLaterInventory).length, 2, + "unavailable runtime inventory must not suppress independent preview reconciliation"); const initialTargetReadFailure = await runDispatcher({ tuples: [tuple, sibling], pullGetFailures: {"101": 502}, }); @@ -1618,19 +1715,19 @@ async function runDispatcher({ const lateSiblingProducer = producer(sibling, "repository_dispatch", "in_progress", null, { id: 90202, created_at: "2026-01-03T00:00:00Z", }); - const refreshedAfterReuse = await runDispatcher({ + const refreshedAfterEarlierTarget = await runDispatcher({ tuples: [tuple, sibling], inventories: {pull_request: [producer(tuple, "pull_request", "in_progress")]}, lateProducer: lateSiblingProducer, }); - assert.deepEqual(numbers(refreshedAfterReuse), [], - "a full fresh producer inventory before the second candidate POST must find a producer hidden from the reused cache"); - assert.equal(refreshedAfterReuse.inventoryCalls.filter(request => + assert.deepEqual(numbers(refreshedAfterEarlierTarget), [], + "a full fresh inventory for the second target must find a producer absent during the earlier target's decision"); + assert.equal(refreshedAfterEarlierTarget.inventoryCalls.filter(request => request.created !== "2026-01-08T00:00:00.000Z..*" - ).length, 4, "a cached initial snapshot is refreshed across both event kinds before a later candidate POST"); - assert.equal(previewDispatches(refreshedAfterReuse).length, 2, - "the last-minute producer discovery must not suppress independent preview reconciliation"); - assert.equal(refreshedAfterReuse.errors.length, 0, refreshedAfterReuse.errors.join("\n")); + ).length, 4, "both event kinds must be refreshed even when the earlier target reused an existing producer"); + assert.equal(previewDispatches(refreshedAfterEarlierTarget).length, 2, + "the later target's producer discovery must not suppress independent preview reconciliation"); + assert.equal(refreshedAfterEarlierTarget.errors.length, 0, refreshedAfterEarlierTarget.errors.join("\n")); const lateNative = await runDispatcher({ tuples: [tuple], lateProducer: producer(tuple, "pull_request", "in_progress", null, { @@ -1857,9 +1954,16 @@ async function runDispatcher({ started_at: "2026-01-03T00:01:01Z", completed_at: "2026-01-03T00:03:00Z", steps: [diagnosticMarker]}; for (const [jobs, total, expected] of [ [[failedJob], 1, ["101"]], + [[{...failedJob, steps: [{...diagnosticMarker, started_at: null, completed_at: null}]}], 1, ["101"]], + [[{...failedJob, steps: [{name: diagnosticMarker.name, status: "completed", conclusion: "skipped"}]}], 1, ["101"]], [[{...failedJob, steps: [{...diagnosticMarker, conclusion: "success"}]}], 1, []], [[{...failedJob, steps: [{...diagnosticMarker, conclusion: null}]}], 1, []], [[{...failedJob, steps: [diagnosticMarker, diagnosticMarker]}], 1, []], + [[{...failedJob, steps: [{...diagnosticMarker, started_at: null}]}], 1, []], + [[{...failedJob, steps: []}], 1, []], + [[{...failedJob, completed_at: undefined}], 1, []], + [[{...failedJob, started_at: "2026-02-30T00:00:00Z"}], 1, []], + [[{...failedJob, started_at: "2026-01-03T00:01:01+00:00", completed_at: "2026-01-02T20:03:00-04:00"}], 1, ["101"]], [[{...failedJob, started_at: "2026-01-03T00:00:59Z"}], 1, []], [[failedJob], 2, []], ]) { @@ -1868,6 +1972,42 @@ async function runDispatcher({ assert.deepEqual(numbers(result), expected); assert.deepEqual(result.errors, []); } + for (const attempt of [{...failedTyped, run_started_at: "2026-01-03T01:00:00Z", updated_at: "2026-01-03T01:04:00Z"}, + {...failedTyped, run_attempt: 2}, {...failedTyped, repository: {full_name: "other/repo"}}, + {...failedTyped, head_repository: {full_name: "fork/repo"}}, + {...failedTyped, path: `${failedTyped.path}@refs/heads/develop`}, null]) { + const held = await runDispatcher({tuples: [tuple], inventories: {repository_dispatch: [failedTyped]}, + runtimeNativeAttempts: {[failedTyped.id]: attempt}, runtimeAttemptJobs: {[failedTyped.id]: {total_count: 1, jobs: [failedJob]}}}); + assert.deepEqual(numbers(held), [], "wrong native attempt identity or copied execution cannot authorize replacement"); + assert.deepEqual(held.errors, []); + } + const supersededFailure = await runDispatcher({tuples: [tuple], inventories: {repository_dispatch: [failedTyped]}, + runtimeRunOverrides: {[failedTyped.id]: reads => reads > 1 ? {run_attempt: 2} : {}}, + runtimeAttemptJobs: {[failedTyped.id]: {total_count: 1, jobs: [failedJob]}}}); + assert.deepEqual(numbers(supersededFailure), [], "a rerun beginning during native attempt/job proof must retain the failed refresh hold"); + assert.deepEqual(supersededFailure.runtimeRunReads, [failedTyped.id, failedTyped.id]); + assert.deepEqual(supersededFailure.errors, []); + const validRerun = {...failedTyped, run_attempt: 2}; + const validRerunJob = {...failedJob, run_attempt: 2, started_at: "2026-01-03T01:00:01Z", completed_at: "2026-01-03T01:03:00Z", + steps: [{name: diagnosticMarker.name, status: "completed", conclusion: "skipped", started_at: null, completed_at: null}]}; + const rerunRecovery = await runDispatcher({tuples: [tuple], inventories: {repository_dispatch: [validRerun]}, + runtimeNativeAttempts: {[validRerun.id]: {...validRerun, run_started_at: "2026-01-03T01:00:00Z", updated_at: "2026-01-03T01:04:00Z"}}, + runtimeAttemptJobs: {[validRerun.id]: {total_count: 1, jobs: [validRerunJob]}}}); + assert.deepEqual(numbers(rerunRecovery), ["101"], "a genuinely executed exact rerun is not constrained by stale run-wide timestamps"); + assert.deepEqual(rerunRecovery.errors, []); + const earlierRunning = producer(tuple, "pull_request", "in_progress", null, { + id: 10101, created_at: "2026-01-02T00:00:00Z", + }); + for (const conclusion of ["cancelled", "timed_out", "failure"]) { + const unusable = conclusion === "failure" ? failedTyped : terminalTyped(conclusion); + const retained = await runDispatcher({tuples: [tuple], + inventories: {pull_request: [earlierRunning], repository_dispatch: [unusable]}, + runtimeAttemptJobs: {[unusable.id]: {total_count: 1, jobs: [failedJob]}}}); + assert.deepEqual(numbers(retained), [], "discarding a terminal typed replacement must reveal an earlier viable exact producer, not dispatch again"); + assert(retained.infos.some(message => message.includes(`exact tuple producer ${earlierRunning.id} remains in_progress`))); + assert.equal(previewDispatches(retained).length, 1, "earlier producer reuse does not suppress preview reconciliation"); + assert.deepEqual(retained.errors, []); + } const cancelledTyped = terminalTyped("cancelled"); for (const changed of [ {run_attempt: 2}, {run_attempt: 0}, {run_attempt: null}, {id: cancelledTyped.id + 1}, diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index 3013fdc216..f7a4e728b2 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -203,32 +203,42 @@ function producerFor(run, required = true) { } async function resolve({ context = baseContext, runs = [source], workflow = { id: 777, name: "Build Runtime Images", path: source.path }, error = false, jobs = null, nativeAttempt, jobPages = null, attemptError = false, jobError = false, - expectException = false, expireAfterAttempt = false, expireAfterJobs = false } = {}) { + expectException = false, expireAfterAttempt = false, expireAfterJobs = false, + expireAfterWorkflow = false, expireAfterRun = false, requestMillis = 0 } = {}) { let reads = 0, clock = 0; let selected; - const output = {}, proofRequests = [], signals = []; + const requestedSourceId = Number(context.eventName === "workflow_run" + ? context.payload.workflow_run.id : context.payload.client_payload.source_run_id); + const output = {}, proofRequests = [], signals = [], requests = []; class FixtureDate extends Date { static now() { return clock; } } - const recordProof = (method, options, paged = false) => { + const recordRequest = (method, options, expected) => { const {request, ...normal} = options; - assert.deepEqual(normal, {...baseContext.repo, run_id: selected.id, attempt_number: selected.run_attempt, - ...(paged ? {per_page: 100, page: proofRequests.filter(row => row.method === method).length + 1} : {})}, - `${method} must address the exact selected native attempt with explicit direct pagination`); + assert.deepEqual(normal, expected, `${method} must preserve its exact API scope`); assert.deepEqual(Object.keys(request), ["signal"]); assert.equal(request.signal, signals.at(-1)); assert.equal(request.signal.timeoutMs, 120000 - clock, "each proof read uses its remaining wall-clock budget"); assert(request.signal.timeoutMs > 0); - proofRequests.push({method, ...normal, signal: request.signal}); + const recorded = {method, ...normal, signal: request.signal}; + requests.push(recorded); + clock += requestMillis; + return recorded; + }; + const recordProof = (method, options, paged = false) => { + proofRequests.push(recordRequest(method, options, {...baseContext.repo, run_id: selected.id, attempt_number: selected.run_attempt, + ...(paged ? {per_page: 100, page: proofRequests.filter(row => row.method === method).length + 1} : {})})); }; const github = { paginate: async () => { throw Error("producer proof must not use the run-wide paginator"); }, rest: { actions: { getWorkflow: async options => { - assert.deepEqual(options, {...baseContext.repo, workflow_id: "runtime-images.yml"}); + recordRequest("getWorkflow", options, {...baseContext.repo, workflow_id: "runtime-images.yml"}); + if (expireAfterWorkflow) clock += 120000; return {data: workflow}; }, getWorkflowRun: async options => { - assert.deepEqual(options, {...baseContext.repo, run_id: 4242}); + recordRequest("getWorkflowRun", options, {...baseContext.repo, run_id: requestedSourceId}); reads++; if (error) throw Error("API unavailable"); selected = runs[Math.min(reads - 1, runs.length - 1)]; + if (expireAfterRun) clock += 120000; return {data: selected}; }, getWorkflowRunAttempt: async options => { @@ -257,17 +267,19 @@ async function resolve({ context = baseContext, runs = [source], workflow = { id } assert.equal(proofRequests[0]?.method, "getWorkflowRunAttempt"); assert(proofRequests.slice(1).every(row => row.method === "listJobsForWorkflowRunAttempt")); - assert.equal(new Set(proofRequests.map(row => row.signal)).size, proofRequests.length, - "each direct proof request must receive a fresh timeout signal"); + assert.equal(new Set(requests.map(row => row.signal)).size, requests.length, + "each direct lookup and proof request must receive a fresh timeout signal"); if (expectException) { assert.deepEqual(output, {}, "exception attempts must expose no publication source"); - return {reads, output, proofRequests}; + return {reads, output, proofRequests, requests}; } assert.equal(output.title, title); assert.equal(output.artifact_name, `pr-runtime-images-pr-merge-${sha("c")}`); assert.equal(JSON.parse(output.source).status, "completed"); - return {reads, output, proofRequests}; + return {reads, output, proofRequests, requests}; } +const rejectsResolver = (promise, pattern, message) => assert.rejects(promise, + error => error.code !== "ERR_ASSERTION" && pattern.test(error.message), message); const runtimeWorkflow = fs.readFileSync(process.argv[4], "utf8"); const diagnosticPaths = [ "dev-tools/validation/collect-gradle-compile-failure.py", @@ -366,6 +378,11 @@ for (const publishable of ["false", "", undefined]) { await dispatch({rest: {repos: {createDispatchEvent: async payload => {dispatched = payload;}}}}, baseContext); assert.deepEqual(dispatched, {...baseContext.repo, event_type: "pr-runtime-image-publication", client_payload: {source_run_id: "4242"}}); const direct = await resolve(); + const timed = await resolve({requestMillis: 250}); + assert.deepEqual(timed.requests.map(({method, signal}) => [method, signal.timeoutMs]), [ + ["getWorkflow", 120000], ["getWorkflowRun", 119750], + ["getWorkflowRunAttempt", 119500], ["listJobsForWorkflowRunAttempt", 119250], + ], "workflow, run, exact-attempt and jobs reads share one decreasing deadline, without resetting the proof budget"); const exceptionJob = {...producerFor(source), steps: [{ name: "Known canonical transition PLAY failure with successful authenticated cleanup", number: 24, status: "completed", conclusion: "success"}]}; @@ -416,21 +433,36 @@ for (const publishable of ["false", "", undefined]) { {head_sha: sha("a")}, {head_sha: undefined}, {repository: {full_name: "fork/FireMUD"}}, {head_repository: {full_name: "fork/FireMUD"}}, {status: "in_progress"}, {conclusion: "failure"}, ]) { - await assert.rejects(resolve({runs: [rerun], nativeAttempt: {...attempt2, ...change}, jobs: [rerunProducer]}), + await rejectsResolver(resolve({runs: [rerun], nativeAttempt: {...attempt2, ...change}, jobs: [rerunProducer]}), + /source attempt (?:\w+ differs|provenance is not trusted)/, `exact native attempt identity must not drift: ${JSON.stringify(change)}`); } await assert.rejects(resolve({nativeAttempt: null}), /source attempt/); await assert.rejects(resolve({attemptError: true}), /native attempt unavailable/); await assert.rejects(resolve({jobError: true}), /native jobs unavailable/); + await rejectsResolver(resolve({expireAfterWorkflow: true}), /bounded deadline/, + "a workflow lookup consuming the shared budget prevents the run lookup"); + await rejectsResolver(resolve({expireAfterRun: true}), /bounded deadline/, + "a run lookup consuming the shared budget prevents any attempt proof or source output"); await assert.rejects(resolve({expireAfterAttempt: true}), /bounded deadline/, "expiry after native metadata prevents any job request or source output"); await assert.rejects(resolve({expireAfterJobs: true}), /bounded deadline/, "a last job response arriving after the proof deadline cannot expose a source"); for (const field of ["created_at", "run_started_at", "updated_at"]) { - for (const value of [undefined, null, "", "not-a-date", "2026-02-30T00:00:00Z", "2026-01-08T00:00:00+00:00"]) { - await assert.rejects(resolve({nativeAttempt: {...source, [field]: value}}), /UTC timestamp/); + for (const value of [undefined, null, "", "not-a-date", "2026-02-30T00:00:00Z", "2026-01-08T00:00:00+24:00", + "2026-01-08T00:00:00+00:60", "2026-01-08T24:00:00+00:00", "2026-01-08T00:00:00"]) { + await rejectsResolver(resolve({nativeAttempt: {...source, [field]: value}}), /invalid ISO timestamp/); } } + for (const [offset, hours] of [["+00:00", 0], ["+05:30", 5.5], ["-04:00", -4]]) { + const shifted = value => new Date(Date.parse(value) + hours * 3600000).toISOString().replace(/Z$/, offset); + const offsetAttempt = Object.fromEntries(Object.entries(source).map(([key, value]) => + [key, ["created_at", "run_started_at", "updated_at"].includes(key) ? shifted(value) : value])); + const offsetJob = {...producer, started_at: shifted(producer.started_at), completed_at: shifted(producer.completed_at), + steps: [{...uploadStep, started_at: shifted(uploadStep.started_at), completed_at: shifted(uploadStep.completed_at)}]}; + assert.equal((await resolve({nativeAttempt: offsetAttempt, jobs: [offsetJob]})).output.title, title, + "valid native numeric offsets preserve the exact execution instants"); + } for (const change of [ {created_at: "2026-01-08T00:00:02Z"}, {updated_at: "2026-01-07T23:59:59Z"}, ]) await assert.rejects(resolve({nativeAttempt: {...source, ...change}}), /chronology/); @@ -443,7 +475,8 @@ for (const publishable of ["false", "", undefined]) { {started_at: undefined}, {completed_at: null}, {started_at: "2026-01-07T23:59:59Z"}, {completed_at: "2026-01-08T00:00:00Z"}, {completed_at: "2026-01-08T00:04:01Z"}, ]) { - await assert.rejects(resolve({jobs: [{...producer, ...change}]}), + await rejectsResolver(resolve({jobs: [{...producer, ...change}]}), + /(?:job inventory|one successful attributable artifact producer|actual successful Upload|invalid ISO timestamp|did not execute within)/, `producer proof must be complete, successful, attributable and chronological: ${JSON.stringify(change)}`); } for (const change of [ @@ -452,7 +485,8 @@ for (const publishable of ["false", "", undefined]) { {started_at: undefined}, {completed_at: undefined}, {started_at: "2026-01-08T00:00:00Z"}, {completed_at: "2026-01-08T00:01:59Z"}, {completed_at: "2026-01-08T00:03:01Z"}, ]) { - await assert.rejects(resolve({jobs: [{...producer, steps: [{...uploadStep, ...change}]}]}), + await rejectsResolver(resolve({jobs: [{...producer, steps: [{...uploadStep, ...change}]}]}), + /(?:actual successful Upload|invalid ISO timestamp|upload did not execute within)/, `the actual upload step must prove successful execution inside its producer: ${JSON.stringify(change)}`); } for (const steps of [[uploadStep, uploadStep], [uploadStep, {...uploadStep, number: 21}], @@ -524,11 +558,12 @@ for (const publishable of ["false", "", undefined]) { {display_title: title.replace("mode-required", "mode-optional")}, {conclusion: "failure"}, ]) { - await assert.rejects(resolve({runs: [{...apiRun, ...change}], context}), + await rejectsResolver(resolve({runs: [{...apiRun, ...change}], context}), /(?:provenance is not trusted|differs from callback)/, `path equivalence must not mask API identity drift: ${JSON.stringify(change)}`); - await assert.rejects(resolve({runs: [apiRun], context: { + await rejectsResolver(resolve({runs: [apiRun], context: { ...context, payload: {repository, workflow_run: {...callbackRun, ...change}}, - }}), `path equivalence must not mask callback identity drift: ${JSON.stringify(change)}`); + }}), /(?:provenance is not trusted|callback path or run identity is not trusted|differs from callback)/, + `path equivalence must not mask callback identity drift: ${JSON.stringify(change)}`); } await assert.rejects(resolve({runs: [{...apiRun, status: "in_progress"}], context}), /bounded wait/); // A typed refresh must retain exact path equality, even for a PR-shaped suffix. @@ -587,13 +622,15 @@ for (const publishable of ["false", "", undefined]) { await assert.rejects(resolve({runs: [malformed], context: {...callbackContext, payload: {repository, workflow_run: malformed}}}), /provenance/); } for (const change of [{status: "completed", conclusion: "failure"}, {head_repository: {full_name: "fork/FireMUD"}}, {repository: {full_name: "fork/FireMUD"}}, {workflow_id: 778}, {path: "other.yml"}, {event: "push"}, {head_branch: "feature"}, {display_title: "unbound"}, {head_sha: "bad"}]) { - await assert.rejects(resolve({runs: [{...source, ...change}]})); + await rejectsResolver(resolve({runs: [{...source, ...change}]}), /publication source run (?:provenance is not trusted|did not succeed)/); } - await assert.rejects(resolve({runs: [pending]}), /bounded wait/); + await rejectsResolver(resolve({runs: [pending]}), /bounded deadline/); await assert.rejects(resolve({error: true}), /API unavailable/); - await assert.rejects(resolve({context: {...baseContext, ref: "refs/heads/feature"}})); - await assert.rejects(resolve({context: {...baseContext, payload: {...baseContext.payload, client_payload: {source_run_id: "4242", extra: true}}}})); - await assert.rejects(resolve({context: {...baseContext, payload: {...baseContext.payload, client_payload: {source_run_id: "../4242"}}}})); + await rejectsResolver(resolve({context: {...baseContext, ref: "refs/heads/feature"}}), /closed default-branch source-run payload/); + await rejectsResolver(resolve({context: {...baseContext, payload: {...baseContext.payload, client_payload: {source_run_id: "4242", extra: true}}}}), + /closed default-branch source-run payload/); + await rejectsResolver(resolve({context: {...baseContext, payload: {...baseContext.payload, client_payload: {source_run_id: "../4242"}}}}), + /source run ID is not a positive safe integer/); await assert.rejects(resolve({context: {...callbackContext, payload: {repository, workflow_run: {...source, head_sha: sha("d")}}}}), /differs from callback/); console.log("Exact source handoff, terminal-resolution and bounded artifact-producer proof fixtures passed."); })().catch(error => { console.error(error); process.exitCode = 1; }); @@ -653,6 +690,7 @@ async function runReconcile({ ambiguousPost = true, expireFirstRequest = false, initialDiscoveryUnavailable = false, ciRuns = [ciRun], ciNativeRuns = {}, ciJobsByRun = {}, postVisibilityRuns = null, postVisibilityFailures = [], preflightRefreshRuns = [], refreshNativeRuns = {}, refreshAttemptJobs = {}, + refreshNativeAttempts = {}, sourceRun = source, sourceCallback = sourceRun, } = {}) { let now = Date.parse("2026-01-08T00:00:00Z"); let expire = expireFirstRequest; @@ -668,6 +706,7 @@ async function runReconcile({ const dispatchRequests = []; const warnings = []; const infos = []; + const mockFailures = []; class FixtureDate extends Date { constructor(...args) { super(...(args.length ? args : [now])); } static now() { return now; } @@ -710,7 +749,7 @@ async function runReconcile({ repo: {owner, repo}, payload: { repository: {full_name: repository, default_branch: "develop"}, - workflow_run: source, + workflow_run: sourceCallback, }, }; const github = { @@ -725,7 +764,7 @@ async function runReconcile({ }, getWorkflowRun: async options => { record("actions.getWorkflowRun", options, {owner, repo, run_id: options.run_id}); - if (options.run_id === source.id) return {data: source}; + if (options.run_id === source.id) return {data: sourceRun}; const refresh = preflightRefreshRuns.find(run => run.id === options.run_id); if (refresh || Object.hasOwn(refreshNativeRuns, options.run_id)) { nativeRefreshRunIds.push(options.run_id); @@ -739,6 +778,16 @@ async function runReconcile({ } return {data: ciNativeRuns[options.run_id] ?? ciRun}; }, + getWorkflowRunAttempt: async options => { + const {run_id, attempt_number} = options; + record("actions.getWorkflowRunAttempt", options, {owner, repo, run_id, attempt_number}); + const run = preflightRefreshRuns.find(run => run.id === run_id); + assert(run, "native attempt proof must address an inventoried typed refresh"); + assert.equal(attempt_number, run.run_attempt, "native attempt proof must retain the selected attempt"); + const attempt = Object.hasOwn(refreshNativeAttempts, run_id) ? refreshNativeAttempts[run_id] : run; + if (attempt instanceof Error) throw attempt; + return {data: attempt}; + }, listJobsForWorkflowRunAttempt: async options => { const {run_id, attempt_number, page} = options; record("actions.listJobsForWorkflowRunAttempt", options, { @@ -824,6 +873,17 @@ async function runReconcile({ }, }; + // Production deliberately catches unavailable evidence. A broken mock request + // assertion must fail the fixture, not masquerade as that refusal evidence. + for (const namespace of Object.values(github.rest)) { + for (const [name, method] of Object.entries(namespace)) namespace[name] = async (...args) => { + try { return await method(...args); } + catch (error) { + if (error.code === "ERR_ASSERTION") mockFailures.push(error.message); + throw error; + } + }; + } let failure = null; try { await reconcile(github, context, {warning: message => warnings.push(message), info: message => infos.push(message)}, @@ -831,6 +891,7 @@ async function runReconcile({ } catch (error) { failure = error; } + assert.deepEqual(mockFailures, [], "mock contract assertion failures never count as production refusals"); return {failure, now, requests, signals, inventoryRequests, nativeJobRunIds, nativeRefreshRunIds, dispatchRequests, postAttempts, warnings, infos}; } @@ -994,14 +1055,69 @@ async function runReconcile({ status: "completed", conclusion: "failure", started_at: "2026-01-06T00:00:01Z", completed_at: "2026-01-06T00:02:00Z", steps: [marker]}; for (const [job, expectedPosts] of [ [failedJob, 1], + [{...failedJob, steps: [{...marker, started_at: null, completed_at: null}]}, 1], + [{...failedJob, steps: [{name: marker.name, status: "completed", conclusion: "skipped"}]}, 1], [{...failedJob, steps: [{...marker, conclusion: "success"}]}, 0], + [{...failedJob, steps: [{...marker, conclusion: null}]}, 0], + [{...failedJob, steps: []}, 0], + [{...failedJob, steps: [marker, marker]}, 0], + [{...failedJob, steps: [{...marker, started_at: null}]}, 0], + [{...failedJob, completed_at: null}, 0], + [{...failedJob, started_at: "2026-02-30T00:00:00Z"}, 0], [{...failedJob, started_at: "2026-01-05T23:59:59Z"}, 0], + [{...failedJob, started_at: "2026-01-06T00:00:01+00:00", completed_at: "2026-01-06T05:32:00+05:30"}, 1], ]) { const result = await runReconcile({preflightRefreshRuns: [legacyFailedPlay], refreshAttemptJobs: {[legacyFailedPlay.id]: {total_count: 1, jobs: [job]}}}); assert.equal(result.failure, null); assert.equal(result.postAttempts, expectedPosts); } + const rerunAttempt = {...legacyFailedPlay, run_started_at: "2026-01-06T01:00:00Z", updated_at: "2026-01-06T01:03:00Z"}; + for (const attempt of [rerunAttempt, {...legacyFailedPlay, run_attempt: 2}, + {...legacyFailedPlay, repository: {full_name: "fork/FireMUD"}}, + {...legacyFailedPlay, head_repository: {full_name: "fork/FireMUD"}}, + {...legacyFailedPlay, path: `${legacyFailedPlay.path}@refs/heads/develop`}, + null, new Error("fixture exact attempt unavailable")]) { + const held = await runReconcile({preflightRefreshRuns: [legacyFailedPlay], + refreshNativeAttempts: {[legacyFailedPlay.id]: attempt}, + refreshAttemptJobs: {[legacyFailedPlay.id]: {total_count: 1, jobs: [failedJob]}}}); + assert.equal(held.failure, null); + assert.equal(held.postAttempts, 0, "only the exact attributable attempt's actual execution window can release a failed refresh hold"); + assert(held.warnings.some(message => /explicit investigation, not automatic replay/.test(message))); + } + const supersededFailure = await runReconcile({preflightRefreshRuns: [legacyFailedPlay], + refreshNativeRuns: {[legacyFailedPlay.id]: [legacyFailedPlay, {...legacyFailedPlay, run_attempt: 2}]}, + refreshAttemptJobs: {[legacyFailedPlay.id]: {total_count: 1, jobs: [failedJob]}}}); + assert.equal(supersededFailure.failure, null); + assert.equal(supersededFailure.postAttempts, 0, "latest-run confirmation after native jobs must reject a superseding attempt"); + assert.deepEqual(supersededFailure.nativeRefreshRunIds, [legacyFailedPlay.id, legacyFailedPlay.id]); + const validRerun = {...legacyFailedPlay, run_attempt: 2}; + const validRerunJob = {...failedJob, run_attempt: 2, started_at: "2026-01-06T01:00:01Z", completed_at: "2026-01-06T01:02:00Z", + steps: [{name: marker.name, status: "completed", conclusion: "skipped", started_at: null, completed_at: null}]}; + const rerunRecovery = await runReconcile({preflightRefreshRuns: [validRerun], + refreshNativeAttempts: {[validRerun.id]: {...rerunAttempt, run_attempt: 2}}, + refreshAttemptJobs: {[validRerun.id]: {total_count: 1, jobs: [validRerunJob]}}}); + assert.equal(rerunRecovery.failure, null); + assert.equal(rerunRecovery.postAttempts, 1, "a freshly executed exact rerun with an unexecuted marker permits recovery despite stale run-wide timestamps"); + const runtimePath = ".github/workflows/runtime-images.yml"; + const ciPath = ".github/workflows/ci.yml"; + for (const [bare, suffixed] of [[runtimePath, `${runtimePath}@refs/pull/42/merge`], + [`${runtimePath}@refs/pull/42/merge`, runtimePath]]) { + const equivalent = await runReconcile({sourceRun: {...source, path: bare}, sourceCallback: {...source, path: suffixed}}); + assert.equal(equivalent.failure, null); + assert.equal(equivalent.postAttempts, 1, "native runtime callback/API canonical PR merge paths are equivalent"); + } + for (const suffix of ["refs/pull/43/merge", "refs/pull/042/merge", "refs/pull/42/head", "refs/heads/develop"]) { + const runtimeDrift = await runReconcile({sourceCallback: {...source, path: `${runtimePath}@${suffix}`}}); + assert.equal(runtimeDrift.failure, null); + assert.equal(runtimeDrift.postAttempts, 0, "unrelated source suffixes cannot use the canonical equivalence"); + const ciDrift = await runReconcile({ciNativeRuns: {[ciRun.id]: {...ciRun, path: `${ciPath}@${suffix}`}}}); + assert.equal(ciDrift.failure, null); + assert.equal(ciDrift.postAttempts, 0, "unrelated CI suffixes cannot change between inventory and native proof"); + } + const equivalentCi = await runReconcile({ciNativeRuns: {[ciRun.id]: {...ciRun, path: `${ciPath}@refs/pull/42/merge`}}}); + assert.equal(equivalentCi.failure, null); + assert.equal(equivalentCi.postAttempts, 1, "exact native CI merge paths can differ from their bare inventory projection"); const legacyFailureHold = await runReconcile({preflightRefreshRuns: [typedRefresh, legacyFailedPlay]}); assert.equal(legacyFailureHold.failure, null); assert.equal(legacyFailureHold.postAttempts, 0, diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index 8b61472fbf..74e3689da4 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -1150,9 +1150,18 @@ discovery_session = CommandResponseSession( ] ) discovery_results = [] -# The fixture controls the responses. Avoid spending its one-second deadline -# on scheduler-dependent sleep while checking that the discovery poll retries. -with patch("smoke_common.time.sleep") as discovery_sleep: +positive_discovery_clock = [0.0] + + +def advance_positive_discovery_clock(duration): + positive_discovery_clock[0] += duration + + +# Both the deadline and polling delay are fixture-owned; a paused CI process +# cannot exhaust the budget between these scripted WORLDS responses. +with patch("smoke_common.time.time", side_effect=lambda: positive_discovery_clock[0]), patch( + "smoke_common.time.sleep", side_effect=advance_positive_discovery_clock +) as discovery_sleep: discovery_responses = run_telnet_smoke_session( "example.test", 2323, @@ -1168,7 +1177,8 @@ with patch("smoke_common.time.sleep") as discovery_sleep: tls_enabled=False, discovery_selector="demo", ) -discovery_sleep.assert_called() +discovery_sleep.assert_called_once_with(0.5) +assert positive_discovery_clock == [0.5] assert discovery_session.sent == [ "WORLDS\r\n", "WORLDS\r\n", @@ -1235,7 +1245,10 @@ for transient_error in ( transient_discovery_sessions.append(session) return session - with patch("smoke_common.time.sleep") as discovery_sleep: + positive_discovery_clock[0] = 0.0 + with patch("smoke_common.time.time", side_effect=lambda: positive_discovery_clock[0]), patch( + "smoke_common.time.sleep", side_effect=advance_positive_discovery_clock + ) as discovery_sleep: run_telnet_smoke_session( "example.test", 2323, @@ -1259,6 +1272,7 @@ for transient_error in ( "PLAY demo\r\n", ] discovery_sleep.assert_called_once_with(0.5) + assert positive_discovery_clock == [0.5] discovery_clock = [0.0] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index 0452f82147..d51aa8ad9c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -29,6 +29,7 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.TransactionTemplate; /** Real forward migration with retained tenant provenance. No existing usage is guessed. */ @@ -66,7 +67,9 @@ void duplicateHistoricalOriginAttemptsStopUpgradeWithoutRewritingEvidence() { UUID attempt = UUID.randomUUID(); for (int index = 0; index < 2; index++) { 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, ?, ?, ?, 'NO_ACCEPT', ?)", + "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, ?, ?, ?, 'NO_ACCEPT', ?)", UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), @@ -78,7 +81,10 @@ void duplicateHistoricalOriginAttemptsStopUpgradeWithoutRewritingEvidence() { capacityMigrations(data, schema).target("1040.3").load().migrate(); var original = dsl.fetch( - "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM account_capacity_origin_decisions ORDER BY decision_id") + "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence," + + " admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex')" + + " AS payload, decision, decision_id, refusal_code, xmin::text AS" + + " row_version FROM account_capacity_origin_decisions ORDER BY decision_id") .intoMaps(); assertThatThrownBy(() -> capacityMigrations(data, schema).target("1040.4").load().migrate()) .isInstanceOf(org.flywaydb.core.api.FlywayException.class) @@ -92,7 +98,11 @@ void duplicateHistoricalOriginAttemptsStopUpgradeWithoutRewritingEvidence() { }); assertThat( dsl.fetch( - "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM account_capacity_origin_decisions ORDER BY decision_id") + "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence," + + " admission_attempt_id, mutation_digest, encode(canonical_payload," + + " 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS" + + " row_version FROM account_capacity_origin_decisions ORDER BY" + + " decision_id") .intoMaps()) .isEqualTo(original); assertThat(original).hasSize(2); @@ -116,7 +126,9 @@ void budgetConflictDoesNotMaskRetainedHistoryAndFirstInstallStillChecksIt() { UUID retainedAttempt = UUID.randomUUID(); for (int index = 0; index < 3; index++) { 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, ?, ?, ?, 'NO_ACCEPT', ?)", + "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, ?, ?, ?, 'NO_ACCEPT', ?)", tenant.canonicalTenantId(), UUID.randomUUID(), UUID.randomUUID(), @@ -163,7 +175,8 @@ void budgetConflictDoesNotMaskRetainedHistoryAndFirstInstallStillChecksIt() { var original = Objects.requireNonNull( dsl.fetchOne( - "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget")) + "SELECT *, xmin::text AS row_version FROM" + + " account_capacity_origin_refusal_budget")) .intoMap(); transaction.executeWithoutResult(status -> budgets.provision(tenant.canonicalTenantId(), 4)); assertThatThrownBy(() -> @@ -179,12 +192,16 @@ void budgetConflictDoesNotMaskRetainedHistoryAndFirstInstallStillChecksIt() { assertThat( Objects.requireNonNull( dsl.fetchOne( - "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget")) + "SELECT *, xmin::text AS row_version FROM" + + " account_capacity_origin_refusal_budget")) .intoMap()) .isEqualTo(original); assertThatThrownBy(() -> 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, ?, ?, ?, 'NO_ACCEPT', ?)", + "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, ?, ?, ?, 'NO_ACCEPT', ?)", tenant.canonicalTenantId(), UUID.randomUUID(), UUID.randomUUID(), @@ -227,7 +244,9 @@ void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { assertThat( Objects.requireNonNull( dsl.fetchOne( - "SELECT capacity_birth_transaction FROM account_fresh_tenant_identity_associations WHERE canonical_tenant_id = ?", + "SELECT capacity_birth_transaction FROM" + + " account_fresh_tenant_identity_associations WHERE" + + " canonical_tenant_id = ?", existing.canonicalTenantId())) .get("capacity_birth_transaction")) .isNull(); @@ -250,7 +269,9 @@ void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { assertThat( Objects.requireNonNull( dsl.fetchOne( - "SELECT capacity_birth_transaction FROM account_fresh_tenant_identity_associations WHERE canonical_tenant_id = ?", + "SELECT capacity_birth_transaction FROM" + + " account_fresh_tenant_identity_associations WHERE" + + " canonical_tenant_id = ?", later.canonicalTenantId())) .get("capacity_birth_transaction")) .isNotNull(); @@ -267,14 +288,16 @@ void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { status -> budgets.provision(existing.canonicalTenantId(), 4)); var beforeBudget = dsl.fetchSingle( - "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget WHERE tenant_uuid=?", + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget" + + " WHERE tenant_uuid=?", existing.canonicalTenantId()) .intoMap(); transaction.executeWithoutResult( status -> budgets.provision(existing.canonicalTenantId(), 4)); assertThat( dsl.fetchSingle( - "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget WHERE tenant_uuid=?", + "SELECT *, xmin::text AS row_version FROM" + + " account_capacity_origin_refusal_budget WHERE tenant_uuid=?", existing.canonicalTenantId()) .intoMap()) .isEqualTo(beforeBudget); @@ -351,7 +374,8 @@ void refusalBudgetRunsAfterIdentityArbitrationAndCountsTheInsertedLastSlot() thr assertThat(dsl.execute(insert, retry)).isZero(); assertThat( dsl.fetchSingle( - "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget") + "SELECT *, xmin::text AS row_version FROM" + + " account_capacity_origin_refusal_budget") .intoMap()) .isEqualTo(retainedBudget); assertThatThrownBy(() -> @@ -416,14 +440,9 @@ void refusalBudgetRunsAfterIdentityArbitrationAndCountsTheInsertedLastSlot() thr UUID losingAdmission = UUID.randomUUID(); UUID losingAttempt = UUID.randomUUID(); UUID losingDecision = UUID.randomUUID(); - UUID freshRequest = UUID.randomUUID(); - UUID freshAdmission = UUID.randomUUID(); - UUID freshAttempt = UUID.randomUUID(); - UUID freshDecision = UUID.randomUUID(); - assertThat(List.of(winningRequest, losingRequest, freshRequest)).doesNotHaveDuplicates(); - assertThat(List.of(winningAdmission, losingAdmission, freshAdmission)) - .doesNotHaveDuplicates(); - assertThat(List.of(winningAttempt, losingAttempt, freshAttempt)).doesNotHaveDuplicates(); + assertThat(losingRequest).isNotEqualTo(winningRequest); + assertThat(losingAdmission).isNotEqualTo(winningAdmission); + assertThat(losingAttempt).isNotEqualTo(winningAttempt); String concurrentRefusalInsert = "INSERT INTO account_capacity_origin_decisions " + "(tenant_uuid, request_id, admission_id, capacity_rearm_fence, " @@ -485,16 +504,20 @@ void refusalBudgetRunsAfterIdentityArbitrationAndCountsTheInsertedLastSlot() thr .containsEntry("decision", "NO_ACCEPT") .containsEntry("decision_id", winningDecision) .containsEntry("refusal_code", "CAPACITY_QUOTA_EXCEEDED"); + // Retry the exact rolled-back loser in a fresh transaction/snapshot, not a new original. + var retryTransaction = new TransactionTemplate(new DataSourceTransactionManager(data)); + retryTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); assertThatThrownBy(() -> - dsl.execute( - concurrentRefusalInsert, - concurrentTenant.canonicalTenantId(), - freshRequest, - freshAdmission, - freshAttempt, - "e".repeat(64), - new byte[] {5}, - freshDecision)) + retryTransaction.executeWithoutResult(status -> + dsl.execute( + concurrentRefusalInsert, + concurrentTenant.canonicalTenantId(), + losingRequest, + losingAdmission, + losingAttempt, + "d".repeat(64), + new byte[] {4}, + losingDecision))) .isInstanceOfSatisfying( org.jooq.exception.DataAccessException.class, failure -> { @@ -557,7 +580,9 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { UUID secondHistoricalDecision = UUID.fromString("00000000-0000-0000-0000-000000001042"); UUID otherHistoricalDecision = UUID.fromString("00000000-0000-0000-0000-000000001043"); String historicalInsert = - "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, ?, ?, ?, 'NO_ACCEPT', ?)"; + "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, ?, ?, ?, 'NO_ACCEPT', ?)"; dsl.execute( historicalInsert, historicalTenant.canonicalTenantId(), @@ -616,7 +641,10 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { Instant reconcileDeadline = reservationExpiresAt.plusSeconds(60); transaction.executeWithoutResult(status -> { 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 (?, ?, ?, ?, 'game-session-service', ?, ?::timestamptz, ?::timestamptz)", + "INSERT INTO account_tenant_capacity_evaluations (evaluation_identity," + + " snapshot_identity, tenant_uuid, caller_workload, owner_service," + + " canonical_evidence, evaluated_at, expires_at) VALUES (?, ?, ?, ?," + + " 'game-session-service', ?, ?::timestamptz, ?::timestamptz)", evaluationIdentity, snapshotIdentity, acceptedTenant.canonicalTenantId(), @@ -626,11 +654,15 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { AccountTenantCapacityRepository.at(evaluationExpiresAt)); assertThat( dsl.execute( - "UPDATE account_tenant_capacity_usage SET held_units = 1, usage_revision = 2 WHERE tenant_uuid = ? AND owner_service = 'game-session-service' AND held_units = 0 AND used_units = 0 AND usage_revision = 1", + "UPDATE account_tenant_capacity_usage SET held_units = 1, usage_revision = 2" + + " WHERE tenant_uuid = ? AND owner_service = 'game-session-service' AND" + + " held_units = 0 AND used_units = 0 AND usage_revision = 1", acceptedTenant.canonicalTenantId())) .isEqualTo(1); 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', ?)", + "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', ?)", acceptedTenant.canonicalTenantId(), acceptedRequest, acceptedAdmission, @@ -639,7 +671,13 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { acceptedPayload, acceptedDecision); 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, reconcile_deadline, state, execution_status) VALUES (?, ?, ?, ?, 'game-session-service', ?, ?, 1, 1, ?, ?, ?, 1, ?::timestamptz, ?::timestamptz, 'RESERVED', 'OWNER_EXECUTION_PENDING')", + "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," + + " reconcile_deadline, state, execution_status) VALUES (?, ?, ?, ?," + + " 'game-session-service', ?, ?, 1, 1, ?, ?, ?, 1, ?::timestamptz, ?::timestamptz," + + " 'RESERVED', 'OWNER_EXECUTION_PENDING')", acceptedTenant.canonicalTenantId(), acceptedRequest, acceptedAdmission, @@ -660,17 +698,22 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { }); var provisionedBudgetAtV1040_5 = dsl.fetchSingle( - "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget" + + " WHERE tenant_uuid = ?", historicalTenant.canonicalTenantId()) .intoMap(); var otherProvisionedBudgetAtV1040_5 = dsl.fetchSingle( - "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", + "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget" + + " WHERE tenant_uuid = ?", otherHistoricalTenant.canonicalTenantId()) .intoMap(); var originalDecisions = dsl.fetch( - "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM account_capacity_origin_decisions ORDER BY decision_id") + "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence," + + " admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex')" + + " AS payload, decision, decision_id, refusal_code, xmin::text AS" + + " row_version FROM account_capacity_origin_decisions ORDER BY decision_id") .intoMaps(); assertThat(originalDecisions).hasSize(4); var acceptedReservationsAtV1040_5 = reservationRows(dsl, acceptedTenant.canonicalTenantId()); @@ -684,13 +727,15 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { .isEqualTo(acceptedUsageAtV1040_5); assertThat( dsl.fetchSingle( - "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", + "SELECT *, xmin::text AS row_version FROM" + + " account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", historicalTenant.canonicalTenantId()) .intoMap()) .isEqualTo(provisionedBudgetAtV1040_5); assertThat( dsl.fetchSingle( - "SELECT *, xmin::text AS row_version FROM account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", + "SELECT *, xmin::text AS row_version FROM" + + " account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", otherHistoricalTenant.canonicalTenantId()) .intoMap()) .isEqualTo(otherProvisionedBudgetAtV1040_5); @@ -704,7 +749,11 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { assertThat(otherRemainingHeadroom).isEqualTo(2L); assertThat( dsl.fetch( - "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM account_capacity_origin_decisions ORDER BY decision_id") + "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence," + + " admission_attempt_id, mutation_digest, encode(canonical_payload," + + " 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS" + + " row_version FROM account_capacity_origin_decisions ORDER BY" + + " decision_id") .intoMaps()) .isEqualTo(originalDecisions); assertThat(refusalSlots(dsl)) @@ -732,7 +781,8 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { otherHistoricalTenant.canonicalTenantId(), 1, otherHistoricalDecision)); assertThatThrownBy(() -> dsl.execute( - "INSERT INTO account_capacity_origin_refusal_slots (tenant_uuid, slot, decision_id) VALUES (?, 3, ?)", + "INSERT INTO account_capacity_origin_refusal_slots (tenant_uuid, slot," + + " decision_id) VALUES (?, 3, ?)", acceptedTenant.canonicalTenantId(), acceptedDecision)) .isInstanceOfSatisfying( @@ -740,7 +790,8 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { failure -> assertThat(failure.sqlState()).isEqualTo("23514")); assertThatThrownBy(() -> dsl.execute( - "INSERT INTO account_capacity_origin_refusal_slots (tenant_uuid, slot, decision_id) VALUES (?, 3, ?)", + "INSERT INTO account_capacity_origin_refusal_slots (tenant_uuid, slot," + + " decision_id) VALUES (?, 3, ?)", acceptedTenant.canonicalTenantId(), firstHistoricalDecision)) .isInstanceOfSatisfying( @@ -749,7 +800,10 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { assertThat(refusalSlots(dsl)).containsExactlyInAnyOrderElementsOf(expectedSlots); String insertedDecision = - "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, refusal_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING"; + "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, refusal_code) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON" + + " CONFLICT DO NOTHING"; assertThat( dsl.fetchOne( "SELECT 1 FROM account_capacity_origin_refusal_budget WHERE tenant_uuid = ?", @@ -823,14 +877,16 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { }); assertThat( dsl.fetchOne( - "SELECT 1 FROM account_capacity_origin_decisions WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + "SELECT 1 FROM account_capacity_origin_decisions WHERE tenant_uuid = ? AND" + + " request_id = ? AND admission_id = ?", acceptedTenant.canonicalTenantId(), rolledBackAccepted.requestId(), rolledBackAccepted.admissionId())) .isNull(); assertThat( dsl.fetchOne( - "SELECT 1 FROM account_tenant_capacity_reservations WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ?", + "SELECT 1 FROM account_tenant_capacity_reservations WHERE tenant_uuid = ? AND" + + " request_id = ? AND admission_id = ?", acceptedTenant.canonicalTenantId(), rolledBackAccepted.requestId(), rolledBackAccepted.admissionId())) @@ -967,7 +1023,8 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { assertThatThrownBy(() -> dsl.execute( - "UPDATE account_capacity_origin_refusal_slots SET slot = slot + 10 WHERE tenant_uuid = ? AND slot = 1", + "UPDATE account_capacity_origin_refusal_slots SET slot = slot + 10 WHERE" + + " tenant_uuid = ? AND slot = 1", historicalTenant.canonicalTenantId())) .isInstanceOfSatisfying( org.jooq.exception.DataAccessException.class, @@ -976,7 +1033,8 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { .hasMessageContaining("Account capacity origin decisions are immutable")); assertThatThrownBy(() -> dsl.execute( - "DELETE FROM account_capacity_origin_refusal_slots WHERE tenant_uuid = ? AND slot = 1", + "DELETE FROM account_capacity_origin_refusal_slots WHERE tenant_uuid = ? AND slot" + + " = 1", historicalTenant.canonicalTenantId())) .isInstanceOfSatisfying( org.jooq.exception.DataAccessException.class, @@ -997,7 +1055,8 @@ void refusalSlotsBackfillRetainedDecisionsAndOnlyFreshRefusalsSpendSlots() { private static List refusalSlots(org.jooq.DSLContext dsl) { return dsl.fetch( - "SELECT tenant_uuid, slot, decision_id FROM account_capacity_origin_refusal_slots ORDER BY tenant_uuid, slot") + "SELECT tenant_uuid, slot, decision_id FROM account_capacity_origin_refusal_slots ORDER" + + " BY tenant_uuid, slot") .map(row -> new RefusalSlot( row.get("tenant_uuid", UUID.class), @@ -1035,7 +1094,10 @@ private static void insertAcceptedCapacityAttempt( assertThat(attempt.reservationExpiresAt()).isBefore(attempt.evaluationExpiresAt()); String callerWorkload = "controlled-capacity-fixture"; 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 (?, ?, ?, ?, 'game-session-service', ?, ?::timestamptz, ?::timestamptz)", + "INSERT INTO account_tenant_capacity_evaluations (evaluation_identity, snapshot_identity," + + " tenant_uuid, caller_workload, owner_service, canonical_evidence, evaluated_at," + + " expires_at) VALUES (?, ?, ?, ?, 'game-session-service', ?, ?::timestamptz," + + " ?::timestamptz)", attempt.evaluationIdentity(), attempt.snapshotIdentity(), tenantUuid, @@ -1045,7 +1107,9 @@ private static void insertAcceptedCapacityAttempt( AccountTenantCapacityRepository.at(attempt.evaluationExpiresAt())); assertThat( dsl.execute( - "UPDATE account_tenant_capacity_usage SET held_units = ?, usage_revision = ? WHERE tenant_uuid = ? AND owner_service = 'game-session-service' AND held_units = ? AND used_units = 0 AND usage_revision = ?", + "UPDATE account_tenant_capacity_usage SET held_units = ?, usage_revision = ? WHERE" + + " tenant_uuid = ? AND owner_service = 'game-session-service' AND held_units =" + + " ? AND used_units = 0 AND usage_revision = ?", newHeldUnits, newHeldUnits + 1, tenantUuid, @@ -1054,7 +1118,10 @@ private static void insertAcceptedCapacityAttempt( .isEqualTo(1); assertThat( 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, refusal_code) VALUES (?, ?, ?, 1, ?, ?, ?, 'ACCEPTED', ?, NULL)", + "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, refusal_code) VALUES (?, ?, ?, 1," + + " ?, ?, ?, 'ACCEPTED', ?, NULL)", tenantUuid, attempt.requestId(), attempt.admissionId(), @@ -1065,7 +1132,13 @@ private static void insertAcceptedCapacityAttempt( .isEqualTo(1); assertThat( 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, reconcile_deadline, state, execution_status) VALUES (?, ?, ?, ?, 'game-session-service', ?, ?, 1, 1, ?, ?, ?, 1, ?::timestamptz, ?::timestamptz, 'RESERVED', 'OWNER_EXECUTION_PENDING')", + "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, reconcile_deadline, state, execution_status) VALUES (?, ?, ?," + + " ?, 'game-session-service', ?, ?, 1, 1, ?, ?, ?, 1, ?::timestamptz," + + " ?::timestamptz, 'RESERVED', 'OWNER_EXECUTION_PENDING')", tenantUuid, attempt.requestId(), attempt.admissionId(), @@ -1083,7 +1156,10 @@ private static void insertAcceptedCapacityAttempt( private static List> originRows( org.jooq.DSLContext dsl, UUID tenantUuid) { return dsl.fetch( - "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence, admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM account_capacity_origin_decisions WHERE tenant_uuid = ? ORDER BY decision_id", + "SELECT tenant_uuid, request_id, admission_id, capacity_rearm_fence," + + " admission_attempt_id, mutation_digest, encode(canonical_payload, 'hex') AS" + + " payload, decision, decision_id, refusal_code, xmin::text AS row_version FROM" + + " account_capacity_origin_decisions WHERE tenant_uuid = ? ORDER BY decision_id", tenantUuid) .intoMaps(); } @@ -1091,7 +1167,16 @@ private static List> originRows( private static List> reservationRows( org.jooq.DSLContext dsl, UUID tenantUuid) { return dsl.fetch( - "SELECT tenant_uuid, request_id, admission_id, reservation_id, owner_service, caller_workload, admission_attempt_id, capacity_rearm_fence, reservation_fence, mutation_digest, encode(canonical_payload, 'hex') AS payload, evaluation_identity, capacity_delta, expires_at, reconcile_deadline, state, execution_status, recovery_owner, recovery_claim_fence, recovery_claim_expires_at, next_reconcile_at, recovery_policy_version, recovery_attempt_count, recovery_escalated_at, encode(owner_readback, 'hex') AS owner_readback, owner_readback_digest, xmin::text AS row_version FROM account_tenant_capacity_reservations WHERE tenant_uuid = ? ORDER BY request_id, admission_id", + "SELECT tenant_uuid, request_id, admission_id, reservation_id, owner_service," + + " caller_workload, admission_attempt_id, capacity_rearm_fence, reservation_fence," + + " mutation_digest, encode(canonical_payload, 'hex') AS payload," + + " evaluation_identity, capacity_delta, expires_at, reconcile_deadline, state," + + " execution_status, recovery_owner, recovery_claim_fence," + + " recovery_claim_expires_at, next_reconcile_at, recovery_policy_version," + + " recovery_attempt_count, recovery_escalated_at, encode(owner_readback, 'hex') AS" + + " owner_readback, owner_readback_digest, xmin::text AS row_version FROM" + + " account_tenant_capacity_reservations WHERE tenant_uuid = ? ORDER BY request_id," + + " admission_id", tenantUuid) .intoMaps(); } @@ -1099,7 +1184,9 @@ private static List> reservationRows( private static List> usageRows( org.jooq.DSLContext dsl, UUID tenantUuid) { return dsl.fetch( - "SELECT tenant_uuid, owner_service, bootstrap_request_id, creation_evidence_digest, held_units, used_units, usage_revision, xmin::text AS row_version FROM account_tenant_capacity_usage WHERE tenant_uuid = ? ORDER BY owner_service", + "SELECT tenant_uuid, owner_service, bootstrap_request_id, creation_evidence_digest," + + " held_units, used_units, usage_revision, xmin::text AS row_version FROM" + + " account_tenant_capacity_usage WHERE tenant_uuid = ? ORDER BY owner_service", tenantUuid) .intoMaps(); } @@ -1108,7 +1195,15 @@ private static void assertTenantCapacityInventoryMatches( org.jooq.DSLContext dsl, UUID tenantUuid) { var rows = dsl.fetch( - "SELECT u.owner_service, u.held_units, u.used_units, COALESCE(sum(r.capacity_delta) FILTER (WHERE r.state IN ('RESERVED', 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION')), 0) AS reservation_held_units, COALESCE(sum(r.capacity_delta) FILTER (WHERE r.state = 'FINALIZED'), 0) AS reservation_used_units FROM account_tenant_capacity_usage u LEFT JOIN account_tenant_capacity_reservations r ON r.tenant_uuid = u.tenant_uuid AND r.owner_service = u.owner_service WHERE u.tenant_uuid = ? GROUP BY u.owner_service, u.held_units, u.used_units ORDER BY u.owner_service", + "SELECT u.owner_service, u.held_units, u.used_units, COALESCE(sum(r.capacity_delta)" + + " FILTER (WHERE r.state IN ('RESERVED'," + + " 'QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION')), 0) AS" + + " reservation_held_units, COALESCE(sum(r.capacity_delta) FILTER (WHERE" + + " r.state = 'FINALIZED'), 0) AS reservation_used_units FROM" + + " account_tenant_capacity_usage u LEFT JOIN" + + " account_tenant_capacity_reservations r ON r.tenant_uuid = u.tenant_uuid AND" + + " r.owner_service = u.owner_service WHERE u.tenant_uuid = ? GROUP BY" + + " u.owner_service, u.held_units, u.used_units ORDER BY u.owner_service", tenantUuid) .intoMaps(); assertThat(rows).hasSize(2); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index 212d448414..4d1d87e605 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -18,6 +18,7 @@ import java.sql.SQLException; import java.time.Clock; import java.time.Instant; +import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.temporal.ChronoUnit; @@ -340,7 +341,8 @@ void actualFirstJoinRetainsItsPositiveMembershipAndExactScopeBinding() { assertThat(value.membershipSource().gameplayAdmissionAllowed()).isTrue(); var retained = f.dsl.fetchOne( - "SELECT canonical_evidence, snapshot_identity FROM account_tenant_capacity_evaluations WHERE evaluation_identity = ?", + "SELECT canonical_evidence, snapshot_identity FROM account_tenant_capacity_evaluations" + + " WHERE evaluation_identity = ?", value.fields().get("evaluationIdentity")); assertThat(retained).isNotNull(); byte[] retainedEvidence = retained.get("canonical_evidence", byte[].class); @@ -416,6 +418,11 @@ void exactCapacityRefusalReplaysAfterHeadroomReturnsAndEvaluationExpires() { + " WHERE tenant_uuid=? AND request_id=? AND admission_id=?"; assertThat(f.dsl.fetchSingle(countDeniedReservations, identity).get("n", Long.class)).isZero(); + // Recovery claims are checked against live PostgreSQL time, not the frozen evaluation clock. + Clock recoveryClock = mock(Clock.class); + when(recoveryClock.instant()) + .thenAnswer(invocation -> + f.dsl.fetchSingle("SELECT clock_timestamp()").get(0, OffsetDateTime.class).toInstant()); // The external no-execution observation is controlled; all Account storage mutations are real. var recovery = new AccountTenantCapacityRecoveryWorker( @@ -433,7 +440,7 @@ void exactCapacityRefusalReplaysAfterHeadroomReturnsAndEvaluationExpires() { 7, "sha256:" + "e".repeat(64), "controlled-owner-no-execution".getBytes(StandardCharsets.US_ASCII)), - f.clock); + recoveryClock); assertThat( recovery .reconcile( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java index f99010e974..ba72bdda61 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java @@ -3,6 +3,7 @@ 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.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -88,16 +89,63 @@ static void createTestPki() throws Exception { @AfterEach void stopTransportAndClearAuthContext() throws Exception { - if (noCertificateChannel != null) { - assertThat(noCertificateChannel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue(); - noCertificateChannel = null; - } - if (server != null) { - server.shutdownNow(); - assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); - server = null; + try { + if (noCertificateChannel != null) { + try { + assertThat(noCertificateChannel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)) + .isTrue(); + } finally { + noCertificateChannel = null; + } + } + } finally { + try { + if (server != null) { + try { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } finally { + server = null; + } + } + } finally { + SessionContext.clear(); + } } - SessionContext.clear(); + } + + @Test + void channelTerminationFailureStillStopsServerAndClearsAuthContext() throws Exception { + var channel = mock(ManagedChannel.class); + var receiver = mock(Server.class); + when(channel.shutdownNow()).thenReturn(channel); + when(channel.awaitTermination(2, TimeUnit.SECONDS)).thenReturn(false); + when(receiver.awaitTermination(2, TimeUnit.SECONDS)).thenReturn(true); + noCertificateChannel = channel; + server = receiver; + SessionContext.setContext("42", List.of("tenantAdmin"), java.util.Map.of()); + + assertThatThrownBy(this::stopTransportAndClearAuthContext).isInstanceOf(AssertionError.class); + + verify(receiver).shutdownNow(); + verify(receiver).awaitTermination(2, TimeUnit.SECONDS); + assertThat(noCertificateChannel).isNull(); + assertThat(server).isNull(); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + } + + @Test + void serverTerminationFailureStillClearsAuthContext() throws Exception { + var receiver = mock(Server.class); + when(receiver.awaitTermination(2, TimeUnit.SECONDS)).thenReturn(false); + server = receiver; + SessionContext.setContext("42", List.of("tenantAdmin"), java.util.Map.of()); + + assertThatThrownBy(this::stopTransportAndClearAuthContext).isInstanceOf(AssertionError.class); + + verify(receiver).shutdownNow(); + assertThat(server).isNull(); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); } @Test From 79138d314b48b1826a8ce4ae3c52a20c49b23628 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:01:50 +1300 Subject: [PATCH 44/96] Require verified retained Account history before V1040.4 activation --- .github/workflows/dev-demo.yml | 22 +- ...system-architecture-database-migrations.md | 2 +- .../detect-hosted-v2-migration-activation.sh | 37 ++- dev-tools/deploy/probe-dev-account-v1040-4.sh | 146 ++++++++++ .../deploy/quiesce-v2-schema-migrations.sh | 136 +++++---- .../deploy/run-dev-account-v1040-4-probe.sh | 153 ++++++++++ .../dev-account-v1040-4-probe-contract.sh | 261 ++++++++++++++++++ dev-tools/tests/dev-demo-workflow-contract.sh | 28 +- ...hosted-v2-migration-activation-contract.sh | 24 +- 9 files changed, 745 insertions(+), 64 deletions(-) create mode 100644 dev-tools/deploy/probe-dev-account-v1040-4.sh create mode 100644 dev-tools/deploy/run-dev-account-v1040-4-probe.sh create mode 100644 dev-tools/tests/dev-account-v1040-4-probe-contract.sh diff --git a/.github/workflows/dev-demo.yml b/.github/workflows/dev-demo.yml index e2e6fb808b..160b45187f 100644 --- a/.github/workflows/dev-demo.yml +++ b/.github/workflows/dev-demo.yml @@ -416,8 +416,24 @@ jobs: RUNTIME_NAMESPACE: ${{ needs.dev-demo-plan.outputs.namespace }} run: bash ./dev-tools/deploy/quiesce-v2-schema-migrations.sh "$RUNTIME_NAMESPACE" + - name: Verify Account V1040.4 retained history before Helm + id: account-v1040-4-preflight + if: ${{ steps.quiesce-writers.outcome == 'success' && steps.v2-migration-mode.outputs.account_origin_probe == 'true' }} + env: + KUBECONFIG: ${{ runner.temp }}/dev-demo-runtime.kubeconfig + DEV_NAMESPACE_MANAGER_KUBECONFIG: ${{ runner.temp }}/dev-demo-namespace-manager.kubeconfig + RUNTIME_NAMESPACE: ${{ needs.dev-demo-plan.outputs.namespace }} + HEAD_SHA: ${{ needs.dev-demo-plan.outputs.head_sha }} + DEPLOYED_SHA: ${{ steps.v2-migration-mode.outputs.account_origin_base_sha }} + NAMESPACE_UID: ${{ steps.v2-migration-mode.outputs.account_origin_namespace_uid }} + ORIGIN_PREFIX: ${{ steps.v2-migration-mode.outputs.account_origin_prefix }} + run: | + echo "DEV_DEMO_STAGE=account-v1040-4-preflight" >> "$GITHUB_ENV" + bash ./dev-tools/deploy/run-dev-account-v1040-4-probe.sh \ + "$RUNTIME_NAMESPACE" "$NAMESPACE_UID" "$DEPLOYED_SHA" "$HEAD_SHA" "$ORIGIN_PREFIX" + - name: Deploy dev-demo release - if: ${{ steps.cluster-access.outputs.available == 'true' }} + if: ${{ steps.cluster-access.outputs.available == 'true' && steps.v2-migration-mode.outcome == 'success' && (steps.v2-migration-mode.outputs.activation != 'true' || steps.quiesce-writers.outcome == 'success') && (steps.v2-migration-mode.outputs.account_origin_probe != 'true' || steps.account-v1040-4-preflight.outcome == 'success') }} id: deploy-release continue-on-error: true env: @@ -975,8 +991,8 @@ jobs: "${{ needs.dev-demo-plan.outputs.telnet_port }}" \ "${DEV_DEMO_STAGE:-unknown}" >> "$GITHUB_STEP_SUMMARY" - - name: Warn about migration writer recovery after quiesce or deploy failure - if: ${{ always() && steps.v2-migration-mode.outputs.activation == 'true' && (steps.quiesce-writers.outcome == 'failure' || steps.deploy-release.outcome == 'failure') }} + - name: Warn about migration writer recovery after quiesce, preflight or deploy failure + if: ${{ always() && steps.v2-migration-mode.outputs.activation == 'true' && (steps.quiesce-writers.outcome == 'failure' || steps.account-v1040-4-preflight.outcome == 'failure' || steps.deploy-release.outcome == 'failure') }} run: | { echo "" diff --git a/design/architecture/system-architecture-database-migrations.md b/design/architecture/system-architecture-database-migrations.md index 482d03ad47..e46556fec7 100644 --- a/design/architecture/system-architecture-database-migrations.md +++ b/design/architecture/system-architecture-database-migrations.md @@ -244,7 +244,7 @@ ORDER BY conrelid::regclass::text, conname; This catalog query identifies enforced references, not all domain-level reachability; the owner must also check release bundles, launch descriptors, remap sets, publish attempts, and asset workflows for the exact candidate IDs. If the draft cannot be proved disposable, the migration remains blocked for owner adjudication. After correction or approved draft removal, rerun both queries and require zero rows before retrying the same release. Never broaden the migration to rewrite or delete retained rows to make V27 pass. -The trusted dev-demo workflow preserves its existing clean namespace reset for ordinary pushes. A push that first adds the Game Session or Automation V2 Flyway migration, Account V25 profile-identity migration, or one of the explicitly listed Account V1040.1–V1040.6 capacity-origin migrations, in the trusted deployed-to-target range instead preserves the runtime database and uses the quiesced activation path. That path first proves the reserved nonmatching selector does not match a Pod, replaces each canonical Account, Game Session, and Automation Service selector, verifies each readback, and waits until all matching EndpointSlices contain no endpoints. It then scales all three writers to zero and proves their Deployments and writer Pods are quiescent before restoring the canonical Service selectors. If selector mutation, endpoint observation, scaling, or drain proof fails, the helper aborts before migration activation and attempts to leave the canonical Services closed. If closure cannot be verified or reapplied, an operator must verify and repair admission before retrying. Account writer quiescence also protects V25 profile uniqueness and the capacity-origin uniqueness, refusal guards and slot backfill. Edits or deletions of an existing supported migration fail before namespace mutation because retained-database and Flyway checksum state are uncertain. Other Flyway migrations in the exact deployed-to-target Git range fail detection before namespace mutation until explicit trusted support exists; non-migration pushes retain the clean reset. Both pushes and redispatches use only the exact deployed-head annotation from the owned `dev` namespace as the classification base and require valid Git ancestry to the target. A supplied push before-SHA can add an ancestry check but never replaces that deployed-head base. Missing or ambiguous namespace evidence stops the workflow before namespace mutation. If a retained database already contains Account V1040.1–V1040.3 origin decisions, the Account owner must verify that each retained admission-attempt UUID occurs once before activating V1040.4. Quiescence stops new writes, while the uniqueness migration rejects existing duplicates and preserves their evidence. Duplicate data requires an Account-owned forward disposition before retry. If the namespace already records the target SHA, classification stops before namespace mutation. A failed rollout or smoke check after the Helm release was recorded requires inspecting the existing release and migration state. Re-running that target must not convert the retained activation into an ordinary namespace reset. This narrow exception avoids using namespace deletion as a substitute for proving the retained V1 data prerequisites. +The trusted dev-demo workflow preserves its existing clean namespace reset for ordinary pushes. A push that first adds the Game Session or Automation V2 Flyway migration, Account V25 profile-identity migration, or one of the explicitly listed Account V1040.1–V1040.6 capacity-origin migrations, in the trusted deployed-to-target range instead preserves the runtime database and uses the quiesced activation path. That path first proves the reserved nonmatching selector does not match a Pod, replaces each canonical Account, Game Session, and Automation Service selector, verifies each readback, and waits until all matching EndpointSlices contain no endpoints. It then scales all three writers to zero and proves their Deployments and writer Pods are quiescent before restoring the canonical Service selectors. If selector mutation, endpoint observation, scaling, or drain proof fails, the helper aborts before migration activation and attempts to leave the canonical Services closed. If closure cannot be verified or reapplied, an operator must verify and repair admission before retrying. Account writer quiescence also protects V25 profile uniqueness and the capacity-origin uniqueness, refusal guards and slot backfill. Edits or deletions of an existing supported migration fail before namespace mutation because retained-database and Flyway checksum state are uncertain. Other Flyway migrations in the exact deployed-to-target Git range fail detection before namespace mutation until explicit trusted support exists; non-migration pushes retain the clean reset. Both pushes and redispatches use only the exact deployed-head annotation from the owned `dev` namespace as the classification base and require valid Git ancestry to the target. A supplied push before-SHA can add an ancestry check but never replaces that deployed-head base. Missing or ambiguous namespace evidence stops the workflow before namespace mutation. When the exact Git range first adds Account V1040.4, the workflow requires the [read-only Account preflight](../../dev-tools/deploy/run-dev-account-v1040-4-probe.sh) between writer quiescence and Helm. The probe checks the deployed V1040–V1040.3 Flyway prefix and checksums. It checks for duplicate admission-attempt UUIDs when the retained origin table exists. The protected runtime identity runs a bounded PostgreSQL client Job and removes its exact UID. The caller rechecks the namespace UID, deployed revision and writer quiescence before Helm. Missing or mismatched evidence stops the rollout. Duplicate data requires an Account-owned forward disposition before retry. If the namespace already records the target SHA, classification stops before namespace mutation. A failed rollout or smoke check after the Helm release was recorded requires inspecting the existing release and migration state. Re-running that target must not convert the retained activation into an ordinary namespace reset. This narrow exception avoids using namespace deletion as a substitute for proving the retained V1 data prerequisites. Hosted candidate previews may activate a migration only when the trusted path independently proves both an isolated fresh database and absence of old writers. A newly recreated namespace or a manifest value is not database provenance when backing storage may be retained. If the preview credential cannot verify that proof, skip or fail the candidate activation before modifying its namespace; use the trusted post-merge quiesce path instead. diff --git a/dev-tools/deploy/detect-hosted-v2-migration-activation.sh b/dev-tools/deploy/detect-hosted-v2-migration-activation.sh index 8669939748..b96b0de2c3 100644 --- a/dev-tools/deploy/detect-hosted-v2-migration-activation.sh +++ b/dev-tools/deploy/detect-hosted-v2-migration-activation.sh @@ -85,7 +85,9 @@ game_session_v2="services/game-session-service/src/main/resources/db/migration/V automation_v2="services/automation-scripting-service/src/main/resources/db/migration/V2__script_patch_readiness_single_active.sql" account_v25="services/account-service/src/main/resources/db/migration/V25__scope_profile_identity.sql" account_migrations="services/account-service/src/main/resources/db/migration" +account_uniqueness_migration="$account_migrations/V1040.4__unique_capacity_origin_attempt.sql" migration_changed=false +probe_account_origin=false while IFS= read -r changed_path; do [[ -z "$changed_path" ]] && continue if [[ "$changed_path" =~ ^services/[^/]+/src/main/(java/db/migration/.+\.java|kotlin/db/migration/.+\.kt)$ ]]; then @@ -98,7 +100,7 @@ while IFS= read -r changed_path; do "$account_migrations/V1040.1__account_capacity_origin_decisions.sql"|\ "$account_migrations/V1040.2__bound_capacity_origin_refusals.sql"|\ "$account_migrations/V1040.3__validate_only_inserted_refusal_budgets.sql"|\ - "$account_migrations/V1040.4__unique_capacity_origin_attempt.sql"|\ + "$account_uniqueness_migration"|\ "$account_migrations/V1040.5__arbitrate_origin_identity_before_refusal_budget.sql"|\ "$account_migrations/V1040.6__index_retained_capacity_refusal_slots.sql") # A retained-database activation is safe only for the first addition of a supported @@ -110,6 +112,9 @@ while IFS= read -r changed_path; do exit 1 fi migration_changed=true + if [[ "$changed_path" == "$account_uniqueness_migration" ]]; then + probe_account_origin=true + fi ;; *) echo "refusing hosted deployment: unsupported Flyway migration path in exact range: $changed_path" >&2 @@ -119,6 +124,36 @@ while IFS= read -r changed_path; do fi done <<<"$changed_paths" +if [[ "$probe_account_origin" == true ]]; then + if ! namespace_uid="$(jq -er '.metadata.uid | select(type == "string")' <<<"$namespace_json")" || + [[ ! "$namespace_uid" =~ ^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$ ]]; then + echo "refusing Account V1040.4 activation: the trusted dev namespace UID is missing or invalid" >&2 + exit 1 + fi + if ! git cat-file -e "$base_sha:$account_migrations/V1040__account_tenant_capacity_owner.sql"; then + echo "refusing Account V1040.4 activation: the deployed Git source lacks the V1040 baseline" >&2 + exit 1 + fi + origin_prefix=0 + absent_origin_migration=false + for origin_file in \ + V1040.1__account_capacity_origin_decisions.sql \ + V1040.2__bound_capacity_origin_refusals.sql \ + V1040.3__validate_only_inserted_refusal_budgets.sql; do + if git cat-file -e "$base_sha:$account_migrations/$origin_file" 2>/dev/null; then + if [[ "$absent_origin_migration" == true ]]; then + echo "refusing Account V1040.4 activation: the deployed Git source has a non-contiguous origin migration prefix" >&2 + exit 1 + fi + origin_prefix=$((origin_prefix + 1)) + else + absent_origin_migration=true + fi + done + printf 'account_origin_probe=true\naccount_origin_prefix=%s\naccount_origin_base_sha=%s\naccount_origin_namespace_uid=%s\n' \ + "$origin_prefix" "$base_sha" "$namespace_uid" +fi + if [[ "$migration_changed" == true ]]; then emit_mode true "$reason_source first adds a supported Account, Game Session, or Automation migration" else diff --git a/dev-tools/deploy/probe-dev-account-v1040-4.sh b/dev-tools/deploy/probe-dev-account-v1040-4.sh new file mode 100644 index 0000000000..0160795e7d --- /dev/null +++ b/dev-tools/deploy/probe-dev-account-v1040-4.sh @@ -0,0 +1,146 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Run only inside the trusted dev database probe, while the existing deployment +# holds writer quiescence. The caller verifies the live Namespace UID, deployed +# and target revisions, and the expected Account history prefix at that base. +if [[ $# -ne 5 ]]; then + echo "usage: $0 " >&2 + exit 2 +fi + +namespace="$1" +namespace_uid="$2" +deployed_sha="$3" +target_sha="$4" +applied_origin_migrations="$5" +if [[ "$namespace" != dev || ! "$namespace_uid" =~ ^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$ || + ! "$deployed_sha" =~ ^[a-f0-9]{40}$ || ! "$target_sha" =~ ^[a-f0-9]{40}$ || + "$deployed_sha" == "$target_sha" || ! "$applied_origin_migrations" =~ ^[0-3]$ ]]; then + echo "Account V1040.4 probe requires a valid dev Namespace and exact retained-to-target comparison." >&2 + exit 2 +fi +if [[ -z "${FIREMUD_POSTGRES_USER:-}" ]]; then + echo "Account V1040.4 probe requires the existing hosted PostgreSQL connection identity." >&2 + exit 2 +fi + +# The caller supplies the existing in-Pod PostgreSQL environment. Direct +# arguments fix the destination and -X excludes local psql startup commands. +unset PGHOSTADDR PGSERVICE PGSERVICEFILE +if ! result="$( + PGCONNECT_TIMEOUT=5 PGOPTIONS='' PGPASSFILE=/dev/null psql -XqAtw \ + --host=postgres.dev.svc.cluster.local --port=5432 --dbname=firemud \ + --username="$FIREMUD_POSTGRES_USER" \ + --set=ON_ERROR_STOP=1 --set="expected_prefix=$applied_origin_migrations" \ + 2>/dev/null <<'SQL' +BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY; +SET LOCAL search_path = pg_catalog; +SET LOCAL statement_timeout = '30s'; +SET LOCAL lock_timeout = '5s'; + +SELECT current_database() = 'firemud' + AND EXISTS ( + SELECT 1 FROM pg_class c + WHERE c.oid = to_regclass('account_service.flyway_schema_history_account_service') + AND c.relkind = 'r' AND NOT c.relrowsecurity + AND NOT EXISTS (SELECT 1 FROM pg_inherits i WHERE i.inhparent = c.oid) + ) + AND EXISTS ( + SELECT 1 FROM pg_class c + WHERE c.oid = to_regclass('account_service.account_tenant_capacity_reservations') + AND c.relkind = 'r' + ) + AND to_regclass('account_service.account_capacity_origin_attempt_unique') IS NULL + AS expected_schema +\gset +\if :expected_schema + -- Flyway 13.13.0 SQL checksums for the immutable migration files. + WITH expected(version, script, prefix, checksum) AS ( + VALUES + ('1040', 'V1040__account_tenant_capacity_owner.sql', 0, 1080396723), + ('1040.1', 'V1040.1__account_capacity_origin_decisions.sql', 1, 2014106789), + ('1040.2', 'V1040.2__bound_capacity_origin_refusals.sql', 2, -1834870498), + ('1040.3', 'V1040.3__validate_only_inserted_refusal_budgets.sql', 3, 1807395108) + ) + SELECT count(*) = :expected_prefix + 1 + AND count(DISTINCT h.version) = :expected_prefix + 1 + AND COALESCE(bool_and(e.prefix IS NOT NULL AND e.prefix <= :expected_prefix + AND h.success IS TRUE AND h.script IS NOT DISTINCT FROM e.script + AND h.checksum IS NOT DISTINCT FROM e.checksum), false) + AS expected_history + FROM account_service.flyway_schema_history_account_service h + LEFT JOIN expected e ON e.version = h.version + WHERE h.version ~ '^1040([.]|$)' + \gset + \if :expected_history + SELECT :expected_prefix = 0 AS first_origin_migration, + to_regclass('account_service.account_capacity_origin_decisions') IS NULL AS origin_missing, + EXISTS ( + SELECT 1 FROM pg_class c + JOIN pg_attribute a ON a.attrelid = c.oid + WHERE c.oid = to_regclass('account_service.account_capacity_origin_decisions') + AND c.relkind = 'r' AND NOT c.relrowsecurity + AND NOT EXISTS (SELECT 1 FROM pg_inherits i WHERE i.inhparent = c.oid) + AND a.attname = 'admission_attempt_id' AND a.atttypid = 'pg_catalog.uuid'::regtype + AND a.attnotnull AND NOT a.attisdropped + ) AS expected_origin_relation + \gset + \if :first_origin_migration + \if :origin_missing + \echo first-origin-migration + \else + \echo unverified-origin-relation + \endif + \elif :expected_origin_relation + SELECT EXISTS ( + SELECT 1 + FROM account_service.account_capacity_origin_decisions + GROUP BY admission_attempt_id + HAVING count(*) > 1 + ) AS has_duplicates + \gset + \if :has_duplicates + \echo duplicates-present + \else + \echo retained-no-duplicates + \endif + \else + \echo unverified-origin-relation + \endif + \else + \echo unverified-account-history + \endif +\else + \echo unverified-account-schema +\endif +ROLLBACK; +SQL +)"; then + echo "Account V1040.4 probe could not complete the read-only PostgreSQL diagnostic." >&2 + exit 1 +fi + +case "$result" in + first-origin-migration|retained-no-duplicates) + if [[ "$result" == first-origin-migration && "$applied_origin_migrations" != 0 ]] || + [[ "$result" == retained-no-duplicates && "$applied_origin_migrations" == 0 ]]; then + echo "Account V1040.4 probe received an inconsistent diagnostic result." >&2 + exit 1 + fi + printf 'account-v1040-4-probe=%s namespace=%s namespace_uid=%s deployed_sha=%s target_sha=%s schema=account_service applied_origin_migrations=%s checksum_comparison=verified-v1040-prefix\n' \ + "$result" "$namespace" "$namespace_uid" "$deployed_sha" "$target_sha" "$applied_origin_migrations" + ;; + duplicates-present) + echo "Account V1040.4 probe found duplicate retained admission attempts. Account-owned disposition is required." >&2 + exit 1 + ;; + unverified-account-schema|unverified-account-history|unverified-origin-relation) + printf 'Account V1040.4 probe refused an unverified database state (%s).\n' "$result" >&2 + exit 1 + ;; + *) + echo "Account V1040.4 probe received an unexpected diagnostic result." >&2 + exit 1 + ;; +esac diff --git a/dev-tools/deploy/quiesce-v2-schema-migrations.sh b/dev-tools/deploy/quiesce-v2-schema-migrations.sh index 48c9adb4c9..75d509efbf 100644 --- a/dev-tools/deploy/quiesce-v2-schema-migrations.sh +++ b/dev-tools/deploy/quiesce-v2-schema-migrations.sh @@ -3,7 +3,7 @@ set -euo pipefail usage() { cat <<'EOF' -Usage: quiesce-v2-schema-migrations.sh +Usage: quiesce-v2-schema-migrations.sh [--verify-only] Close service admission for Account, Game Session, and Automation, prove their EndpointSlices are empty, scale their schema writers to zero, and prove their @@ -12,6 +12,7 @@ helper attempts to keep all canonical Services closed. If closure cannot be verified or reapplied, an operator must verify and repair admission before retrying a migration. On success, canonical selectors are restored while all writer Deployments stay at zero for the caller to apply the reviewed release. +The --verify-only mode checks the existing zero-replica hold without writes. EOF } @@ -20,6 +21,12 @@ fail() { exit 1 } +verify_only=false +if [[ "${1:-}" == --verify-only ]]; then + verify_only=true + shift +fi + if [[ $# -ne 1 ]]; then usage >&2 exit 2 @@ -79,6 +86,76 @@ read_endpoint_slices() { printf '%s\n' "$result" } +verify_writer_quiescence() { + local writer_deadline="$1" + local service deployment_json replicas pods_json pod_count + for service in "${services[@]}"; do + while :; do + if ! deployment_json="$(kubectl -n "$namespace" get deployment "$service" --ignore-not-found -o json)"; then + fail "cannot verify Deployment/$service after quiesce" + fi + if [[ -n "$deployment_json" ]]; then + replicas="$(jq -er '.spec.replicas | select(type == "number")' <<<"$deployment_json")" || + fail "cannot read desired replicas for Deployment/$service" + [[ "$replicas" == 0 ]] || + fail "Deployment/$service did not remain at zero replicas" + fi + + if ! pods_json="$(kubectl -n "$namespace" get pods -o json)"; then + fail "cannot verify pods for Deployment/$service" + fi + if ! pod_count="$(jq -er --arg service "$service" ' + def valid_pod_list: + (.kind == "PodList" or .kind == "List") + and ((.items | type) == "array") + and (.kind != "List" or all(.items[]?; type == "object" and .kind == "Pod")); + if valid_pod_list | not then + error("invalid PodList") + else + [ + .items[]? + | select( + (.metadata.labels.app == $service) + or any(.spec.containers[]?; + .name == $service + or ((.image // "") | split("@")[0] | split(":")[0] | split("/")[-1]) == $service + ) + ) + ] | length + end + ' <<<"$pods_json")"; then + fail "cannot parse pods for Deployment/$service" + fi + if [[ "$pod_count" == 0 ]]; then + break + fi + (( SECONDS < writer_deadline )) || + fail "old writer pods for $service remain present ($pod_count)" + sleep 2 + done + done +} + +verify_writer_autoscaling_absent() { + local hpa_json matching_hpas + # An HPA can undo the scale-to-zero maintenance boundary. Do not proceed if + # another controller can re-admit a writer while the migration is applying. + if ! hpa_json="$(kubectl -n "$namespace" get hpa -o json)"; then + fail "cannot inspect namespace HPAs" + fi + if ! matching_hpas="$(jq -er '[.items[]? | select(.spec.scaleTargetRef.kind == "Deployment" and (.spec.scaleTargetRef.name == "account-service" or .spec.scaleTargetRef.name == "game-session-service" or .spec.scaleTargetRef.name == "automation-scripting-service"))] | length' <<<"$hpa_json")"; then + fail "cannot parse namespace HPAs" + fi + [[ "$matching_hpas" == 0 ]] || + fail "an HPA targets a migration writer; remove or suspend that controller before migration" +} + +if [[ "$verify_only" == true ]]; then + verify_writer_autoscaling_absent + verify_writer_quiescence "$SECONDS" + exit 0 +fi + # The in-scope Services must exist and use the exact canonical selector. If # selectors have drifted, the helper cannot prove which traffic they admit. for service in "${services[@]}"; do @@ -89,16 +166,7 @@ for service in "${services[@]}"; do fail "Service/$service does not have the canonical app=$service selector" done -# An HPA can undo the scale-to-zero maintenance boundary. Do not proceed if -# another controller can re-admit a writer while the migration is applying. -if ! hpa_json="$(kubectl -n "$namespace" get hpa -o json)"; then - fail "cannot inspect namespace HPAs" -fi -if ! matching_hpas="$(jq -er '[.items[]? | select(.spec.scaleTargetRef.kind == "Deployment" and (.spec.scaleTargetRef.name == "account-service" or .spec.scaleTargetRef.name == "game-session-service" or .spec.scaleTargetRef.name == "automation-scripting-service"))] | length' <<<"$hpa_json")"; then - fail "cannot parse namespace HPAs" -fi -[[ "$matching_hpas" == 0 ]] || - fail "an HPA targets a migration writer; remove or suspend that controller before migration" +verify_writer_autoscaling_absent if ! pods_json="$(kubectl -n "$namespace" get pods -o json)"; then fail "cannot inspect namespace Pods before closing Service selectors" @@ -173,51 +241,7 @@ for service in "${services[@]}"; do fi done -for service in "${services[@]}"; do - while :; do - if ! deployment_json="$(kubectl -n "$namespace" get deployment "$service" --ignore-not-found -o json)"; then - fail "cannot verify Deployment/$service after quiesce" - fi - if [[ -n "$deployment_json" ]]; then - replicas="$(jq -er '.spec.replicas // 0' <<<"$deployment_json")" || - fail "cannot read desired replicas for Deployment/$service" - [[ "$replicas" == 0 ]] || - fail "Deployment/$service did not remain at zero replicas" - fi - - if ! pods_json="$(kubectl -n "$namespace" get pods -o json)"; then - fail "cannot verify pods for Deployment/$service" - fi - if ! pod_count="$(jq -er --arg service "$service" ' - def valid_pod_list: - (.kind == "PodList" or .kind == "List") - and ((.items | type) == "array") - and (.kind != "List" or all(.items[]?; type == "object" and .kind == "Pod")); - if valid_pod_list | not then - error("invalid PodList") - else - [ - .items[]? - | select( - (.metadata.labels.app == $service) - or any(.spec.containers[]?; - .name == $service - or ((.image // "") | split("@")[0] | split(":")[0] | split("/")[-1]) == $service - ) - ) - ] | length - end - ' <<<"$pods_json")"; then - fail "cannot parse pods for Deployment/$service" - fi - if [[ "$pod_count" == 0 ]]; then - break - fi - (( SECONDS < deadline )) || - fail "old writer pods for $service did not terminate within 300 seconds ($pod_count remain)" - sleep 2 - done -done +verify_writer_quiescence "$deadline" # Restore only after every writer Deployment and Pod has been proven quiescent. # If any write/readback fails, the EXIT trap closes all three selectors again. diff --git a/dev-tools/deploy/run-dev-account-v1040-4-probe.sh b/dev-tools/deploy/run-dev-account-v1040-4-probe.sh new file mode 100644 index 0000000000..602bcda377 --- /dev/null +++ b/dev-tools/deploy/run-dev-account-v1040-4-probe.sh @@ -0,0 +1,153 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ $# -ne 5 ]]; then + echo "usage: $0 " >&2 + exit 2 +fi + +namespace="$1" +namespace_uid="$2" +deployed_sha="$3" +target_sha="$4" +origin_prefix="$5" +helper_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +fail() { + echo "Account V1040.4 preflight failed: $*" >&2 + exit 1 +} + +if [[ "$namespace" != dev || ! "$namespace_uid" =~ ^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$ || + ! "$deployed_sha" =~ ^[a-f0-9]{40}$ || ! "$target_sha" =~ ^[a-f0-9]{40}$ || + "$deployed_sha" == "$target_sha" || ! "$origin_prefix" =~ ^[0-3]$ || + -z "${DEV_NAMESPACE_MANAGER_KUBECONFIG:-}" || -z "${KUBECONFIG:-}" ]]; then + fail "the protected caller must provide the exact dev deployment comparison and its scoped kubeconfigs" +fi +[[ "$(git -C "$helper_dir" rev-parse HEAD)" == "$target_sha" ]] || + fail "the checked-out probe source does not match the target" + +verify_namespace() { + kubectl --kubeconfig "$DEV_NAMESPACE_MANAGER_KUBECONFIG" --request-timeout=10s get namespace "$namespace" -o json | + jq -e --arg namespace "$namespace" --arg uid "$namespace_uid" --arg deployed "$deployed_sha" ' + .metadata.name == $namespace and .metadata.uid == $uid and + .metadata.labels["firemud.dev/dev-demo"] == "true" and + .metadata.labels["firemud.dev/environment-class"] == "dev-demo-cluster" and + .metadata.annotations["firemud.dev/last-dev-demo-head-sha"] == $deployed + ' >/dev/null +} + +verify_held_source() { + verify_namespace || fail "the namespace identity or deployed head changed" + bash "$helper_dir/quiesce-v2-schema-migrations.sh" --verify-only "$namespace" +} + +verify_held_source +image="$(kubectl --request-timeout=10s -n "$namespace" get statefulset postgres -o json | + jq -er '.spec.template.spec.containers | map(select(.name == "postgres")) | + select(length == 1) | .[0].image | select(type == "string")')" || + fail "the retained PostgreSQL image is unavailable" +[[ "$image" =~ ^postgres:[0-9][a-zA-Z0-9._-]*@sha256:[0-9a-f]{64}$ ]] || + fail "the retained PostgreSQL image is not an approved digest-pinned client" + +probe_source="$(<"$helper_dir/probe-dev-account-v1040-4.sh")" +probe_id="$(openssl rand -hex 16)" +[[ "$probe_id" =~ ^[0-9a-f]{32}$ ]] || fail "the probe job identity could not be generated" +job_name="firemud-account-v1040-4-$probe_id" +job_uid="" + +read_owned_job_uid() { + jq -er --arg name "$job_name" --arg namespace "$namespace" --arg uid "$namespace_uid" --arg target "$target_sha" ' + select(.kind == "Job" and .metadata.name == $name and .metadata.namespace == $namespace + and .metadata.annotations["firemud.dev/probe-namespace-uid"] == $uid + and .metadata.annotations["firemud.dev/probe-target"] == $target) + | .metadata.uid | select(type == "string" and test("^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$")) + ' +} + +remove_probe_job() { + local uid="$job_uid" + job_uid="" + jq -n --arg uid "$uid" \ + '{apiVersion:"v1",kind:"DeleteOptions",preconditions:{uid:$uid},propagationPolicy:"Foreground"}' | + kubectl --request-timeout=10s delete --raw "/apis/batch/v1/namespaces/$namespace/jobs/$job_name" -f - >/dev/null && + kubectl -n "$namespace" wait --for=delete --timeout=30s "job/$job_name" >/dev/null +} + +cleanup() { + local status=$? + trap - EXIT + if [[ -n "$job_uid" ]] && ! remove_probe_job; then + echo "Account V1040.4 preflight could not confirm probe Job cleanup" >&2 + status=1 + fi + exit "$status" +} +trap cleanup EXIT + +if ! created_job="$(jq -n \ + --arg name "$job_name" \ + --arg namespace "$namespace" --arg uid "$namespace_uid" --arg deployed "$deployed_sha" \ + --arg target "$target_sha" --arg prefix "$origin_prefix" --arg image "$image" --arg probe "$probe_source" ' + { + apiVersion: "batch/v1", kind: "Job", + metadata: {namespace: $namespace, name: $name, annotations: { + "firemud.dev/probe-namespace-uid": $uid, "firemud.dev/probe-target": $target + }}, + spec: { + backoffLimit: 0, activeDeadlineSeconds: 70, ttlSecondsAfterFinished: 300, + template: {spec: { + restartPolicy: "Never", automountServiceAccountToken: false, + securityContext: {runAsNonRoot: true, runAsUser: 999, runAsGroup: 999, seccompProfile: {type: "RuntimeDefault"}}, + containers: [{ + name: "probe", image: $image, imagePullPolicy: "IfNotPresent", + securityContext: {allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: {drop: ["ALL"]}}, + command: ["bash", "-c"], + args: [$probe, "probe-dev-account-v1040-4", $namespace, $uid, $deployed, $target, $prefix], + env: [ + {name: "FIREMUD_POSTGRES_USER", valueFrom: {secretKeyRef: {name: "firemud-secret", key: "FIREMUD_POSTGRES_USER"}}}, + {name: "PGPASSWORD", valueFrom: {secretKeyRef: {name: "firemud-secret", key: "FIREMUD_POSTGRES_PASSWORD"}}} + ] + }] + }} + } + } + ' | kubectl --request-timeout=10s -n "$namespace" create -f - -o json)"; then + # An ambiguous create is never sufficient for Helm. Clean up only if a + # fresh read identifies the owned Job; its deadline and TTL are the fallback. + if verify_namespace; then + job_uid="$(kubectl --request-timeout=10s -n "$namespace" get job "$job_name" --ignore-not-found -o json | + read_owned_job_uid)" || job_uid="" + fi + fail "the protected probe Job could not be confirmed" +fi +job_uid="$(read_owned_job_uid <<<"$created_job")" || fail "Kubernetes did not return the owned probe Job UID" + +if ! kubectl -n "$namespace" wait --for=condition=complete --timeout=75s "job/$job_name" >/dev/null; then + probe_error="$(kubectl --request-timeout=10s -n "$namespace" logs "job/$job_name" --tail=1 2>/dev/null || true)" + case "$probe_error" in + 'Account V1040.4 probe found duplicate retained admission attempts. Account-owned disposition is required.'|\ + 'Account V1040.4 probe refused an unverified database state (unverified-account-history).'|\ + 'Account V1040.4 probe refused an unverified database state (unverified-account-schema).'|\ + 'Account V1040.4 probe refused an unverified database state (unverified-origin-relation).') + fail "$probe_error" + ;; + *) + fail "the read-only PostgreSQL probe did not complete" + ;; + esac +fi +observed_job="$(kubectl --request-timeout=10s -n "$namespace" get job "$job_name" -o json)" || + fail "the completed probe Job is unavailable" +[[ "$(read_owned_job_uid <<<"$observed_job")" == "$job_uid" ]] || fail "the probe Job was replaced" +receipt="$(kubectl --request-timeout=10s -n "$namespace" logs "job/$job_name")" || + fail "the probe receipt is unavailable" +outcome=retained-no-duplicates +if [[ "$origin_prefix" == 0 ]]; then + outcome=first-origin-migration +fi +expected="account-v1040-4-probe=$outcome namespace=$namespace namespace_uid=$namespace_uid deployed_sha=$deployed_sha target_sha=$target_sha schema=account_service applied_origin_migrations=$origin_prefix checksum_comparison=verified-v1040-prefix" +[[ "$receipt" == "$expected" ]] || fail "the probe receipt does not match the held deployment comparison" +remove_probe_job || fail "the probe Job cleanup could not be confirmed" +verify_held_source +printf '%s\n' "$receipt" diff --git a/dev-tools/tests/dev-account-v1040-4-probe-contract.sh b/dev-tools/tests/dev-account-v1040-4-probe-contract.sh new file mode 100644 index 0000000000..b4749c04e8 --- /dev/null +++ b/dev-tools/tests/dev-account-v1040-4-probe-contract.sh @@ -0,0 +1,261 @@ +#!/usr/bin/env bash +set -euo pipefail + +root_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +probe="$root_dir/dev-tools/deploy/probe-dev-account-v1040-4.sh" +temp_dir="$(mktemp -d)" +trap 'rm -rf -- "$temp_dir"' EXIT + +export PATH="$temp_dir:$PATH" +export PROBE_SQL="$temp_dir/probe.sql" +export PROBE_ARGS="$temp_dir/probe.args" +export FIREMUD_POSTGRES_USER=fixture-user + +cat >"$temp_dir/psql" <<'EOF' +#!/usr/bin/env bash +set -euo pipefail +[[ "$PGCONNECT_TIMEOUT" == 5 && -z "$PGOPTIONS" && "$PGPASSFILE" == /dev/null ]] +[[ ! -v PGHOSTADDR && ! -v PGSERVICE && ! -v PGSERVICEFILE ]] +printf '%s\n' "$@" >"$PROBE_ARGS" +cat >"$PROBE_SQL" +if [[ "${MOCK_PSQL_EXIT:-0}" != 0 ]]; then + echo 'fixture detail must not be forwarded' >&2 + exit "$MOCK_PSQL_EXIT" +fi +printf '%s\n' "$MOCK_PSQL_RESULT" +EOF +chmod +x "$temp_dir/psql" + +namespace_uid=dev-fixture-uid +deployed_sha=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +target_sha=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +run_probe() { + bash "$probe" dev "$namespace_uid" "$deployed_sha" "$target_sha" "$1" +} + +receipt="$( + MOCK_PSQL_RESULT=first-origin-migration \ + PGHOSTADDR=unexpected-address PGSERVICE=unexpected-service PGSERVICEFILE=unexpected-file \ + PGOPTIONS=unexpected-options run_probe 0 +)" +[[ "$receipt" == "account-v1040-4-probe=first-origin-migration namespace=dev namespace_uid=$namespace_uid deployed_sha=$deployed_sha target_sha=$target_sha schema=account_service applied_origin_migrations=0 checksum_comparison=verified-v1040-prefix" ]] +diff -u <(printf '%s\n' \ + -XqAtw --host=postgres.dev.svc.cluster.local --port=5432 --dbname=firemud \ + --username=fixture-user --set=ON_ERROR_STOP=1 --set=expected_prefix=0) "$PROBE_ARGS" + +for prefix in 1 2 3; do + receipt="$(MOCK_PSQL_RESULT=retained-no-duplicates run_probe "$prefix")" + [[ "$receipt" == "account-v1040-4-probe=retained-no-duplicates namespace=dev namespace_uid=$namespace_uid deployed_sha=$deployed_sha target_sha=$target_sha schema=account_service applied_origin_migrations=$prefix checksum_comparison=verified-v1040-prefix" ]] +done + +for status in duplicates-present unverified-account-schema unverified-account-history unverified-origin-relation \ + first-origin-migration unexpected ""; do + if MOCK_PSQL_RESULT="$status" run_probe 3 >"$temp_dir/stdout" 2>"$temp_dir/stderr"; then + echo "Probe accepted unexpected retained result '$status'." >&2 + exit 1 + fi + [[ ! -s "$temp_dir/stdout" && -s "$temp_dir/stderr" ]] + if [[ "$status" == duplicates-present ]]; then + grep -Fq 'found duplicate retained admission attempts' "$temp_dir/stderr" + fi +done +for status in retained-no-duplicates $'first-origin-migration\nretained-no-duplicates'; do + if MOCK_PSQL_RESULT="$status" run_probe 0 >"$temp_dir/stdout" 2>"$temp_dir/stderr"; then + echo "Probe accepted inconsistent baseline result." >&2 + exit 1 + fi + [[ ! -s "$temp_dir/stdout" ]] +done +if MOCK_PSQL_EXIT=3 run_probe 3 >"$temp_dir/stdout" 2>"$temp_dir/stderr"; then + echo "Probe accepted failed PostgreSQL execution." >&2 + exit 1 +fi +[[ ! -s "$temp_dir/stdout" ]] +grep -Fq 'could not complete the read-only PostgreSQL diagnostic' "$temp_dir/stderr" +if grep -Fq 'fixture detail' "$temp_dir/stderr"; then + echo "Probe forwarded internal PostgreSQL details." >&2 + exit 1 +fi + +for comparison in \ + "staging $namespace_uid $deployed_sha $target_sha 0" \ + "dev invalid/uid $deployed_sha $target_sha 0" \ + "dev $namespace_uid $deployed_sha $deployed_sha 0" \ + "dev $namespace_uid $deployed_sha $target_sha 4"; do + rm -f -- "$PROBE_ARGS" + read -r -a args <<<"$comparison" + if bash "$probe" "${args[@]}" >"$temp_dir/stdout" 2>"$temp_dir/stderr"; then + echo "Probe accepted invalid comparison." >&2 + exit 1 + fi + [[ ! -e "$PROBE_ARGS" && ! -s "$temp_dir/stdout" ]] +done + +python3 - "$root_dir" "$PROBE_SQL" <<'PY' +import hashlib +import re +import sys +from pathlib import Path + +root, sql_path = map(Path, sys.argv[1:]) +sql = sql_path.read_text(encoding="utf-8") +assert sql.startswith("BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;\n") +assert sql.strip().endswith("ROLLBACK;") +assert "SET LOCAL statement_timeout = '30s';" in sql +assert "SET LOCAL lock_timeout = '5s';" in sql +assert not re.search(r"\b(INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|TRUNCATE|COMMIT|COPY)\b", sql, re.I) +assert "current_database() = 'firemud'" in sql +assert "account_service.flyway_schema_history_account_service" in sql +assert "account_service.account_tenant_capacity_reservations" in sql +assert "count(DISTINCT h.version) = :expected_prefix + 1" in sql +assert "h.success IS TRUE AND h.script IS NOT DISTINCT FROM e.script" in sql +assert "h.checksum IS NOT DISTINCT FROM e.checksum" in sql + +migrations = root / "services/account-service/src/main/resources/db/migration" +checksums = { + "1040": (1080396723, "b4f3d08e6272eb1757331fcfed187ab3035fdbc900274506b1d710ac5daf543e"), + "1040.1": (2014106789, "a81c98c6f192abace2b98c7ebac89926f68978bd9d911077d0b2aa7a666e6aa0"), + "1040.2": (-1834870498, "fc049730afe251b4b7c79b282cc647ec88da0ecebb4c0041bbf3045fd2b0c7f3"), + "1040.3": (1807395108, "4a50e0c7e6ac24d7862daedd8448b0c793a1bd5b2664e8bce79e2461388fe3d6"), +} +for prefix, (version, (checksum, source_hash)) in enumerate(checksums.items()): + script, = migrations.glob(f"V{version}__*.sql") + assert hashlib.sha256(script.read_bytes()).hexdigest() == source_hash + assert f"('{version}', '{script.name}', {prefix}, {checksum})" in sql +assert sql.index("WITH expected") < sql.index(r"\if :expected_history") +assert sql.index(r"\if :first_origin_migration") < sql.index(r"\if :origin_missing") +assert sql.index(r"\elif :expected_origin_relation") < sql.index("GROUP BY admission_attempt_id") +assert "AND NOT c.relrowsecurity" in sql +assert "a.atttypid = 'pg_catalog.uuid'::regtype" in sql +assert re.search( + r"SELECT EXISTS \(\s*SELECT 1\s+FROM account_service\.account_capacity_origin_decisions" + r"\s+GROUP BY admission_attempt_id\s+HAVING count\(\*\) > 1", + sql, +) +PY + +echo "Dev Account V1040.4 probe contract passed (mock PostgreSQL transport)." + +export PROBE_JOB_MANIFEST="$temp_dir/probe-job.json" +export PROBE_JOB_DELETED="$temp_dir/probe-job-deleted" +export PROBE_JOB_READ="$temp_dir/probe-job-read" +PROBE_FIXTURE_HEAD="$(git -C "$root_dir" rev-parse HEAD)" +export PROBE_FIXTURE_HEAD +export PROBE_FIXTURE_BASE="$deployed_sha" +export PROBE_FIXTURE_UID="$namespace_uid" +export PROBE_FIXTURE_JOB_NAME="firemud-account-v1040-4-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" +export KUBECONFIG=fixture-runtime +export DEV_NAMESPACE_MANAGER_KUBECONFIG=fixture-namespace-manager + +openssl() { + [[ "$*" == "rand -hex 16" ]] || return 2 + printf '%s\n' aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +} +export -f openssl + +kubectl() { + case "$*" in + '--kubeconfig fixture-namespace-manager --request-timeout=10s get namespace dev -o json') + local uid="$PROBE_FIXTURE_UID" + if [[ "${PROBE_SCENARIO:-}" == replaced && -f "$PROBE_JOB_READ" ]]; then + uid=replaced-namespace + fi + jq -n --arg uid "$uid" --arg base "$PROBE_FIXTURE_BASE" ' + {metadata: {name: "dev", uid: $uid, labels: {"firemud.dev/dev-demo": "true", + "firemud.dev/environment-class": "dev-demo-cluster"}, + annotations: {"firemud.dev/last-dev-demo-head-sha": $base}}}' + ;; + '-n dev get deployment '*) + [[ "$KUBECONFIG" == fixture-runtime ]] + printf '{"spec":{"replicas":0}}\n' + ;; + '-n dev get hpa -o json') + if [[ "${PROBE_SCENARIO:-}" == renewed-writer && -f "$PROBE_JOB_READ" ]]; then + printf '{"items":[{"spec":{"scaleTargetRef":{"kind":"Deployment","name":"account-service"}}}]}\n' + else + printf '{"items":[]}\n' + fi + ;; + '-n dev get pods -o json') + printf '{"kind":"PodList","items":[]}\n' + ;; + '--request-timeout=10s -n dev get statefulset postgres -o json') + printf '{"spec":{"template":{"spec":{"containers":[{"name":"postgres","image":"postgres:18@sha256:eb63372c1e05c755f55fa30cbd07aecc443676fc6c0fa90b9002d01537841e1a"}]}}}}\n' + ;; + '--request-timeout=10s -n dev create -f - -o json') + cat >"$PROBE_JOB_MANIFEST" + [[ "${PROBE_SCENARIO:-}" != ambiguous-create ]] || return 1 + jq '.metadata.uid = "fixture-owned-job-uid"' "$PROBE_JOB_MANIFEST" + ;; + "--request-timeout=10s -n dev get job $PROBE_FIXTURE_JOB_NAME -o json" | \ + "--request-timeout=10s -n dev get job $PROBE_FIXTURE_JOB_NAME --ignore-not-found -o json") + local observed_uid=fixture-owned-job-uid + if [[ "${PROBE_SCENARIO:-}" == job-replacement ]]; then + observed_uid=different-job-uid + fi + jq --arg uid "$observed_uid" '.metadata.uid = $uid' "$PROBE_JOB_MANIFEST" + ;; + "-n dev wait --for=condition=complete --timeout=75s job/$PROBE_FIXTURE_JOB_NAME") + [[ "${PROBE_SCENARIO:-}" != duplicate ]] + ;; + "--request-timeout=10s -n dev logs job/$PROBE_FIXTURE_JOB_NAME") + touch "$PROBE_JOB_READ" + printf 'account-v1040-4-probe=retained-no-duplicates namespace=dev namespace_uid=%s deployed_sha=%s target_sha=%s schema=account_service applied_origin_migrations=3 checksum_comparison=verified-v1040-prefix\n' \ + "$PROBE_FIXTURE_UID" "$PROBE_FIXTURE_BASE" "$PROBE_FIXTURE_HEAD" + ;; + "--request-timeout=10s -n dev logs job/$PROBE_FIXTURE_JOB_NAME --tail=1") + printf '%s\n' 'Account V1040.4 probe found duplicate retained admission attempts. Account-owned disposition is required.' + ;; + "--request-timeout=10s delete --raw /apis/batch/v1/namespaces/dev/jobs/$PROBE_FIXTURE_JOB_NAME -f -") + jq -e '.preconditions.uid == "fixture-owned-job-uid" and .propagationPolicy == "Foreground"' >/dev/null + [[ "${PROBE_SCENARIO:-}" != job-replacement ]] || return 1 + touch "$PROBE_JOB_DELETED" + ;; + "-n dev wait --for=delete --timeout=30s job/$PROBE_FIXTURE_JOB_NAME") + [[ -f "$PROBE_JOB_DELETED" ]] + ;; + *) + echo "unexpected kubectl command in the protected probe fixture: $*" >&2 + return 2 + ;; + esac +} +export -f kubectl + +run_protected_probe() { + bash "$root_dir/dev-tools/deploy/run-dev-account-v1040-4-probe.sh" \ + dev "$namespace_uid" "$deployed_sha" "$PROBE_FIXTURE_HEAD" 3 +} + +run_protected_probe >"$temp_dir/receipt" +grep -q 'checksum_comparison=verified-v1040-prefix' "$temp_dir/receipt" +[[ -f "$PROBE_JOB_DELETED" ]] +jq -e ' + .kind == "Job" and .metadata.namespace == "dev" and + .spec.backoffLimit == 0 and .spec.activeDeadlineSeconds == 70 and .spec.ttlSecondsAfterFinished == 300 and + .spec.template.spec.automountServiceAccountToken == false and + (.spec.template.spec.containers | if type == "array" then + length == 1 and .[0].command == ["bash", "-c"] and + (.[0].args[0] | contains("REPEATABLE READ READ ONLY")) and + .[0].env == [ + {name:"FIREMUD_POSTGRES_USER",valueFrom:{secretKeyRef:{name:"firemud-secret",key:"FIREMUD_POSTGRES_USER"}}}, + {name:"PGPASSWORD",valueFrom:{secretKeyRef:{name:"firemud-secret",key:"FIREMUD_POSTGRES_PASSWORD"}}} + ] + else false end) +' "$PROBE_JOB_MANIFEST" >/dev/null + +for scenario in duplicate replaced renewed-writer ambiguous-create job-replacement; do + rm -f -- "$PROBE_JOB_DELETED" "$PROBE_JOB_READ" + if PROBE_SCENARIO="$scenario" run_protected_probe >"$temp_dir/receipt" 2>"$temp_dir/error"; then + echo "Protected probe accepted $scenario." >&2 + exit 1 + fi + [[ ! -s "$temp_dir/receipt" ]] + if [[ "$scenario" == job-replacement ]]; then + [[ ! -f "$PROBE_JOB_DELETED" ]] + else + [[ -f "$PROBE_JOB_DELETED" ]] + fi +done + +echo "Protected dev Account V1040.4 probe contract passed (mock Kubernetes transport)." diff --git a/dev-tools/tests/dev-demo-workflow-contract.sh b/dev-tools/tests/dev-demo-workflow-contract.sh index 03b101f188..170a6bbc1b 100644 --- a/dev-tools/tests/dev-demo-workflow-contract.sh +++ b/dev-tools/tests/dev-demo-workflow-contract.sh @@ -18,6 +18,7 @@ python3 "$ROOT_DIR/dev-tools/validation/check_dev_demo_summary.py" "$ROOT_DIR" python3 "$ROOT_DIR/dev-tools/validation/test_check_dev_demo_summary.py" bash "$ROOT_DIR/dev-tools/tests/v2-schema-migration-quiescence-contract.sh" bash "$ROOT_DIR/dev-tools/tests/hosted-v2-migration-activation-contract.sh" +bash "$ROOT_DIR/dev-tools/tests/dev-account-v1040-4-probe-contract.sh" bash "$ROOT_DIR/dev-tools/tests/standalone-grpc-certificates-contract.sh" bash "$ROOT_DIR/dev-tools/tests/ensure-grpc-tls-secret-contract.sh" @@ -1289,6 +1290,7 @@ expected_deploy_kubeconfigs = { "Ensure dev-demo gRPC TLS secret exists": "${{ runner.temp }}/dev-demo-runtime.kubeconfig", "Validate dev-demo chart render": "${{ runner.temp }}/dev-demo-runtime.kubeconfig", "Quiesce Account, Game Session, and Automation migration writers": "${{ runner.temp }}/dev-demo-runtime.kubeconfig", + "Verify Account V1040.4 retained history before Helm": "${{ runner.temp }}/dev-demo-runtime.kubeconfig", "Deploy dev-demo release": "${{ runner.temp }}/dev-demo-runtime.kubeconfig", "Record exact deployed dev-demo head": "${{ runner.temp }}/dev-demo-namespace-manager.kubeconfig", "Show deployed dev-demo services": "${{ runner.temp }}/dev-demo-runtime.kubeconfig", @@ -1316,6 +1318,29 @@ if deploy_names.index("Classify trusted V2 migration activation") > deploy_names raise SystemExit("migration status must be proven before any namespace mutation") if positions[ordered.index("Quiesce Account, Game Session, and Automation migration writers")] > positions[ordered.index("Deploy dev-demo release")]: raise SystemExit("dev-demo migration writers must be quiesced before Helm activation") +origin_probe_name = "Verify Account V1040.4 retained history before Helm" +origin_probe = deploy_by_name[origin_probe_name] +if not (deploy_names.index(quiesce["name"]) < deploy_names.index(origin_probe_name) < deploy_position): + raise SystemExit("the Account V1040.4 probe must run between writer quiescence and Helm") +if origin_probe.get("continue-on-error") or origin_probe.get("if") != ( + "${{ steps.quiesce-writers.outcome == 'success' && " + "steps.v2-migration-mode.outputs.account_origin_probe == 'true' }}" +): + raise SystemExit("the exact Account V1040.4 probe must be fail-closed and limited to affected deployments") +if origin_probe.get("env", {}).get("DEV_NAMESPACE_MANAGER_KUBECONFIG") != ( + "${{ runner.temp }}/dev-demo-namespace-manager.kubeconfig" +): + raise SystemExit("the Account probe must use the existing namespace-manager kubeconfig for readback") +if "run-dev-account-v1040-4-probe.sh" not in origin_probe.get("run", ""): + raise SystemExit("the V1040.4 gate must call the protected probe helper") +deploy_condition = deploy_by_name["Deploy dev-demo release"].get("if", "") +for required_preflight in ( + "steps.v2-migration-mode.outcome == 'success'", + "(steps.v2-migration-mode.outputs.activation != 'true' || steps.quiesce-writers.outcome == 'success')", + "(steps.v2-migration-mode.outputs.account_origin_probe != 'true' || steps.account-v1040-4-preflight.outcome == 'success')", +): + if required_preflight not in deploy_condition: + raise SystemExit("Helm must require successful classification and any required migration preflight") for step_name, expected_kubeconfig in expected_deploy_kubeconfigs.items(): actual_env = deploy_by_name[step_name].get("env", {}) if actual_env.get("KUBECONFIG") != expected_kubeconfig: @@ -1475,11 +1500,12 @@ quiesce_writers = deploy_by_name[ if quiesce_writers.get("id") != "quiesce-writers": raise SystemExit("dev-demo migration writer quiesce must expose its outcome") quiesced_writer_warning = deploy_by_name[ - "Warn about migration writer recovery after quiesce or deploy failure" + "Warn about migration writer recovery after quiesce, preflight or deploy failure" ] expected_quiesced_writer_warning_condition = ( "${{ always() && steps.v2-migration-mode.outputs.activation == 'true' && " "(steps.quiesce-writers.outcome == 'failure' || " + "steps.account-v1040-4-preflight.outcome == 'failure' || " "steps.deploy-release.outcome == 'failure') }}" ) if quiesced_writer_warning.get("if") != expected_quiesced_writer_warning_condition: diff --git a/dev-tools/tests/hosted-v2-migration-activation-contract.sh b/dev-tools/tests/hosted-v2-migration-activation-contract.sh index 0043cad401..e942c0774b 100644 --- a/dev-tools/tests/hosted-v2-migration-activation-contract.sh +++ b/dev-tools/tests/hosted-v2-migration-activation-contract.sh @@ -21,7 +21,7 @@ kubectl() { export -f kubectl namespace_for_head() { - FAKE_NAMESPACE_JSON="$(jq -cn --arg head "$1" '{metadata:{name:"dev",labels:{"firemud.dev/dev-demo":"true","firemud.dev/environment-class":"dev-demo-cluster"},annotations:{"firemud.dev/last-dev-demo-head-sha":$head}}}')" + FAKE_NAMESPACE_JSON="$(jq -cn --arg head "$1" '{metadata:{name:"dev",uid:"fixture-dev-uid",labels:{"firemud.dev/dev-demo":"true","firemud.dev/environment-class":"dev-demo-cluster"},annotations:{"firemud.dev/last-dev-demo-head-sha":$head}}}')" export FAKE_NAMESPACE_JSON } @@ -51,6 +51,9 @@ assert_rejected() { mkdir -p "$repo/services/example/src/main/resources/db/migration" printf '%s\n' 'CREATE TABLE baseline (id integer PRIMARY KEY);' \ >"$repo/services/example/src/main/resources/db/migration/V1__baseline.sql" +mkdir -p "$repo/services/account-service/src/main/resources/db/migration" +printf '%s\n' '-- deployed capacity baseline' \ + >"$repo/services/account-service/src/main/resources/db/migration/V1040__account_tenant_capacity_owner.sql" git -C "$repo" add . git -C "$repo" commit -qm "baseline" baseline_sha="$(git -C "$repo" rev-parse HEAD)" @@ -121,7 +124,13 @@ capacity_migration_dir="$repo/services/account-service/src/main/resources/db/mig for migration in \ V1040.1__account_capacity_origin_decisions.sql \ V1040.2__bound_capacity_origin_refusals.sql \ - V1040.3__validate_only_inserted_refusal_budgets.sql \ + V1040.3__validate_only_inserted_refusal_budgets.sql; do + printf '%s\n' '-- retained capacity origin migration fixture' >"$capacity_migration_dir/$migration" +done +git -C "$repo" add . +git -C "$repo" commit -qm "Account capacity origin prefix" +capacity_prefix_sha="$(git -C "$repo" rev-parse HEAD)" +for migration in \ V1040.4__unique_capacity_origin_attempt.sql \ V1040.5__arbitrate_origin_identity_before_refusal_budget.sql \ V1040.6__index_retained_capacity_refusal_slots.sql; do @@ -133,6 +142,17 @@ capacity_origin_sha="$(git -C "$repo" rev-parse HEAD)" namespace_for_head "$account_v25_sha" assert_activation true push "$account_v25_sha" "$capacity_origin_sha" assert_activation true workflow_dispatch "" "$capacity_origin_sha" +origin_receipt="$(cd "$repo" && bash "$detector" push "$account_v25_sha" "$capacity_origin_sha" dev)" +grep -Fxq 'account_origin_probe=true' <<<"$origin_receipt" +grep -Fxq 'account_origin_prefix=0' <<<"$origin_receipt" +grep -Fxq "account_origin_base_sha=$account_v25_sha" <<<"$origin_receipt" +grep -Fxq 'account_origin_namespace_uid=fixture-dev-uid' <<<"$origin_receipt" + +namespace_for_head "$capacity_prefix_sha" +origin_receipt="$(cd "$repo" && bash "$detector" push "$capacity_prefix_sha" "$capacity_origin_sha" dev)" +grep -Fxq 'account_origin_prefix=3' <<<"$origin_receipt" +FAKE_NAMESPACE_JSON="$(jq 'del(.metadata.uid)' <<<"$FAKE_NAMESPACE_JSON")" +assert_rejected push "$capacity_prefix_sha" "$capacity_origin_sha" namespace_for_head "$capacity_origin_sha" assert_rejected workflow_dispatch "" "$capacity_origin_sha" From f4e517a5f0a4ef7f4aad2abe4c834d5047f85dcb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:54:49 +1300 Subject: [PATCH 45/96] Read the retained dev-demo PostgreSQL Deployment for preflight --- .../deploy/run-dev-account-v1040-4-probe.sh | 8 +++++--- .../dev-account-v1040-4-probe-contract.sh | 18 ++++++++++++++++-- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/dev-tools/deploy/run-dev-account-v1040-4-probe.sh b/dev-tools/deploy/run-dev-account-v1040-4-probe.sh index 602bcda377..495a1f4b0f 100644 --- a/dev-tools/deploy/run-dev-account-v1040-4-probe.sh +++ b/dev-tools/deploy/run-dev-account-v1040-4-probe.sh @@ -43,9 +43,11 @@ verify_held_source() { } verify_held_source -image="$(kubectl --request-timeout=10s -n "$namespace" get statefulset postgres -o json | - jq -er '.spec.template.spec.containers | map(select(.name == "postgres")) | - select(length == 1) | .[0].image | select(type == "string")')" || +image="$(kubectl --request-timeout=10s -n "$namespace" get deployment postgres -o json | + jq -er --arg namespace "$namespace" ' + select(.kind == "Deployment" and .metadata.name == "postgres" and .metadata.namespace == $namespace) + | .spec.template.spec.containers | map(select(.name == "postgres")) + | select(length == 1) | .[0].image | select(type == "string")')" || fail "the retained PostgreSQL image is unavailable" [[ "$image" =~ ^postgres:[0-9][a-zA-Z0-9._-]*@sha256:[0-9a-f]{64}$ ]] || fail "the retained PostgreSQL image is not an approved digest-pinned client" diff --git a/dev-tools/tests/dev-account-v1040-4-probe-contract.sh b/dev-tools/tests/dev-account-v1040-4-probe-contract.sh index b4749c04e8..a45b9a7f07 100644 --- a/dev-tools/tests/dev-account-v1040-4-probe-contract.sh +++ b/dev-tools/tests/dev-account-v1040-4-probe-contract.sh @@ -179,8 +179,14 @@ kubectl() { '-n dev get pods -o json') printf '{"kind":"PodList","items":[]}\n' ;; - '--request-timeout=10s -n dev get statefulset postgres -o json') - printf '{"spec":{"template":{"spec":{"containers":[{"name":"postgres","image":"postgres:18@sha256:eb63372c1e05c755f55fa30cbd07aecc443676fc6c0fa90b9002d01537841e1a"}]}}}}\n' + '--request-timeout=10s -n dev get deployment postgres -o json') + local kind=Deployment + if [[ "${PROBE_SCENARIO:-}" == wrong-postgres-kind ]]; then + kind=StatefulSet + fi + jq -n --arg kind "$kind" '{kind:$kind,metadata:{name:"postgres",namespace:"dev"}, + spec:{template:{spec:{containers:[{name:"postgres", + image:"postgres:18@sha256:eb63372c1e05c755f55fa30cbd07aecc443676fc6c0fa90b9002d01537841e1a"}]}}}}' ;; '--request-timeout=10s -n dev create -f - -o json') cat >"$PROBE_JOB_MANIFEST" @@ -258,4 +264,12 @@ for scenario in duplicate replaced renewed-writer ambiguous-create job-replaceme fi done +rm -f -- "$PROBE_JOB_MANIFEST" "$PROBE_JOB_DELETED" +if PROBE_SCENARIO=wrong-postgres-kind run_protected_probe >"$temp_dir/receipt" 2>"$temp_dir/error"; then + echo "Protected probe accepted the wrong PostgreSQL workload kind." >&2 + exit 1 +fi +grep -q 'retained PostgreSQL image is unavailable' "$temp_dir/error" +[[ ! -e "$PROBE_JOB_MANIFEST" && ! -s "$temp_dir/receipt" ]] + echo "Protected dev Account V1040.4 probe contract passed (mock Kubernetes transport)." From 59b15ca9123fafd7a4e3060a82c8840e7ed6067b Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:59:23 +1300 Subject: [PATCH 46/96] Show the supported verification path after a recorded dev-demo failure --- .github/workflows/dev-demo.yml | 17 +++++++ dev-tools/tests/dev-demo-workflow-contract.sh | 46 +++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/.github/workflows/dev-demo.yml b/.github/workflows/dev-demo.yml index 160b45187f..3160676918 100644 --- a/.github/workflows/dev-demo.yml +++ b/.github/workflows/dev-demo.yml @@ -445,6 +445,7 @@ jobs: /tmp/dev-demo-values.yaml - name: Record exact deployed dev-demo head + id: record-deployed-head if: ${{ steps.cluster-access.outputs.available == 'true' && steps.deploy-release.outcome == 'success' }} env: KUBECONFIG: ${{ runner.temp }}/dev-demo-namespace-manager.kubeconfig @@ -546,6 +547,7 @@ jobs: } >> "$GITHUB_ENV" - name: Create dev-demo smoke account + id: bootstrap-smoke if: ${{ steps.cluster-access.outputs.available == 'true' && steps.deploy-release.outcome == 'success' }} env: KUBECONFIG: ${{ runner.temp }}/dev-demo-runtime.kubeconfig @@ -982,6 +984,9 @@ jobs: - name: Summarize dev-demo failure if: ${{ always() && failure() && steps.cluster-access.outputs.available == 'true' }} + env: + RECORD_OUTCOME: ${{ steps.record-deployed-head.outcome }} + BOOTSTRAP_OUTCOME: ${{ steps.bootstrap-smoke.outcome }} run: | bash ./dev-tools/hosted/dev-demo/write-dev-demo-summary.sh \ failure \ @@ -990,6 +995,18 @@ jobs: "${{ needs.dev-demo-plan.outputs.hostname }}" \ "${{ needs.dev-demo-plan.outputs.telnet_port }}" \ "${DEV_DEMO_STAGE:-unknown}" >> "$GITHUB_STEP_SUMMARY" + if [[ "$RECORD_OUTCOME" == success ]]; then + guide="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/blob/${GITHUB_WORKFLOW_SHA}/design/architecture/system-architecture-database-migrations.md#verification-after-the-dev-demo-target-is-recorded" + { + echo "" + if [[ "$BOOTSTRAP_OUTCOME" == success ]]; then + echo "The target was recorded and the original smoke bootstrap completed in this attempt. Use the [verification procedure]($guide) to check the existing release and migration state before repeating readiness or smoke." + else + echo "The target was recorded but the original smoke bootstrap did not complete successfully in this attempt. Use the [verification procedure]($guide) to inspect the existing release and refer bootstrap recovery to the affected owners." + fi + echo "Keep the recorded target and existing namespace. Do not replay Helm or bootstrap to verify this release." + } >> "$GITHUB_STEP_SUMMARY" + fi - name: Warn about migration writer recovery after quiesce, preflight or deploy failure if: ${{ always() && steps.v2-migration-mode.outputs.activation == 'true' && (steps.quiesce-writers.outcome == 'failure' || steps.account-v1040-4-preflight.outcome == 'failure' || steps.deploy-release.outcome == 'failure') }} diff --git a/dev-tools/tests/dev-demo-workflow-contract.sh b/dev-tools/tests/dev-demo-workflow-contract.sh index 170a6bbc1b..427998cbfc 100644 --- a/dev-tools/tests/dev-demo-workflow-contract.sh +++ b/dev-tools/tests/dev-demo-workflow-contract.sh @@ -1416,6 +1416,52 @@ if "steps.deploy-release.outcome == 'success'" not in deployed_head_step.get("if raise SystemExit("deployed-head evidence is not gated on successful Helm completion") if "firemud.dev/last-dev-demo-head-sha=${HEAD_SHA}" not in deployed_head_step["run"]: raise SystemExit("successful Helm completion does not record exact deployed-head evidence") +bootstrap_step = deploy_by_name["Create dev-demo smoke account"] +failure_summary = deploy_by_name["Summarize dev-demo failure"] +if failure_summary["env"] != { + "RECORD_OUTCOME": "${{ steps." + deployed_head_step["id"] + ".outcome }}", + "BOOTSTRAP_OUTCOME": "${{ steps." + bootstrap_step["id"] + ".outcome }}", +}: + raise SystemExit("recorded-target verification advice must use this attempt's native outcomes") +failure_summary_run = failure_summary["run"] +for name, value in { + "head_sha": "a" * 40, + "image_tag": "contract-image", + "hostname": "dev.example.invalid", + "telnet_port": "32016", +}.items(): + failure_summary_run = failure_summary_run.replace( + "${{ needs.dev-demo-plan.outputs." + name + " }}", value + ) +with tempfile.TemporaryDirectory() as directory: + summary = Path(directory) / "summary.md" + for recorded, bootstrap, expected in ( + ("skipped", "skipped", None), + ("success", "failure", "refer bootstrap recovery to the affected owners"), + ("success", "success", "before repeating readiness or smoke"), + ): + summary.write_text("", encoding="utf-8") + subprocess.run( + ["bash", "-e", "-c", failure_summary_run], + cwd=repository_root, + env={ + **os.environ, + "GITHUB_STEP_SUMMARY": str(summary), + "GITHUB_SERVER_URL": "https://github.example.invalid", + "GITHUB_REPOSITORY": "example/FireMUD", + "GITHUB_WORKFLOW_SHA": "b" * 40, + "RECORD_OUTCOME": recorded, + "BOOTSTRAP_OUTCOME": bootstrap, + }, + check=True, + ) + evidence = summary.read_text(encoding="utf-8") + guide = "/blob/" + "b" * 40 + "/design/architecture/" + if expected is None: + if guide in evidence: + raise SystemExit("unrecorded target received recorded-target advice") + elif expected not in evidence or guide not in evidence or "Do not replay Helm or bootstrap" not in evidence: + raise SystemExit("recorded target lacks the correct verification boundary") runtime_target_run = deploy_by_name["Record exact dev-demo runtime target"]["run"] target_validator_call = ( "bash ./dev-tools/hosted/dev-demo/validate-dev-demo-target.sh \\\n" From 1215c6a6d14e37912642a8cdf1d60ee68ff52a39 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:24:02 +1300 Subject: [PATCH 47/96] Read the original Account quota denial without replaying capacity --- .../account-service/api-contracts.md | 2 +- .../player-access-and-session.md | 2 + protos/account/v1/account_service.proto | 3 + ...countCapacityOriginDecisionRepository.java | 17 +- .../AccountTenantCapacityWorkloadGuard.java | 36 ++++- .../service/AccountTenantCapacityOwner.java | 39 +++++ .../AccountTenantCapacityGrpcService.java | 66 +++++++- ...titlementOwnerPostgresIntegrationTest.java | 35 ++++- ...ccountTenantCapacityWorkloadGuardTest.java | 28 +++- .../AccountTenantCapacityGrpcServiceTest.java | 147 +++++++++++++++++- .../client/AccountTenantCapacityClient.java | 79 +++++++--- .../AccountTenantCapacityClientMtlsTest.java | 49 ++++++ 12 files changed, 468 insertions(+), 35 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 15f451fd15..b7b4fc8842 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -238,7 +238,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued Exact replay is guaranteed only for outcomes Account durably retained. A billing or non-creating entitlement refusal that did not retain a decision receipt is not a replayable outcome; a later retry rechecks current evidence freshness before deciding and cannot treat the earlier refusal as a retained result. -Lost-response recovery remains an activation prerequisite for the unregistered capacity caller. Before enabling it, Account and Game Session must supply and qualify the read-only reconciliation step for the original outer identity, attempt, fence, complete payload and digest, including recovery of the exact durable quota-denial ID while the original Game Session reserve remains active. The existing commit adapter and Account's retained-denial replay do not supply that caller recovery step. Its qualification must lose the original denial response, restore quota headroom and restart the caller, then recover the same denial without a new attempt, reservation or refusal slot. Missing or ambiguous evidence keeps the original reserve and admission closed; a fresh request or automatic mutation retry is not a recovery substitute. The remaining caller and owner-readback scope is recorded in the [strict tenant-capacity owner tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). +`ReadTenantCapacityQuotaDenial` is the private read-only reconciliation operation for the exact Game Session mTLS peer while its original reserve remains active. It takes the original commit request and matches the outer identity, attempt, fence, complete payload and digest. Account returns the original durable quota denial and no other outcome. Missing or ambiguous evidence keeps the original reserve and admission closed. A fresh request or automatic mutation retry does not recover the original outcome. Before enabling this composition, qualify recovery after the original response is lost, quota headroom returns and the caller restarts. Verify that no new attempt, reservation or refusal slot was used. The [strict tenant-capacity owner tracker](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation) records the remaining caller and owner proof. The shared [capacity-admission/v1 schema](../../../../services/common-platform-core/src/main/resources/capacity/capacity-admission-v1.schema.json) declares the exact ADR 0047 seven-field mapping and bounds. Its `accountEvidence` member is canonical padded base64 of the complete existing Account bundle bytes, validated by the closed variant codec with canonical re-encoding equality before hashing. This binds every evidence field and cutoff/checkpoint byte, not a digest or reconstructed subset. `capacity_delta` is `optional int64`; missing presence is invalid and a present zero remains distinct. The Game Session and World alternatives retain distinct typed contexts. The ordinary registered Account receiver does not expose this private composition, and no route is enabled by adding the proto. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index b51b387b71..e6c8fe4aee 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -40,6 +40,8 @@ Account [V1040.6](../../../services/account-service/src/main/resources/db/migrat Existing focused proof anchors include the [Account owner units](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java), [creation/ledger/recovery PostgreSQL cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java), [player-owner retained-denial case](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java), [migration/refusal-slot cases](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java), [shared codec cases](../../../services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java) and [Game Session client mTLS cases](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java). These cover controlled owner/storage, exact refusal/replay and separate loopback transport boundaries, not a genuine cross-owner runtime-admission chain. The codec cases now prepare contradictory billing-refusal rejection on both encode and decode while preserving valid non-creating billing evidence and quota-denial invariants. This bounded correction runs only the four-file `git diff --check`; canonical Gradle formatting and focused test execution remain delegated to the parent, with no new compilation, test-pass or physical-execution claim here. +The unregistered retained-denial read composes the Game Session client, the authenticated Account mTLS receiver, and physical PostgreSQL. The fixture recovers the original decision after quota headroom returns and the original evaluation expires, then verifies unchanged reservation, usage, refusal slot and denial rows. A separate controlled transport test discards the first commit response and reopens the client before reading the same result. Recovery from a persisted Game Session reserve after a real process restart still needs proof. + The Account owner can retry a rolled-back PostgreSQL serialization failure up to three times in fresh transactions, with short randomized delays and one retry-admission deadline. The player evaluation transaction rolls back and reports source unavailability when exact retention readback fails. An exact reservation replay in RELEASED or QUARANTINED state cannot authorize original NEW execution. Game Session original-NEW execution and its authenticated recovery source, normal owner handoff, and the origin and historical FINAL receiving paths remain dependent work. Finalized usage retirement and settlement remain deferred: they require a genuine admitted-session teardown receipt from the selected owner and an exactly-once Account usage transition that preserves finalized replay. Bounded conservation and owner-governed evidence retention remain downstream. Preserve immutable predecessor evidence, deployed source and PKI qualification, and runtime registration, admission and activation holds. diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 0d5cc807cb..dad814ccb5 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -12,6 +12,9 @@ option java_multiple_files = true; service AccountService { // Strict capacity owner. Available only through an explicitly composed bounded mTLS receiver. rpc CommitTenantCapacityAdmission(CommitTenantCapacityAdmissionRequest) returns (CommitTenantCapacityAdmissionResponse); + // Private read-only reconciliation of an exact retained quota denial. An unavailable + // outcome does not prove the original attempt did not commit. + rpc ReadTenantCapacityQuotaDenial(CommitTenantCapacityAdmissionRequest) returns (CommitTenantCapacityAdmissionResponse); rpc Ping(PingRequest) returns (PingResponse); rpc CreateAccount(CreateAccountRequest) returns (CreateAccountResponse); rpc Authenticate(AuthenticateRequest) returns (AuthenticateResponse); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java index 147309351f..9108bec80b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCapacityOriginDecisionRepository.java @@ -13,6 +13,7 @@ import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; import org.jooq.DSLContext; import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** Immutable Account decision; unique-key arbitration also excludes caller/account aliases. */ @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Private transaction collaborator.") @@ -28,6 +29,10 @@ public AccountCapacityOriginDecisionRepository(DSLContext dsl) { /** Read only. Missing row is not a refusal. */ public Record find(Request request) { transaction(); + return findExact(request); + } + + private Record findExact(Request request) { Record row = findRow(request); if (row != null) requireExact(request, row, CapacityAdmissionDigest.preimage(request)); return row; @@ -47,7 +52,17 @@ public UUID refuse(Request request) { /** Replays an exact durable quota refusal before any mutable eligibility check. */ public UUID retainedQuotaDenial(Request request) { - Record row = find(request); + return quotaDenialId(find(request)); + } + + /** Historical recovery SELECT, never part of the mutation transaction. */ + public UUID readRetainedQuotaDenial(Request request) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) throw unavailable(); + return quotaDenialId(findExact(request)); + } + + private static UUID quotaDenialId(Record row) { if (row == null) return null; return requireOutcome(row, "NO_ACCEPT", QUOTA_REFUSAL).get("decision_id", UUID.class); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java index 88e1694a6f..cd3f6d6684 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuard.java @@ -18,14 +18,18 @@ /** Sole producer of the receiver's private exact-method TLS caller assertion. */ public final class AccountTenantCapacityWorkloadGuard implements ServerInterceptor { private final Context.Key caller = Context.key("tenant-capacity-authenticated-peer"); + private final Context.Key quotaDenialReader = + Context.key("tenant-capacity-denial-reader"); + private final String gameSession; private final Set allowed; public AccountTenantCapacityWorkloadGuard(String namespace) { if (!GrpcPeerIdentity.isValidNamespace(namespace)) throw new IllegalArgumentException("Namespace required"); + gameSession = TenantCapacityAdmission.expectedWorkload(namespace, Owner.GAME_SESSION); allowed = Set.of( - TenantCapacityAdmission.expectedWorkload(namespace, Owner.GAME_SESSION), + gameSession, TenantCapacityAdmission.expectedWorkload(namespace, Owner.WORLD_MANAGEMENT)); } @@ -36,20 +40,36 @@ public String requireAuthenticatedCaller() { return value; } + public String requireQuotaDenialReader() { + String value = quotaDenialReader.get(); + if (!gameSession.equals(value) || ambient()) throw Status.UNAUTHENTICATED.asRuntimeException(); + return value; + } + @Override public ServerCall.Listener interceptCall( ServerCall call, Metadata headers, ServerCallHandler next) { var peer = GrpcPeerIdentity.fromSslSession(call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)); if (peer.isEmpty()) return deny(call, Status.UNAUTHENTICATED); - if (ambient() - || !allowed.contains(peer.orElseThrow().uri()) - || !AccountServiceGrpc.getCommitTenantCapacityAdmissionMethod() + if (ambient()) return deny(call, Status.PERMISSION_DENIED); + String method = call.getMethodDescriptor().getFullMethodName(); + String workload = peer.orElseThrow().uri(); + if (AccountServiceGrpc.getCommitTenantCapacityAdmissionMethod() + .getFullMethodName() + .equals(method) + && allowed.contains(workload)) { + return Contexts.interceptCall( + Context.current().withValue(caller, workload), call, headers, next); + } + if (AccountServiceGrpc.getReadTenantCapacityQuotaDenialMethod() .getFullMethodName() - .equals(call.getMethodDescriptor().getFullMethodName())) - return deny(call, Status.PERMISSION_DENIED); - return Contexts.interceptCall( - Context.current().withValue(caller, peer.orElseThrow().uri()), call, headers, next); + .equals(method) + && gameSession.equals(workload)) { + return Contexts.interceptCall( + Context.current().withValue(quotaDenialReader, workload), call, headers, next); + } + return deny(call, Status.PERMISSION_DENIED); } private static boolean ambient() { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index 8d64011910..40f08a92d2 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -29,6 +29,7 @@ import net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence; import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Owner; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.PlayerContext; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Result; @@ -65,6 +66,7 @@ public final class AccountTenantCapacityOwner { private final AccountTenantCapacityRepository capacity; private final AccountCapacityOriginDecisionRepository originDecisions; private final TransactionTemplate transaction; + private final TransactionTemplate denialReadTransaction; private final Clock clock; private final String namespace; @@ -92,6 +94,43 @@ public AccountTenantCapacityOwner( transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); transaction.setTimeout(TRANSACTION_TIMEOUT_SECONDS); + denialReadTransaction = new TransactionTemplate(transactions); + denialReadTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + denialReadTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + denialReadTransaction.setReadOnly(true); + denialReadTransaction.setTimeout(TRANSACTION_TIMEOUT_SECONDS); + } + + /** Reads only an exact historical quota refusal; absence does not resolve an unknown commit. */ + public UUID readRetainedQuotaDenial(Request request, String authenticatedCaller) { + requireCaller(request, authenticatedCaller); + if (!TenantCapacityAdmission.expectedWorkload(namespace, Owner.GAME_SESSION) + .equals(authenticatedCaller)) throw new CapacityException(Failure.PERMISSION_DENIED); + request.requireStructurallyValid(); + requireSupportedShape(request); + if (request.capacityRearmFence() != 1 || !request.evidence().permitsCreation()) + throw unavailable(); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive() + || Context.current().isCancelled()) throw unavailable(); + try { + UUID denialId = + denialReadTransaction.execute(status -> { + if (Context.current().isCancelled()) throw unavailable(); + dsl.connection(connection -> { + if (connection.getAutoCommit() || !connection.isReadOnly()) throw unavailable(); + }); + return originDecisions.readRetainedQuotaDenial(request); + }); + if (denialId == null) throw unavailable(); + return TenantCapacityAdmission.uuid(denialId); + } catch (CapacityException failure) { + // A different original or decision is not settlement evidence on this read. + if (failure.code() == Failure.IDEMPOTENCY_CONFLICT) throw unavailable(); + throw failure; + } catch (IllegalArgumentException invalidEvidence) { + throw unavailable(); + } } public Result commit(Request request, String authenticatedCaller) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java index 5fb660e152..c0da7cb8aa 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcService.java @@ -16,6 +16,7 @@ import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.CapacityException; import net.firedevops.firemud.accountservice.security.AccountTenantCapacityWorkloadGuard; import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; +import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; @@ -66,7 +67,7 @@ public void commitTenantCapacityAdmission( Failure.ENTITLEMENT_UNAVAILABLE.toStatusException(Status.Code.FAILED_PRECONDITION)); return; } - final net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request request; + final Request request; try { request = TenantCapacityAdmissionGrpcCodec.parseRequest(wire); } catch (IllegalArgumentException | ArithmeticException invalid) { @@ -109,4 +110,67 @@ public void commitTenantCapacityAdmission( observer.onError(Status.INTERNAL.asRuntimeException()); } } + + @Override + public void readTenantCapacityQuotaDenial( + CommitTenantCapacityAdmissionRequest wire, + StreamObserver observer) { + Objects.requireNonNull(observer); + final String peer; + try { + peer = guard.requireQuotaDenialReader(); + } catch (StatusRuntimeException denied) { + observer.onError(Failure.AUTH_UNAVAILABLE.toStatusException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError(Failure.ENTITLEMENT_UNAVAILABLE.toStatusException()); + return; + } + final Request request; + try { + request = TenantCapacityAdmissionGrpcCodec.parseRequest(wire); + } catch (IllegalArgumentException | ArithmeticException invalid) { + observer.onError(Failure.INVALID_ARGUMENT.toStatusException()); + return; + } + if (!request.evidence().callerWorkload().equals(peer)) { + observer.onError(Failure.PERMISSION_DENIED.toStatusException()); + return; + } + final CommitTenantCapacityAdmissionResponse result; + try { + var denialId = owner.readRetainedQuotaDenial(request, peer); + if (denialId == null) { + observer.onError(Failure.ENTITLEMENT_UNAVAILABLE.toStatusException()); + return; + } + result = + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, Failure.CAPACITY_QUOTA_EXCEEDED, denialId); + } catch (CapacityException denied) { + Failure code = + switch (denied.code()) { + case INVALID_ARGUMENT, PERMISSION_DENIED -> denied.code(); + default -> Failure.ENTITLEMENT_UNAVAILABLE; + }; + observer.onError(code.toStatusException()); + return; + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException + | org.springframework.transaction.TransactionException unavailable) { + observer.onError(Failure.ENTITLEMENT_UNAVAILABLE.toStatusException()); + return; + } catch (RuntimeException internal) { + observer.onError(Status.INTERNAL.asRuntimeException()); + return; + } + try { + observer.onNext(result); + observer.onCompleted(); + } catch (RuntimeException callback) { + observer.onError(Status.INTERNAL.asRuntimeException()); + } + } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index 4d1d87e605..a4d6decec4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -66,6 +66,7 @@ import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner.Request; import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; +import net.firedevops.firemud.accountservice.service.impl.AccountTenantCapacityGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier.VerifiedCaller; import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner.AuthenticatedSignerCorrespondence; @@ -85,6 +86,7 @@ import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.gamesession.client.AccountPlayerAdmissionEntitlementClient; +import net.firedevops.firemud.gamesession.client.AccountTenantCapacityClient; import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; import net.firedevops.firemud.gamesession.service.FirstPartyConnectContext; @@ -371,7 +373,8 @@ void actualFirstJoinRetainsItsPositiveMembershipAndExactScopeBinding() { } @Test - void exactCapacityRefusalReplaysAfterHeadroomReturnsAndEvaluationExpires() { + void exactCapacityRefusalRemainsReadableAfterHeadroomReturnsAndEvaluationExpires() + throws Exception { Fixture f = fixture(true, true); var request = capacityRequest(f); long quota = request.evidence().quota(); @@ -472,6 +475,36 @@ void exactCapacityRefusalReplaysAfterHeadroomReturnsAndEvaluationExpires() { .intoMaps(); assertThat(retainedSlots).hasSize(1); assertThat(retainedSlots.get(0)).containsEntry("decision_id", decision.get()); + var pki = + LoopbackMtlsTestPki.create( + certificateDirectory, + "Retained quota denial read", + new LoopbackMtlsTestPki.IdentitySpec("client", PEER, false), + new LoopbackMtlsTestPki.IdentitySpec( + "account", "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service", true)); + var server = + new AccountTenantCapacityGrpcService(f.capacityOwner, NAMESPACE) + .createUnregisteredServer( + "127.0.0.1:0", + pki.keyManagerFactory(pki.identity("account")), + pki.trustManagerFactory()) + .start(); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + try (var recovered = + new AccountTenantCapacityClient( + endpoints, + pki.clientProperties(certificateDirectory, pki.identity("client")), + new GrpcChannelFactory(), + NAMESPACE, + f.clock)) { + recovered.init(); + assertThat(recovered.readRetainedQuotaDenial(request, f.clock.millis() + 5_000L)) + .isEqualTo(decision.get()); + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } assertThatThrownBy(() -> f.capacityOwner.commit(request, PEER)) .isInstanceOfSatisfying( CapacityException.class, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java index 61a29963a4..2d7c2b4ce9 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java @@ -89,6 +89,22 @@ void arbitraryPeerContextAndSessionClaimsNeverAuthenticate() throws Exception { } } + @Test + void quotaDenialReadRequiresExactGameSessionTlsWithoutAmbientAuthority() throws Exception { + var method = AccountServiceGrpc.getReadTenantCapacityQuotaDenialMethod(); + var gameSession = tls("firemud", "game-session-service"); + assertThat(invoke(method, gameSession, "spiffe://firemud/ns/firemud/sa/game-session-service")) + .isNull(); + assertThatThrownBy(guard::requireQuotaDenialReader).isInstanceOf(StatusRuntimeException.class); + assertThat(invoke(method, null).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(invoke(method, tls("firemud", "world-management-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(invoke(method, tls("other", "game-session-service")).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.setContext("caller", List.of(), Map.of()); + assertThat(invoke(method, gameSession).getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); + } + private Status invoke(MethodDescriptor method, SSLSession ssl) { return invoke(method, ssl, null); } @@ -105,7 +121,17 @@ private Status invoke(MethodDescriptor method, SSLSession ssl, String expectedCa AtomicInteger starts = new AtomicInteger(); ServerCallHandler next = (ignored, headers) -> { - assertThat(guard.requireAuthenticatedCaller()).isEqualTo(expectedCallerUri); + if (AccountServiceGrpc.getReadTenantCapacityQuotaDenialMethod() + .getFullMethodName() + .equals(method.getFullMethodName())) { + assertThat(guard.requireQuotaDenialReader()).isEqualTo(expectedCallerUri); + assertThatThrownBy(guard::requireAuthenticatedCaller) + .isInstanceOf(StatusRuntimeException.class); + } else { + assertThat(guard.requireAuthenticatedCaller()).isEqualTo(expectedCallerUri); + assertThatThrownBy(guard::requireQuotaDenialReader) + .isInstanceOf(StatusRuntimeException.class); + } starts.incrementAndGet(); return new ServerCall.Listener() {}; }; diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java index 685222f470..25147698a9 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockConstruction; @@ -15,25 +16,48 @@ import io.grpc.StatusRuntimeException; import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; +import java.sql.Connection; +import java.time.Clock; import java.util.UUID; import java.util.stream.Stream; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.CapacityException; import net.firedevops.firemud.accountservice.security.AccountTenantCapacityWorkloadGuard; import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; +import net.firedevops.firemud.common.account.capacity.CapacityAdmissionDigest; import net.firedevops.firemud.common.account.capacity.CapacityAdmissionTestFixture; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Failure; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmissionGrpcCodec.Refusal; +import org.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.jooq.Record; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import org.mockito.MockedConstruction; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; -/** Controlled handler classification only, not authenticated transport or owner-source proof. */ +/** Controlled handler and owner SQL-path tests, not physical database or mTLS proof. */ class AccountTenantCapacityGrpcServiceTest { + private enum RetainedEvidence { + EXACT_QUOTA_DENIAL, + ABSENT, + ACCEPTED, + GENERIC_NO_ACCEPT, + WRONG_FINGERPRINT + } + @Test void malformedWireAndStructurallyInvalidRequestsRefuseBeforeOwner() { var valid = @@ -181,6 +205,120 @@ void retainedQuotaDenialCarriesTheExactAccountDecision() { } } + @ParameterizedTest + @EnumSource(RetainedEvidence.class) + void quotaDenialReadUsesOnlyTheImmutableSelect(RetainedEvidence evidence) throws Exception { + var request = CapacityAdmissionTestFixture.playerRequest(); + var decisionId = UUID.randomUUID(); + DSLContext dsl = mock(); + Connection connection = mock(); + when(connection.isReadOnly()).thenReturn(true); + doAnswer( + invocation -> { + invocation.getArgument(0, ConnectionRunnable.class).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + Record row = evidence == RetainedEvidence.ABSENT ? null : mock(Record.class); + if (row != null) { + when(row.get("admission_attempt_id", UUID.class)).thenReturn(request.admissionAttemptId()); + when(row.get("mutation_digest", String.class)).thenReturn(request.mutationDigest()); + when(row.get("canonical_payload", byte[].class)) + .thenReturn( + evidence == RetainedEvidence.WRONG_FINGERPRINT + ? new byte[] {0} + : CapacityAdmissionDigest.preimage(request)); + when(row.get("decision_id", UUID.class)).thenReturn(decisionId); + when(row.get("decision", String.class)) + .thenReturn(evidence == RetainedEvidence.ACCEPTED ? "ACCEPTED" : "NO_ACCEPT"); + when(row.get("refusal_code", String.class)) + .thenReturn( + evidence == RetainedEvidence.ACCEPTED + || evidence == RetainedEvidence.GENERIC_NO_ACCEPT + ? null + : Failure.CAPACITY_QUOTA_EXCEEDED.name()); + } + String sql = + "SELECT * FROM account_capacity_origin_decisions WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND capacity_rearm_fence = ?"; + Object[] key = { + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.capacityRearmFence() + }; + when(dsl.fetchOne(sql, key)) + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); + return row; + }); + PlatformTransactionManager transactions = mock(); + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(invocation -> { + var definition = invocation.getArgument(0, TransactionDefinition.class); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getTimeout()).isEqualTo(5); + assertThat(definition.isReadOnly()).isTrue(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + return new SimpleTransactionStatus(); + }); + AccountRepository accounts = mock(); + AccountCanonicalRuntimeMembershipSnapshotRepository memberships = mock(); + AccountGameplayDelegationIssuanceRepository issuances = mock(); + AccountConnectScopeRepository scopes = mock(); + Clock clock = mock(); + var owner = + new AccountTenantCapacityOwner( + dsl, accounts, memberships, issuances, scopes, transactions, clock, "prod"); + StreamObserver observer = mock(); + try (var guards = quotaDenialReader(CapacityAdmissionTestFixture.PEER)) { + new AccountTenantCapacityGrpcService(owner, "prod") + .readTenantCapacityQuotaDenial( + TenantCapacityAdmissionGrpcCodec.toRequest(request), observer); + } finally { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + if (evidence == RetainedEvidence.EXACT_QUOTA_DENIAL) { + var response = ArgumentCaptor.forClass(CommitTenantCapacityAdmissionResponse.class); + var ordered = inOrder(observer); + ordered.verify(observer).onNext(response.capture()); + assertThat(TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response.getValue())) + .contains(new Refusal(Failure.CAPACITY_QUOTA_EXCEEDED, decisionId)); + ordered.verify(observer).onCompleted(); + } else { + assertFailure(observer, Failure.ENTITLEMENT_UNAVAILABLE); + } + verifyNoMoreInteractions(observer); + verify(dsl).connection(any(ConnectionRunnable.class)); + verify(dsl).fetchOne(sql, key); + verifyNoMoreInteractions(dsl); + verifyNoInteractions(accounts, memberships, issuances, scopes, clock); + } + + @Test + void quotaDenialReadRejectsWrongCallerBindingAndMalformedOriginalBeforeOwner() { + var request = CapacityAdmissionTestFixture.playerRequest(); + var wire = TenantCapacityAdmissionGrpcCodec.toRequest(request); + AccountTenantCapacityOwner owner = mock(); + try (var guards = quotaDenialReader("spiffe://firemud/ns/prod/sa/world-management-service")) { + StreamObserver observer = mock(); + new AccountTenantCapacityGrpcService(owner, "prod") + .readTenantCapacityQuotaDenial(wire, observer); + assertFailure(observer, Failure.PERMISSION_DENIED); + } + try (var guards = quotaDenialReader(CapacityAdmissionTestFixture.PEER)) { + StreamObserver observer = mock(); + new AccountTenantCapacityGrpcService(owner, "prod") + .readTenantCapacityQuotaDenial(wire.toBuilder().setCapacityDelta(0).build(), observer); + assertFailure(observer, Failure.INVALID_ARGUMENT); + } + verifyNoInteractions(owner); + } + private static Stream ownerUnavailableFailures() { return Stream.of( new CapacityException(Failure.ENTITLEMENT_UNAVAILABLE), @@ -207,6 +345,13 @@ private static MockedConstruction authentica when(guard.requireAuthenticatedCaller()).thenReturn(CapacityAdmissionTestFixture.PEER)); } + private static MockedConstruction quotaDenialReader( + String peer) { + return mockConstruction( + AccountTenantCapacityWorkloadGuard.class, + (guard, context) -> when(guard.requireQuotaDenialReader()).thenReturn(peer)); + } + private static void assertFailure( StreamObserver observer, Failure expected) { var error = ArgumentCaptor.forClass(Throwable.class); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java index 4996d9d043..13892d755d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClient.java @@ -12,7 +12,10 @@ import java.util.Objects; import java.util.UUID; import java.util.concurrent.TimeUnit; +import java.util.function.BiFunction; import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.AccountServiceGrpc.AccountServiceBlockingStub; +import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionResponse; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission; import net.firedevops.firemud.common.account.capacity.TenantCapacityAdmission.Request; @@ -66,10 +69,55 @@ public void init() throws IOException { * only replay this mutation with the exact original request when reconciliation permits it. */ public Result commit(Request request, long absoluteDeadlineMillis) { + var response = + invoke( + request, + absoluteDeadlineMillis, + AccountServiceBlockingStub::commitTenantCapacityAdmission); + try { + var refusal = TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response); + if (refusal.isPresent()) throw new CapacityRefusedException(refusal.orElseThrow()); + // Exact retry may replay an expired/terminal reservation. The final owner still checks it. + return TenantCapacityAdmissionGrpcCodec.requireResponse(request, response); + } catch (IllegalArgumentException inexactResponse) { + throw Status.UNKNOWN + .withDescription("Account capacity commitment response was inexact") + .asRuntimeException(); + } + } + + /** Recovers an exact quota denial while the caller still owns the original held attempt. */ + public UUID readRetainedQuotaDenial(Request request, long absoluteDeadlineMillis) { + var response = + invoke( + request, + absoluteDeadlineMillis, + AccountServiceBlockingStub::readTenantCapacityQuotaDenial); + try { + return TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response) + .filter(refusal -> + refusal.code() == TenantCapacityAdmissionGrpcCodec.Failure.CAPACITY_QUOTA_EXCEEDED) + .map(TenantCapacityAdmissionGrpcCodec.Refusal::durableDenialId) + .orElseThrow(IllegalArgumentException::new); + } catch (IllegalArgumentException inexactResponse) { + throw Status.UNKNOWN + .withDescription("Account retained quota denial was not proven") + .asRuntimeException(); + } + } + + private CommitTenantCapacityAdmissionResponse invoke( + Request request, + long absoluteDeadlineMillis, + BiFunction< + AccountServiceBlockingStub, + CommitTenantCapacityAdmissionRequest, + CommitTenantCapacityAdmissionResponse> + call) { long maximumMillis = TimeUnit.SECONDS.toMillis(TenantCapacityAdmissionGrpcCodec.CALL_DEADLINE_SECONDS); Deadline maximum = Deadline.after(maximumMillis, TimeUnit.MILLISECONDS); - requireNoAmbientSql("Capacity commitment requires no ambient SQL"); + requireNoAmbientSql("Capacity request requires no ambient SQL"); // Anchor conversion near the wall-clock sample, not at invocation entry. A pause // during sampling can only shorten the bound; it must never extend the caller budget. Deadline sampledAt = Deadline.after(0, TimeUnit.NANOSECONDS); @@ -85,33 +133,22 @@ public Result commit(Request request, long absoluteDeadlineMillis) { Context.current().getDeadline(), absoluteDeadlineMillis, sampledInstant); - CommitTenantCapacityAdmissionResponse response; try { - response = - withPublishedInitializedStub( - "Account capacity unavailable", - stub -> { - if (deadline.isExpired()) throw Status.DEADLINE_EXCEEDED.asRuntimeException(); - return stub.withDeadline(deadline) + return withPublishedInitializedStub( + "Account capacity unavailable", + stub -> { + if (deadline.isExpired()) throw Status.DEADLINE_EXCEEDED.asRuntimeException(); + var bounded = + stub.withDeadline(deadline) .withMaxOutboundMessageSize( TenantCapacityAdmissionGrpcCodec.MAX_REQUEST_WIRE_BYTES) .withMaxInboundMessageSize( - TenantCapacityAdmissionGrpcCodec.MAX_RESPONSE_WIRE_BYTES) - .commitTenantCapacityAdmission(wire); - }); + TenantCapacityAdmissionGrpcCodec.MAX_RESPONSE_WIRE_BYTES); + return call.apply(bounded, wire); + }); } catch (StatusRuntimeException failure) { throw TenantCapacityAdmissionGrpcCodec.validateFailure(failure); } - try { - var refusal = TenantCapacityAdmissionGrpcCodec.readRefusalDetails(request, response); - if (refusal.isPresent()) throw new CapacityRefusedException(refusal.orElseThrow()); - // Exact retry may replay an expired/terminal reservation. The final owner still checks it. - return TenantCapacityAdmissionGrpcCodec.requireResponse(request, response); - } catch (IllegalArgumentException inexactResponse) { - throw Status.UNKNOWN - .withDescription("Account capacity commitment response was inexact") - .asRuntimeException(); - } } /** Converts paired clock samples without resetting the invocation or incoming cap. */ diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index 4a112ad6dd..9fabb43b1b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -294,6 +294,55 @@ public void commitTenantCapacityAdmission( } } + @Test + void restartedClientRecoversTheOriginalQuotaDenialWithoutAnotherCommit() throws Exception { + var request = CapacityAdmissionTestFixture.playerRequest(); + var denialId = UUID.randomUUID(); + var commits = new AtomicInteger(); + var reads = new AtomicInteger(); + Server server = + startServer( + "account", + new AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest wire, + StreamObserver observer) { + commits.incrementAndGet(); + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } + + @Override + public void readTenantCapacityQuotaDenial( + CommitTenantCapacityAdmissionRequest wire, + StreamObserver observer) { + reads.incrementAndGet(); + assertThat(TenantCapacityAdmissionGrpcCodec.parseRequest(wire)).isEqualTo(request); + observer.onNext( + TenantCapacityAdmissionGrpcCodec.toRefusal( + request, + TenantCapacityAdmissionGrpcCodec.Failure.CAPACITY_QUOTA_EXCEEDED, + denialId)); + observer.onCompleted(); + } + }); + try { + try (var original = client(server)) { + original.init(); + assertThatThrownBy(() -> original.commit(request, deadline())) + .isInstanceOf(StatusRuntimeException.class); + } + try (var restarted = client(server)) { + restarted.init(); + assertThat(restarted.readRetainedQuotaDenial(request, deadline())).isEqualTo(denialId); + } + assertThat(commits).hasValue(1); + assertThat(reads).hasValue(1); + } finally { + stop(server); + } + } + @Test void localDenialReplayRequiresADurableDecisionId() { var denialId = UUID.randomUUID(); From 3fb4577e3b7e2f3329add1ad06a34f0e01d9c896 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:40:20 +1300 Subject: [PATCH 48/96] Keep the shared Account fixture closed to both private capacity RPCs --- ...ountRuntimeStubServerCompatibilityTest.java | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index 052cef8630..ba1b287749 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -47,9 +47,9 @@ class AccountRuntimeStubServerCompatibilityTest { "RequestEmailVerification", "VerifyEmail", "VerifyEmailLoginOtp"); - // Private runtime mutations require their actual bounded mTLS owner, never fake authority. + // Private capacity RPCs require their actual bounded mTLS owner. private static final Set UNIMPLEMENTED_RUNTIME_METHODS = - Set.of("CommitTenantCapacityAdmission"); + Set.of("CommitTenantCapacityAdmission", "ReadTenantCapacityQuotaDenial"); @Test void accountServiceMethodSetIsFullyCategorized() { @@ -72,17 +72,21 @@ void accountServiceMethodSetIsFullyCategorized() { } @Test - void privateCapacityMutationRemainsUnimplementedOnSharedFakeRuntimeServer() throws Exception { + void privateCapacityRpcsRemainUnimplementedOnSharedFakeRuntimeServer() throws Exception { assertThat(AccountRuntimeStubServer.implementedRuntimeMethodNames()) - .doesNotContain("CommitTenantCapacityAdmission"); + .doesNotContain("CommitTenantCapacityAdmission", "ReadTenantCapacityQuotaDenial"); try (AccountRuntimeStubServer server = new AccountRuntimeStubServer(0)) { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); try { var stub = AccountServiceGrpc.newBlockingStub(channel); - assertThatThrownBy(() -> - stub.commitTenantCapacityAdmission( - CommitTenantCapacityAdmissionRequest.getDefaultInstance())) + var request = CommitTenantCapacityAdmissionRequest.getDefaultInstance(); + assertThatThrownBy(() -> stub.commitTenantCapacityAdmission(request)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNIMPLEMENTED)); + assertThatThrownBy(() -> stub.readTenantCapacityQuotaDenial(request)) .isInstanceOfSatisfying( StatusRuntimeException.class, failure -> From 306260d9e6e549836c4b90fc5114fad2f78b46fa Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:59:32 +1300 Subject: [PATCH 49/96] Resolve the retained Account capacity and runtime review batch --- .github/workflows/dev-demo.yml | 13 ++- .github/workflows/runtime-images.yml | 48 ++++++++--- .github/workflows/smoke.yml | 80 ++++++++++++++++--- .../account-service/api-contracts.md | 2 +- .../account-service/runtime-and-data.md | 2 +- .../subscription-management.md | 2 +- .../game-session-service/runtime-and-data.md | 4 +- ...system-architecture-database-migrations.md | 10 ++- .../deploy/quiesce-v2-schema-migrations.sh | 14 ++-- .../deploy/run-dev-account-v1040-4-probe.sh | 4 +- .../dev-account-v1040-4-probe-contract.sh | 25 +++--- dev-tools/tests/dev-demo-workflow-contract.sh | 45 ++++++++--- ...hosted-v2-migration-activation-contract.sh | 6 ++ .../pr-required-gate-context-contract.sh | 38 ++++++++- .../tests/pr-retarget-workflow-contract.sh | 74 +++++++++++++---- .../pr-runtime-image-publication-contract.sh | 13 +++ ...v2-schema-migration-quiescence-contract.sh | 12 ++- .../AccountTenantCapacityOwnerTest.java | 29 ++++--- .../CapacityAdmissionTestFixture.java | 4 + .../AccountTenantCapacityClientMtlsTest.java | 4 + 20 files changed, 339 insertions(+), 90 deletions(-) diff --git a/.github/workflows/dev-demo.yml b/.github/workflows/dev-demo.yml index 3160676918..da5f43748e 100644 --- a/.github/workflows/dev-demo.yml +++ b/.github/workflows/dev-demo.yml @@ -985,16 +985,21 @@ jobs: - name: Summarize dev-demo failure if: ${{ always() && failure() && steps.cluster-access.outputs.available == 'true' }} env: + DEPLOY_OUTCOME: ${{ steps.deploy-release.outcome }} RECORD_OUTCOME: ${{ steps.record-deployed-head.outcome }} BOOTSTRAP_OUTCOME: ${{ steps.bootstrap-smoke.outcome }} run: | + failure_stage="${DEV_DEMO_STAGE:-unknown}" + if [[ "$DEPLOY_OUTCOME" == success && "$RECORD_OUTCOME" != success ]]; then + failure_stage=record-deployed-head + fi bash ./dev-tools/hosted/dev-demo/write-dev-demo-summary.sh \ failure \ "${{ needs.dev-demo-plan.outputs.head_sha }}" \ "${{ needs.dev-demo-plan.outputs.image_tag }}" \ "${{ needs.dev-demo-plan.outputs.hostname }}" \ "${{ needs.dev-demo-plan.outputs.telnet_port }}" \ - "${DEV_DEMO_STAGE:-unknown}" >> "$GITHUB_STEP_SUMMARY" + "$failure_stage" >> "$GITHUB_STEP_SUMMARY" if [[ "$RECORD_OUTCOME" == success ]]; then guide="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/blob/${GITHUB_WORKFLOW_SHA}/design/architecture/system-architecture-database-migrations.md#verification-after-the-dev-demo-target-is-recorded" { @@ -1006,6 +1011,12 @@ jobs: fi echo "Keep the recorded target and existing namespace. Do not replay Helm or bootstrap to verify this release." } >> "$GITHUB_STEP_SUMMARY" + elif [[ "$DEPLOY_OUTCOME" == success ]]; then + { + echo "" + echo "Helm deployment succeeded, but recording the deployed head on the namespace failed or could not be confirmed. Runtime qualification is incomplete." + echo "Do not retry the deployment, reset the namespace, or replay bootstrap. Before any recovery, the deployment owner must verify the original Helm release and revision, the owned dev namespace UID, and the retained Flyway version for each affected schema." + } >> "$GITHUB_STEP_SUMMARY" fi - name: Warn about migration writer recovery after quiesce, preflight or deploy failure diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 47305b10ac..8d71944a93 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -806,7 +806,8 @@ jobs: // The older PLAY diagnostic can leave the source run red. Only a // complete native attempt with its marker explicitly skipped can // prove that a failed producer did not supply that exception. - const provesOrdinaryTypedFailure = async (run, workflowName) => { + const provesOrdinaryTypedOutcome = async (run, workflowName) => { + const successful = run.conclusion === "success"; const repository = `${context.repo.owner}/${context.repo.repo}`; const matchesSelected = candidate => candidate && ["id", "workflow_id", "run_attempt", "path", "display_title", "event", "head_branch", "head_sha", "status", "conclusion"] @@ -816,17 +817,23 @@ jobs: const {data: attempt} = await github.rest.actions.getWorkflowRunAttempt(fanoutOptions({ ...context.repo, run_id: run.id, attempt_number: run.run_attempt, })); - if (!matchesSelected(attempt)) return false; + if (!matchesSelected(attempt) || successful && attempt.created_at !== run.created_at) { + if (successful) throw new Error(`Successful typed runtime producer ${run.id} has inconsistent exact attempt identity`); + return false; + } const {data} = await github.rest.actions.listJobsForWorkflowRunAttempt(fanoutOptions({ ...context.repo, run_id: run.id, attempt_number: run.run_attempt, per_page: 100, page: 1, })); - if (!Array.isArray(data?.jobs) || data.jobs.length > 100 || data.total_count !== data.jobs.length) return false; + if (!Array.isArray(data?.jobs) || data.jobs.length > 100 || data.total_count !== data.jobs.length) { + if (successful) throw new Error(`Successful typed runtime producer ${run.id} has incomplete exact attempt jobs`); + return false; + } const producers = data.jobs.filter(job => job?.name === "PR Full-Stack Smoke (runtime-required=true)"); const job = producers[0]; if (producers.length !== 1 || !Number.isSafeInteger(job.id) || job.id <= 0 || job.run_id !== run.id || job.run_attempt !== run.run_attempt || job.head_sha !== run.head_sha || ![workflowName, run.display_title].includes(job.workflow_name) || - job.status !== "completed" || job.conclusion !== "failure" || !Array.isArray(job.steps)) return false; + job.status !== "completed" || job.conclusion !== run.conclusion || !Array.isArray(job.steps)) return false; const markers = job.steps.filter(step => step?.name === "Known canonical transition PLAY failure with successful authenticated cleanup"); if (markers.length !== 1 || markers[0].status !== "completed" || markers[0].conclusion !== "skipped") return false; const timestamp = value => { @@ -847,7 +854,20 @@ jobs: if (!Number.isFinite(markerStart) || !Number.isFinite(markerEnd) || markerStart < jobStart || markerEnd < markerStart || markerEnd > jobEnd) return false; } + if (successful) { + // A green run or job alone can be a no-op or the diagnostic exception. + // Require affirmative ordinary smoke and authenticated cleanup in this attempt. + for (const name of ["Run credential-free full-stack smoke", "Stop smoke stack", + "Require successful runtime smoke and authenticated cleanup"]) { + const steps = job.steps.filter(step => step?.name === name); + if (steps.length !== 1 || steps[0].status !== "completed" || steps[0].conclusion !== "success") return false; + } + if (job.steps.some(step => step?.status !== "completed" || !["success", "skipped"].includes(step.conclusion))) return false; + } const {data: latest} = await github.rest.actions.getWorkflowRun(fanoutOptions({...context.repo, run_id: run.id})); + if (successful && (!matchesSelected(latest) || latest.created_at !== run.created_at)) { + throw new Error(`Successful typed runtime producer ${run.id} changed during exact attempt proof`); + } return matchesSelected(latest); }; // Bind both admission reads to the same terminal attempt; never cache native proof. @@ -900,7 +920,7 @@ jobs: return [newest]; } if (newest.status === "completed") { - if (newest.event === "repository_dispatch" && ["cancelled", "timed_out", "failure"].includes(newest.conclusion)) { + if (newest.event === "repository_dispatch" && ["cancelled", "timed_out", "failure", "success"].includes(newest.conclusion)) { const repository = `${context.repo.owner}/${context.repo.repo}`; const defaultBranch = context.payload.repository?.default_branch; const attemptBinding = JSON.stringify([ @@ -932,16 +952,26 @@ jobs: latest.conclusion !== newest.conclusion) { throw new Error(`Terminal typed runtime producer ${newest.id} no longer has the same trusted terminal attempt`); } - if (newest.conclusion === "failure" && !await provesOrdinaryTypedFailure(latest, workflow.name)) { - return [newest]; + if (["success", "failure"].includes(newest.conclusion)) { + const ordinary = await provesOrdinaryTypedOutcome(latest, workflow.name); + if (newest.conclusion === "success" ? ordinary : !ordinary) return [newest]; + } + // A recent success can be a validated transition diagnostic or + // awaiting downstream evidence. Preserve its existing hold. + if (newest.conclusion === "success") { + const ciCompleted = Date.parse(workflowRun.updated_at || ""); + if (!Number.isFinite(ciCompleted) || + Math.floor(Date.parse(newest.created_at) / 1000) >= Math.floor(ciCompleted / 1000)) { + return [newest]; + } } disregardedTypedAttempts.set(newest.id, attemptBinding); // Discarding an unusable replacement does not establish // absence: an earlier exact producer may still be running. continue; } - // Same-second or incomparable completion evidence is ambiguous and - // suppresses a duplicate; only a valid, strictly older producer may recover. + // Keep the existing chronological hold for other dispositions. A + // successful exact typed attempt is classified by proof, not creation time. const ciCompleted = Date.parse(workflowRun.updated_at || ""); if (newest.event === "repository_dispatch" && (!Number.isFinite(ciCompleted) || diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index d6ffca8b1f..f12e3e5af1 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -632,7 +632,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "094ece17d1b7418151b808959028fea2584f434629e1c5f1e5bfaed3cebeeb3c"; + const canonicalRuntimeWorkflowSha256 = "05571b3b89ea77cdff497aa8f93bea13d10de12300c205a42e32da00d81dd98d"; // Only authenticated default-branch refreshes may use retained successful definitions. // Keep the pre-rollout default and predecessor definitions for mixed-version runs. const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set([ @@ -1238,11 +1238,11 @@ jobs: // Cancellation/timeout grants waiting time, never smoke proof. Even that bounded // recovery requires an attributable native typed producer for this tuple. - function isReplaceableTypedProducer(run, identity) { + function isReplaceableTypedProducer(run, identity, conclusions = ["cancelled", "timed_out"]) { const title = `Build Runtime Images secure-pr-artifact pr-${prNumber} ` + `base-${identity.baseSha} head-${identity.headSha} merge-${identity.mergeSha} mode-required`; return run.event === "repository_dispatch" && run.status === "completed" && - ["cancelled", "timed_out"].includes(run.conclusion) && positiveInteger(run.id) && positiveInteger(run.run_attempt) && + conclusions.includes(run.conclusion) && positiveInteger(run.id) && positiveInteger(run.run_attempt) && positiveInteger(run.workflow_id) && run.repository?.full_name === repositoryName && run.head_repository?.full_name === repositoryName && isRuntimeSourceWorkflowPath(run.path, run.event, prNumber) && run.display_title === title && @@ -1252,6 +1252,60 @@ jobs: typeof run.head_sha === "string" && /^[0-9a-f]{40}$/.test(run.head_sha); } + // Match the dispatcher's release of a failed typed attempt. This disposition + // only buys time for a replacement; it cannot attest smoke or the PLAY exception. + async function provesOrdinaryTypedFailure(run, identity) { + if (!isReplaceableTypedProducer(run, identity, ["failure"]) || + !["Build Runtime Images", run.display_title].includes(run.name)) return false; + const matchesSelected = candidate => candidate && + ["id", "workflow_id", "run_attempt", "path", "display_title", "event", "head_branch", "head_sha", + "created_at", "status", "conclusion"].every(field => candidate[field] === run[field]) && + ["Build Runtime Images", run.display_title].includes(candidate.name) && + candidate.repository?.full_name === repositoryName && candidate.head_repository?.full_name === repositoryName; + const {data: workflow} = await withTransientGitHubRetry("failed typed runtime workflow identity lookup", + () => github.rest.actions.getWorkflow({owner, repo, workflow_id: "runtime-images.yml"})); + if (workflow?.id !== run.workflow_id || workflow.path !== workflowPath || + workflow.name !== "Build Runtime Images") return false; + const {data: attempt} = await withTransientGitHubRetry("failed typed exact attempt lookup", + () => github.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}", { + owner, repo, run_id: run.id, attempt_number: run.run_attempt, + })); + if (!matchesSelected(attempt)) return false; + const {data} = await withTransientGitHubRetry("failed typed exact attempt jobs lookup", + () => github.rest.actions.listJobsForWorkflowRunAttempt({ + owner, repo, run_id: run.id, attempt_number: run.run_attempt, per_page: 100, page: 1, + })); + if (!Array.isArray(data?.jobs) || data.jobs.length > 100 || data.total_count !== data.jobs.length) return false; + const producers = data.jobs.filter(job => job?.name === canonicalSmokeJobName); + const job = producers[0]; + if (producers.length !== 1 || !positiveInteger(job.id) || job.run_id !== run.id || + job.run_attempt !== run.run_attempt || job.head_sha !== run.head_sha || + ![workflow.name, run.display_title].includes(job.workflow_name) || + job.status !== "completed" || job.conclusion !== "failure" || !Array.isArray(job.steps)) return false; + const markers = job.steps.filter(step => + step?.name === "Known canonical transition PLAY failure with successful authenticated cleanup"); + if (markers.length !== 1 || markers[0].status !== "completed" || markers[0].conclusion !== "skipped") return false; + const timestamp = value => { + const match = typeof value === "string" && /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?(Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.exec(value); + const time = match ? Date.parse(value) : NaN; + const wall = match ? `${match[1]}.${(match[2] || "").padEnd(3, "0")}Z` : ""; + const wallMillis = Date.parse(wall); + return Number.isFinite(time) && Number.isFinite(wallMillis) && new Date(wallMillis).toISOString() === wall ? time : NaN; + }; + const [start, jobStart, jobEnd, end] = [attempt.run_started_at, job.started_at, job.completed_at, attempt.updated_at].map(timestamp); + if (![start, jobStart, jobEnd, end].every(Number.isFinite) || end < start || + jobStart < Math.floor(start / 1000) * 1000 || jobEnd < jobStart || jobEnd > Math.floor(end / 1000) * 1000 + 999) return false; + const marker = markers[0]; + if (marker.started_at != null || marker.completed_at != null) { + const markerStart = timestamp(marker.started_at), markerEnd = timestamp(marker.completed_at); + if (!Number.isFinite(markerStart) || !Number.isFinite(markerEnd) || + markerStart < jobStart || markerEnd < markerStart || markerEnd > jobEnd) return false; + } + const {data: latest} = await withTransientGitHubRetry("current failed typed attempt lookup", + () => github.rest.actions.getWorkflowRun({owner, repo, run_id: run.id})); + return matchesSelected(latest); + } + async function verifyFailedPullCanonicalRefresh(run, identity) { if (repositoryName !== "benhook1013/FireMUD" || context.payload.pull_request.head.repo?.full_name !== repositoryName || @@ -1282,6 +1336,7 @@ jobs: if (replacement.run_attempt == null || replacement.conclusion == null) { return {status: "snapshot-pending", run: proofRun}; } + if (await provesOrdinaryTypedFailure(replacement, identity)) return "replaceable-failure"; const jobs = await withTransientGitHubRetry("canonical transition refresh jobs lookup", () => github.paginate("GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", { owner, repo, run_id: replacement.id, attempt_number: replacement.run_attempt, per_page: 100, @@ -1761,8 +1816,10 @@ jobs: replacement.run_attempt !== cancelledReplacement.run_attempt)) { cancelledReplacement = {id: replacement.id, run_attempt: replacement.run_attempt, terminalObservedAt: null}; } - if (replacement.status === "completed" && ["cancelled", "timed_out"].includes(replacement.conclusion)) { - if (!isReplaceableTypedProducer(replacement, currentIdentity)) { + const cancelledOrTimedOut = replacement.status === "completed" && + ["cancelled", "timed_out"].includes(replacement.conclusion); + if (cancelledOrTimedOut || await provesOrdinaryTypedFailure(replacement, currentIdentity)) { + if (cancelledOrTimedOut && !isReplaceableTypedProducer(replacement, currentIdentity)) { core.setFailed("Cancelled or timed-out typed runtime producer has an invalid source identity."); return; } @@ -1951,9 +2008,10 @@ jobs: await new Promise((resolve) => setTimeout(resolve, snapshotSleepMs)); continue smokeGatePolling; } - if (matching.event === "repository_dispatch" && matching.status === "completed" && - ["cancelled", "timed_out"].includes(matching.conclusion)) { - if (!isReplaceableTypedProducer(matching, currentIdentity)) { + const cancelledOrTimedOut = matching.event === "repository_dispatch" && matching.status === "completed" && + ["cancelled", "timed_out"].includes(matching.conclusion); + if (cancelledOrTimedOut || await provesOrdinaryTypedFailure(matching, currentIdentity)) { + if (cancelledOrTimedOut && !isReplaceableTypedProducer(matching, currentIdentity)) { core.setFailed("Cancelled or timed-out typed runtime producer has an invalid source identity."); return; } @@ -1963,7 +2021,9 @@ jobs: cancelledTypedRecoveryObservedAt = Date.now(); } if (Date.now() - cancelledTypedRecoveryObservedAt >= refreshDiscoveryTimeoutMs) { - core.setFailed("Cancelled or timed-out typed runtime producer has no newer exact producer within the recovery allowance."); + core.setFailed(cancelledOrTimedOut + ? "Cancelled or timed-out typed runtime producer has no newer exact producer within the recovery allowance." + : "Failed typed runtime producer has no newer exact producer within the recovery allowance."); return; } core.info(`Exact typed runtime producer ${matching.id}/${matching.run_attempt} ended ${matching.conclusion}; waiting for a newer exact producer.`); @@ -2048,7 +2108,7 @@ jobs: } const refreshProof = await verifyFailedPullCanonicalRefresh(matching, currentIdentity); const refreshKey = `${matching.id}:${identityKey(currentIdentity)}`; - const replaceableRefresh = ["cancelled", "timed_out"].includes(refreshProof); + const replaceableRefresh = ["cancelled", "timed_out", "replaceable-failure"].includes(refreshProof); if (replaceableRefresh) discoveredRefreshKey = null; if ((refreshProof === "absent" && discoveredRefreshKey !== refreshKey) || replaceableRefresh) { const missingKey = refreshKey; diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index b7b4fc8842..7c7576d4b4 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -233,7 +233,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 canonical Account UUIDs. Account resolves known subjects through one local UUID batch query with the same persisted provenance and source-row checks as scalar identity reads, then returns policies keyed by UUID. Unknown or unproven entries are intentionally omitted so Social applies complete `PRIVATE` redaction. - `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current gRPC adapter returns `FAILED_PRECONDITION` before selector parsing or owner reads; this does not implement the target export operation. -- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry of the currently bound reservation attempt, fence, complete payload and digest replays its durably retained result. A request outside the proof-backed rearm contract that changes a bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest returns an idempotency conflict before usage mutation. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns the typed `TENANT_BILLING_BLOCKED` response. This billing refusal does not consume the quota-refusal budget or create a durable decision receipt; it remains available when no refusal-budget row exists. Fresh creation-eligible evidence with checked insufficient capacity returns the typed `CAPACITY_QUOTA_EXCEEDED` response only after the exact durable `NO_ACCEPT` decision commits. If its refusal budget is missing or exhausted, Account returns non-OK `ENTITLEMENT_UNAVAILABLE` instead; no quota receipt or settlement authority is issued. Each refusal is bound to the exact original attempt, mutation digest, snapshot and evaluation. A quota refusal includes the immutable Account decision UUID only after an exact durable `NO_ACCEPT` commits. A matching exact retry returns the retained receipt. A quota refusal without that receipt grants no evidence settlement authority. The response contains exactly one commitment or one typed refusal. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a changed exact retry. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry of the currently bound reservation attempt, fence, complete payload and digest replays its durably retained result. Outside proof-backed rearm, a change to a bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest conflicts before usage mutation only if it differs from an existing retained binding. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns the typed `TENANT_BILLING_BLOCKED` response. This billing refusal does not itself bind the attempt, consume the quota-refusal budget, or create a durable decision receipt; it remains available when no refusal-budget row exists. Fresh creation-eligible evidence with checked insufficient capacity returns the typed `CAPACITY_QUOTA_EXCEEDED` response only after the exact durable `NO_ACCEPT` decision commits. If its refusal budget is missing or exhausted, Account returns non-OK `ENTITLEMENT_UNAVAILABLE` instead; no quota receipt or settlement authority is issued. Each refusal response is correlated to the exact original attempt, mutation digest, snapshot and evaluation. A quota refusal includes the immutable Account decision UUID only after an exact durable `NO_ACCEPT` commits. A matching exact retry returns the retained receipt. A quota refusal without that receipt grants no evidence settlement authority. The response contains exactly one commitment or one typed refusal. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a mismatch against an existing retained binding outside proof-backed rearm. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact retries of the currently bound attempt, fence, complete payload and digest replay its durably retained reservation result; superseded pre-rearm attempts do not replay after a committed rearm. This reservation rule is separate from replay of an exact retained quota-denial decision, which has no reservation. A changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. Exact replay is guaranteed only for outcomes Account durably retained. A billing or non-creating entitlement refusal that did not retain a decision receipt is not a replayable outcome; a later retry rechecks current evidence freshness before deciding and cannot treat the earlier refusal as a retained result. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index f9ead5fcca..0c433d9f79 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -94,7 +94,7 @@ Pre-v1 Account reset or deletion remains only the proposal in [ADR 0185](../../d V1040.6 backfills one immutable refusal slot per retained `NO_ACCEPT` decision as the contiguous sequence `1..N`. After origin identity arbitration, a fresh refusal takes the existing tenant budget lock, reads the highest slot through the tenant-slot index, and appends `N+1` in the same transaction. `requireReady` uses that indexed highest slot as the retained refusal count under this invariant to compute bounded headroom; the missing or mismatched budget and insufficient headroom remain fail-closed. Replay, conflict, and failed inserts leave the inventory unchanged. The migration preserves origin rows and provisioned limits. -The unregistered capacity owner requires exact retained evidence and current Account membership/issuance/scope source equality before creating a new positive player-binding reservation. Exact attempt retries replay only durably retained outcomes before fresh-source or usage work; changed complete payloads conflict. A non-retained billing denial is not replayable and requires fresh current evidence on retry. The Account recovery component alone can finalize, release or rearm under its current durable claim and exact selected-owner readback; an ambiguous observation records only the bounded retry/deadline and retains the hold. No runtime readback producer or recovery client is registered. World lifecycle, authoritative prior-shape/zero-delta recovery, current selected-owner activation and complete end-to-end qualification remain held as detailed in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). +The unregistered capacity owner requires exact retained evidence and current Account membership/issuance/scope source equality before creating a new positive player-binding reservation. Before fresh-source or usage work, exact attempt retries replay durably retained outcomes, and changed payloads conflict with an existing retained binding. A non-retained billing refusal does not itself bind the attempt for replay or conflict; a retry still requires fresh current evidence. The Account recovery component alone can finalize, release or rearm under its current durable claim and exact selected-owner readback; an ambiguous observation records only the bounded retry/deadline and retains the hold. No runtime readback producer or recovery client is registered. World lifecycle, authoritative prior-shape/zero-delta recovery, current selected-owner activation and complete end-to-end qualification remain held as detailed in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). The canonical gameplay LOGIN primary-credential adapter reuses Account’s password and email-OTP authority without creating a legacy token or session. Its owner transaction retains the verified challenge identity and consumes it only after new PENDING issuance; denial accounting and expiry cleanup commit under the existing owner denial path. Exact pending retry does not reverify or reconsume. Canonical-only verification pads to two KDF comparisons with non-authorizing process-local random decoy evidence using the existing Argon2 profile. The adapter participates only in the explicitly enabled protected LOGIN composition; default deployment behavior remains unchanged. Focused unit and real PostgreSQL proof and its controlled upstream/external-owner limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). Deployed authenticated issuance and timing parity remain unproved. diff --git a/design/architecture/microservices/account-service/subscription-management.md b/design/architecture/microservices/account-service/subscription-management.md index 3c6ee18739..b98c53c999 100644 --- a/design/architecture/microservices/account-service/subscription-management.md +++ b/design/architecture/microservices/account-service/subscription-management.md @@ -205,7 +205,7 @@ Downstream services depend on billing events for timely entitlement enforcement, - **Periodic refresh** – even when events are flowing, every healthy runtime consumer must refresh or reconcile cached entitlements at least once per 60 seconds so extended event outages meet the `<=60-second` delayed/missed-event SLA rather than causing unbounded drift. - `CreateSubscription` – Create one hosting subscription for an immutable `tenantId` and initial `plan_code`. The caller supplies a high-entropy stable `requestId`; Account resolves the authoritative billing owner and computes and persists a versioned `requestDigest` from the normalized create tuple, including that owner, immutable `tenantId`, initial `plan_code`, and exact instrument-selection input. The digest and resolved billing owner are not request fields. A retry with the same `requestId` and normalized create fields recomputes the same digest and replays the same durable operation and outcome; changed fields that produce a different digest return `IDEMPOTENCY_CONFLICT`; the caller identity is distinct from provider operation identities. It rejects an existing `subscriptionId`, expected row version, update operation ID, or any other update-only field. Creation must resolve the authoritative billing owner before its subscription row exists, capture the owner's authority version/generation, authorize the actor against that resolved owner (or require the explicit audited cross-tenant handoff), and require either an explicit saved `paymentInstrumentId` or deterministic instrument-selection input that resolves to exactly one saved instrument owned by that owner. In one local Account transaction, Account locks or CAS-validates the resolved owner and exact captured version/generation before committing the subscription operation, immutable internal `subscriptionId` and `tenantId`, owner, owner fence, customer-operation reference, confirmed provider customer when available, instrument binding and reserved instrument version, `pending` status, immutable `subscription_provisioning_request_id`, separate cleanup/cancellation provider-operation identity, and outbox work item before customer reconciliation or provider creation. An owner-fence mismatch fails closed before any provider operation. The worker may reconcile the customer operation while the row remains pending, but its provisioning claim atomically requires a confirmed matching customer and revalidates ownership, exact instrument version, and attachability; detach racing with provisioning is serialized by that reservation/version boundary and a stale claim fails before Stripe. Creation retries retain the creation identity for lookup; cleanup retries reuse the distinct cleanup identity. Stripe customer and provider defaults are prohibited. -- `CommitTenantCapacityAdmission` – Target Account-owned internal RPC and final capacity fence described above. Its canonical callers are Game Session and World Management; it requires stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by evaluation, bounded `capacityDelta`, and a versioned `mutationDigest` over the attempt identity, fence, and complete payload. An exact identity-and-payload retry replays; any changed bundle version, snapshot/evaluation identity, entitlement field, tuple, cutoff, checkpoint, delta, attempt ID, fence, or digest conflicts before usage mutation. The initial attempt needs no rearm CAS. A new attempt requires an Account-owned CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; that CAS advances the fence without creating a second reservation. Stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. It is the only contract that can turn a fresh entitlement snapshot into a strict capacity commitment. Downstream owners cannot replace it with a local compare or cached flag. The shared contract, Account durable owner and private receiver, and Game Session adapter are locally prepared without runtime registration or qualification; current source/proof limits remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +- `CommitTenantCapacityAdmission` – Target Account-owned internal RPC and final capacity fence described above. Its canonical callers are Game Session and World Management; it requires stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by evaluation, bounded `capacityDelta`, and a versioned `mutationDigest` over the attempt identity, fence, and complete payload. An exact identity-and-payload retry replays a retained outcome; a change to an existing retained binding outside proof-backed rearm conflicts before usage mutation. A non-retained billing refusal does not create such a binding. The initial attempt needs no rearm CAS. A new attempt on an existing reservation requires an Account-owned CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; that CAS advances the fence without creating a second reservation. Stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. It is the only contract that can turn a fresh entitlement snapshot into a strict capacity commitment. Downstream owners cannot replace it with a local compare or cached flag. The shared contract, Account durable owner and private receiver, and Game Session adapter are locally prepared without runtime registration or qualification; current source/proof limits remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `UpdateSubscription` – Apply one plan, instrument, cancellation, or other supported update to an existing immutable `subscriptionId`. Period-end and immediate cancellation both use this mutation; no separate `CancelSubscription` mutation exists. It requires the target subscription identity, a distinct immutable operation-specific request ID, and the expected subscription row version/CAS; it rejects `subscription_provisioning_request_id`, creation-only fields, and any attempted `tenantId` change. Retries reuse the same update identity and guard and never reuse the initial provisioning identity. Provider activation and billing require a confirmed provider subscription ID. Caller-bound tenant variants derive actor identity from auth context; cross-tenant admin variants are separate APIs. - `GetSubscriptionTenantHighLevel` / `ListSubscriptionsTenantHighLevel` – Query subscription state for one tenant, scoped by tenant authorization. - `ListSubscriptionsCrossTenantSupportSafe` – Cross-tenant support-safe high-level listing for troubleshooting only. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index a1d439efa5..5242be5a92 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -14,9 +14,9 @@ The exact current Game Session owner establishes irreversible closure of serving The target Game Session owner persists the teardown identity and progress in its own PostgreSQL storage, then retains the immutable terminal evidence under that same identity. A replacement worker reads the persisted progress and exact receipt rather than reconstructing either from Redis, an in-memory job or the current binding alone. The receipt binds the original admission, FINAL evidence, binding lineage and exact Account reservation; conflicting identities or stale owner fences must be refused. After a lost or ambiguous Account response, that retained receipt and its original fence remain historical immutable evidence, not present sender authority: redelivery is performed only by the currently authenticated replacement owner under its current owner authority, without replacing or advancing the original teardown identity or receipt fence. -Each applicable settlement must either commit atomically with its Game Session progress record in the same owner-local transaction, or expose exact durable owner readback under an immutable sub-operation identity and request digest retained before dispatch. For an already-admitted effect, retain its original mutation identity and participant binding under the [effect reconciliation contract](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects); teardown must not allocate a replacement effect. If settlement commits but its response or progress update is lost, the replacement owner reads that exact outcome and persists the recovered progress before completing the terminal receipt. The teardown identity, a missing progress row, a timeout or Redis absence alone proves neither settlement nor no-commit. Unavailable, ambiguous or mismatched owner evidence keeps teardown unresolved, serving and resume closed, and the corresponding Account used units unretired. A settlement without either recovery boundary blocks retirement qualification. +Irreversible closure of serving and resume and each applicable settlement must either commit atomically with its Game Session progress record in the same owner-local transaction, or expose exact durable owner readback under an immutable sub-operation identity and request digest retained before dispatch. For an already-admitted effect, retain its original mutation identity and participant binding under the [effect reconciliation contract](../../system-architecture-transactions.md#reconciliation-owner-of-record-spatialambient-effects); teardown must not allocate a replacement effect. If the fence holder crashes after external closure or settlement completes but before writing progress, the replacement uses the existing closure or settlement authority to read back that exact outcome and persist the recovered progress before completing the terminal receipt. Any retry uses the same sub-operation identity and existing idempotence rules. The teardown identity, a missing progress row, a timeout or Redis absence alone proves neither completion nor no-commit. Unavailable, ambiguous or mismatched owner evidence keeps teardown unresolved, serving and resume closed, and the corresponding Account used units unretired. Closure or settlement without either recovery boundary blocks retirement qualification. -Qualification must prove a restart after irreversible closure or settlement but before the terminal receipt exists, then verify the replacement completes that same teardown from durable progress with serving and resume still closed. For every independently committing settlement, also prove settlement commit followed by response loss and a crash before progress persistence: the replacement must recover the exact original owner outcome without a second logical settlement or a new sub-operation identity. Separately prove restart before send, Account commit followed by response loss and worker restart, and exact receipt replay without a second decrement. Account—not Game Session—atomically retains the retirement receipt and decrements used capacity. Wrong identity or fence must fail closed, and no failure or retry may reopen serving or resume. These are acceptance requirements, not claims that the target path or its restart proof exists today. +Qualification must prove a restart after irreversible closure or settlement but before the terminal receipt exists, then verify the replacement completes that same teardown from durable progress with serving and resume still closed. For independently committing closure and for every independently committing settlement, also prove completion followed by response loss and a crash before progress persistence: the replacement must recover the exact original owner outcome without repeating the logical operation or using a new sub-operation identity. Separately prove restart before send, Account commit followed by response loss and worker restart, and exact receipt replay without a second decrement. Account—not Game Session—atomically retains the retirement receipt and decrements used capacity. Wrong identity or fence must fail closed, and no failure or retry may reopen serving or resume. These are acceptance requirements, not claims that the target path or its restart proof exists today. ## Implementation Status diff --git a/design/architecture/system-architecture-database-migrations.md b/design/architecture/system-architecture-database-migrations.md index e46556fec7..69a22ff59d 100644 --- a/design/architecture/system-architecture-database-migrations.md +++ b/design/architecture/system-architecture-database-migrations.md @@ -254,10 +254,12 @@ Migration changes use the canonical [Validation and Runtime Proof](../developer- The trusted workflow records `firemud.dev/last-dev-demo-head-sha` after staged deployment succeeds, before the remaining readiness, bootstrap and TCP smoke steps. That annotation records deployment, not successful runtime qualification. The [deployment classifier](../../dev-tools/deploy/detect-hosted-v2-migration-activation.sh) deliberately refuses the same target SHA; do not clear, rewind or replace the annotation, reset the namespace, or rerun Helm merely to repeat validation. The verification-only procedure below applies to an existing release whose original smoke-account bootstrap completed; it is not a workflow-resume or bootstrap-recovery mechanism. An authorized operator may verify that release and repeat only its remaining checks: -1. Recover the exact target SHA, namespace, release name, image identities, selected certificate profile, rendered manifest and values from the original deployment record. Verify that the namespace is the owned `dev` environment and its annotation still equals that SHA. Read the existing Helm release status, revision and manifest, and compare the running workloads and image identities with that exact release. A changed release, mixed target, incomplete deployment or ambiguous namespace stops verification and requires deployment-owner recovery; this procedure neither deploys nor authorizes repair. -2. Have each affected database owner verify the actual configured service schema and Flyway history against the target's immutable migration set, including exact versions, script names, checksums and successful installation. Retain that read-only result with the original deployment record. Missing, failed or contradictory history blocks continuation. Do not use `flywayRepair`, edit history, rerun migrations or infer migration success from the namespace annotation or Pod readiness. -3. Repeat the remaining readiness checks from the [trusted dev-demo workflow](../../.github/workflows/dev-demo.yml), using its original runtime/requester credential separation and selected certificate profile. The existing [`wait-for-hosted-runtime-rollouts.sh`](../../dev-tools/hosted/shared/wait-for-hosted-runtime-rollouts.sh) accepts `dev 120`. For the hosted-controller profile, also run [`wait-for-hosted-identity.sh`](../../dev-tools/hosted/preview/wait-for-hosted-identity.sh) with `dev-demo`, the exact target SHA, `dev` and `900`, then the workflow's operator `hosted-bridge` preflight against the retained rendered artifact, release and Telnet NodePort. Verify the workflow's application readiness endpoints too; rollout completion alone is not application readiness. Missing original inputs or any failed readiness check leaves qualification incomplete. -4. Confirm that the original smoke-account bootstrap completed and use that existing account, world, hostname, port and TLS trust configuration with [`hosted-login-look-smoke.sh`](../../dev-tools/hosted/shared/hosted-login-look-smoke.sh). Supply the original `SMOKE_TELNET_HOST`, `TCP_PORT`, `SMOKE_LOGIN_EMAIL`, `SMOKE_PASSWORD`, `SMOKE_WORLD` and any explicit CA input through their protected channels; never print credentials or weaken TLS or expected `LOGIN`/`PLAY`/`LOOK` outcomes. If bootstrap did not complete, stop for separately authorized Account/bootstrap recovery rather than creating replacement data as part of verification. Retain the new readiness results and smoke transcript against the same target and release, explicitly separate from the original failed run. A failed repeat remains failed qualification; it is not permission to reset or redeploy. +1. Arrange an exclusive verification window with the dev-demo deployment owner before the first readback. The owner must exclude concurrent deploys, destroys, reconciler redispatches, and manual mutations of the release or runtime namespace until the final readback. If that window cannot be secured or maintained, stop; readbacks alone cannot rule out an intervening change. +2. Recover the exact target SHA, namespace UID, Helm release name and revision, image identities, selected certificate profile, rendered manifest and values from the original deployment evidence. Before collecting new evidence, verify and record the exact Helm revision, owned `dev` namespace UID, and target SHA from its deployed-head annotation against that original deployment. Read the existing Helm release status and manifest and compare the running workloads and image identities with that exact revision. Missing original identities, a changed release, mixed target, incomplete deployment or ambiguous namespace stops verification and requires deployment-owner recovery; this procedure neither deploys nor authorizes repair. +3. Have each affected database owner verify the actual configured service schema and Flyway history against the target's immutable migration set, including exact versions, script names, checksums and successful installation. Retain that read-only result with the original deployment record. Missing, failed or contradictory history blocks continuation. Do not use `flywayRepair`, edit history, rerun migrations or infer migration success from the namespace annotation or Pod readiness. +4. Repeat the remaining readiness checks from the [trusted dev-demo workflow](../../.github/workflows/dev-demo.yml), using its original runtime/requester credential separation and selected certificate profile. The existing [`wait-for-hosted-runtime-rollouts.sh`](../../dev-tools/hosted/shared/wait-for-hosted-runtime-rollouts.sh) accepts `dev 120`. For the hosted-controller profile, also run [`wait-for-hosted-identity.sh`](../../dev-tools/hosted/preview/wait-for-hosted-identity.sh) with `dev-demo`, the exact target SHA, `dev` and `900`, then the workflow's operator `hosted-bridge` preflight against the retained rendered artifact, release and Telnet NodePort. Verify the workflow's application readiness endpoints too; rollout completion alone is not application readiness. Missing original inputs or any failed readiness check leaves qualification incomplete. +5. Confirm that the original smoke-account bootstrap completed and use that existing account, world, hostname, port and TLS trust configuration with [`hosted-login-look-smoke.sh`](../../dev-tools/hosted/shared/hosted-login-look-smoke.sh). Supply the original `SMOKE_TELNET_HOST`, `TCP_PORT`, `SMOKE_LOGIN_EMAIL`, `SMOKE_PASSWORD`, `SMOKE_WORLD` and any explicit CA input through their protected channels; never print credentials or weaken TLS or expected `LOGIN`/`PLAY`/`LOOK` outcomes. If bootstrap did not complete, stop for separately authorized Account/bootstrap recovery rather than creating replacement data as part of verification. +6. After collecting the readiness and smoke evidence and before releasing the window, read back and record the same Helm revision, owned namespace UID, and deployed target SHA. If any identity differs or cannot be verified, the new evidence does not qualify the release. Retain the before and after identities, readiness results, and smoke transcript together, explicitly separate from the original failed run. A failed repeat remains failed qualification; it is not permission to reset or redeploy. ### Cross-Service Identifier Migration diff --git a/dev-tools/deploy/quiesce-v2-schema-migrations.sh b/dev-tools/deploy/quiesce-v2-schema-migrations.sh index 75d509efbf..a6486cad8a 100644 --- a/dev-tools/deploy/quiesce-v2-schema-migrations.sh +++ b/dev-tools/deploy/quiesce-v2-schema-migrations.sh @@ -62,7 +62,7 @@ trap leave_admission_closed_on_failure EXIT service_json() { local service="$1" local result - if ! result="$(kubectl -n "$namespace" get service "$service" --ignore-not-found -o json)"; then + if ! result="$(kubectl --request-timeout=10s -n "$namespace" get service "$service" --ignore-not-found -o json)"; then fail "cannot inspect Service/$service in namespace $namespace" fi [[ -n "$result" ]] || fail "Service/$service is absent in namespace $namespace" @@ -79,7 +79,7 @@ patch_service_selector() { read_endpoint_slices() { local service="$1" local result - if ! result="$(kubectl -n "$namespace" get endpointslices.discovery.k8s.io \ + if ! result="$(kubectl --request-timeout=10s -n "$namespace" get endpointslices.discovery.k8s.io \ --selector "kubernetes.io/service-name=$service" -o json)"; then fail "cannot inspect EndpointSlices for Service/$service" fi @@ -91,7 +91,7 @@ verify_writer_quiescence() { local service deployment_json replicas pods_json pod_count for service in "${services[@]}"; do while :; do - if ! deployment_json="$(kubectl -n "$namespace" get deployment "$service" --ignore-not-found -o json)"; then + if ! deployment_json="$(kubectl --request-timeout=10s -n "$namespace" get deployment "$service" --ignore-not-found -o json)"; then fail "cannot verify Deployment/$service after quiesce" fi if [[ -n "$deployment_json" ]]; then @@ -101,7 +101,7 @@ verify_writer_quiescence() { fail "Deployment/$service did not remain at zero replicas" fi - if ! pods_json="$(kubectl -n "$namespace" get pods -o json)"; then + if ! pods_json="$(kubectl --request-timeout=10s -n "$namespace" get pods -o json)"; then fail "cannot verify pods for Deployment/$service" fi if ! pod_count="$(jq -er --arg service "$service" ' @@ -140,7 +140,7 @@ verify_writer_autoscaling_absent() { local hpa_json matching_hpas # An HPA can undo the scale-to-zero maintenance boundary. Do not proceed if # another controller can re-admit a writer while the migration is applying. - if ! hpa_json="$(kubectl -n "$namespace" get hpa -o json)"; then + if ! hpa_json="$(kubectl --request-timeout=10s -n "$namespace" get hpa -o json)"; then fail "cannot inspect namespace HPAs" fi if ! matching_hpas="$(jq -er '[.items[]? | select(.spec.scaleTargetRef.kind == "Deployment" and (.spec.scaleTargetRef.name == "account-service" or .spec.scaleTargetRef.name == "game-session-service" or .spec.scaleTargetRef.name == "automation-scripting-service"))] | length' <<<"$hpa_json")"; then @@ -168,7 +168,7 @@ done verify_writer_autoscaling_absent -if ! pods_json="$(kubectl -n "$namespace" get pods -o json)"; then +if ! pods_json="$(kubectl --request-timeout=10s -n "$namespace" get pods -o json)"; then fail "cannot inspect namespace Pods before closing Service selectors" fi if ! sentinel_pod_count="$(jq -er --arg selector "$closed_selector" ' @@ -232,7 +232,7 @@ done # owners before checking any Deployment or Pod so no writer can overlap apply. deadline=$((SECONDS + 300)) for service in "${services[@]}"; do - if ! deployment_name="$(kubectl -n "$namespace" get deployment "$service" --ignore-not-found -o name)"; then + if ! deployment_name="$(kubectl --request-timeout=10s -n "$namespace" get deployment "$service" --ignore-not-found -o name)"; then fail "cannot inspect Deployment/$service" fi if [[ -n "$deployment_name" ]]; then diff --git a/dev-tools/deploy/run-dev-account-v1040-4-probe.sh b/dev-tools/deploy/run-dev-account-v1040-4-probe.sh index 495a1f4b0f..350f347def 100644 --- a/dev-tools/deploy/run-dev-account-v1040-4-probe.sh +++ b/dev-tools/deploy/run-dev-account-v1040-4-probe.sh @@ -73,7 +73,7 @@ remove_probe_job() { jq -n --arg uid "$uid" \ '{apiVersion:"v1",kind:"DeleteOptions",preconditions:{uid:$uid},propagationPolicy:"Foreground"}' | kubectl --request-timeout=10s delete --raw "/apis/batch/v1/namespaces/$namespace/jobs/$job_name" -f - >/dev/null && - kubectl -n "$namespace" wait --for=delete --timeout=30s "job/$job_name" >/dev/null + kubectl --request-timeout=10s -n "$namespace" wait --for=delete --timeout=30s "job/$job_name" >/dev/null } cleanup() { @@ -125,7 +125,7 @@ if ! created_job="$(jq -n \ fi job_uid="$(read_owned_job_uid <<<"$created_job")" || fail "Kubernetes did not return the owned probe Job UID" -if ! kubectl -n "$namespace" wait --for=condition=complete --timeout=75s "job/$job_name" >/dev/null; then +if ! kubectl --request-timeout=10s -n "$namespace" wait --for=condition=complete --timeout=75s "job/$job_name" >/dev/null; then probe_error="$(kubectl --request-timeout=10s -n "$namespace" logs "job/$job_name" --tail=1 2>/dev/null || true)" case "$probe_error" in 'Account V1040.4 probe found duplicate retained admission attempts. Account-owned disposition is required.'|\ diff --git a/dev-tools/tests/dev-account-v1040-4-probe-contract.sh b/dev-tools/tests/dev-account-v1040-4-probe-contract.sh index a45b9a7f07..e7d0de0b9c 100644 --- a/dev-tools/tests/dev-account-v1040-4-probe-contract.sh +++ b/dev-tools/tests/dev-account-v1040-4-probe-contract.sh @@ -165,18 +165,14 @@ kubectl() { "firemud.dev/environment-class": "dev-demo-cluster"}, annotations: {"firemud.dev/last-dev-demo-head-sha": $base}}}' ;; - '-n dev get deployment '*) - [[ "$KUBECONFIG" == fixture-runtime ]] - printf '{"spec":{"replicas":0}}\n' - ;; - '-n dev get hpa -o json') + '--request-timeout=10s -n dev get hpa -o json') if [[ "${PROBE_SCENARIO:-}" == renewed-writer && -f "$PROBE_JOB_READ" ]]; then printf '{"items":[{"spec":{"scaleTargetRef":{"kind":"Deployment","name":"account-service"}}}]}\n' else printf '{"items":[]}\n' fi ;; - '-n dev get pods -o json') + '--request-timeout=10s -n dev get pods -o json') printf '{"kind":"PodList","items":[]}\n' ;; '--request-timeout=10s -n dev get deployment postgres -o json') @@ -188,6 +184,10 @@ kubectl() { spec:{template:{spec:{containers:[{name:"postgres", image:"postgres:18@sha256:eb63372c1e05c755f55fa30cbd07aecc443676fc6c0fa90b9002d01537841e1a"}]}}}}' ;; + '--request-timeout=10s -n dev get deployment '*" --ignore-not-found -o json") + [[ "$KUBECONFIG" == fixture-runtime ]] || return 2 + printf '{"spec":{"replicas":0}}\n' + ;; '--request-timeout=10s -n dev create -f - -o json') cat >"$PROBE_JOB_MANIFEST" [[ "${PROBE_SCENARIO:-}" != ambiguous-create ]] || return 1 @@ -201,7 +201,7 @@ kubectl() { fi jq --arg uid "$observed_uid" '.metadata.uid = $uid' "$PROBE_JOB_MANIFEST" ;; - "-n dev wait --for=condition=complete --timeout=75s job/$PROBE_FIXTURE_JOB_NAME") + "--request-timeout=10s -n dev wait --for=condition=complete --timeout=75s job/$PROBE_FIXTURE_JOB_NAME") [[ "${PROBE_SCENARIO:-}" != duplicate ]] ;; "--request-timeout=10s -n dev logs job/$PROBE_FIXTURE_JOB_NAME") @@ -213,11 +213,11 @@ kubectl() { printf '%s\n' 'Account V1040.4 probe found duplicate retained admission attempts. Account-owned disposition is required.' ;; "--request-timeout=10s delete --raw /apis/batch/v1/namespaces/dev/jobs/$PROBE_FIXTURE_JOB_NAME -f -") - jq -e '.preconditions.uid == "fixture-owned-job-uid" and .propagationPolicy == "Foreground"' >/dev/null + jq -e '.preconditions.uid == "fixture-owned-job-uid" and .propagationPolicy == "Foreground"' >/dev/null || return 1 [[ "${PROBE_SCENARIO:-}" != job-replacement ]] || return 1 touch "$PROBE_JOB_DELETED" ;; - "-n dev wait --for=delete --timeout=30s job/$PROBE_FIXTURE_JOB_NAME") + "--request-timeout=10s -n dev wait --for=delete --timeout=30s job/$PROBE_FIXTURE_JOB_NAME") [[ -f "$PROBE_JOB_DELETED" ]] ;; *) @@ -228,6 +228,13 @@ kubectl() { } export -f kubectl +if printf '%s\n' '{"preconditions":{"uid":"unexpected-job-uid"},"propagationPolicy":"Foreground"}' | + kubectl --request-timeout=10s delete --raw "/apis/batch/v1/namespaces/dev/jobs/$PROBE_FIXTURE_JOB_NAME" -f -; then + echo "Mock probe Job deletion accepted an incorrect UID precondition." >&2 + exit 1 +fi +[[ ! -e "$PROBE_JOB_DELETED" ]] + run_protected_probe() { bash "$root_dir/dev-tools/deploy/run-dev-account-v1040-4-probe.sh" \ dev "$namespace_uid" "$deployed_sha" "$PROBE_FIXTURE_HEAD" 3 diff --git a/dev-tools/tests/dev-demo-workflow-contract.sh b/dev-tools/tests/dev-demo-workflow-contract.sh index 427998cbfc..b0a551047d 100644 --- a/dev-tools/tests/dev-demo-workflow-contract.sh +++ b/dev-tools/tests/dev-demo-workflow-contract.sh @@ -1334,13 +1334,14 @@ if origin_probe.get("env", {}).get("DEV_NAMESPACE_MANAGER_KUBECONFIG") != ( if "run-dev-account-v1040-4-probe.sh" not in origin_probe.get("run", ""): raise SystemExit("the V1040.4 gate must call the protected probe helper") deploy_condition = deploy_by_name["Deploy dev-demo release"].get("if", "") -for required_preflight in ( - "steps.v2-migration-mode.outcome == 'success'", - "(steps.v2-migration-mode.outputs.activation != 'true' || steps.quiesce-writers.outcome == 'success')", - "(steps.v2-migration-mode.outputs.account_origin_probe != 'true' || steps.account-v1040-4-preflight.outcome == 'success')", -): - if required_preflight not in deploy_condition: - raise SystemExit("Helm must require successful classification and any required migration preflight") +expected_deploy_condition = ( + "${{ steps.cluster-access.outputs.available == 'true' && " + "steps.v2-migration-mode.outcome == 'success' && " + "(steps.v2-migration-mode.outputs.activation != 'true' || steps.quiesce-writers.outcome == 'success') && " + "(steps.v2-migration-mode.outputs.account_origin_probe != 'true' || steps.account-v1040-4-preflight.outcome == 'success') }}" +) +if deploy_condition != expected_deploy_condition: + raise SystemExit("Helm must require cluster access, successful classification, and all applicable migration preflights") for step_name, expected_kubeconfig in expected_deploy_kubeconfigs.items(): actual_env = deploy_by_name[step_name].get("env", {}) if actual_env.get("KUBECONFIG") != expected_kubeconfig: @@ -1419,6 +1420,7 @@ if "firemud.dev/last-dev-demo-head-sha=${HEAD_SHA}" not in deployed_head_step["r bootstrap_step = deploy_by_name["Create dev-demo smoke account"] failure_summary = deploy_by_name["Summarize dev-demo failure"] if failure_summary["env"] != { + "DEPLOY_OUTCOME": "${{ steps." + deploy_by_name["Deploy dev-demo release"]["id"] + ".outcome }}", "RECORD_OUTCOME": "${{ steps." + deployed_head_step["id"] + ".outcome }}", "BOOTSTRAP_OUTCOME": "${{ steps." + bootstrap_step["id"] + ".outcome }}", }: @@ -1435,10 +1437,13 @@ for name, value in { ) with tempfile.TemporaryDirectory() as directory: summary = Path(directory) / "summary.md" - for recorded, bootstrap, expected in ( - ("skipped", "skipped", None), - ("success", "failure", "refer bootstrap recovery to the affected owners"), - ("success", "success", "before repeating readiness or smoke"), + for deployed, recorded, bootstrap, stage, expected in ( + ("failure", "skipped", "skipped", "deploy", None), + ("skipped", "skipped", "skipped", "account-v1040-4-preflight", None), + ("success", "failure", "skipped", "deploy", None), + ("success", "skipped", "skipped", "deploy", None), + ("success", "success", "failure", "bootstrap-smoke", "refer bootstrap recovery to the affected owners"), + ("success", "success", "success", "smoke", "before repeating readiness or smoke"), ): summary.write_text("", encoding="utf-8") subprocess.run( @@ -1450,6 +1455,8 @@ with tempfile.TemporaryDirectory() as directory: "GITHUB_SERVER_URL": "https://github.example.invalid", "GITHUB_REPOSITORY": "example/FireMUD", "GITHUB_WORKFLOW_SHA": "b" * 40, + "DEV_DEMO_STAGE": stage, + "DEPLOY_OUTCOME": deployed, "RECORD_OUTCOME": recorded, "BOOTSTRAP_OUTCOME": bootstrap, }, @@ -1457,6 +1464,22 @@ with tempfile.TemporaryDirectory() as directory: ) evidence = summary.read_text(encoding="utf-8") guide = "/blob/" + "b" * 40 + "/design/architecture/" + unconfirmed_recording = deployed == "success" and recorded != "success" + expected_stage = "record-deployed-head" if unconfirmed_recording else stage + if f"Failed stage: `{expected_stage}`" not in evidence: + raise SystemExit("dev-demo failure summary misidentified the failed stage") + if unconfirmed_recording: + for detail in ( + "Helm deployment succeeded, but recording the deployed head on the namespace failed or could not be confirmed", + "Do not retry the deployment, reset the namespace, or replay bootstrap", + "original Helm release and revision", + "owned dev namespace UID", + "retained Flyway version", + ): + if detail not in evidence: + raise SystemExit(f"dev-demo unconfirmed recording summary lacks: {detail}") + elif "Helm deployment succeeded, but recording" in evidence: + raise SystemExit("dev-demo summary wrongly reported a successful Helm deploy with unconfirmed recording") if expected is None: if guide in evidence: raise SystemExit("unrecorded target received recorded-target advice") diff --git a/dev-tools/tests/hosted-v2-migration-activation-contract.sh b/dev-tools/tests/hosted-v2-migration-activation-contract.sh index e942c0774b..5dc1252595 100644 --- a/dev-tools/tests/hosted-v2-migration-activation-contract.sh +++ b/dev-tools/tests/hosted-v2-migration-activation-contract.sh @@ -151,6 +151,12 @@ grep -Fxq 'account_origin_namespace_uid=fixture-dev-uid' <<<"$origin_receipt" namespace_for_head "$capacity_prefix_sha" origin_receipt="$(cd "$repo" && bash "$detector" push "$capacity_prefix_sha" "$capacity_origin_sha" dev)" grep -Fxq 'account_origin_prefix=3' <<<"$origin_receipt" +dispatch_receipt="$(cd "$repo" && bash "$detector" repository_dispatch "" "$capacity_origin_sha" dev)" +grep -Fxq 'activation=true' <<<"$dispatch_receipt" +grep -Fxq 'account_origin_probe=true' <<<"$dispatch_receipt" +grep -Fxq 'account_origin_prefix=3' <<<"$dispatch_receipt" +grep -Fxq "account_origin_base_sha=$capacity_prefix_sha" <<<"$dispatch_receipt" +grep -Fxq 'account_origin_namespace_uid=fixture-dev-uid' <<<"$dispatch_receipt" FAKE_NAMESPACE_JSON="$(jq 'del(.metadata.uid)' <<<"$FAKE_NAMESPACE_JSON")" assert_rejected push "$capacity_prefix_sha" "$capacity_origin_sha" diff --git a/dev-tools/tests/pr-required-gate-context-contract.sh b/dev-tools/tests/pr-required-gate-context-contract.sh index b7fd4f5e3d..a7b5315a0d 100644 --- a/dev-tools/tests/pr-required-gate-context-contract.sh +++ b/dev-tools/tests/pr-required-gate-context-contract.sh @@ -668,6 +668,7 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single", t updated_at: status === "completed" ? "2026-09-01T00:30:02Z" : "2026-09-01T00:05:00Z", pull_requests: [], }); + const failedTyped = {...refreshSource(1, "completed", "failure"), id: 43, created_at: "2026-09-01T00:00:00Z"}; const smokeJob = (runId, runAttempt, smokeConclusion) => { const jobConclusion = runId === 44 ? "success" : smokeConclusion; const jobId = runId === 44 ? 144 : runId * 100 + 1; @@ -745,7 +746,17 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single", t git: {getRef: async () => ({data: {ref: "refs/heads/develop", object: {sha: base}}})}, actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs, getWorkflow: async () => ({data: {id: 7, path: ".github/workflows/runtime-images.yml", name: "Build Runtime Images"}}), + listJobsForWorkflowRunAttempt: async input => { + assert.equal(input.run_id, failedTyped.id); + assert.equal(input.attempt_number, failedTyped.run_attempt); + const job = {...smokeJob(44, 1, "failure"), run_id: failedTyped.id, conclusion: "failure"}; + if (selectionCase === "recoverable-ambiguous-failure") { + job.steps.find(step => step.name.startsWith("Known canonical transition")).conclusion = null; + } + return {data: {total_count: 1, jobs: [job]}}; + }, getWorkflowRun: async ({run_id}) => { + if (run_id === failedTyped.id && selectionCase.startsWith("recoverable-")) return {data: failedTyped}; if (run_id === 44) { typedCurrentChecks++; const rerunning = selectionCase === "recoverable-replacement-rerun" && typedCurrentChecks === 1; @@ -761,6 +772,7 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single", t } }, }, request: async (route, input) => { assert.equal(route, "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}"); + if (input.run_id === failedTyped.id && selectionCase.startsWith("recoverable-")) return {data: failedTyped}; if (input.run_id === 44) { const attempt = selectionCase === "recoverable-replacement-rerun" && typedCurrentChecks > 0 ? 2 : 1; assert.equal(input.attempt_number, attempt); @@ -792,6 +804,10 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single", t assert.equal(method, listRuns); assert.equal(input.workflow_id, "runtime-images.yml"); if (input.event === "repository_dispatch") { + if (["recoverable-failed-typed", "recoverable-ambiguous-failure"].includes(selectionCase)) { + yield {data: now - start >= 6 * 60 * 1000 ? [refreshSource(1), failedTyped] : [failedTyped]}; + return; + } const originalRerun = selectionCase === "recoverable-original-rerun"; const replacementRerun = selectionCase === "recoverable-replacement-rerun"; const ready = originalRerun || replacementRerun || selectionCase === "recoverable-delayed" && now - start >= 6 * 60 * 1000; @@ -862,7 +878,7 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single", t complete ? "completed" : "in_progress", complete ? outcome : null)] }; }; const core = { info: () => {}, warning: () => {}, setFailed: message => failures.push(message) }; - const clock = { now: () => now, parse: Date.parse }; + const clock = class extends Date { static now() { return now; } }; const sleep = (callback, duration) => { now += duration; queueMicrotask(callback); }; await execute(github, context, core, clock, sleep); return { failures, minutes: (now - start) / 60000, typedJobAttempts }; @@ -909,6 +925,13 @@ async function scenario(outcome, completedAtMinutes, selectionCase = "single", t const delayedRecovery = await scenario("cancelled", 0, "recoverable-delayed"); assert.deepEqual(delayedRecovery.failures, []); assert.equal(delayedRecovery.minutes, 6, "Validation may dispatch an exact replacement after five minutes"); + const delayedAfterTypedFailure = await scenario("cancelled", 0, "recoverable-failed-typed"); + assert.deepEqual(delayedAfterTypedFailure.failures, []); + assert.equal(delayedAfterTypedFailure.minutes, 6, "an authenticated ordinary typed failure waits beyond snapshot convergence for its replacement"); + assert.deepEqual(delayedAfterTypedFailure.typedJobAttempts, [1, 1], "the newer run still needs exact terminal smoke proof"); + const ambiguousTypedFailure = await scenario("cancelled", 0, "recoverable-ambiguous-failure"); + assert.equal(ambiguousTypedFailure.failures.length, 1); + assert.ok(ambiguousTypedFailure.minutes < 6, "an ambiguous failure does not get the replacement allowance"); const originalRerun = await scenario("success", 1, "recoverable-original-rerun"); assert.deepEqual(originalRerun.failures, [], "a queued then failed same-tuple replacement cannot hide the successful original rerun"); assert.equal(originalRerun.minutes, 1); @@ -1072,6 +1095,10 @@ async function scenario(kind, event = "pull_request", listedConclusion = null) { }, actions: { listWorkflowRuns: listRuns, listJobsForWorkflowRun: listJobs, + listJobsForWorkflowRunAttempt: async ({run_id, attempt_number}) => { + assert.equal(run_id, source.id); assert.equal(attempt_number, source.run_attempt); + return {data: {total_count: 1, jobs: [job]}}; + }, getWorkflow: async () => ({data: {id: 7, path: source.path, name: "Build Runtime Images"}}), getWorkflowRun: async () => { if (refs.length) qualifiedAttemptReads++; @@ -4099,7 +4126,7 @@ async function recoveredFailure(options = {}, selectedRun = null, selectedIdenti } const execute = new Function("repositoryName", "prNumber", "positiveInteger", "findMatchingRuntimeImagesRun", "withTransientGitHubRetry", "github", "owner", "repo", "canonicalSmokeJobName", "verifyKnownPlayFailure", - "verifyCanonicalSmokeProducer", "context", "isReplaceableTypedProducer", + "verifyCanonicalSmokeProducer", "context", "isReplaceableTypedProducer", "provesOrdinaryTypedFailure", `${refreshFunction}; return verifyFailedPullCanonicalRefresh;`); const recover = execute(options.repository || repositoryName, "3390", value => Number.isSafeInteger(value) && value > 0, async (event, title, selected) => { @@ -4125,7 +4152,8 @@ async function recoveredFailure(options = {}, selectedRun = null, selectedIdenti verifyReplacement(selected, job, proofIdentity, true, allowIncompleteSteps, allowOrdinary), (selected, job, proofIdentity, requireTerminalSmokeProof) => verifyReplacement(selected, job, proofIdentity, false, requireTerminalSmokeProof), - {payload: {pull_request: {head: {repo: {full_name: options.headRepository || repositoryName}}}}}, isReplaceableTypedProducer); + {payload: {pull_request: {head: {repo: {full_name: options.headRepository || repositoryName}}}}}, isReplaceableTypedProducer, + async () => false); const proof = await recover(original, selectedIdentity); return {accepted: raw ? proof : proof?.status === "verified" ? true : proof?.status === "snapshot-pending" ? "snapshot-pending" : proof, verified, queries}; @@ -5815,7 +5843,9 @@ async function run(kind, shared = {visible: false, posts: 0}) { return shared.posts; } (async () => { - assert.equal(await run("valid"), 1); + const valid = {visible: false, posts: 0}; + assert.equal(await run("valid", valid), 1); + assert.equal(valid.failure, undefined, "a completed exact handoff must not report workflow failure"); const sameSecondHandoff = {visible: false, posts: 0}; assert.equal(await run("same-second", sameSecondHandoff), 1); assert.equal(sameSecondHandoff.observations, 1, "a unique new exact run is visible in the POST's own timestamp second"); diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index bfb834b790..325da1ae69 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -989,6 +989,11 @@ async function runDispatcher({ fakeNow += apiRequestMillis; return options.request.signal; }; + const inventoriedRuntimeRuns = () => [ + ...Object.values(inventories).flatMap(inventory => Array.isArray(inventory) + ? inventory : [...(inventory.initial ?? inventory.runs ?? []), ...(inventory.refined ?? [])]), + ...lateProducers, ...postedRuns, + ]; const github = { rest: { git: { @@ -1101,10 +1106,7 @@ async function runDispatcher({ if (request.run_id !== ciRun.id) { runtimeRunReads.push(request.run_id); const reads = runtimeRunReads.filter(id => id === request.run_id).length; - const runs = [...Object.values(inventories).flatMap(inventory => Array.isArray(inventory) - ? inventory : [...(inventory.initial ?? inventory.runs ?? []), ...(inventory.refined ?? [])]), - ...lateProducers, ...postedRuns]; - const run = runs.find(run => run?.id === request.run_id); + const run = inventoriedRuntimeRuns().find(run => run?.id === request.run_id); assert(run, "native runtime lookup must target an inventoried producer"); const override = runtimeRunOverrides[request.run_id]; return {data: {...run, ...(typeof override === "function" ? override(reads, run) : override ?? {})}}; @@ -1116,8 +1118,7 @@ async function runDispatcher({ recordApiRequest("actions.getWorkflowRunAttempt", request); const {request: requestOptions, ...normal} = request; assert.deepEqual(normal, {owner: "owner", repo: "repo", run_id: request.run_id, attempt_number: request.attempt_number}); - const runs = Object.values(inventories).flatMap(inventory => Array.isArray(inventory) ? inventory : inventory.runs ?? []); - const run = runs.find(run => run?.id === request.run_id); + const run = inventoriedRuntimeRuns().find(run => run?.id === request.run_id); assert(run, "native exact attempt must address an inventoried runtime producer"); assert.equal(request.attempt_number, run.run_attempt); const attempt = Object.hasOwn(runtimeNativeAttempts, run.id) ? runtimeNativeAttempts[run.id] : run; @@ -1126,7 +1127,12 @@ async function runDispatcher({ }, listJobsForWorkflowRunAttempt: async (request) => { recordApiRequest("actions.listJobsForWorkflowRunAttempt", request); - if (request.run_id !== ciRun.id) return {data: runtimeAttemptJobs[request.run_id] ?? {total_count: 0, jobs: []}}; + if (request.run_id !== ciRun.id) { + const producer = inventoriedRuntimeRuns().find(run => run?.id === request.run_id); + assert(producer, "native job listing must address an inventoried producer"); + assert.equal(request.attempt_number, producer.run_attempt, "native jobs must be read from the selected attempt"); + return {data: runtimeAttemptJobs[request.run_id] ?? {total_count: 0, jobs: []}}; + } ciJobRequests.push(request); const jobs = ciEvidence.jobs ?? [ciGate]; return {data: ciEvidence.jobPage ? ciEvidence.jobPage(request, jobs) : { @@ -1852,7 +1858,17 @@ async function runDispatcher({ const unrelatedInflight = producer(sibling, "pull_request", "in_progress", null, {created_at: "2026-01-02T00:00:00Z"}); const completedRefresh = producer(tuple, "repository_dispatch", "completed", "success", { created_at: "2026-01-01T12:00:00Z", + run_started_at: "2026-01-01T12:01:00Z", updated_at: "2026-01-01T12:10:00Z", }); + const successfulJob = {id: 73, name: "PR Full-Stack Smoke (runtime-required=true)", + workflow_name: completedRefresh.display_title, run_id: completedRefresh.id, run_attempt: completedRefresh.run_attempt, + head_sha: completedRefresh.head_sha, status: "completed", conclusion: "success", + started_at: "2026-01-01T12:02:00Z", completed_at: "2026-01-01T12:09:00Z", steps: [ + ...["Run credential-free full-stack smoke", "Stop smoke stack", "Require successful runtime smoke and authenticated cleanup"] + .map(name => ({name, status: "completed", conclusion: "success"})), + {name: "Known canonical transition PLAY failure with successful authenticated cleanup", status: "completed", conclusion: "skipped"}, + ]}; + const successfulJobs = {[completedRefresh.id]: {total_count: 1, jobs: [successfulJob]}}; const refinedCompleted = await runDispatcher({ tuples: [tuple], callback: {updated_at: "2026-01-01T06:00:00Z"}, inventories: { @@ -1860,6 +1876,7 @@ async function runDispatcher({ refined: [unrelatedInflight], refinedTotalCount: 1}, repository_dispatch: [completedRefresh], }, + runtimeAttemptJobs: successfulJobs, }); assert.deepEqual(numbers(refinedCompleted), [], "refinement must retain completed refresh between CI completion and sampled inflight floor"); assert(refinedCompleted.inventoryCalls.some(request => request.created === "2026-01-01T06:00:00Z..*")); @@ -1904,15 +1921,40 @@ async function runDispatcher({ "unknown inventory must be an explicit error, not apparent success"); } - for (const [signalAt, expected] of [["2026-01-02T00:00:00Z", 0], ["2026-01-03T00:00:00.200Z", 0], ["2026-01-04T00:00:00Z", 1]]) { + for (const signalAt of ["2026-01-01T06:00:00Z", "2026-01-01T12:00:00.200Z", "2026-01-04T00:00:00Z"]) { const result = await runDispatcher({ tuples: [tuple], callback: { updated_at: signalAt }, - inventories: { repository_dispatch: [producer(tuple, "repository_dispatch", "completed", "success", { - created_at: "2026-01-03T00:00:00Z", - })] }, + inventories: {repository_dispatch: [completedRefresh]}, runtimeAttemptJobs: successfulJobs, }); - assert.equal(numbers(result).length, expected, "completed refresh suppresses an earlier or same-second signal"); + assert.deepEqual(numbers(result), [], "a usable exact completed refresh suppresses a duplicate even if it completed before Validation"); + assert.deepEqual(result.errors, []); + assert.deepEqual(result.runtimeRunReads, [completedRefresh.id, completedRefresh.id], "reuse requires a final current-attempt read"); } + for (const job of [ + {...successfulJob, name: "PR Full-Stack Smoke (runtime-required=false)"}, + {...successfulJob, steps: successfulJob.steps.filter(step => step.name !== "Stop smoke stack")}, + {...successfulJob, steps: [...successfulJob.steps, successfulJob.steps[0]]}, + {...successfulJob, started_at: "2026-01-01T12:00:59Z"}, + ]) { + const result = await runDispatcher({tuples: [tuple], callback: {updated_at: "2026-01-04T00:00:00Z"}, + inventories: {repository_dispatch: [completedRefresh]}, runtimeAttemptJobs: {[completedRefresh.id]: {total_count: 1, jobs: [job]}}}); + assert.deepEqual(numbers(result), ["101"], "a green but unusable exact attempt must not suppress the refresh"); + assert.deepEqual(result.errors, []); + } + const recentTransition = await runDispatcher({ + tuples: [tuple], callback: {updated_at: "2026-01-01T06:00:00Z"}, + inventories: {repository_dispatch: [completedRefresh]}, + runtimeAttemptJobs: {[completedRefresh.id]: {total_count: 1, jobs: [{...successfulJob, + steps: successfulJob.steps.map(step => ({...step, conclusion: + step.name.startsWith("Known canonical transition") ? "success" : "skipped"})), + }]}}, + }); + assert.deepEqual(numbers(recentTransition), [], "a recent successful PLAY diagnostic keeps its existing dispatch hold"); + assert.deepEqual(recentTransition.errors, []); + const staleSuccess = await runDispatcher({tuples: [tuple], inventories: {repository_dispatch: [completedRefresh]}, + runtimeAttemptJobs: successfulJobs, runtimeRunOverrides: {[completedRefresh.id]: reads => reads > 1 ? {run_attempt: 2} : {}}}); + assert.deepEqual(numbers(staleSuccess), [], "a concurrent rerun leaves inventory uncertain, not duplicate suppression or dispatch authority"); + assert(staleSuccess.errors.some(message => message.includes("changed during exact attempt proof"))); const terminalTyped = conclusion => producer(tuple, "repository_dispatch", "completed", conclusion, { created_at: "2026-01-03T00:00:00Z", }); @@ -1937,12 +1979,12 @@ async function runDispatcher({ assert(unresolved.errors.some(message => message.includes("attempted but visibility is unknown")), "the old terminal run cannot confirm receipt of its replacement"); } - for (const conclusion of ["failure", "success", null]) { + for (const conclusion of ["failure", null]) { const held = await runDispatcher({tuples: [tuple], callback: {updated_at: "2026-01-02T00:00:00Z"}, inventories: {repository_dispatch: [terminalTyped(conclusion)]}, }); assert.deepEqual(numbers(held), [], - "legacy failure/PLAY, success and unknown dispositions keep the existing typed refresh hold"); + "legacy failure/PLAY and unknown dispositions keep the existing typed refresh hold"); if (conclusion !== "failure") assert.deepEqual(held.runtimeRunReads, [], "unrelated conclusions need no native classification"); assert.deepEqual(held.errors, []); } @@ -3767,8 +3809,8 @@ const github = { id: 881, name: typed ? "PR Full-Stack Smoke (runtime-required=true)" : "PR Full-Stack Smoke", check_run_url: "https://api.github.com/repos/owner/repo/check-runs/881", - run_id: input.run_id, - run_attempt: input.attempt_number, + run_id: run?.id, + run_attempt: run?.run_attempt, head_sha: run?.head_sha, status: "completed", conclusion: "success", diff --git a/dev-tools/tests/pr-runtime-image-publication-contract.sh b/dev-tools/tests/pr-runtime-image-publication-contract.sh index f7a4e728b2..14ba448233 100644 --- a/dev-tools/tests/pr-runtime-image-publication-contract.sh +++ b/dev-tools/tests/pr-runtime-image-publication-contract.sh @@ -1586,6 +1586,11 @@ run_validation() { python3 "$validation_script" } +set_source_run_attempt() { + jq --argjson attempt "$1" '.run_attempt = $attempt' "$fixture_dir/source-run.json" > "$fixture_dir/source-run-next.json" + mv "$fixture_dir/source-run-next.json" "$fixture_dir/source-run.json" +} + set_source_run_path() { python3 - "$fixture_dir/source-run.json" "$1" <<'PY' import json @@ -1605,6 +1610,14 @@ if SOURCE_RUN_ATTEMPT=2 run_validation >/dev/null 2>"$fixture_dir/attempt-error" exit 1 fi grep -Fq 'source workflow attempt changed before artifact validation' "$fixture_dir/attempt-error" +set_source_run_attempt 2 +if run_validation >/dev/null 2>"$fixture_dir/newer-attempt-error"; then + echo "publisher accepted an older resolution after a newer source attempt" >&2 + exit 1 +fi +grep -Fq 'source workflow attempt changed before artifact validation' "$fixture_dir/newer-attempt-error" +SOURCE_RUN_ATTEMPT=2 run_validation +set_source_run_attempt 1 if run_validation pull_request feature/ci "$head_sha" repository_dispatch 2>"$fixture_dir/typed-source-error"; then echo "typed publication accepted a pull-request producer" >&2 exit 1 diff --git a/dev-tools/tests/v2-schema-migration-quiescence-contract.sh b/dev-tools/tests/v2-schema-migration-quiescence-contract.sh index e6af281e5d..a9515cf01c 100644 --- a/dev-tools/tests/v2-schema-migration-quiescence-contract.sh +++ b/dev-tools/tests/v2-schema-migration-quiescence-contract.sh @@ -18,6 +18,12 @@ cat >"$fake_bin/kubectl" <<'EOF' #!/usr/bin/env bash set -euo pipefail printf '%s\n' "$*" >>"$QUIESCE_CALLS" +if [[ "${1:-}" == --request-timeout=10s && "${4:-}" == get ]]; then + shift +elif [[ "${3:-}" == get ]]; then + echo "kubectl read lacks the expected request timeout: $*" >&2 + exit 2 +fi pod_list_kind='List' endpoint_slice_list_kind='List' if [[ "${QUIESCE_MODE:-}" == typed-lists ]]; then @@ -150,9 +156,9 @@ last_close_line="$(grep -nF -- 'firemud-v2-migration-quiesced' "$calls" | grep ' last_endpoint_line="$(grep -nF -- 'get endpointslices.discovery.k8s.io' "$calls" | tail -n1 | cut -d: -f1)" first_scale_line="$(grep -nF -- ' scale deployment/' "$calls" | head -n1 | cut -d: -f1)" last_scale_line="$(grep -nF -- ' scale deployment/' "$calls" | tail -n1 | cut -d: -f1)" -initial_pod_check_line="$(grep -nFx -- '-n contract get pods -o json' "$calls" | sed -n '1p' | cut -d: -f1)" -first_pod_check_line="$(grep -nFx -- '-n contract get pods -o json' "$calls" | sed -n '2p' | cut -d: -f1)" -last_pod_check_line="$(grep -nFx -- '-n contract get pods -o json' "$calls" | tail -n1 | cut -d: -f1)" +initial_pod_check_line="$(grep -nFx -- '--request-timeout=10s -n contract get pods -o json' "$calls" | sed -n '1p' | cut -d: -f1)" +first_pod_check_line="$(grep -nFx -- '--request-timeout=10s -n contract get pods -o json' "$calls" | sed -n '2p' | cut -d: -f1)" +last_pod_check_line="$(grep -nFx -- '--request-timeout=10s -n contract get pods -o json' "$calls" | tail -n1 | cut -d: -f1)" first_restore_line="$(grep -nF -- 'patch service account-service --type=merge --patch {"spec":{"selector":{"app":"account-service"}}}' "$calls" | head -n1 | cut -d: -f1)" [[ "$initial_pod_check_line" -lt "$last_close_line" && "$last_close_line" -lt "$first_endpoint_line" && "$last_endpoint_line" -lt "$first_scale_line" && "$last_scale_line" -lt "$first_pod_check_line" && "$last_pod_check_line" -lt "$first_restore_line" ]] || { echo "Services must close before empty EndpointSlices are proved, all writers scale before pod checks, and selectors restore last" >&2 diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index ec19a58327..04d920b783 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -771,23 +771,24 @@ void expiryDuringSourceQualificationCannotBecomeBillingRefusal() throws Exceptio var f = new Fixture(false, qualifiedRequest(false)); f.existing = false; f.retained = true; - qualifySources(f); + var scope = qualifySources(f); + var scopeTokenHash = verifiedScopeTokenHash(f.request); var now = new java.util.concurrent.atomic.AtomicReference<>( CapacityAdmissionTestFixture.NOW.plusSeconds(1)); when(f.clock.instant()).thenAnswer(ignored -> now.get()); - var scope = f.scopes.findCanonicalEvidenceByTokenHash("fixture"); - org.mockito.Mockito.clearInvocations(f.scopes); - when(f.scopes.findCanonicalEvidenceByTokenHash(anyString())) + when(f.scopes.findCanonicalEvidenceByTokenHash(scopeTokenHash)) .thenAnswer(ignored -> { now.set(f.request.evidence().expiresAt()); - return scope; + return Optional.of(scope); }); assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) .isInstanceOfSatisfying( AccountTenantCapacityRepository.CapacityException.class, failure -> assertThat(failure.code()).isEqualTo(Failure.CAPACITY_ADMISSION_STALE)); - verify(f.scopes).findCanonicalEvidenceByTokenHash(anyString()); + verify(f.issuances) + .readCurrentCommittedCandidateByJti(CapacityAdmissionTestFixture.DELEGATION_JTI); + verify(f.scopes).findCanonicalEvidenceByTokenHash(scopeTokenHash); verify(f.dsl, never()).execute(anyString(), any(Object[].class)); } @@ -852,7 +853,14 @@ private static Request qualifiedRequest(boolean creating) { .withDigest(); } - private static void qualifySources(Fixture f) { + private static String verifiedScopeTokenHash(Request request) { + return net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence + .parseCanonical(request.evidence().canonicalBytes()) + .verifiedConnectScopeTokenHash(); + } + + private static AccountConnectScopeRepository.CanonicalConnectScopeEvidence qualifySources( + Fixture f) { var player = (TenantCapacityAdmission.PlayerContext) f.request.context(); var parsed = net.firedevops.firemud.common.account.authority.RuntimePlayerAdmissionEntitlementEvidence @@ -878,7 +886,8 @@ private static void qualifySources(Fixture f) { when(issuance.canonicalRegistryRecordSha256()) .thenReturn((String) source.get("callerRegistryRecordSha256")); when(issuance.commitProofSha256()).thenReturn((String) source.get("callerCommitProofSha256")); - when(f.issuances.readCurrentCommittedCandidateByJti(any(UUID.class))) + var delegationJti = UUID.fromString((String) source.get("callerTokenJti")); + when(f.issuances.readCurrentCommittedCandidateByJti(delegationJti)) .thenReturn(Optional.of(issuance)); var scope = mock(AccountConnectScopeRepository.CanonicalConnectScopeEvidence.class); when(scope.accountUuid()).thenReturn(player.accountId()); @@ -890,7 +899,9 @@ private static void qualifySources(Fixture f) { when(scope.playableStateScope()).thenReturn(player.playableStateScope()); when(scope.connectScopeExpiresAt()) .thenReturn(CapacityAdmissionTestFixture.NOW.plusSeconds(3600).toString()); - when(f.scopes.findCanonicalEvidenceByTokenHash(anyString())).thenReturn(Optional.of(scope)); + when(f.scopes.findCanonicalEvidenceByTokenHash(parsed.verifiedConnectScopeTokenHash())) + .thenReturn(Optional.of(scope)); + return scope; } private static final class Fixture { diff --git a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java index 3dbb82c187..1173ba9dee 100644 --- a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionTestFixture.java @@ -34,6 +34,7 @@ public final class CapacityAdmissionTestFixture { public static final UUID CHARACTER = UUID.fromString("88888888-8888-4888-8888-888888888888"); public static final UUID SESSION = UUID.fromString("99999999-9999-4999-8999-999999999999"); public static final UUID REALM = UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + public static final UUID DELEGATION_JTI = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); public static final String PEER = "spiffe://firemud/ns/prod/sa/game-session-service"; public static final Instant NOW = Instant.parse("2026-11-02T00:00:00Z"); private static final String HASH = "a".repeat(64); @@ -86,6 +87,9 @@ public static TenantCapacityAdmission.Request playerRequestFor( Map target, Instant at) { Map source = new LinkedHashMap<>(sources()); + source.put("callerTokenJti", DELEGATION_JTI.toString()); + source.put("callerContextId", "cccccccc-cccc-4ccc-8ccc-cccccccccccc"); + source.put("callerOperationId", "dddddddd-dddd-4ddd-8ddd-dddddddddddd"); source.put("callerTokenExpiresAt", at.plusSeconds(90).toString()); var evidence = RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index 9fabb43b1b..87c555be2f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -300,6 +300,7 @@ void restartedClientRecoversTheOriginalQuotaDenialWithoutAnotherCommit() throws var denialId = UUID.randomUUID(); var commits = new AtomicInteger(); var reads = new AtomicInteger(); + var failedCommit = new AtomicReference(); Server server = startServer( "account", @@ -309,6 +310,7 @@ public void commitTenantCapacityAdmission( CommitTenantCapacityAdmissionRequest wire, StreamObserver observer) { commits.incrementAndGet(); + failedCommit.set(wire); observer.onError(Status.UNAVAILABLE.asRuntimeException()); } @@ -332,6 +334,8 @@ public void readTenantCapacityQuotaDenial( assertThatThrownBy(() -> original.commit(request, deadline())) .isInstanceOf(StatusRuntimeException.class); } + assertThat(failedCommit.get()) + .isEqualTo(TenantCapacityAdmissionGrpcCodec.toRequest(request)); try (var restarted = client(server)) { restarted.init(); assertThat(restarted.readRetainedQuotaDenial(request, deadline())).isEqualTo(denialId); From b041b677aa4a2ce5027532f7c21f7a1a2e899e59 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Tue, 24 Nov 2026 01:37:15 +1300 Subject: [PATCH 50/96] Address returned runtime and Account proof review findings --- .github/workflows/runtime-images.yml | 29 ++++--- .github/workflows/smoke.yml | 44 +++++++++-- .../account-service/api-contracts.md | 2 +- .../dev-account-v1040-4-probe-contract.sh | 15 +++- dev-tools/tests/dev-demo-workflow-contract.sh | 17 +++- .../tests/pr-retarget-workflow-contract.sh | 24 +++++- ...acityMigrationPostgresIntegrationTest.java | 48 ++++++++++++ .../AccountTenantCapacityGrpcServiceTest.java | 14 +++- .../TenantCapacityAdmissionGrpcCodecTest.java | 9 +++ ...untRuntimeStubServerCompatibilityTest.java | 7 +- .../AccountTenantCapacityClientMtlsTest.java | 24 +++++- ...tSessionOwnerEvidenceReadGrpcMtlsTest.java | 77 +++++++++++++------ .../stubs/EntityManagementStubServerTest.java | 31 ++++---- 13 files changed, 266 insertions(+), 75 deletions(-) diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 8d71944a93..667d966b8a 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -806,7 +806,7 @@ jobs: // The older PLAY diagnostic can leave the source run red. Only a // complete native attempt with its marker explicitly skipped can // prove that a failed producer did not supply that exception. - const provesOrdinaryTypedOutcome = async (run, workflowName) => { + const classifyTypedOutcome = async (run, workflowName) => { const successful = run.conclusion === "success"; const repository = `${context.repo.owner}/${context.repo.repo}`; const matchesSelected = candidate => candidate && @@ -835,7 +835,9 @@ jobs: ![workflowName, run.display_title].includes(job.workflow_name) || job.status !== "completed" || job.conclusion !== run.conclusion || !Array.isArray(job.steps)) return false; const markers = job.steps.filter(step => step?.name === "Known canonical transition PLAY failure with successful authenticated cleanup"); - if (markers.length !== 1 || markers[0].status !== "completed" || markers[0].conclusion !== "skipped") return false; + if (markers.length !== 1 || markers[0].status !== "completed") return false; + const diagnostic = successful && markers[0].conclusion === "success"; + if (!diagnostic && markers[0].conclusion !== "skipped") return false; const timestamp = value => { const match = typeof value === "string" && /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d{1,3}))?(Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.exec(value); const time = match ? Date.parse(value) : NaN; @@ -854,7 +856,7 @@ jobs: if (!Number.isFinite(markerStart) || !Number.isFinite(markerEnd) || markerStart < jobStart || markerEnd < markerStart || markerEnd > jobEnd) return false; } - if (successful) { + if (successful && !diagnostic) { // A green run or job alone can be a no-op or the diagnostic exception. // Require affirmative ordinary smoke and authenticated cleanup in this attempt. for (const name of ["Run credential-free full-stack smoke", "Stop smoke stack", @@ -868,7 +870,7 @@ jobs: if (successful && (!matchesSelected(latest) || latest.created_at !== run.created_at)) { throw new Error(`Successful typed runtime producer ${run.id} changed during exact attempt proof`); } - return matchesSelected(latest); + return matchesSelected(latest) ? (diagnostic ? "diagnostic" : "ordinary") : false; }; // Bind both admission reads to the same terminal attempt; never cache native proof. const disregardedTypedAttempts = new Map(); @@ -953,8 +955,8 @@ jobs: throw new Error(`Terminal typed runtime producer ${newest.id} no longer has the same trusted terminal attempt`); } if (["success", "failure"].includes(newest.conclusion)) { - const ordinary = await provesOrdinaryTypedOutcome(latest, workflow.name); - if (newest.conclusion === "success" ? ordinary : !ordinary) return [newest]; + const outcome = await classifyTypedOutcome(latest, workflow.name); + if (newest.conclusion === "success" ? Boolean(outcome) : outcome !== "ordinary") return [newest]; } // A recent success can be a validated transition diagnostic or // awaiting downstream evidence. Preserve its existing hold. @@ -1103,6 +1105,15 @@ jobs: ["main", "develop"].includes(refreshBranch); const pullRequests = protectedPrHead ? [] : await listOpenPullRequests({base: refreshBranch}); const refreshTargets = []; + const refreshTargetKeys = new Set(); + const addRefreshTarget = (resolved) => { + if (!resolved) return; + const {prNumber, baseRef, baseSha, headSha, mergeSha} = resolved.tuple; + const key = JSON.stringify([prNumber, baseRef, baseSha, headSha, mergeSha]); + if (refreshTargetKeys.has(key)) return; + refreshTargetKeys.add(key); + refreshTargets.push(resolved); + }; for (let pullRequestIndex = 0; pullRequestIndex < pullRequests.length; pullRequestIndex += 1) { const listedPullRequest = pullRequests[pullRequestIndex]; if (listedPullRequest.state !== "open" || @@ -1130,9 +1141,7 @@ jobs: ); continue; } - if (resolved) { - refreshTargets.push(resolved); - } + addRefreshTarget(resolved); } if (workflowRun.event === "pull_request") { // A retarget/edit can carry an unusable event merge SHA. CI completion @@ -1159,7 +1168,7 @@ jobs: } const resolved = await resolveExactMerge(source.number, source.base.ref, sourceBaseSha, refreshSha); if (resolved && !refreshTargets.some((target) => target.tuple.prNumber === resolved.tuple.prNumber)) { - refreshTargets.push(resolved); + addRefreshTarget(resolved); } } } diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index f12e3e5af1..c2d147d353 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -1814,11 +1814,22 @@ jobs: if (positiveInteger(replacement.run_attempt) && (!cancelledReplacement || replacement.id !== cancelledReplacement.id || replacement.run_attempt !== cancelledReplacement.run_attempt)) { - cancelledReplacement = {id: replacement.id, run_attempt: replacement.run_attempt, terminalObservedAt: null}; + cancelledReplacement = {id: replacement.id, run_attempt: replacement.run_attempt, terminalObservedAt: null, sparseStatusObservedAt: null}; } const cancelledOrTimedOut = replacement.status === "completed" && ["cancelled", "timed_out"].includes(replacement.conclusion); - if (cancelledOrTimedOut || await provesOrdinaryTypedFailure(replacement, currentIdentity)) { + let ordinaryTypedFailure = false; + if (!cancelledOrTimedOut) { + try { + ordinaryTypedFailure = await provesOrdinaryTypedFailure(replacement, currentIdentity); + } catch (error) { + if (!isTransientGitHubFailure(error)) throw error; + core.warning(`Exact typed failure proof temporarily unavailable: ${error.message ?? String(error)}`); + await new Promise((resolve) => setTimeout(resolve, snapshotSleepMs)); + continue smokeGatePolling; + } + } + if (cancelledOrTimedOut || ordinaryTypedFailure) { if (cancelledOrTimedOut && !isReplaceableTypedProducer(replacement, currentIdentity)) { core.setFailed("Cancelled or timed-out typed runtime producer has an invalid source identity."); return; @@ -1835,9 +1846,17 @@ jobs: await new Promise((resolve) => setTimeout(resolve, sleepMs)); continue smokeGatePolling; } - if (cancelledReplacement?.id === replacement.id && - (replacement.status === "completed" || replacement.status == null)) { - cancelledReplacement.terminalObservedAt ??= Date.now(); + if (cancelledReplacement?.id === replacement.id) { + if (replacement.status == null) { + cancelledReplacement.sparseStatusObservedAt ??= Date.now(); + if (Date.now() - cancelledReplacement.sparseStatusObservedAt >= completedSnapshotTimeoutMs) { + core.setFailed("Cancelled runtime replacement did not expose exact status within the snapshot convergence allowance."); + return; + } + } else { + cancelledReplacement.sparseStatusObservedAt = null; + if (replacement.status === "completed") cancelledReplacement.terminalObservedAt ??= Date.now(); + } } // Discovery bounds absence, not execution of an identified replacement. // Its completion still shares the unchanged overall Smoke deadline. @@ -1847,7 +1866,7 @@ jobs: (cancelledReplacement?.id === replacement.id ? cancelledReplacement.run_attempt : "missing"); const replacementProofKey = `same-tuple-replacement:${identityKey(currentIdentity)}:${replacement.id}:${snapshotAttempt}`; - if ((replacement.status === "completed" || replacement.status == null) && + if (replacement.status === "completed" && incompleteRefreshKey !== replacementProofKey) { incompleteRefreshKey = replacementProofKey; incompleteRefreshObservedAt = Date.now(); @@ -2010,7 +2029,18 @@ jobs: } const cancelledOrTimedOut = matching.event === "repository_dispatch" && matching.status === "completed" && ["cancelled", "timed_out"].includes(matching.conclusion); - if (cancelledOrTimedOut || await provesOrdinaryTypedFailure(matching, currentIdentity)) { + let ordinaryTypedFailure = false; + if (!cancelledOrTimedOut) { + try { + ordinaryTypedFailure = await provesOrdinaryTypedFailure(matching, currentIdentity); + } catch (error) { + if (!isTransientGitHubFailure(error)) throw error; + core.warning(`Exact typed failure proof temporarily unavailable: ${error.message ?? String(error)}`); + await new Promise((resolve) => setTimeout(resolve, snapshotSleepMs)); + continue smokeGatePolling; + } + } + if (cancelledOrTimedOut || ordinaryTypedFailure) { if (cancelledOrTimedOut && !isReplaceableTypedProducer(matching, currentIdentity)) { core.setFailed("Cancelled or timed-out typed runtime producer has an invalid source identity."); return; diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 7c7576d4b4..add17bc443 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -233,7 +233,7 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 canonical Account UUIDs. Account resolves known subjects through one local UUID batch query with the same persisted provenance and source-row checks as scalar identity reads, then returns policies keyed by UUID. Unknown or unproven entries are intentionally omitted so Social applies complete `PRIVATE` redaction. - `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current gRPC adapter returns `FAILED_PRECONDITION` before selector parsing or owner reads; this does not implement the target export operation. -- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry of the currently bound reservation attempt, fence, complete payload and digest replays its durably retained result. Outside proof-backed rearm, a change to a bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest conflicts before usage mutation only if it differs from an existing retained binding. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns the typed `TENANT_BILLING_BLOCKED` response. This billing refusal does not itself bind the attempt, consume the quota-refusal budget, or create a durable decision receipt; it remains available when no refusal-budget row exists. Fresh creation-eligible evidence with checked insufficient capacity returns the typed `CAPACITY_QUOTA_EXCEEDED` response only after the exact durable `NO_ACCEPT` decision commits. If its refusal budget is missing or exhausted, Account returns non-OK `ENTITLEMENT_UNAVAILABLE` instead; no quota receipt or settlement authority is issued. Each refusal response is correlated to the exact original attempt, mutation digest, snapshot and evaluation. A quota refusal includes the immutable Account decision UUID only after an exact durable `NO_ACCEPT` commits. A matching exact retry returns the retained receipt. A quota refusal without that receipt grants no evidence settlement authority. The response contains exactly one commitment or one typed refusal. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a mismatch against an existing retained binding outside proof-backed rearm. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). +- `CommitTenantCapacityAdmission` – **internal RPC with an unregistered receiving implementation** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the target contract's exact complete Account-authenticated entitlement bundle from `GetTenantEntitlementsForRuntime`, including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. The current numeric runtime endpoint returns `ENTITLEMENT_UNAVAILABLE` and is not qualified player evidence; the separately prepared `PLAYER_ADMISSION` evidence comes from Account's manually composed caller-bound `AccountPlayerAdmissionEntitlementOwner`/receiver and Game Session client. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry of the currently bound reservation attempt, fence, complete payload and digest replays its durably retained result. Outside proof-backed rearm, a change to a bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest conflicts before usage mutation when it differs from an existing retained binding. After transport validation, Account resolves exact replay/conflict first, then checks retained/current evidence, supported shape, and quota. Fresh authoritative billing or non-creating entitlement refusal returns the typed `TENANT_BILLING_BLOCKED` response. This billing refusal does not itself bind the attempt, consume the quota-refusal budget, or create a durable decision receipt; it remains available when no refusal-budget row exists. Fresh creation-eligible evidence with checked insufficient capacity returns the typed `CAPACITY_QUOTA_EXCEEDED` response only after the exact durable `NO_ACCEPT` decision commits. If its refusal budget is missing or exhausted, Account returns non-OK `ENTITLEMENT_UNAVAILABLE` instead; no quota receipt or settlement authority is issued. Each refusal response is correlated to the exact original attempt, mutation digest, snapshot and evaluation. A quota refusal includes the immutable Account decision UUID only after an exact durable `NO_ACCEPT` commits. A matching exact retry returns the retained receipt. A quota refusal without that receipt grants no evidence settlement authority. The response contains exactly one commitment or one typed refusal. An authenticated exact retained evaluation outside its qualified time window or superseded by a qualified newer billing cutoff returns `CAPACITY_ADMISSION_STALE` with `UNAVAILABLE`. Missing or unqualified current entitlement owner evidence or its dependency returns `ENTITLEMENT_UNAVAILABLE`. The receiver preserves `AUTH_UNAVAILABLE` for authentication authority unavailability, `PERMISSION_DENIED` for an authenticated caller mismatch, `INVALID_ARGUMENT` for malformed requests, and `IDEMPOTENCY_CONFLICT` with `ALREADY_EXISTS` for a mismatch against an existing retained binding outside proof-backed rearm. The prepared receiver also rejects a structurally valid initial attempt whose `capacityRearmFence` is not `1`, even when no reservation exists; that rejection occurs before retained quota-denial lookup. The Game Session client validates the bounded details and preserves the gRPC outcome. These errors grant no release or rearm authority. Rearm, recovery, and execution still require creation-committable evidence. The shared proto/codec, bounded private mTLS receiver, Game Session adapter and Account durable owner are locally prepared but unqualified and unregistered. The current owner accepts only exact new player-binding shape; World lifecycle activation and zero-delta recovery remain held without genuine current producers. Current source and proof limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#strict-tenant-capacity-owner-preparation). See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact retries of the currently bound attempt, fence, complete payload and digest replay its durably retained reservation result; superseded pre-rearm attempts do not replay after a committed rearm. This reservation rule is separate from replay of an exact retained quota-denial decision, which has no reservation. A changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. Exact replay is guaranteed only for outcomes Account durably retained. A billing or non-creating entitlement refusal that did not retain a decision receipt is not a replayable outcome; a later retry rechecks current evidence freshness before deciding and cannot treat the earlier refusal as a retained result. diff --git a/dev-tools/tests/dev-account-v1040-4-probe-contract.sh b/dev-tools/tests/dev-account-v1040-4-probe-contract.sh index e7d0de0b9c..1dcb852afb 100644 --- a/dev-tools/tests/dev-account-v1040-4-probe-contract.sh +++ b/dev-tools/tests/dev-account-v1040-4-probe-contract.sh @@ -206,8 +206,12 @@ kubectl() { ;; "--request-timeout=10s -n dev logs job/$PROBE_FIXTURE_JOB_NAME") touch "$PROBE_JOB_READ" - printf 'account-v1040-4-probe=retained-no-duplicates namespace=dev namespace_uid=%s deployed_sha=%s target_sha=%s schema=account_service applied_origin_migrations=3 checksum_comparison=verified-v1040-prefix\n' \ - "$PROBE_FIXTURE_UID" "$PROBE_FIXTURE_BASE" "$PROBE_FIXTURE_HEAD" + local captured_namespace captured_uid captured_base captured_head captured_prefix + IFS=$'\t' read -r captured_namespace captured_uid captured_base captured_head captured_prefix < <( + jq -er '.spec.template.spec.containers[0].args[2:] | @tsv' "$PROBE_JOB_MANIFEST" + ) + printf 'account-v1040-4-probe=retained-no-duplicates namespace=%s namespace_uid=%s deployed_sha=%s target_sha=%s schema=account_service applied_origin_migrations=%s checksum_comparison=verified-v1040-prefix\n' \ + "$captured_namespace" "$captured_uid" "$captured_base" "$captured_head" "$captured_prefix" ;; "--request-timeout=10s -n dev logs job/$PROBE_FIXTURE_JOB_NAME --tail=1") printf '%s\n' 'Account V1040.4 probe found duplicate retained admission attempts. Account-owned disposition is required.' @@ -243,13 +247,16 @@ run_protected_probe() { run_protected_probe >"$temp_dir/receipt" grep -q 'checksum_comparison=verified-v1040-prefix' "$temp_dir/receipt" [[ -f "$PROBE_JOB_DELETED" ]] -jq -e ' +jq -e \ + --arg probe "$(cat "$root_dir/dev-tools/deploy/probe-dev-account-v1040-4.sh")" \ + --arg namespace dev --arg uid "$namespace_uid" --arg base "$deployed_sha" \ + --arg head "$PROBE_FIXTURE_HEAD" --arg prefix 3 ' .kind == "Job" and .metadata.namespace == "dev" and .spec.backoffLimit == 0 and .spec.activeDeadlineSeconds == 70 and .spec.ttlSecondsAfterFinished == 300 and .spec.template.spec.automountServiceAccountToken == false and (.spec.template.spec.containers | if type == "array" then length == 1 and .[0].command == ["bash", "-c"] and - (.[0].args[0] | contains("REPEATABLE READ READ ONLY")) and + .[0].args == [$probe, "probe-dev-account-v1040-4", $namespace, $uid, $base, $head, $prefix] and .[0].env == [ {name:"FIREMUD_POSTGRES_USER",valueFrom:{secretKeyRef:{name:"firemud-secret",key:"FIREMUD_POSTGRES_USER"}}}, {name:"PGPASSWORD",valueFrom:{secretKeyRef:{name:"firemud-secret",key:"FIREMUD_POSTGRES_PASSWORD"}}} diff --git a/dev-tools/tests/dev-demo-workflow-contract.sh b/dev-tools/tests/dev-demo-workflow-contract.sh index b0a551047d..6fb65d7339 100644 --- a/dev-tools/tests/dev-demo-workflow-contract.sh +++ b/dev-tools/tests/dev-demo-workflow-contract.sh @@ -1331,8 +1331,21 @@ if origin_probe.get("env", {}).get("DEV_NAMESPACE_MANAGER_KUBECONFIG") != ( "${{ runner.temp }}/dev-demo-namespace-manager.kubeconfig" ): raise SystemExit("the Account probe must use the existing namespace-manager kubeconfig for readback") -if "run-dev-account-v1040-4-probe.sh" not in origin_probe.get("run", ""): - raise SystemExit("the V1040.4 gate must call the protected probe helper") +origin_probe_bindings = { + "RUNTIME_NAMESPACE": "${{ needs.dev-demo-plan.outputs.namespace }}", + "NAMESPACE_UID": "${{ steps.v2-migration-mode.outputs.account_origin_namespace_uid }}", + "DEPLOYED_SHA": "${{ steps.v2-migration-mode.outputs.account_origin_base_sha }}", + "HEAD_SHA": "${{ needs.dev-demo-plan.outputs.head_sha }}", + "ORIGIN_PREFIX": "${{ steps.v2-migration-mode.outputs.account_origin_prefix }}", +} +if any(origin_probe.get("env", {}).get(key) != value for key, value in origin_probe_bindings.items()): + raise SystemExit("the V1040.4 gate must bind exact classifier comparison outputs") +origin_probe_command = [ + "bash ./dev-tools/deploy/run-dev-account-v1040-4-probe.sh " + chr(92), + '"$RUNTIME_NAMESPACE" "$NAMESPACE_UID" "$DEPLOYED_SHA" "$HEAD_SHA" "$ORIGIN_PREFIX"', +] +if [line.strip() for line in origin_probe.get("run", "").splitlines()[-2:]] != origin_probe_command: + raise SystemExit("the V1040.4 gate must call the probe with the exact ordered comparison") deploy_condition = deploy_by_name["Deploy dev-demo release"].get("if", "") expected_deploy_condition = ( "${{ steps.cluster-access.outputs.available == 'true' && " diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index 325da1ae69..86d1acb32a 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -1352,6 +1352,26 @@ async function runDispatcher({ name === "pulls.listFiles" && String(options.pull_number) === source.prNumber).map(({options}) => options), {pull_number: Number(source.prNumber)}); assertRequestContracts(pagedFanout); + // Model both windows independently of AbortSignal.timeout and of one another. + const fanoutStart = Date.parse("2026-01-08T00:00:00Z"); + const lastPost = pagedFanout.apiRequestRecords.findLastIndex(({name}) => name === "repos.createDispatchEvent"); + assert(lastPost >= 0 && lastPost < pagedFanout.apiRequestRecords.length - 1, + "exercise both fan-out and post-dispatch visibility requests"); + const visibilityStart = pagedFanout.apiRequestRecords[lastPost].issuedAt + 25; + for (const [index, {name, options, issuedAt}] of pagedFanout.apiRequestRecords.entries()) { + const phaseDeadline = index <= lastPost ? fanoutStart + 12 * 60 * 1000 : visibilityStart + 120000; + assert.equal(options.request.signal.timeoutMs, phaseDeadline - issuedAt, + `${name} must use the remaining budget of its independently modeled phase`); + } + const samePageBoundary = await runDispatcher({ + tuples: [tuple, tupleFor(102, "d", "e")], + pullListResponse: (request, pulls) => request.page === 1 + ? [...Array.from({length: 99}, () => ({state: "closed"})), pulls[0]] + : pulls, + }); + assert.deepEqual(runtimeDispatches(samePageBoundary).map(item => item.client_payload.pr_number).sort(), + ["101", "102"], "a duplicated page boundary must not dispatch one exact tuple twice"); + assert.deepEqual(samePageBoundary.errors, []); for (const jobPage of [ () => ({total_count: 1, jobs: []}), () => ({total_count: 1, jobs: {}}), @@ -1942,14 +1962,14 @@ async function runDispatcher({ assert.deepEqual(result.errors, []); } const recentTransition = await runDispatcher({ - tuples: [tuple], callback: {updated_at: "2026-01-01T06:00:00Z"}, + tuples: [tuple], callback: {updated_at: "2026-01-04T00:00:00Z"}, inventories: {repository_dispatch: [completedRefresh]}, runtimeAttemptJobs: {[completedRefresh.id]: {total_count: 1, jobs: [{...successfulJob, steps: successfulJob.steps.map(step => ({...step, conclusion: step.name.startsWith("Known canonical transition") ? "success" : "skipped"})), }]}}, }); - assert.deepEqual(numbers(recentTransition), [], "a recent successful PLAY diagnostic keeps its existing dispatch hold"); + assert.deepEqual(numbers(recentTransition), [], "an exact successful PLAY diagnostic retains its hold after later Validation"); assert.deepEqual(recentTransition.errors, []); const staleSuccess = await runDispatcher({tuples: [tuple], inventories: {repository_dispatch: [completedRefresh]}, runtimeAttemptJobs: successfulJobs, runtimeRunOverrides: {[completedRefresh.id]: reads => reads > 1 ? {run_attempt: 2} : {}}}); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index d51aa8ad9c..e9d6311f4e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -324,6 +324,54 @@ void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { } } + @Test + void v1040_5AllowsTheFinalRefusalAndAnExactRetryWithoutSpendingAnotherSlot() { + String schema = "capacity_v1040_5_" + UUID.randomUUID().toString().replace("-", ""); + new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + var flyway = capacityMigrations(data, schema).target("1040.5").load(); + flyway.migrate(); + assertThat(flyway.info().current().getVersion().getVersion()).isEqualTo("1040.5"); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); + var tenant = source(); + transaction.executeWithoutResult(status -> { + new FreshTenantIdentityAssociationRepository(dsl, "prod").importVerified(tenant); + new AccountCapacityRefusalBudgetRepository(dsl).provision(tenant.canonicalTenantId(), 1); + }); + String insert = + """ + 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, refusal_code) + VALUES (?, ?, ?, 1, ?, ?, ?, 'NO_ACCEPT', ?, 'CAPACITY_QUOTA_EXCEEDED') + ON CONFLICT DO NOTHING + """; + UUID decision = UUID.randomUUID(); + Object[] original = { + tenant.canonicalTenantId(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), + "a".repeat(64), new byte[] {1}, decision + }; + assertThat(dsl.execute(insert, original)).isOne(); + Object[] retry = original.clone(); + retry[retry.length - 1] = UUID.randomUUID(); + assertThat(dsl.execute(insert, retry)).isZero(); + assertThatThrownBy(() -> + dsl.execute( + insert, tenant.canonicalTenantId(), UUID.randomUUID(), UUID.randomUUID(), + UUID.randomUUID(), "b".repeat(64), new byte[] {2}, UUID.randomUUID())) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + assertThat(dsl.fetch("SELECT decision_id FROM account_capacity_origin_decisions") + .getValues("decision_id", UUID.class)) + .containsExactly(decision); + } finally { + new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + @Test void refusalBudgetRunsAfterIdentityArbitrationAndCountsTheInsertedLastSlot() throws Exception { String schema = "capacity_arbitration_" + UUID.randomUUID().toString().replace("-", ""); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java index 25147698a9..0dc6506fe7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountTenantCapacityGrpcServiceTest.java @@ -55,7 +55,9 @@ private enum RetainedEvidence { ABSENT, ACCEPTED, GENERIC_NO_ACCEPT, - WRONG_FINGERPRINT + WRONG_FINGERPRINT, + WRITABLE_CONNECTION, + AUTOCOMMIT_CONNECTION } @Test @@ -212,7 +214,8 @@ void quotaDenialReadUsesOnlyTheImmutableSelect(RetainedEvidence evidence) throws var decisionId = UUID.randomUUID(); DSLContext dsl = mock(); Connection connection = mock(); - when(connection.isReadOnly()).thenReturn(true); + when(connection.isReadOnly()).thenReturn(evidence != RetainedEvidence.WRITABLE_CONNECTION); + when(connection.getAutoCommit()).thenReturn(evidence == RetainedEvidence.AUTOCOMMIT_CONNECTION); doAnswer( invocation -> { invocation.getArgument(0, ConnectionRunnable.class).run(connection); @@ -294,7 +297,12 @@ void quotaDenialReadUsesOnlyTheImmutableSelect(RetainedEvidence evidence) throws } verifyNoMoreInteractions(observer); verify(dsl).connection(any(ConnectionRunnable.class)); - verify(dsl).fetchOne(sql, key); + if (evidence == RetainedEvidence.WRITABLE_CONNECTION + || evidence == RetainedEvidence.AUTOCOMMIT_CONNECTION) { + verify(dsl, never()).fetchOne(sql, key); + } else { + verify(dsl).fetchOne(sql, key); + } verifyNoMoreInteractions(dsl); verifyNoInteractions(accounts, memberships, issuances, scopes, clock); } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java index 7887429652..f62a42ca0b 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java @@ -66,6 +66,15 @@ void domainRefusalsRequireTheExactOriginalAndExclusiveResponseAlternative() { var commitment = TenantCapacityAdmissionGrpcCodec.toResponse(creatingRequest, result(creatingRequest)); assertThat(TenantCapacityAdmissionGrpcCodec.readRefusal(creatingRequest, commitment)).isEmpty(); + assertThat(TenantCapacityAdmissionGrpcCodec.requireResponse(creatingRequest, commitment)) + .isEqualTo(result(creatingRequest)); + var exactRefusal = + TenantCapacityAdmissionGrpcCodec.toRefusal(creatingRequest, Failure.CAPACITY_QUOTA_EXCEEDED); + var mixed = commitment.toBuilder().addRefusal(exactRefusal.getRefusal(0)).build(); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.requireResponse(creatingRequest, mixed)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusal(creatingRequest, mixed)) + .isInstanceOf(IllegalArgumentException.class); for (var code : List.of(Failure.TENANT_BILLING_BLOCKED, Failure.CAPACITY_QUOTA_EXCEEDED)) { Request request = CapacityAdmissionTestFixture.playerRequest(code == Failure.CAPACITY_QUOTA_EXCEEDED); diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index ba1b287749..f2a5cded47 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -14,6 +14,7 @@ import java.time.ZoneOffset; import java.util.List; import java.util.Set; +import java.util.concurrent.TimeUnit; import net.firedevops.firemud.account.v1.AccountServiceGrpc; import net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeRequest; @@ -81,12 +82,14 @@ void privateCapacityRpcsRemainUnimplementedOnSharedFakeRuntimeServer() throws Ex try { var stub = AccountServiceGrpc.newBlockingStub(channel); var request = CommitTenantCapacityAdmissionRequest.getDefaultInstance(); - assertThatThrownBy(() -> stub.commitTenantCapacityAdmission(request)) + assertThatThrownBy(() -> + stub.withDeadlineAfter(2, TimeUnit.SECONDS).commitTenantCapacityAdmission(request)) .isInstanceOfSatisfying( StatusRuntimeException.class, failure -> assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNIMPLEMENTED)); - assertThatThrownBy(() -> stub.readTenantCapacityQuotaDenial(request)) + assertThatThrownBy(() -> + stub.withDeadlineAfter(2, TimeUnit.SECONDS).readTenantCapacityQuotaDenial(request)) .isInstanceOfSatisfying( StatusRuntimeException.class, failure -> diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java index 87c555be2f..936c2a41da 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountTenantCapacityClientMtlsTest.java @@ -296,8 +296,17 @@ public void commitTenantCapacityAdmission( @Test void restartedClientRecoversTheOriginalQuotaDenialWithoutAnotherCommit() throws Exception { + assertOriginalQuotaDenialRecovery(true); + } + + @Test + void restartedClientRefusesQuotaDenialWithoutAReceiptAndDoesNotCommitAgain() throws Exception { + assertOriginalQuotaDenialRecovery(false); + } + + private void assertOriginalQuotaDenialRecovery(boolean receiptPresent) throws Exception { var request = CapacityAdmissionTestFixture.playerRequest(); - var denialId = UUID.randomUUID(); + UUID denialId = receiptPresent ? UUID.randomUUID() : null; var commits = new AtomicInteger(); var reads = new AtomicInteger(); var failedCommit = new AtomicReference(); @@ -334,11 +343,18 @@ public void readTenantCapacityQuotaDenial( assertThatThrownBy(() -> original.commit(request, deadline())) .isInstanceOf(StatusRuntimeException.class); } - assertThat(failedCommit.get()) - .isEqualTo(TenantCapacityAdmissionGrpcCodec.toRequest(request)); + assertThat(failedCommit.get()).isEqualTo(TenantCapacityAdmissionGrpcCodec.toRequest(request)); try (var restarted = client(server)) { restarted.init(); - assertThat(restarted.readRetainedQuotaDenial(request, deadline())).isEqualTo(denialId); + if (receiptPresent) { + assertThat(restarted.readRetainedQuotaDenial(request, deadline())).isEqualTo(denialId); + } else { + assertThatThrownBy(() -> restarted.readRetainedQuotaDenial(request, deadline())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNKNOWN)); + } } assertThat(commits).hasValue(1); assertThat(reads).hasValue(1); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java index ba72bdda61..946a9f08ab 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java @@ -89,28 +89,31 @@ static void createTestPki() throws Exception { @AfterEach void stopTransportAndClearAuthContext() throws Exception { - try { - if (noCertificateChannel != null) { - try { - assertThat(noCertificateChannel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)) - .isTrue(); - } finally { - noCertificateChannel = null; - } - } - } finally { - try { - if (server != null) { - try { - server.shutdownNow(); - assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); - } finally { - server = null; - } - } - } finally { - SessionContext.clear(); - } + ManagedChannel channel = noCertificateChannel; + Server receiver = server; + noCertificateChannel = null; + server = null; + // Close in reverse order. A server failure is suppressed beneath the first channel failure. + try (AutoCloseable clearAuthContext = SessionContext::clear; + AutoCloseable stopServer = + () -> { + if (receiver != null) { + receiver.shutdownNow(); + assertThat(receiver.awaitTermination(2, TimeUnit.SECONDS)) + .as("server termination") + .isTrue(); + } + }; + AutoCloseable stopChannel = + () -> { + if (channel != null) { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)) + .as("channel termination") + .isTrue(); + } + }) { + // All cleanup is owned by the resources. } } @@ -134,6 +137,36 @@ void channelTerminationFailureStillStopsServerAndClearsAuthContext() throws Exce assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); } + @Test + void bothTerminationFailuresPreserveTheChannelFailureAndClearAuthContext() throws Exception { + var channel = mock(ManagedChannel.class); + var receiver = mock(Server.class); + when(channel.awaitTermination(2, TimeUnit.SECONDS)).thenReturn(false); + when(receiver.awaitTermination(2, TimeUnit.SECONDS)).thenReturn(false); + noCertificateChannel = channel; + server = receiver; + SessionContext.setContext("42", List.of("tenantAdmin"), java.util.Map.of()); + + assertThatThrownBy(this::stopTransportAndClearAuthContext) + .isInstanceOfSatisfying( + AssertionError.class, + failure -> { + assertThat(failure).hasMessageContaining("channel termination"); + assertThat(failure.getSuppressed()) + .singleElement() + .satisfies(suppressed -> + assertThat(suppressed) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("server termination")); + }); + + verify(channel).shutdownNow(); + verify(receiver).shutdownNow(); + assertThat(noCertificateChannel).isNull(); + assertThat(server).isNull(); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + } + @Test void serverTerminationFailureStillClearsAuthContext() throws Exception { var receiver = mock(Server.class); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java index 9b3a44c515..8c20cb624b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServerTest.java @@ -19,12 +19,19 @@ class EntityManagementStubServerTest { + private static AutoCloseable verifyChannelShutdown(ManagedChannel channel) { + return () -> { + channel.shutdownNow(); + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + }; + } + @Test void returnsPongToPingOverLoopbackGrpc() throws Exception { try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); - try { + try (var shutdown = verifyChannelShutdown(channel)) { EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = EntityManagementServiceGrpc.newBlockingStub(channel); @@ -32,8 +39,6 @@ void returnsPongToPingOverLoopbackGrpc() throws Exception { assertThat(response.getMessage()).isEqualTo("pong"); assertThat(response.hasError()).isFalse(); - } finally { - assertThat(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue(); } } } @@ -43,7 +48,7 @@ void listsOnlyThePersistedSharedCharacterForTheRequestedTenantAndAccount() throw try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); - try { + try (var shutdown = verifyChannelShutdown(channel)) { EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = EntityManagementServiceGrpc.newBlockingStub(channel); @@ -59,8 +64,6 @@ void listsOnlyThePersistedSharedCharacterForTheRequestedTenantAndAccount() throw assertThat(response.hasError()).isFalse(); assertThat(response.getCharactersList()).containsExactly(sharedCharacter(fixture.name())); } - } finally { - assertThat(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue(); } } } @@ -71,7 +74,7 @@ void resetCharactersRestoresDefaultSharedCharactersAfterAnEmptyOverride() throws server.setCharacters(List.of()); ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); - try { + try (var shutdown = verifyChannelShutdown(channel)) { EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = EntityManagementServiceGrpc.newBlockingStub(channel); @@ -88,8 +91,6 @@ void resetCharactersRestoresDefaultSharedCharactersAfterAnEmptyOverride() throws stub, "1", accountUuid(7L), PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); assertThat(resetResponse.hasError()).isFalse(); assertThat(resetResponse.getCharactersList()).containsExactly(sharedCharacter("Emberline")); - } finally { - assertThat(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue(); } } } @@ -115,7 +116,7 @@ void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { server.setCharacters(List.of(firstPlayer, secondPlayer)); ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); - try { + try (var shutdown = verifyChannelShutdown(channel)) { EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = EntityManagementServiceGrpc.newBlockingStub(channel); @@ -143,8 +144,6 @@ void listsLoadActorsByTheirPersistedTenantAndAccountOwner() throws Exception { PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); - } finally { - assertThat(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue(); } } } @@ -154,7 +153,7 @@ void unknownOrMismatchedTenantAndAccountReturnNoCharacters() throws Exception { try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); - try { + try (var shutdown = verifyChannelShutdown(channel)) { EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = EntityManagementServiceGrpc.newBlockingStub(channel); @@ -171,8 +170,6 @@ void unknownOrMismatchedTenantAndAccountReturnNoCharacters() throws Exception { PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) .getCharactersList()) .isEmpty(); - } finally { - assertThat(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue(); } } } @@ -182,7 +179,7 @@ void unsupportedPlayableStateScopesReturnNoCharacters() throws Exception { try (EntityManagementStubServer server = new EntityManagementStubServer(0)) { ManagedChannel channel = ManagedChannelBuilder.forTarget(server.endpoint()).usePlaintext().build(); - try { + try (var shutdown = verifyChannelShutdown(channel)) { EntityManagementServiceGrpc.EntityManagementServiceBlockingStub stub = EntityManagementServiceGrpc.newBlockingStub(channel); @@ -202,8 +199,6 @@ void unsupportedPlayableStateScopesReturnNoCharacters() throws Exception { PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED) .getCharactersList()) .isEmpty(); - } finally { - assertThat(channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)).isTrue(); } } } From 3fad0acbce2e97e89e894474f5d51aa828018689 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Tue, 24 Nov 2026 03:27:46 +1300 Subject: [PATCH 51/96] Pin the exact revised runtime producer proof --- .github/workflows/smoke.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index c2d147d353..727654e930 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -632,10 +632,11 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "05571b3b89ea77cdff497aa8f93bea13d10de12300c205a42e32da00d81dd98d"; + const canonicalRuntimeWorkflowSha256 = "1d09fe191e67b07be1c4d01cd677a94b32871fd3640ebce2c96f7e696f08014a"; // Only authenticated default-branch refreshes may use retained successful definitions. // Keep the pre-rollout default and predecessor definitions for mixed-version runs. const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set([ + "05571b3b89ea77cdff497aa8f93bea13d10de12300c205a42e32da00d81dd98d", // immediate predecessor; verified typed refresh only "2a769961890119fc91a83b2987537122704f6624035d1572b446569d5f9d11a1", // default at 1eca914a "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b", // default at 3b81c438 "107a7bc895f890173161ea09f707ce93d8e170093aa8c8c528fc5f98430e1bac", // immediate pre-retry definition From 279b943e8533484518b97f6a951f6721726c038e Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Tue, 24 Nov 2026 03:34:48 +1300 Subject: [PATCH 52/96] Format Account and codec regression fixtures --- ...acityMigrationPostgresIntegrationTest.java | 24 ++++++++++++++----- .../TenantCapacityAdmissionGrpcCodecTest.java | 6 +++-- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index e9d6311f4e..3afd0234ba 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -350,8 +350,13 @@ void v1040_5AllowsTheFinalRefusalAndAnExactRetryWithoutSpendingAnotherSlot() { """; UUID decision = UUID.randomUUID(); Object[] original = { - tenant.canonicalTenantId(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), - "a".repeat(64), new byte[] {1}, decision + tenant.canonicalTenantId(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "a".repeat(64), + new byte[] {1}, + decision }; assertThat(dsl.execute(insert, original)).isOne(); Object[] retry = original.clone(); @@ -359,13 +364,20 @@ void v1040_5AllowsTheFinalRefusalAndAnExactRetryWithoutSpendingAnotherSlot() { assertThat(dsl.execute(insert, retry)).isZero(); assertThatThrownBy(() -> dsl.execute( - insert, tenant.canonicalTenantId(), UUID.randomUUID(), UUID.randomUUID(), - UUID.randomUUID(), "b".repeat(64), new byte[] {2}, UUID.randomUUID())) + insert, + tenant.canonicalTenantId(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "b".repeat(64), + new byte[] {2}, + UUID.randomUUID())) .isInstanceOfSatisfying( org.jooq.exception.DataAccessException.class, failure -> assertThat(failure.sqlState()).isEqualTo("23514")); - assertThat(dsl.fetch("SELECT decision_id FROM account_capacity_origin_decisions") - .getValues("decision_id", UUID.class)) + assertThat( + dsl.fetch("SELECT decision_id FROM account_capacity_origin_decisions") + .getValues("decision_id", UUID.class)) .containsExactly(decision); } finally { new JdbcTemplate(POSTGRES.dataSource()).execute("DROP SCHEMA " + schema + " CASCADE"); diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java index f62a42ca0b..cd0645b4f6 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/capacity/TenantCapacityAdmissionGrpcCodecTest.java @@ -69,9 +69,11 @@ void domainRefusalsRequireTheExactOriginalAndExclusiveResponseAlternative() { assertThat(TenantCapacityAdmissionGrpcCodec.requireResponse(creatingRequest, commitment)) .isEqualTo(result(creatingRequest)); var exactRefusal = - TenantCapacityAdmissionGrpcCodec.toRefusal(creatingRequest, Failure.CAPACITY_QUOTA_EXCEEDED); + TenantCapacityAdmissionGrpcCodec.toRefusal( + creatingRequest, Failure.CAPACITY_QUOTA_EXCEEDED); var mixed = commitment.toBuilder().addRefusal(exactRefusal.getRefusal(0)).build(); - assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.requireResponse(creatingRequest, mixed)) + assertThatThrownBy( + () -> TenantCapacityAdmissionGrpcCodec.requireResponse(creatingRequest, mixed)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> TenantCapacityAdmissionGrpcCodec.readRefusal(creatingRequest, mixed)) .isInstanceOf(IllegalArgumentException.class); From 4fe2ff806cb7bfc62ea1437280f487bcb7d16908 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Tue, 24 Nov 2026 04:26:11 +1300 Subject: [PATCH 53/96] Preserve exact authorized trusted refresh definitions --- .github/workflows/smoke.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 727654e930..bffcb2761d 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -636,7 +636,6 @@ jobs: // Only authenticated default-branch refreshes may use retained successful definitions. // Keep the pre-rollout default and predecessor definitions for mixed-version runs. const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set([ - "05571b3b89ea77cdff497aa8f93bea13d10de12300c205a42e32da00d81dd98d", // immediate predecessor; verified typed refresh only "2a769961890119fc91a83b2987537122704f6624035d1572b446569d5f9d11a1", // default at 1eca914a "877a1a1656f6b625c9c2cbece0cf55d8657de320ceae45f3e6c50301a850b30b", // default at 3b81c438 "107a7bc895f890173161ea09f707ce93d8e170093aa8c8c528fc5f98430e1bac", // immediate pre-retry definition From 301d7d2665c2ffcd3378d3695bb9cd04172b2a28 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 28 Nov 2026 06:32:13 +1300 Subject: [PATCH 54/96] Retain exact dev-demo and runtime publication evidence in workflow outputs --- .github/workflows/dev-demo.yml | 198 +++++++++++++----- .../workflows/publish-pr-runtime-images.yml | 50 ++++- .github/workflows/runtime-images.yml | 5 +- .github/workflows/smoke.yml | 2 +- .../architecture/system-architecture-cicd.md | 4 +- ...system-architecture-database-migrations.md | 4 + .../detect-hosted-v2-migration-activation.sh | 1 + .../hosted/dev-demo/write-bootstrap-result.py | 50 +++++ .../hosted/shared/wait-for-runtime-images.sh | 125 +++++++++-- dev-tools/tests/dev-demo-workflow-contract.sh | 116 ++++++++++ .../tests/pr-retarget-workflow-contract.sh | 86 ++++++-- .../pr-runtime-image-publication-contract.sh | 86 ++++++-- .../tests/preview-merge-image-tag-contract.sh | 16 +- .../validation/check_dev_demo_summary.py | 2 +- 14 files changed, 623 insertions(+), 122 deletions(-) create mode 100644 dev-tools/hosted/dev-demo/write-bootstrap-result.py diff --git a/.github/workflows/dev-demo.yml b/.github/workflows/dev-demo.yml index da5f43748e..34e9feb5d6 100644 --- a/.github/workflows/dev-demo.yml +++ b/.github/workflows/dev-demo.yml @@ -546,13 +546,84 @@ jobs: echo "DEMO_SMOKE_WORLD=${DEMO_SMOKE_WORLD}" } >> "$GITHUB_ENV" + - name: Capture dev-demo bootstrap intent + id: bootstrap-intent + if: ${{ success() && steps.record-deployed-head.outcome == 'success' }} + env: + NAMESPACE_KUBECONFIG: ${{ runner.temp }}/dev-demo-namespace-manager.kubeconfig + KUBECONFIG: ${{ runner.temp }}/dev-demo-runtime.kubeconfig + HEAD_SHA: ${{ needs.dev-demo-plan.outputs.head_sha }} + IMAGE_TAG: ${{ needs.dev-demo-plan.outputs.image_tag }} + CERTIFICATE_PROFILE: ${{ steps.certificate-identity.outputs.mode }} + DEPLOYED_BASE_SHA: ${{ steps.v2-migration-mode.outputs.deployed_base_sha }} + run: | + set -euo pipefail + echo "DEV_DEMO_STAGE=bootstrap-intent" >> "$GITHUB_ENV" + [[ "$GITHUB_RUN_ID" =~ ^[1-9][0-9]*$ && "$GITHUB_RUN_ATTEMPT" =~ ^[1-9][0-9]*$ ]] + [[ "$HEAD_SHA" =~ ^[0-9a-f]{40}$ && "$DEPLOYED_BASE_SHA" =~ ^[0-9a-f]{40}$ ]] + [[ "$(git rev-parse HEAD)" == "$HEAD_SHA" && "$DEPLOYED_BASE_SHA" != "$HEAD_SHA" ]] + namespace_uid="$( + KUBECONFIG="$NAMESPACE_KUBECONFIG" kubectl get namespace dev -o json | + jq -er --arg sha "$HEAD_SHA" ' + select(.kind == "Namespace" and .metadata.name == "dev" + and .metadata.deletionTimestamp == null + and .metadata.labels["firemud.dev/dev-demo"] == "true" + and .metadata.labels["firemud.dev/environment-class"] == "dev-demo-cluster" + and .metadata.annotations["firemud.dev/last-dev-demo-head-sha"] == $sha) + | .metadata.uid + | select(type == "string" and test("^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$")) + ' + )" + helm_revision="$( + helm list -n dev --filter '^dev$' -o json | + jq -er ' + select(type == "array" and length == 1) + | .[0] + | select(.name == "dev" and .namespace == "dev" and .status == "deployed") + | .revision | tostring | select(test("^[1-9][0-9]*$")) + ' + )" + rendered_digest="$(sha256sum "$evidence_dir/intent.json" + { + echo "evidence_dir=$evidence_dir" + echo "request_id=$request_id" + } >> "$GITHUB_OUTPUT" + + - name: Retain dev-demo bootstrap intent before sending + id: retain-bootstrap-intent + if: ${{ success() && steps.bootstrap-intent.outcome == 'success' }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: dev-demo-bootstrap-intent-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ steps.bootstrap-intent.outputs.evidence_dir }}/intent.json + if-no-files-found: error + - name: Create dev-demo smoke account id: bootstrap-smoke - if: ${{ steps.cluster-access.outputs.available == 'true' && steps.deploy-release.outcome == 'success' }} + if: ${{ success() && steps.retain-bootstrap-intent.outcome == 'success' }} env: KUBECONFIG: ${{ runner.temp }}/dev-demo-runtime.kubeconfig PREVIEW_NAMESPACE: ${{ needs.dev-demo-plan.outputs.namespace }} PREVIEW_TENANT_ID: "1" + BOOTSTRAP_REQUEST_ID: ${{ steps.bootstrap-intent.outputs.request_id }} + BOOTSTRAP_EVIDENCE_DIR: ${{ steps.bootstrap-intent.outputs.evidence_dir }} run: | echo "DEV_DEMO_STAGE=bootstrap" >> "$GITHUB_ENV" BOOTSTRAP_SCRIPT=/tmp/dev-demo-bootstrap.py @@ -562,6 +633,7 @@ jobs: import time import urllib.error import urllib.request + import uuid tenant_id = 1 game_template_id = 1 @@ -569,7 +641,11 @@ jobs: email = os.environ["DEMO_SMOKE_EMAIL"] password = os.environ["DEMO_SMOKE_PASSWORD"] username = os.environ["DEMO_SMOKE_USERNAME"] - control_plane_request_id = f"dev-demo-smoke-bootstrap-{int(time.time())}" + if bootstrap_mode == "session": + with open("/tmp/request-id", encoding="utf-8") as request_file: + control_plane_request_id = request_file.read() + else: + control_plane_request_id = os.environ["BOOTSTRAP_REQUEST_ID"] def readiness_ok(url): try: @@ -602,59 +678,26 @@ jobs: except urllib.error.URLError as exc: return 503, str(exc) - def sanitize_error_body(body): - if not body: - return "redacted response body" - try: - payload = json.loads(body) - except json.JSONDecodeError: - return "redacted non-json response body" - error = payload.get("error") - if isinstance(error, dict): - code = error.get("code") - message = error.get("message") - if code and message: - return f"{code}: {message}" - if code: - return str(code) - if message: - return str(message) - return "redacted response body" - def public_account_url(path): return f"{gateway_base_url}/api/account{path}" - def bootstrap_session(account_id, timeout_seconds=120): - deadline = time.time() + timeout_seconds - attempt = 1 - last_status = None - last_body = None - while time.time() < deadline: - status, session_body = post_json( - "http://game-session-service:8080/sessions", - { - "tenantId": tenant_id, - "gameTemplateId": game_template_id, - "controlPlaneRequestId": control_plane_request_id, - "ownerAccountId": account_id, - }, - ) - print(f"Session bootstrap attempt {attempt} returned {status}") - if status < 400: - return status, session_body - last_status = status - last_body = session_body - if status < 500: - break - attempt += 1 - time.sleep(2) - raise SystemExit( - "Dev-demo smoke session bootstrap failed with status " - f"{last_status}: {sanitize_error_body(last_body)}" + def bootstrap_session(account_id): + # A failed response may follow a committed launch. Send only once. + status, session_body = post_json( + "http://game-session-service:8080/sessions", + { + "tenantId": tenant_id, + "gameTemplateId": game_template_id, + "controlPlaneRequestId": control_plane_request_id, + "ownerAccountId": account_id, + }, ) + if status != 200: + raise SystemExit(f"Dev-demo smoke session bootstrap failed with status {status}") + return status, session_body def ensure_demo_account(): - status, body = post_json( + status, _ = post_json( public_account_url("/accounts"), { "tenantId": tenant_id, @@ -674,14 +717,13 @@ jobs: return False raise SystemExit( "Dev-demo account creation failed with status " - f"{status}: {sanitize_error_body(body)}" + f"{status}" ) def issue_player_bootstrap(timeout_seconds=120): deadline = time.time() + timeout_seconds attempt = 1 last_status = None - last_body = None account_create_confirmed = False while time.time() < deadline: status, bootstrap_body = post_json( @@ -695,7 +737,6 @@ jobs: if status < 400: return status, bootstrap_body last_status = status - last_body = bootstrap_body if status == 401: if not account_create_confirmed: account_create_confirmed = ensure_demo_account() @@ -709,7 +750,7 @@ jobs: break raise SystemExit( "Player bootstrap failed with status " - f"{last_status}: {sanitize_error_body(last_body)}" + f"{last_status}" ) gateway_base_url = "" @@ -723,12 +764,16 @@ jobs: if status >= 400: raise SystemExit( "Player bootstrap failed with status " - f"{status}: {sanitize_error_body(bootstrap_body)}" + f"{status}" ) bootstrap_payload = json.loads(bootstrap_body or "{}") account_id = (((bootstrap_payload.get("data") or {}).get("accountId"))) - if not account_id: - raise SystemExit("Dev-demo bootstrap response did not include account id") + try: + parsed_account_id = uuid.UUID(account_id) + if str(parsed_account_id) != account_id or parsed_account_id.int == 0: + raise ValueError + except (AttributeError, TypeError, ValueError): + raise SystemExit("Dev-demo bootstrap response did not include a canonical Account UUID") from None with open(os.environ["BOOTSTRAP_ACCOUNT_ID_FILE"], "w", encoding="utf-8") as account_file: account_file.write(str(account_id)) raise SystemExit(0) @@ -753,6 +798,25 @@ jobs: wait_for_ready("spring-cloud-gateway", "http://spring-cloud-gateway/actuator/health/readiness") status, session_body = bootstrap_session(account_id) + try: + session = json.loads(session_body)["data"] + if status != 200 or not isinstance(session, dict): + raise ValueError + returned_ids = { + key: session[key] + for key in ("id", "tenantId", "gameTemplateId", "ownerAccountId") + } + if any(type(value) is not int or value <= 0 for value in returned_ids.values()): + raise ValueError + if returned_ids["tenantId"] != tenant_id or returned_ids["gameTemplateId"] != game_template_id: + raise ValueError + except (KeyError, TypeError, ValueError): + raise SystemExit("Dev-demo session bootstrap did not return valid owner identifiers") from None + print("DEV_DEMO_BOOTSTRAP_RESULT=" + json.dumps({ + "controlPlaneRequestId": control_plane_request_id, + "accountUuid": account_id, + "gameSession": returned_ids, + }, separators=(",", ":"))) PY BOOTSTRAP_POD_LOG=/tmp/dev-demo-bootstrap-pod.log BOOTSTRAP_SECRET_DIR= @@ -807,6 +871,7 @@ jobs: cleanup_bootstrap_port_forward kubectl -n "${PREVIEW_NAMESPACE}" delete pod dev-demo-bootstrap --ignore-not-found >/dev/null 2>&1 kubectl -n "${PREVIEW_NAMESPACE}" delete configmap dev-demo-bootstrap-script --ignore-not-found >/dev/null 2>&1 + rm -f -- "$BOOTSTRAP_POD_LOG" "$BOOTSTRAP_SCRIPT" if ! cleanup_bootstrap_account_id_file; then status=1 fi @@ -879,6 +944,7 @@ jobs: kubectl -n "${PREVIEW_NAMESPACE}" create configmap dev-demo-bootstrap-script \ --from-file=bootstrap.py="${BOOTSTRAP_SCRIPT}" \ --from-file=account-id="${BOOTSTRAP_ACCOUNT_ID_FILE}" \ + --from-literal=request-id="${BOOTSTRAP_REQUEST_ID}" \ --dry-run=client -o yaml | kubectl apply -f - ( umask 077 @@ -932,10 +998,28 @@ jobs: kubectl -n "${PREVIEW_NAMESPACE}" describe pod dev-demo-bootstrap || true exit 1 fi - kubectl -n "${PREVIEW_NAMESPACE}" logs dev-demo-bootstrap | tee "${BOOTSTRAP_POD_LOG}" + kubectl -n "${PREVIEW_NAMESPACE}" logs dev-demo-bootstrap >"${BOOTSTRAP_POD_LOG}" kubectl -n "${PREVIEW_NAMESPACE}" delete pod dev-demo-bootstrap --ignore-not-found >/dev/null 2>&1 || true kubectl -n "${PREVIEW_NAMESPACE}" delete configmap dev-demo-bootstrap-script --ignore-not-found >/dev/null 2>&1 || true cleanup_bootstrap_secret + python3 ./dev-tools/hosted/dev-demo/write-bootstrap-result.py \ + "$BOOTSTRAP_EVIDENCE_DIR" "$BOOTSTRAP_ACCOUNT_ID_FILE" "$BOOTSTRAP_POD_LOG" + + - name: Retain successful dev-demo bootstrap result + if: ${{ success() && steps.bootstrap-smoke.outcome == 'success' }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: dev-demo-bootstrap-result-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ steps.bootstrap-intent.outputs.evidence_dir }}/result.json + if-no-files-found: error + + - name: Clean local dev-demo bootstrap evidence + if: ${{ always() && steps.bootstrap-intent.outcome == 'success' }} + env: + BOOTSTRAP_EVIDENCE_DIR: ${{ steps.bootstrap-intent.outputs.evidence_dir }} + run: | + rm -f -- "$BOOTSTRAP_EVIDENCE_DIR/intent.json" "$BOOTSTRAP_EVIDENCE_DIR/result.json" + rmdir -- "$BOOTSTRAP_EVIDENCE_DIR" - name: Smoke dev-demo over TCP id: smoke diff --git a/.github/workflows/publish-pr-runtime-images.yml b/.github/workflows/publish-pr-runtime-images.yml index 5911fe2c6f..a3141619e8 100644 --- a/.github/workflows/publish-pr-runtime-images.yml +++ b/.github/workflows/publish-pr-runtime-images.yml @@ -7,7 +7,7 @@ on: repository_dispatch: types: [pr-runtime-image-publication] -run-name: Publish PR Runtime Images ${{ github.event.workflow_run.display_title || format('source-run-{0}', github.event.client_payload.source_run_id) }} +run-name: Publish PR Runtime Images ${{ github.event_name == 'workflow_run' && format('{0} source-run-{1} attempt-{2}', github.event.workflow_run.display_title, github.event.workflow_run.id, github.event.workflow_run.run_attempt) || format('source-run-{0} attempt-{1}', github.event.client_payload.source_run_id, github.event.client_payload.source_run_attempt) }} permissions: {} @@ -662,6 +662,8 @@ jobs: source: ${{ steps.resolve.outputs.source }} title: ${{ steps.resolve.outputs.title }} artifact_name: ${{ steps.resolve.outputs.artifact_name }} + artifact_id: ${{ steps.resolve.outputs.artifact_id }} + artifact_digest: ${{ steps.resolve.outputs.artifact_digest }} steps: - name: Harden runner uses: step-security/harden-runner@aebdcf6156ab6691adf63218240e476564a1ed4c # v2.23.0 @@ -679,7 +681,8 @@ jobs: context.payload.action !== "pr-runtime-image-publication" || context.ref !== `refs/heads/${context.payload.repository.default_branch}` || !payload || Array.isArray(payload) || typeof payload !== "object" || - Object.keys(payload).length !== 1 || !Object.hasOwn(payload, "source_run_id"))) { + Object.keys(payload).length !== 2 || !Object.hasOwn(payload, "source_run_id") || + !Object.hasOwn(payload, "source_run_attempt"))) { throw new Error("publication handoff is not the closed default-branch source-run payload"); } const sourceIdText = String(callback ? context.payload.workflow_run.id : payload.source_run_id); @@ -687,6 +690,11 @@ jobs: throw new Error("publication source run ID is not a positive safe integer"); } const sourceId = Number(sourceIdText); + const sourceAttemptText = callback ? "" : String(payload.source_run_attempt); + if (!callback && (!/^[1-9][0-9]*$/.test(sourceAttemptText) || !Number.isSafeInteger(Number(sourceAttemptText)))) { + throw new Error("publication source run attempt is not a positive safe integer"); + } + const sourceAttempt = Number(sourceAttemptText); const repository = `${context.repo.owner}/${context.repo.repo}`; const deadline = Date.now() + 120000; const proofOptions = options => { @@ -735,6 +743,9 @@ jobs: const { data: run } = await github.rest.actions.getWorkflowRun(proofOptions({ ...context.repo, run_id: sourceId, })); + if (!callback && run.run_attempt !== sourceAttempt) { + throw new Error("publication source run attempt differs from the dispatch"); + } const title = typeof run.display_title === "string" && run.display_title.match(titlePattern); if (run.id !== sourceId || run.workflow_id !== workflow.id || !Number.isSafeInteger(run.run_attempt) || run.run_attempt <= 0 || @@ -848,10 +859,34 @@ jobs: if (uploadStart < jobStart || uploadEnd < uploadStart || uploadEnd > jobEnd) { throw new Error("publication artifact upload did not execute within the selected producer job"); } + const artifactName = `pr-runtime-images-pr-merge-${title[4]}`; + const {data: inventory} = await github.rest.actions.listWorkflowRunArtifacts(proofOptions({ + ...context.repo, run_id: sourceId, name: artifactName, per_page: 100, page: 1, + })); + if (inventory?.total_count !== 1 || !Array.isArray(inventory.artifacts) || + inventory.artifacts.length !== 1) { + throw new Error("publication requires exactly one artifact in the complete exact-name source inventory"); + } + const artifact = inventory.artifacts[0]; + if (!Number.isSafeInteger(artifact?.id) || artifact.id <= 0 || + artifact.name !== artifactName || artifact.expired !== false || + artifact.workflow_run?.id !== sourceId || artifact.workflow_run.head_sha !== run.head_sha || + typeof artifact.digest !== "string" || !/^sha256:[0-9a-f]{64}$/.test(artifact.digest)) { + throw new Error("publication artifact identity, digest, or retention is not qualified"); + } + // The run artifact API has no attempt number. Bind creation to + // the exact upload step, allowing for native timestamp precision. + const artifactCreated = timestamp(artifact.created_at); + if (artifactCreated < Math.floor(uploadStart / 1000) * 1000 || + artifactCreated > Math.floor(uploadEnd / 1000) * 1000 + 999) { + throw new Error("publication artifact was not created within the selected upload step"); + } if (Date.now() >= deadline) throw new Error("publication producer proof exceeded its bounded deadline"); core.setOutput("source", JSON.stringify(run)); core.setOutput("title", run.display_title); - core.setOutput("artifact_name", `pr-runtime-images-pr-merge-${title[4]}`); + core.setOutput("artifact_name", artifactName); + core.setOutput("artifact_id", String(artifact.id)); + core.setOutput("artifact_digest", artifact.digest); break; } if (callback || !["queued", "in_progress", "waiting", "pending", "requested"].includes(run.status) || @@ -895,7 +930,8 @@ jobs: - name: Download successful PR image artifacts uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 with: - name: ${{ needs.source.outputs.artifact_name }} + artifact-ids: ${{ needs.source.outputs.artifact_id }} + digest-mismatch: error # The pinned action extracts a sole artifact directly into path. path: /tmp/pr-runtime-artifacts/${{ needs.source.outputs.artifact_name }} github-token: ${{ github.token }} @@ -1215,6 +1251,9 @@ jobs: - name: Summarize trusted publication source env: + SOURCE_RUN_ATTEMPT: ${{ fromJSON(needs.source.outputs.source).run_attempt }} + SOURCE_ARTIFACT_ID: ${{ needs.source.outputs.artifact_id }} + SOURCE_ARTIFACT_DIGEST: ${{ needs.source.outputs.artifact_digest }} SOURCE_RUN_ID: ${{ fromJSON(needs.source.outputs.source).id }} SOURCE_RUN_URL: ${{ fromJSON(needs.source.outputs.source).html_url }} SOURCE_RUN_TITLE: ${{ fromJSON(needs.source.outputs.source).display_title }} @@ -1231,7 +1270,8 @@ jobs: summary = f"""### Trusted PR runtime image publication - - Source workflow run: [{os.environ['SOURCE_RUN_ID']}]({os.environ['SOURCE_RUN_URL']}) + - Source workflow run: [{os.environ['SOURCE_RUN_ID']}]({os.environ['SOURCE_RUN_URL']}) (attempt `{os.environ['SOURCE_RUN_ATTEMPT']}`) + - Source artifact ID and SHA-256: `{os.environ['SOURCE_ARTIFACT_ID']}` / `{os.environ['SOURCE_ARTIFACT_DIGEST']}` - Source run title: {markdown_code(os.environ['SOURCE_RUN_TITLE'])} - Source workflow branch/SHA: {markdown_code(os.environ['SOURCE_HEAD_BRANCH'])} / `{os.environ['SOURCE_HEAD_SHA']}` - Current PR head branch/SHA: {markdown_code(os.environ.get('PR_HEAD_BRANCH', ''))} / `{os.environ['HEAD_SHA']}` diff --git a/.github/workflows/runtime-images.yml b/.github/workflows/runtime-images.yml index 667d966b8a..4467604fa6 100644 --- a/.github/workflows/runtime-images.yml +++ b/.github/workflows/runtime-images.yml @@ -2457,7 +2457,10 @@ jobs: await github.rest.repos.createDispatchEvent({ ...context.repo, event_type: "pr-runtime-image-publication", - client_payload: { source_run_id: String(context.runId) }, + client_payload: { + source_run_id: String(context.runId), + source_run_attempt: process.env.GITHUB_RUN_ATTEMPT, + }, }); smoke-full: diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 5087187eec..941b666854 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -632,7 +632,7 @@ jobs: } // Current producer definition; the contract test reports fingerprint upkeep. - const canonicalRuntimeWorkflowSha256 = "1d09fe191e67b07be1c4d01cd677a94b32871fd3640ebce2c96f7e696f08014a"; + const canonicalRuntimeWorkflowSha256 = "e694c8ee926fd3021a5aba831509c584e8d239a1471de6300319f9d886b6bbd5"; // Only authenticated default-branch refreshes may use retained successful definitions. // Keep the pre-rollout default and predecessor definitions for mixed-version runs. const canonicalCompatibleTrustedRefreshRuntimeWorkflowSha256 = new Set([ diff --git a/design/architecture/system-architecture-cicd.md b/design/architecture/system-architecture-cicd.md index 445b215b40..e41599450d 100644 --- a/design/architecture/system-architecture-cicd.md +++ b/design/architecture/system-architecture-cicd.md @@ -86,9 +86,9 @@ The optional [PR LOC Report](../../.github/workflows/pr-loc-report.yml) is also The trust split is deliberate: PR-controlled source can build and execute without package-write authority, while the trusted publisher never checks out or executes PR source. The current base branch ref and the test merge's ordered base/head parents establish the exact tuple for image publication and preview selection; a pull request event or API `base.sha` can lag the branch ref and is not current-base authority for those actions. The required Smoke Gate accepts a successful credential-free smoke run for its verified PR-event base/head/merge tuple. If GitHub supplies no usable event merge SHA or the event base SHA already lags the event merge's parents, the gate instead requires a successful trusted, typed refresh for the verified current base/head/merge tuple. An unrelated base advance after valid event-tuple smoke does not invalidate that tested merge or require the PR head to absorb new dependencies; a changed PR head or base branch requires new proof. The source run records the verified base, head, and merge SHAs, and the merge SHA keys the immutable PR image tag. Ordinary previews remain limited to same-repository, non-dependency-bot pull requests targeting `main` or `develop`. The credential-free runtime producer and required Smoke Gate cover every PR base, including same-repository feature branches, while retaining runtime path classification and an explicit no-op for irrelevant changes. Hosted preview and registry publication retain their separate eligibility policy: a stacked pull request requires the maintainer-controlled `preview:priority` label, an open mergeable state, and a current same-repository base. Completed Validation callbacks qualify long-lived branch pushes or substantive same-repository PR heads against the current branch ref before dispatching child-specific exact base/head/merge runtime refreshes. PR callbacks verify the current native CI attempt and executed substantive enforcement with skipped metadata preservation before reconciling their source PR's current tuple, recovering retarget edits whose event merge cannot qualify. Metadata-only, superseded, or unclassifiable attempts do not reconstruct runtime. PR-completion reconciliation is isolated by source run ID and attempt, so a metadata completion cannot cancel a substantive refresh; protected branch publication retains its separate branch serialization. Dependent refresh for `main` and `develop` belongs only to their push callback; PR callbacks whose head is one of those branches still reconcile their own source PR. A stale parent callback cannot dispatch proof for an advanced branch, and the callback itself supplies no child smoke proof. Preview reconciliation is dispatched only for independently eligible targets; scheduled preview reconciliation remains an additional recovery path. A failed branch CI run cannot publish branch images; the separately dispatched PR merge images can be published only after their own held-admission qualification succeeds and the trusted publisher validates their current eligibility and provenance. Preview selection fails closed until a successful image run for the new merge is published. An ordinary `main`/`develop` PR with no runtime-image change may instead reuse the proven base-commit service images. A stacked PR always uses its exact merge image because its feature-branch base SHA is not a trusted branch-image identity. -A typed runtime refresh hands off publication explicitly after its required credential-free image and smoke jobs succeed and its image artifact upload succeeds; an exception pass with no uploaded artifact cannot dispatch publication. Its separate trusted default-ref job checks out no source and receives only job-scoped `contents: write` to send `pr-runtime-image-publication` with the sole `source_run_id` field. PR build jobs retain read-only repository permissions. The publisher accepts this fixed repository-dispatch type and ordinary successful runtime workflow-run callbacks, both using the trusted default-branch definition. It exposes no branch-selectable manual publication entrypoint and requires no additional credential. +A typed runtime refresh hands off publication explicitly after its required credential-free image and smoke jobs succeed and its image artifact upload succeeds; an exception pass with no uploaded artifact cannot dispatch publication. Its separate trusted default-ref job checks out no source and receives only job-scoped `contents: write` to send `pr-runtime-image-publication` with the exact `source_run_id` and `source_run_attempt` selectors. PR build jobs retain read-only repository permissions. The publisher accepts this fixed repository-dispatch type and ordinary successful runtime workflow-run callbacks, both using the trusted default-branch definition. It exposes no branch-selectable manual publication entrypoint and requires no additional credential. -For typed publication, `source_run_id` selects a native Actions run for lookup; neither the payload nor its title is source authority. The no-checkout resolver binds the returned native `run.id` to that supplied ID and its `workflow_id` to the separately resolved runtime workflow identity (`Build Runtime Images` at `.github/workflows/runtime-images.yml`). The native run path must be that workflow path or its validated ref-suffixed form, and its name must be the owner workflow name or exact canonical display title. It requires native `event=repository_dispatch`, the current repository in both `repository` and `head_repository`, `head_branch` equal to the repository default branch, a lowercase 40-character native `head_sha` for that default-branch source revision, and the canonical runtime title carrying the exact PR number/base/head/merge tuple and `mode-required`. The type and default-branch ref are also checked at the handoff boundary. This trusted typed source identity comes from GitHub's Actions run and workflow records, not from caller-supplied tuple fields. +For typed publication, the ID and attempt select a native Actions attempt for lookup. The resolver checks both against the native current run, and the waiter correlates the publisher to that exact source attempt. The no-checkout resolver binds the returned native `run.id` to that supplied ID and its `workflow_id` to the separately resolved runtime workflow identity (`Build Runtime Images` at `.github/workflows/runtime-images.yml`). The native run path must be that workflow path or its validated ref-suffixed form, and its name must be the owner workflow name or exact canonical display title. It requires native `event=repository_dispatch`, the current repository in both `repository` and `head_repository`, `head_branch` equal to the repository default branch, a lowercase 40-character native `head_sha` for that default-branch source revision, and the canonical runtime title carrying the exact PR number/base/head/merge tuple and `mode-required`. The type and default-branch ref are also checked at the handoff boundary. This trusted typed source identity comes from GitHub's Actions run and workflow records, not from caller-supplied tuple fields. The publisher's no-checkout, Actions-read-only resolver reads only the supplied exact source run and owning runtime workflow identity. A dispatch can arrive before its source workflow finishes, so the resolver waits for actual terminal success within a two-minute budget; malformed provenance, an API error, a failed or cancelled source, and an exhausted wait fail closed. The resolver never substitutes a successful status. Both trigger paths retain the same exact source, current PR/base/head/merge, artifact provenance, and immutable-tag validation. Before selecting the artifact, the resolver requires one successful native producer job and its successful upload step within the exact attempt’s execution window. A partial rerun that retains an earlier upload cannot qualify that upload as part of the current attempt. The publisher checks the resolved native source attempt again after download and refuses a superseded attempt before registry access. Publishing jobs serialize on the verified merge-bound source title across both paths; duplicate publication preserves identical existing images and rejects conflicting image bytes. Explicit dispatch avoids relying on a workflow-run callback from a token-origin refresh without weakening the source or registry boundary. diff --git a/design/architecture/system-architecture-database-migrations.md b/design/architecture/system-architecture-database-migrations.md index 13740831dd..eaccf708bb 100644 --- a/design/architecture/system-architecture-database-migrations.md +++ b/design/architecture/system-architecture-database-migrations.md @@ -265,6 +265,10 @@ The trusted workflow records `firemud.dev/last-dev-demo-head-sha` after staged d A recorded target with an unsuccessful, skipped, cancelled, or unprovable bootstrap is not eligible for the verification-only smoke step. An Account creation response, a bootstrap Pod phase, an email lookup, or the presence of an authored world alone is not a durable success record for the exact original account and world. If the deployment owner cannot identify the original attempt and retained target, stop rather than infer them from the current namespace or a newer run. A source review can demonstrate this interruption window without identifying a historical incident. +For workflow versions with bootstrap evidence retention, obtain the original run and attempt's `dev-demo-bootstrap-intent--` and, if present, `dev-demo-bootstrap-result--` artifacts from that exact trusted run. The intent is retained before any bootstrap send. It records the workflow and attempt, the deployed-to-target comparison, namespace UID, deployed Helm revision, rendered-input digests and the stable Game Session request ID. The result retains only the Account UUID and the Game Session instance, tenant, template and numeric owner identifiers returned by the original bootstrap. It is available only after successful bootstrap and retains the exact intent. Keep both artifacts with the original deployment evidence before artifact expiry. These records give owners exact correlation inputs for their inspection. Verify the actual deployed image identities and Flyway history and have the owners establish the Account-to-Game Session identity mapping and World installation from their authoritative state. + +An absent result may reflect cancellation, lost response, cleanup or artifact retention failure, or genuinely unstarted bootstrap. An older run may have neither artifact. A positive no-start continuation would require all affected owners to prove the exact original operation had no effect and a durable fence to exclude any delayed original execution before they permit another attempt. The current workflow does not provide that proof or a repair path. + Keep the ordinary same-target refusal. Do not clear the annotation, create a new target to obtain a clean reset, rerun Helm, rerun player bootstrap, or use a different account or world. For a separately authorized owner recovery, the deployment owner first establishes the original attempt and retains the namespace UID, target SHA, Helm revision and exact Flyway evidence described above. Account then correlates the original bootstrap and exact Account UUID, and the Game Session and World owners confirm the exact installed authored-world binding and the durable bootstrap result. If any evidence is missing, ambiguous or mismatched, preserve the existing release and stop. Only if those owners establish that the original bootstrap had already completed may an authorized operator return to the verification-only procedure with that exact account and world. This handoff does not implement or authorize a resume or repair when completion cannot be established. Qualify any future owner recovery mechanism on a disposable release before offering it to operators. At minimum prove interruption before durable bootstrap, durable bootstrap with the response lost, and wrong or missing account/world binding. In each refusal case verify that the original namespace UID, Helm revision, recorded SHA, and Flyway history remain unchanged, and that no replacement account, world, or bootstrap write occurs. In the completed-original case verify the same durable identities and a new smoke transcript without replaying deployment or bootstrap. Keep disposable proof separate from any production incident record. diff --git a/dev-tools/deploy/detect-hosted-v2-migration-activation.sh b/dev-tools/deploy/detect-hosted-v2-migration-activation.sh index b96b0de2c3..88b7752b25 100644 --- a/dev-tools/deploy/detect-hosted-v2-migration-activation.sh +++ b/dev-tools/deploy/detect-hosted-v2-migration-activation.sh @@ -154,6 +154,7 @@ if [[ "$probe_account_origin" == true ]]; then "$origin_prefix" "$base_sha" "$namespace_uid" fi +printf 'deployed_base_sha=%s\n' "$base_sha" if [[ "$migration_changed" == true ]]; then emit_mode true "$reason_source first adds a supported Account, Game Session, or Automation migration" else diff --git a/dev-tools/hosted/dev-demo/write-bootstrap-result.py b/dev-tools/hosted/dev-demo/write-bootstrap-result.py new file mode 100644 index 0000000000..cef687e656 --- /dev/null +++ b/dev-tools/hosted/dev-demo/write-bootstrap-result.py @@ -0,0 +1,50 @@ +import json +import sys +import uuid +from pathlib import Path + +RESULT_PREFIX = "DEV_DEMO_BOOTSTRAP_RESULT=" +SESSION_IDS = ("id", "tenantId", "gameTemplateId", "ownerAccountId") + + +def main(): + evidence_dir, account_id_file, pod_log = map(Path, sys.argv[1:]) + try: + intent = json.loads((evidence_dir / "intent.json").read_text(encoding="utf-8")) + account_id = account_id_file.read_text(encoding="utf-8") + parsed_account_id = uuid.UUID(account_id) + if parsed_account_id.int == 0 or str(parsed_account_id) != account_id: + raise ValueError + lines = [ + line.removeprefix(RESULT_PREFIX) + for line in pod_log.read_text(encoding="utf-8").splitlines() + if line.startswith(RESULT_PREFIX) + ] + (encoded_result,) = lines + result = json.loads(encoded_result) + if ( + result["accountUuid"] != account_id + or result["controlPlaneRequestId"] != intent["controlPlaneRequestId"] + ): + raise ValueError + session = {key: result["gameSession"][key] for key in SESSION_IDS} + if any(type(value) is not int or value <= 0 for value in session.values()): + raise ValueError + if any(session[key] != intent[key] for key in ("tenantId", "gameTemplateId")): + raise ValueError + except (OSError, KeyError, TypeError, ValueError): + raise SystemExit("Cannot verify the exact successful dev-demo bootstrap result") from None + + receipt = { + "schema": "dev-demo-bootstrap-result/v1", + "intent": intent, + "accountUuid": account_id, + "gameSession": session, + } + with (evidence_dir / "result.json").open("x", encoding="utf-8") as output: + json.dump(receipt, output, indent=2) + output.write("\n") + + +if __name__ == "__main__": + main() diff --git a/dev-tools/hosted/shared/wait-for-runtime-images.sh b/dev-tools/hosted/shared/wait-for-runtime-images.sh index 7c84d3bb13..3175872339 100644 --- a/dev-tools/hosted/shared/wait-for-runtime-images.sh +++ b/dev-tools/hosted/shared/wait-for-runtime-images.sh @@ -62,11 +62,13 @@ import sys import re from datetime import datetime, timezone -wait_mode, image_tag, merge_sha, base_sha, head_sha = sys.argv[1:] +wait_mode, image_tag, merge_sha, base_sha, head_sha, *native = sys.argv[1:] try: payload = json.load(sys.stdin) except json.JSONDecodeError: raise SystemExit(1) +if native: + payload = {"workflow_runs": [payload]} pages = payload if isinstance(payload, list) else [payload] if not pages or any( not isinstance(page, dict) or not isinstance(page.get("workflow_runs"), list) @@ -117,6 +119,9 @@ run = sorted(matching_runs, key=lambda item: item.get("created_at", ""), reverse def clean_field(value): return isinstance(value, str) and bool(value) and not any(character.isspace() or ord(character) < 32 or ord(character) == 127 for character in value) +run_attempt = run.get("run_attempt") if wait_mode == "pull-request" else "-" +if wait_mode == "pull-request" and (type(run_attempt) is not int or run_attempt <= 0): + raise SystemExit(1) run_id = run.get("id") if type(run_id) is not int or run_id <= 0: raise SystemExit(1) @@ -139,16 +144,17 @@ except ValueError: if created > datetime.now(timezone.utc): raise SystemExit(1) print( - "found\t{}\t{}\t{}\t{}\t{}\t{}".format( + "found\t{}\t{}\t{}\t{}\t{}\t{}\t{}".format( run_id, run["status"], conclusion, run["html_url"], run["event"], created_at, + run_attempt, ) ) -' "${wait_mode}" "${image_tag}" "${merge_sha}" "${base_sha}" "${head_sha}" +' "${wait_mode}" "${image_tag}" "${merge_sha}" "${base_sha}" "${head_sha}" "$@" } fetch_publisher_runs() { @@ -219,8 +225,8 @@ import json import re import sys -wait_mode, image_tag, merge_sha, base_sha, head_sha, source_run_id = sys.argv[1:] -if not re.fullmatch(r"[1-9][0-9]*", source_run_id): +wait_mode, image_tag, merge_sha, base_sha, head_sha, source_run_id, source_run_attempt = sys.argv[1:] +if not all(re.fullmatch(r"[1-9][0-9]*", value) for value in (source_run_id, source_run_attempt)): raise SystemExit(1) try: payload = json.load(sys.stdin) @@ -240,21 +246,23 @@ workflow_runs = [ if any(not isinstance(run, dict) for run in workflow_runs): raise SystemExit(1) if wait_mode == "pull-request": + source_suffix = f"source-run-{source_run_id} attempt-{source_run_attempt}" matching_runs = [ run for run in workflow_runs if (run.get("event") == "repository_dispatch" and - run.get("display_title") == f"Publish PR Runtime Images source-run-{source_run_id}") + run.get("display_title") == f"Publish PR Runtime Images {source_suffix}") or (run.get("event") == "workflow_run" and (tokens := run.get("display_title", "").split())[:8] == [ "Publish", "PR", "Runtime", "Images", "Build", "Runtime", "Images", "secure-pr-artifact", ] - and len(tokens) == 13 + and len(tokens) == 15 and re.fullmatch(r"pr-[1-9][0-9]{0,50}", tokens[8]) and tokens[9] == f"base-{base_sha}" and tokens[10] == f"head-{head_sha}" and tokens[11] == f"merge-{merge_sha}" - and tokens[12] == "mode-required") + and tokens[12] == "mode-required" + and " ".join(tokens[13:]) == source_suffix) ] else: matching_runs = [] @@ -263,20 +271,71 @@ if not matching_runs: raise SystemExit(0) run = sorted(matching_runs, key=lambda item: item.get("created_at", ""), reverse=True)[0] +attempt = run.get("run_attempt") +if type(attempt) is not int or attempt <= 0: + raise SystemExit(1) +url = run.get("html_url") or "-" print( - "found\t{}\t{}\t{}\t{}".format( - run.get("id", ""), - run.get("status", ""), - run.get("conclusion", ""), - run.get("html_url", ""), + "found\t{}\t{}\t{}\t{}\t{}".format( + run["id"], run.get("status"), run.get("conclusion"), url, attempt, ) ) -' "${wait_mode}" "${image_tag}" "${merge_sha}" "${base_sha}" "${head_sha}" "$1" +' "${wait_mode}" "${image_tag}" "${merge_sha}" "${base_sha}" "${head_sha}" "$1" "$2" +} + +verify_publisher_attempt() { + local run_id="$1" run_attempt="$2" remaining="$3" jobs + (( remaining > 0 )) || return 1 + if ! jobs="$(timeout "${remaining}s" gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${run_id}/attempts/${run_attempt}/jobs?per_page=100&page=1")"; then + return 1 + fi + python3 -c ' +import json +import sys + +run_id, attempt = map(int, sys.argv[1:]) +try: + payload = json.load(sys.stdin) +except json.JSONDecodeError: + raise SystemExit(1) +if not isinstance(payload, dict): + raise SystemExit(1) +jobs = payload.get("jobs") +total = payload.get("total_count") +if type(total) is not int or not 1 <= total <= 100 or not isinstance(jobs, list) or len(jobs) != total: + raise SystemExit(1) +seen = set() +publish = [] +for job in jobs: + if not isinstance(job, dict): + raise SystemExit(1) + job_id = job.get("id") + if (type(job_id) is not int or job_id <= 0 or job_id in seen + or type(job.get("run_id")) is not int or job["run_id"] != run_id + or type(job.get("run_attempt")) is not int or job["run_attempt"] != attempt): + raise SystemExit(1) + seen.add(job_id) + if job.get("name") == "Publish Fixed PR Merge Image Tags": + publish.append(job) +if len(publish) != 1 or publish[0].get("status") != "completed" or publish[0].get("conclusion") != "success": + raise SystemExit(1) +steps = publish[0].get("steps") +if not isinstance(steps, list) or any(not isinstance(step, dict) for step in steps): + raise SystemExit(1) +for name in ("Download successful PR image artifacts", + "Validate exact PR source and artifact before registry login", + "Publish fixed PR image tags"): + matching = [step for step in steps if step.get("name") == name] + if len(matching) != 1 or matching[0].get("status") != "completed" or matching[0].get("conclusion") != "success": + raise SystemExit(1) +' "${run_id}" "${run_attempt}" <<<"${jobs}" } wait_for_pr_publisher() { local source_run_id="$1" - local source_created_at="$2" + local source_run_attempt="$2" + local source_created_at="$3" + local source_event="$4" local coverage_unavailable=false local publisher_start_epoch="${SECONDS}" local publisher_deadline=$((SECONDS + publisher_timeout_seconds)) @@ -303,14 +362,14 @@ wait_for_pr_publisher() { fi coverage_unavailable=false publisher_payload="[${publisher_payload}]" - if ! publisher_state="$(read_publisher_state "${source_run_id}" <<<"${publisher_payload}")"; then + if ! publisher_state="$(read_publisher_state "${source_run_id}" "${source_run_attempt}" <<<"${publisher_payload}")"; then printf 'GitHub API response was empty or invalid while waiting for the trusted PR image publisher; retrying.\n' >&2 sleep "${sleep_seconds}" continue fi - local state run_id run_status run_conclusion run_url - IFS=$'\t' read -r state run_id run_status run_conclusion run_url <<<"${publisher_state}" + local state run_id run_status run_conclusion run_url publisher_attempt + IFS=$'\t' read -r state run_id run_status run_conclusion run_url publisher_attempt <<<"${publisher_state}" if [[ "${state}" == "missing" ]]; then local elapsed_seconds=$((SECONDS - publisher_start_epoch)) @@ -326,13 +385,37 @@ wait_for_pr_publisher() { fi if [[ "${run_status}" == "completed" && "${run_conclusion}" == "success" ]]; then + if ! verify_publisher_attempt "${run_id}" "${publisher_attempt}" "$((publisher_deadline - SECONDS))"; then + printf 'Exact PR image publisher job and step success is unavailable for run %s attempt %s.\n' \ + "${run_id}" "${publisher_attempt}" >&2 + sleep "${sleep_seconds}" + continue + fi + local remaining=$((publisher_deadline - SECONDS)) current_payload current_state + local current_kind current_id current_status current_conclusion _current_url current_event _current_created_at current_attempt + if (( remaining <= 0 )) || + ! current_payload="$(timeout "${remaining}s" gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${source_run_id}")" || + ! current_state="$(read_run_state native <<<"${current_payload}")"; then + printf 'Current runtime-image producer evidence is unavailable for run %s attempt %s.\n' \ + "${source_run_id}" "${source_run_attempt}" >&2 + return 1 + fi + IFS=$'\t' read -r current_kind current_id current_status current_conclusion _current_url current_event _current_created_at current_attempt <<<"${current_state}" + if (( SECONDS >= publisher_deadline )) || + [[ "${current_kind}" != "found" || "${current_id}" != "${source_run_id}" || + "${current_attempt}" != "${source_run_attempt}" || "${current_event}" != "${source_event}" || + "${current_status}" != "completed" || "${current_conclusion}" != "success" ]]; then + printf 'Current runtime-image producer does not match the successful run %s attempt %s for %s.\n' \ + "${source_run_id}" "${source_run_attempt}" "${image_tag}" >&2 + return 1 + fi printf 'Trusted PR image publisher %s succeeded for %s.\n' "${run_id}" "${image_tag}" return 0 fi if [[ "${run_status}" == "completed" ]]; then printf 'Trusted PR image publisher %s completed with %s for %s.\n' \ "${run_id}" "${run_conclusion}" "${image_tag}" >&2 - [[ -z "${run_url}" ]] || printf 'Workflow URL: %s\n' "${run_url}" >&2 + [[ -z "${run_url}" || "${run_url}" == "-" ]] || printf 'Workflow URL: %s\n' "${run_url}" >&2 exit 1 fi @@ -364,7 +447,7 @@ while (( SECONDS < deadline )); do continue fi - IFS=$'\t' read -r state run_id run_status run_conclusion run_url _run_event run_created_at <<<"${run_state}" + IFS=$'\t' read -r state run_id run_status run_conclusion run_url run_event run_created_at run_attempt <<<"${run_state}" if [[ "${state}" == "missing" ]]; then elapsed_seconds=$((SECONDS - start_epoch)) @@ -390,7 +473,7 @@ while (( SECONDS < deadline )); do printf 'Matching runtime-images workflow %s succeeded for %s after %ss.\n' \ "${run_id}" "${image_tag}" "$((SECONDS - start_epoch))" if [[ "${wait_mode}" == "pull-request" ]]; then - wait_for_pr_publisher "${run_id}" "${run_created_at}" + wait_for_pr_publisher "${run_id}" "${run_attempt}" "${run_created_at}" "${run_event}" fi exit 0 fi diff --git a/dev-tools/tests/dev-demo-workflow-contract.sh b/dev-tools/tests/dev-demo-workflow-contract.sh index 1a635fe4b6..603eb1809e 100644 --- a/dev-tools/tests/dev-demo-workflow-contract.sh +++ b/dev-tools/tests/dev-demo-workflow-contract.sh @@ -692,6 +692,7 @@ python3 - "$workflow" "$reconciler" "$requester" "$waiter" "$annotator" "$target from __future__ import annotations import importlib.util +import json import os import subprocess import sys @@ -1431,6 +1432,121 @@ if "steps.deploy-release.outcome == 'success'" not in deployed_head_step.get("if if "firemud.dev/last-dev-demo-head-sha=${HEAD_SHA}" not in deployed_head_step["run"]: raise SystemExit("successful Helm completion does not record exact deployed-head evidence") bootstrap_step = deploy_by_name["Create dev-demo smoke account"] +intent_step = deploy_by_name["Capture dev-demo bootstrap intent"] +retain_intent = deploy_by_name["Retain dev-demo bootstrap intent before sending"] +retain_result = deploy_by_name["Retain successful dev-demo bootstrap result"] +if not ( + deploy_steps.index(deployed_head_step) < deploy_steps.index(intent_step) + < deploy_steps.index(retain_intent) < deploy_steps.index(bootstrap_step) + < deploy_steps.index(retain_result) +): + raise SystemExit("dev-demo bootstrap custody ordering is incorrect") +if intent_step["if"] != "${{ success() && steps.record-deployed-head.outcome == 'success' }}": + raise SystemExit("dev-demo bootstrap intent must follow successful deployment recording") +if bootstrap_step["if"] != "${{ success() && steps.retain-bootstrap-intent.outcome == 'success' }}": + raise SystemExit("dev-demo bootstrap must wait for durable intent retention") +if bootstrap_step["env"]["BOOTSTRAP_REQUEST_ID"] != "${{ steps.bootstrap-intent.outputs.request_id }}": + raise SystemExit("dev-demo bootstrap request must consume the captured attempt identity") +if retain_result["if"] != "${{ success() && steps.bootstrap-smoke.outcome == 'success' }}": + raise SystemExit("failed bootstrap must never upload result evidence") +if "dev-demo-smoke-bootstrap-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" not in intent_step["run"]: + raise SystemExit("dev-demo bootstrap intent must use a stable native run/attempt identity") +for key in ("workflowSha", "headSha", "deployedBaseSha", "namespaceUid", "helmRevision", + "renderedManifestSha256", "renderedValuesSha256", "controlPlaneRequestId"): + if key not in intent_step["run"]: + raise SystemExit(f"dev-demo bootstrap intent omitted {key}") +for prefix, filename, step in (("intent", "intent.json", retain_intent), ("result", "result.json", retain_result)): + artifact = step["with"] + if artifact != { + "name": "dev-demo-bootstrap-" + prefix + "-${{ github.run_id }}-${{ github.run_attempt }}", + "path": "${{ steps.bootstrap-intent.outputs.evidence_dir }}/" + filename, + "if-no-files-found": "error", + }: + raise SystemExit("dev-demo must retain only the immutable attempt-qualified evidence file") +if any(keyword in intent_step["run"] for keyword in ("DEMO_SMOKE_PASSWORD", "DEMO_SMOKE_EMAIL", "DEMO_SMOKE_USERNAME")): + raise SystemExit("dev-demo bootstrap intent must not consume smoke credentials") +if ( + '--from-literal=request-id="${BOOTSTRAP_REQUEST_ID}"' not in bootstrap_step["run"] + or '"controlPlaneRequestId": control_plane_request_id' not in bootstrap_step["run"] + or "write-bootstrap-result.py" not in bootstrap_step["run"] +): + raise SystemExit("dev-demo bootstrap must carry the recorded identity into the request and receipt") +bootstrap_python = bootstrap_step["run"].split("<<'PY'\n", 1)[1].split("\nPY\n", 1)[0] +compile(bootstrap_python, "dev-demo-bootstrap.py", "exec") +session_function = "def bootstrap_session(" + bootstrap_python.split( + "def bootstrap_session(", 1 +)[1].split("\ndef ensure_demo_account(", 1)[0] +for response_status in (200, 400, 503): + sends = [] + + def post_session(url, payload): + sends.append((url, payload)) + return response_status, "response" + + context = { + "post_json": post_session, + "tenant_id": 1, + "game_template_id": 2, + "control_plane_request_id": "original-attempt", + } + exec(session_function, context) + try: + result = context["bootstrap_session"]("account") + except SystemExit as failure: + if response_status == 200 or not str(failure).endswith(f"status {response_status}"): + raise SystemExit("dev-demo bootstrap must report the unsuccessful session status") + else: + if response_status != 200 or result != (200, "response"): + raise SystemExit("dev-demo bootstrap must return only a successful session response") + if sends != [("http://game-session-service:8080/sessions", { + "tenantId": 1, + "gameTemplateId": 2, + "controlPlaneRequestId": "original-attempt", + "ownerAccountId": "account", + })]: + raise SystemExit("dev-demo bootstrap must send the original session request exactly once") +with tempfile.TemporaryDirectory() as directory: + evidence = Path(directory) + account_uuid = "12345678-1234-1234-1234-123456789abc" + request_id = "dev-demo-smoke-bootstrap-123-2" + intent = { + "schema": "dev-demo-bootstrap-intent/v1", + "controlPlaneRequestId": request_id, + "tenantId": 1, + "gameTemplateId": 1, + } + session = {"id": 9007199254740993, "ownerAccountId": 5, "tenantId": 1, "gameTemplateId": 1} + result = {"accountUuid": account_uuid, "controlPlaneRequestId": request_id, "gameSession": session} + (evidence / "intent.json").write_text(json.dumps(intent), encoding="utf-8") + account_file = evidence / "account-id" + account_file.write_text(account_uuid, encoding="utf-8") + log = evidence / "bootstrap.log" + receipt = evidence / "result.json" + marker = "DEV_DEMO_BOOTSTRAP_RESULT=" + command = ["python3", str(repository_root / "dev-tools/hosted/dev-demo/write-bootstrap-result.py"), + str(evidence), str(account_file), str(log)] + for contents in ( + "session response missing", + marker + json.dumps({**result, "controlPlaneRequestId": "different-attempt"}), + marker + json.dumps({**result, "accountUuid": "different-account"}), + marker + json.dumps({**result, "gameSession": {**session, "gameTemplateId": 2}}), + "\n".join([marker + json.dumps(result)] * 2), + ): + log.write_text(contents, encoding="utf-8") + if subprocess.run(command, capture_output=True).returncode == 0 or receipt.exists(): + raise SystemExit("dev-demo retained a missing, foreign, or ambiguous success result") + log.write_text("synthetic-password\n" + marker + json.dumps({ + **result, "token": "synthetic-token", "gameSession": {**session, "token": "nested-token"} + }), encoding="utf-8") + subprocess.run(command, check=True, capture_output=True) + expected = { + "schema": "dev-demo-bootstrap-result/v1", "intent": intent, + "accountUuid": account_uuid, "gameSession": session, + } + if json.loads(receipt.read_text(encoding="utf-8")) != expected: + raise SystemExit("dev-demo result lost exact IDs or copied unapproved response material") + if subprocess.run(command, capture_output=True).returncode == 0: + raise SystemExit("dev-demo result was allowed to overwrite its immutable receipt") failure_summary = deploy_by_name["Summarize dev-demo failure"] if failure_summary["env"] != { "DEPLOY_OUTCOME": "${{ steps." + deploy_by_name["Deploy dev-demo release"]["id"] + ".outcome }}", diff --git a/dev-tools/tests/pr-retarget-workflow-contract.sh b/dev-tools/tests/pr-retarget-workflow-contract.sh index c00320131e..d5d0ef1d50 100644 --- a/dev-tools/tests/pr-retarget-workflow-contract.sh +++ b/dev-tools/tests/pr-retarget-workflow-contract.sh @@ -2755,7 +2755,8 @@ done require_contains "$pr_image_publisher_path" 'workflow_run:' require_exact_line "$pr_image_publisher_path" 'permissions: {}' # shellcheck disable=SC2016 # This assertion intentionally matches a literal GitHub expression. -require_contains "$pr_image_publisher_path" "run-name: Publish PR Runtime Images \${{ github.event.workflow_run.display_title || format('source-run-{0}', github.event.client_payload.source_run_id) }}" +require_contains "$pr_image_publisher_path" "format('{0} source-run-{1} attempt-{2}', github.event.workflow_run.display_title, github.event.workflow_run.id, github.event.workflow_run.run_attempt)" +require_contains "$pr_image_publisher_path" "format('source-run-{0} attempt-{1}', github.event.client_payload.source_run_id, github.event.client_payload.source_run_attempt)" require_contains "$pr_image_publisher_path" "github.event.workflow_run.event == 'pull_request'" require_contains "$pr_image_publisher_path" "github.event.workflow_run.conclusion == 'success'" require_contains "$pr_image_publisher_path" 'github.event.workflow_run.head_repository.full_name == github.repository' @@ -2805,6 +2806,9 @@ with tempfile.NamedTemporaryFile(mode="r+", encoding="utf-8") as summary_file: "GITHUB_STEP_SUMMARY": summary_file.name, "SOURCE_RUN_ID": "123", "SOURCE_RUN_URL": "https://github.example/runs/123", + "SOURCE_RUN_ATTEMPT": "2", + "SOURCE_ARTIFACT_ID": "456", + "SOURCE_ARTIFACT_DIGEST": "sha256:" + "a" * 64, "SOURCE_RUN_TITLE": "build `title`